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
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
| //===-- ObjectFileMachO.cpp -------------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/StringRef.h"
#include "Plugins/Process/Utility/RegisterContextDarwin_arm.h"
#include "Plugins/Process/Utility/RegisterContextDarwin_arm64.h"
#include "Plugins/Process/Utility/RegisterContextDarwin_i386.h"
#include "Plugins/Process/Utility/RegisterContextDarwin_x86_64.h"
#include "lldb/Core/Debugger.h"
#include "lldb/Core/FileSpecList.h"
#include "lldb/Core/Module.h"
#include "lldb/Core/ModuleSpec.h"
#include "lldb/Core/PluginManager.h"
#include "lldb/Core/Section.h"
#include "lldb/Core/StreamFile.h"
#include "lldb/Host/Host.h"
#include "lldb/Symbol/DWARFCallFrameInfo.h"
#include "lldb/Symbol/ObjectFile.h"
#include "lldb/Target/DynamicLoader.h"
#include "lldb/Target/MemoryRegionInfo.h"
#include "lldb/Target/Platform.h"
#include "lldb/Target/Process.h"
#include "lldb/Target/SectionLoadList.h"
#include "lldb/Target/Target.h"
#include "lldb/Target/Thread.h"
#include "lldb/Target/ThreadList.h"
#include "lldb/Utility/ArchSpec.h"
#include "lldb/Utility/DataBuffer.h"
#include "lldb/Utility/FileSpec.h"
#include "lldb/Utility/Log.h"
#include "lldb/Utility/RangeMap.h"
#include "lldb/Utility/RegisterValue.h"
#include "lldb/Utility/Status.h"
#include "lldb/Utility/StreamString.h"
#include "lldb/Utility/Timer.h"
#include "lldb/Utility/UUID.h"
#include "lldb/Host/SafeMachO.h"
#include "llvm/Support/MemoryBuffer.h"
#include "ObjectFileMachO.h"
#if defined(__APPLE__) && \
(defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
// GetLLDBSharedCacheUUID() needs to call dlsym()
#include <dlfcn.h>
#endif
#ifndef __APPLE__
#include "Utility/UuidCompatibility.h"
#else
#include <uuid/uuid.h>
#endif
#include <memory>
#define THUMB_ADDRESS_BIT_MASK 0xfffffffffffffffeull
using namespace lldb;
using namespace lldb_private;
using namespace llvm::MachO;
// Some structure definitions needed for parsing the dyld shared cache files
// found on iOS devices.
struct lldb_copy_dyld_cache_header_v1 {
char magic[16]; // e.g. "dyld_v0 i386", "dyld_v1 armv7", etc.
uint32_t mappingOffset; // file offset to first dyld_cache_mapping_info
uint32_t mappingCount; // number of dyld_cache_mapping_info entries
uint32_t imagesOffset;
uint32_t imagesCount;
uint64_t dyldBaseAddress;
uint64_t codeSignatureOffset;
uint64_t codeSignatureSize;
uint64_t slideInfoOffset;
uint64_t slideInfoSize;
uint64_t localSymbolsOffset;
uint64_t localSymbolsSize;
uint8_t uuid[16]; // v1 and above, also recorded in dyld_all_image_infos v13
// and later
};
struct lldb_copy_dyld_cache_mapping_info {
uint64_t address;
uint64_t size;
uint64_t fileOffset;
uint32_t maxProt;
uint32_t initProt;
};
struct lldb_copy_dyld_cache_local_symbols_info {
uint32_t nlistOffset;
uint32_t nlistCount;
uint32_t stringsOffset;
uint32_t stringsSize;
uint32_t entriesOffset;
uint32_t entriesCount;
};
struct lldb_copy_dyld_cache_local_symbols_entry {
uint32_t dylibOffset;
uint32_t nlistStartIndex;
uint32_t nlistCount;
};
static void PrintRegisterValue(RegisterContext *reg_ctx, const char *name,
const char *alt_name, size_t reg_byte_size,
Stream &data) {
const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(name);
if (reg_info == nullptr)
reg_info = reg_ctx->GetRegisterInfoByName(alt_name);
if (reg_info) {
lldb_private::RegisterValue reg_value;
if (reg_ctx->ReadRegister(reg_info, reg_value)) {
if (reg_info->byte_size >= reg_byte_size)
data.Write(reg_value.GetBytes(), reg_byte_size);
else {
data.Write(reg_value.GetBytes(), reg_info->byte_size);
for (size_t i = 0, n = reg_byte_size - reg_info->byte_size; i < n; ++i)
data.PutChar(0);
}
return;
}
}
// Just write zeros if all else fails
for (size_t i = 0; i < reg_byte_size; ++i)
data.PutChar(0);
}
class RegisterContextDarwin_x86_64_Mach : public RegisterContextDarwin_x86_64 {
public:
RegisterContextDarwin_x86_64_Mach(lldb_private::Thread &thread,
const DataExtractor &data)
: RegisterContextDarwin_x86_64(thread, 0) {
SetRegisterDataFrom_LC_THREAD(data);
}
void InvalidateAllRegisters() override {
// Do nothing... registers are always valid...
}
void SetRegisterDataFrom_LC_THREAD(const DataExtractor &data) {
lldb::offset_t offset = 0;
SetError(GPRRegSet, Read, -1);
SetError(FPURegSet, Read, -1);
SetError(EXCRegSet, Read, -1);
bool done = false;
while (!done) {
int flavor = data.GetU32(&offset);
if (flavor == 0)
done = true;
else {
uint32_t i;
uint32_t count = data.GetU32(&offset);
switch (flavor) {
case GPRRegSet:
for (i = 0; i < count; ++i)
(&gpr.rax)[i] = data.GetU64(&offset);
SetError(GPRRegSet, Read, 0);
done = true;
break;
case FPURegSet:
// TODO: fill in FPU regs....
// SetError (FPURegSet, Read, -1);
done = true;
break;
case EXCRegSet:
exc.trapno = data.GetU32(&offset);
exc.err = data.GetU32(&offset);
exc.faultvaddr = data.GetU64(&offset);
SetError(EXCRegSet, Read, 0);
done = true;
break;
case 7:
case 8:
case 9:
// fancy flavors that encapsulate of the above flavors...
break;
default:
done = true;
break;
}
}
}
}
static bool Create_LC_THREAD(Thread *thread, Stream &data) {
RegisterContextSP reg_ctx_sp(thread->GetRegisterContext());
if (reg_ctx_sp) {
RegisterContext *reg_ctx = reg_ctx_sp.get();
data.PutHex32(GPRRegSet); // Flavor
data.PutHex32(GPRWordCount);
PrintRegisterValue(reg_ctx, "rax", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "rbx", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "rcx", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "rdx", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "rdi", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "rsi", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "rbp", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "rsp", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "r8", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "r9", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "r10", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "r11", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "r12", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "r13", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "r14", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "r15", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "rip", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "rflags", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "cs", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "fs", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "gs", nullptr, 8, data);
// // Write out the FPU registers
// const size_t fpu_byte_size = sizeof(FPU);
// size_t bytes_written = 0;
// data.PutHex32 (FPURegSet);
// data.PutHex32 (fpu_byte_size/sizeof(uint64_t));
// bytes_written += data.PutHex32(0); // uint32_t pad[0]
// bytes_written += data.PutHex32(0); // uint32_t pad[1]
// bytes_written += WriteRegister (reg_ctx, "fcw", "fctrl", 2,
// data); // uint16_t fcw; // "fctrl"
// bytes_written += WriteRegister (reg_ctx, "fsw" , "fstat", 2,
// data); // uint16_t fsw; // "fstat"
// bytes_written += WriteRegister (reg_ctx, "ftw" , "ftag", 1,
// data); // uint8_t ftw; // "ftag"
// bytes_written += data.PutHex8 (0); // uint8_t pad1;
// bytes_written += WriteRegister (reg_ctx, "fop" , NULL, 2,
// data); // uint16_t fop; // "fop"
// bytes_written += WriteRegister (reg_ctx, "fioff", "ip", 4,
// data); // uint32_t ip; // "fioff"
// bytes_written += WriteRegister (reg_ctx, "fiseg", NULL, 2,
// data); // uint16_t cs; // "fiseg"
// bytes_written += data.PutHex16 (0); // uint16_t pad2;
// bytes_written += WriteRegister (reg_ctx, "dp", "fooff" , 4,
// data); // uint32_t dp; // "fooff"
// bytes_written += WriteRegister (reg_ctx, "foseg", NULL, 2,
// data); // uint16_t ds; // "foseg"
// bytes_written += data.PutHex16 (0); // uint16_t pad3;
// bytes_written += WriteRegister (reg_ctx, "mxcsr", NULL, 4,
// data); // uint32_t mxcsr;
// bytes_written += WriteRegister (reg_ctx, "mxcsrmask", NULL,
// 4, data);// uint32_t mxcsrmask;
// bytes_written += WriteRegister (reg_ctx, "stmm0", NULL,
// sizeof(MMSReg), data);
// bytes_written += WriteRegister (reg_ctx, "stmm1", NULL,
// sizeof(MMSReg), data);
// bytes_written += WriteRegister (reg_ctx, "stmm2", NULL,
// sizeof(MMSReg), data);
// bytes_written += WriteRegister (reg_ctx, "stmm3", NULL,
// sizeof(MMSReg), data);
// bytes_written += WriteRegister (reg_ctx, "stmm4", NULL,
// sizeof(MMSReg), data);
// bytes_written += WriteRegister (reg_ctx, "stmm5", NULL,
// sizeof(MMSReg), data);
// bytes_written += WriteRegister (reg_ctx, "stmm6", NULL,
// sizeof(MMSReg), data);
// bytes_written += WriteRegister (reg_ctx, "stmm7", NULL,
// sizeof(MMSReg), data);
// bytes_written += WriteRegister (reg_ctx, "xmm0" , NULL,
// sizeof(XMMReg), data);
// bytes_written += WriteRegister (reg_ctx, "xmm1" , NULL,
// sizeof(XMMReg), data);
// bytes_written += WriteRegister (reg_ctx, "xmm2" , NULL,
// sizeof(XMMReg), data);
// bytes_written += WriteRegister (reg_ctx, "xmm3" , NULL,
// sizeof(XMMReg), data);
// bytes_written += WriteRegister (reg_ctx, "xmm4" , NULL,
// sizeof(XMMReg), data);
// bytes_written += WriteRegister (reg_ctx, "xmm5" , NULL,
// sizeof(XMMReg), data);
// bytes_written += WriteRegister (reg_ctx, "xmm6" , NULL,
// sizeof(XMMReg), data);
// bytes_written += WriteRegister (reg_ctx, "xmm7" , NULL,
// sizeof(XMMReg), data);
// bytes_written += WriteRegister (reg_ctx, "xmm8" , NULL,
// sizeof(XMMReg), data);
// bytes_written += WriteRegister (reg_ctx, "xmm9" , NULL,
// sizeof(XMMReg), data);
// bytes_written += WriteRegister (reg_ctx, "xmm10", NULL,
// sizeof(XMMReg), data);
// bytes_written += WriteRegister (reg_ctx, "xmm11", NULL,
// sizeof(XMMReg), data);
// bytes_written += WriteRegister (reg_ctx, "xmm12", NULL,
// sizeof(XMMReg), data);
// bytes_written += WriteRegister (reg_ctx, "xmm13", NULL,
// sizeof(XMMReg), data);
// bytes_written += WriteRegister (reg_ctx, "xmm14", NULL,
// sizeof(XMMReg), data);
// bytes_written += WriteRegister (reg_ctx, "xmm15", NULL,
// sizeof(XMMReg), data);
//
// // Fill rest with zeros
// for (size_t i=0, n = fpu_byte_size - bytes_written; i<n; ++
// i)
// data.PutChar(0);
// Write out the EXC registers
data.PutHex32(EXCRegSet);
data.PutHex32(EXCWordCount);
PrintRegisterValue(reg_ctx, "trapno", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "err", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "faultvaddr", nullptr, 8, data);
return true;
}
return false;
}
protected:
int DoReadGPR(lldb::tid_t tid, int flavor, GPR &gpr) override { return 0; }
int DoReadFPU(lldb::tid_t tid, int flavor, FPU &fpu) override { return 0; }
int DoReadEXC(lldb::tid_t tid, int flavor, EXC &exc) override { return 0; }
int DoWriteGPR(lldb::tid_t tid, int flavor, const GPR &gpr) override {
return 0;
}
int DoWriteFPU(lldb::tid_t tid, int flavor, const FPU &fpu) override {
return 0;
}
int DoWriteEXC(lldb::tid_t tid, int flavor, const EXC &exc) override {
return 0;
}
};
class RegisterContextDarwin_i386_Mach : public RegisterContextDarwin_i386 {
public:
RegisterContextDarwin_i386_Mach(lldb_private::Thread &thread,
const DataExtractor &data)
: RegisterContextDarwin_i386(thread, 0) {
SetRegisterDataFrom_LC_THREAD(data);
}
void InvalidateAllRegisters() override {
// Do nothing... registers are always valid...
}
void SetRegisterDataFrom_LC_THREAD(const DataExtractor &data) {
lldb::offset_t offset = 0;
SetError(GPRRegSet, Read, -1);
SetError(FPURegSet, Read, -1);
SetError(EXCRegSet, Read, -1);
bool done = false;
while (!done) {
int flavor = data.GetU32(&offset);
if (flavor == 0)
done = true;
else {
uint32_t i;
uint32_t count = data.GetU32(&offset);
switch (flavor) {
case GPRRegSet:
for (i = 0; i < count; ++i)
(&gpr.eax)[i] = data.GetU32(&offset);
SetError(GPRRegSet, Read, 0);
done = true;
break;
case FPURegSet:
// TODO: fill in FPU regs....
// SetError (FPURegSet, Read, -1);
done = true;
break;
case EXCRegSet:
exc.trapno = data.GetU32(&offset);
exc.err = data.GetU32(&offset);
exc.faultvaddr = data.GetU32(&offset);
SetError(EXCRegSet, Read, 0);
done = true;
break;
case 7:
case 8:
case 9:
// fancy flavors that encapsulate of the above flavors...
break;
default:
done = true;
break;
}
}
}
}
static bool Create_LC_THREAD(Thread *thread, Stream &data) {
RegisterContextSP reg_ctx_sp(thread->GetRegisterContext());
if (reg_ctx_sp) {
RegisterContext *reg_ctx = reg_ctx_sp.get();
data.PutHex32(GPRRegSet); // Flavor
data.PutHex32(GPRWordCount);
PrintRegisterValue(reg_ctx, "eax", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "ebx", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "ecx", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "edx", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "edi", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "esi", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "ebp", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "esp", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "ss", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "eflags", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "eip", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "cs", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "ds", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "es", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "fs", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "gs", nullptr, 4, data);
// Write out the EXC registers
data.PutHex32(EXCRegSet);
data.PutHex32(EXCWordCount);
PrintRegisterValue(reg_ctx, "trapno", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "err", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "faultvaddr", nullptr, 4, data);
return true;
}
return false;
}
protected:
int DoReadGPR(lldb::tid_t tid, int flavor, GPR &gpr) override { return 0; }
int DoReadFPU(lldb::tid_t tid, int flavor, FPU &fpu) override { return 0; }
int DoReadEXC(lldb::tid_t tid, int flavor, EXC &exc) override { return 0; }
int DoWriteGPR(lldb::tid_t tid, int flavor, const GPR &gpr) override {
return 0;
}
int DoWriteFPU(lldb::tid_t tid, int flavor, const FPU &fpu) override {
return 0;
}
int DoWriteEXC(lldb::tid_t tid, int flavor, const EXC &exc) override {
return 0;
}
};
class RegisterContextDarwin_arm_Mach : public RegisterContextDarwin_arm {
public:
RegisterContextDarwin_arm_Mach(lldb_private::Thread &thread,
const DataExtractor &data)
: RegisterContextDarwin_arm(thread, 0) {
SetRegisterDataFrom_LC_THREAD(data);
}
void InvalidateAllRegisters() override {
// Do nothing... registers are always valid...
}
void SetRegisterDataFrom_LC_THREAD(const DataExtractor &data) {
lldb::offset_t offset = 0;
SetError(GPRRegSet, Read, -1);
SetError(FPURegSet, Read, -1);
SetError(EXCRegSet, Read, -1);
bool done = false;
while (!done) {
int flavor = data.GetU32(&offset);
uint32_t count = data.GetU32(&offset);
lldb::offset_t next_thread_state = offset + (count * 4);
switch (flavor) {
case GPRAltRegSet:
case GPRRegSet:
for (uint32_t i = 0; i < count; ++i) {
gpr.r[i] = data.GetU32(&offset);
}
// Note that gpr.cpsr is also copied by the above loop; this loop
// technically extends one element past the end of the gpr.r[] array.
SetError(GPRRegSet, Read, 0);
offset = next_thread_state;
break;
case FPURegSet: {
uint8_t *fpu_reg_buf = (uint8_t *)&fpu.floats.s[0];
const int fpu_reg_buf_size = sizeof(fpu.floats);
if (data.ExtractBytes(offset, fpu_reg_buf_size, eByteOrderLittle,
fpu_reg_buf) == fpu_reg_buf_size) {
offset += fpu_reg_buf_size;
fpu.fpscr = data.GetU32(&offset);
SetError(FPURegSet, Read, 0);
} else {
done = true;
}
}
offset = next_thread_state;
break;
case EXCRegSet:
if (count == 3) {
exc.exception = data.GetU32(&offset);
exc.fsr = data.GetU32(&offset);
exc.far = data.GetU32(&offset);
SetError(EXCRegSet, Read, 0);
}
done = true;
offset = next_thread_state;
break;
// Unknown register set flavor, stop trying to parse.
default:
done = true;
}
}
}
static bool Create_LC_THREAD(Thread *thread, Stream &data) {
RegisterContextSP reg_ctx_sp(thread->GetRegisterContext());
if (reg_ctx_sp) {
RegisterContext *reg_ctx = reg_ctx_sp.get();
data.PutHex32(GPRRegSet); // Flavor
data.PutHex32(GPRWordCount);
PrintRegisterValue(reg_ctx, "r0", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "r1", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "r2", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "r3", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "r4", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "r5", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "r6", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "r7", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "r8", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "r9", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "r10", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "r11", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "r12", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "sp", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "lr", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "pc", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "cpsr", nullptr, 4, data);
// Write out the EXC registers
// data.PutHex32 (EXCRegSet);
// data.PutHex32 (EXCWordCount);
// WriteRegister (reg_ctx, "exception", NULL, 4, data);
// WriteRegister (reg_ctx, "fsr", NULL, 4, data);
// WriteRegister (reg_ctx, "far", NULL, 4, data);
return true;
}
return false;
}
protected:
int DoReadGPR(lldb::tid_t tid, int flavor, GPR &gpr) override { return -1; }
int DoReadFPU(lldb::tid_t tid, int flavor, FPU &fpu) override { return -1; }
int DoReadEXC(lldb::tid_t tid, int flavor, EXC &exc) override { return -1; }
int DoReadDBG(lldb::tid_t tid, int flavor, DBG &dbg) override { return -1; }
int DoWriteGPR(lldb::tid_t tid, int flavor, const GPR &gpr) override {
return 0;
}
int DoWriteFPU(lldb::tid_t tid, int flavor, const FPU &fpu) override {
return 0;
}
int DoWriteEXC(lldb::tid_t tid, int flavor, const EXC &exc) override {
return 0;
}
int DoWriteDBG(lldb::tid_t tid, int flavor, const DBG &dbg) override {
return -1;
}
};
class RegisterContextDarwin_arm64_Mach : public RegisterContextDarwin_arm64 {
public:
RegisterContextDarwin_arm64_Mach(lldb_private::Thread &thread,
const DataExtractor &data)
: RegisterContextDarwin_arm64(thread, 0) {
SetRegisterDataFrom_LC_THREAD(data);
}
void InvalidateAllRegisters() override {
// Do nothing... registers are always valid...
}
void SetRegisterDataFrom_LC_THREAD(const DataExtractor &data) {
lldb::offset_t offset = 0;
SetError(GPRRegSet, Read, -1);
SetError(FPURegSet, Read, -1);
SetError(EXCRegSet, Read, -1);
bool done = false;
while (!done) {
int flavor = data.GetU32(&offset);
uint32_t count = data.GetU32(&offset);
lldb::offset_t next_thread_state = offset + (count * 4);
switch (flavor) {
case GPRRegSet:
// x0-x29 + fp + lr + sp + pc (== 33 64-bit registers) plus cpsr (1
// 32-bit register)
if (count >= (33 * 2) + 1) {
for (uint32_t i = 0; i < 29; ++i)
gpr.x[i] = data.GetU64(&offset);
gpr.fp = data.GetU64(&offset);
gpr.lr = data.GetU64(&offset);
gpr.sp = data.GetU64(&offset);
gpr.pc = data.GetU64(&offset);
gpr.cpsr = data.GetU32(&offset);
SetError(GPRRegSet, Read, 0);
}
offset = next_thread_state;
break;
case FPURegSet: {
uint8_t *fpu_reg_buf = (uint8_t *)&fpu.v[0];
const int fpu_reg_buf_size = sizeof(fpu);
if (fpu_reg_buf_size == count * sizeof(uint32_t) &&
data.ExtractBytes(offset, fpu_reg_buf_size, eByteOrderLittle,
fpu_reg_buf) == fpu_reg_buf_size) {
SetError(FPURegSet, Read, 0);
} else {
done = true;
}
}
offset = next_thread_state;
break;
case EXCRegSet:
if (count == 4) {
exc.far = data.GetU64(&offset);
exc.esr = data.GetU32(&offset);
exc.exception = data.GetU32(&offset);
SetError(EXCRegSet, Read, 0);
}
offset = next_thread_state;
break;
default:
done = true;
break;
}
}
}
static bool Create_LC_THREAD(Thread *thread, Stream &data) {
RegisterContextSP reg_ctx_sp(thread->GetRegisterContext());
if (reg_ctx_sp) {
RegisterContext *reg_ctx = reg_ctx_sp.get();
data.PutHex32(GPRRegSet); // Flavor
data.PutHex32(GPRWordCount);
PrintRegisterValue(reg_ctx, "x0", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x1", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x2", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x3", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x4", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x5", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x6", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x7", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x8", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x9", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x10", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x11", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x12", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x13", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x14", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x15", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x16", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x17", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x18", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x19", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x20", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x21", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x22", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x23", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x24", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x25", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x26", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x27", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x28", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "fp", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "lr", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "sp", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "pc", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "cpsr", nullptr, 4, data);
// Write out the EXC registers
// data.PutHex32 (EXCRegSet);
// data.PutHex32 (EXCWordCount);
// WriteRegister (reg_ctx, "far", NULL, 8, data);
// WriteRegister (reg_ctx, "esr", NULL, 4, data);
// WriteRegister (reg_ctx, "exception", NULL, 4, data);
return true;
}
return false;
}
protected:
int DoReadGPR(lldb::tid_t tid, int flavor, GPR &gpr) override { return -1; }
int DoReadFPU(lldb::tid_t tid, int flavor, FPU &fpu) override { return -1; }
int DoReadEXC(lldb::tid_t tid, int flavor, EXC &exc) override { return -1; }
int DoReadDBG(lldb::tid_t tid, int flavor, DBG &dbg) override { return -1; }
int DoWriteGPR(lldb::tid_t tid, int flavor, const GPR &gpr) override {
return 0;
}
int DoWriteFPU(lldb::tid_t tid, int flavor, const FPU &fpu) override {
return 0;
}
int DoWriteEXC(lldb::tid_t tid, int flavor, const EXC &exc) override {
return 0;
}
int DoWriteDBG(lldb::tid_t tid, int flavor, const DBG &dbg) override {
return -1;
}
};
static uint32_t MachHeaderSizeFromMagic(uint32_t magic) {
switch (magic) {
case MH_MAGIC:
case MH_CIGAM:
return sizeof(struct mach_header);
case MH_MAGIC_64:
case MH_CIGAM_64:
return sizeof(struct mach_header_64);
break;
default:
break;
}
return 0;
}
#define MACHO_NLIST_ARM_SYMBOL_IS_THUMB 0x0008
char ObjectFileMachO::ID;
void ObjectFileMachO::Initialize() {
PluginManager::RegisterPlugin(
GetPluginNameStatic(), GetPluginDescriptionStatic(), CreateInstance,
CreateMemoryInstance, GetModuleSpecifications, SaveCore);
}
void ObjectFileMachO::Terminate() {
PluginManager::UnregisterPlugin(CreateInstance);
}
lldb_private::ConstString ObjectFileMachO::GetPluginNameStatic() {
static ConstString g_name("mach-o");
return g_name;
}
const char *ObjectFileMachO::GetPluginDescriptionStatic() {
return "Mach-o object file reader (32 and 64 bit)";
}
ObjectFile *ObjectFileMachO::CreateInstance(const lldb::ModuleSP &module_sp,
DataBufferSP &data_sp,
lldb::offset_t data_offset,
const FileSpec *file,
lldb::offset_t file_offset,
lldb::offset_t length) {
if (!data_sp) {
data_sp = MapFileData(*file, length, file_offset);
if (!data_sp)
return nullptr;
data_offset = 0;
}
if (!ObjectFileMachO::MagicBytesMatch(data_sp, data_offset, length))
return nullptr;
// Update the data to contain the entire file if it doesn't already
if (data_sp->GetByteSize() < length) {
data_sp = MapFileData(*file, length, file_offset);
if (!data_sp)
return nullptr;
data_offset = 0;
}
auto objfile_up = std::make_unique<ObjectFileMachO>(
module_sp, data_sp, data_offset, file, file_offset, length);
if (!objfile_up || !objfile_up->ParseHeader())
return nullptr;
return objfile_up.release();
}
ObjectFile *ObjectFileMachO::CreateMemoryInstance(
const lldb::ModuleSP &module_sp, DataBufferSP &data_sp,
const ProcessSP &process_sp, lldb::addr_t header_addr) {
if (ObjectFileMachO::MagicBytesMatch(data_sp, 0, data_sp->GetByteSize())) {
std::unique_ptr<ObjectFile> objfile_up(
new ObjectFileMachO(module_sp, data_sp, process_sp, header_addr));
if (objfile_up.get() && objfile_up->ParseHeader())
return objfile_up.release();
}
return nullptr;
}
size_t ObjectFileMachO::GetModuleSpecifications(
const lldb_private::FileSpec &file, lldb::DataBufferSP &data_sp,
lldb::offset_t data_offset, lldb::offset_t file_offset,
lldb::offset_t length, lldb_private::ModuleSpecList &specs) {
const size_t initial_count = specs.GetSize();
if (ObjectFileMachO::MagicBytesMatch(data_sp, 0, data_sp->GetByteSize())) {
DataExtractor data;
data.SetData(data_sp);
llvm::MachO::mach_header header;
if (ParseHeader(data, &data_offset, header)) {
size_t header_and_load_cmds =
header.sizeofcmds + MachHeaderSizeFromMagic(header.magic);
if (header_and_load_cmds >= data_sp->GetByteSize()) {
data_sp = MapFileData(file, header_and_load_cmds, file_offset);
data.SetData(data_sp);
data_offset = MachHeaderSizeFromMagic(header.magic);
}
if (data_sp) {
ModuleSpec base_spec;
base_spec.GetFileSpec() = file;
base_spec.SetObjectOffset(file_offset);
base_spec.SetObjectSize(length);
GetAllArchSpecs(header, data, data_offset, base_spec, specs);
}
}
}
return specs.GetSize() - initial_count;
}
ConstString ObjectFileMachO::GetSegmentNameTEXT() {
static ConstString g_segment_name_TEXT("__TEXT");
return g_segment_name_TEXT;
}
ConstString ObjectFileMachO::GetSegmentNameDATA() {
static ConstString g_segment_name_DATA("__DATA");
return g_segment_name_DATA;
}
ConstString ObjectFileMachO::GetSegmentNameDATA_DIRTY() {
static ConstString g_segment_name("__DATA_DIRTY");
return g_segment_name;
}
ConstString ObjectFileMachO::GetSegmentNameDATA_CONST() {
static ConstString g_segment_name("__DATA_CONST");
return g_segment_name;
}
ConstString ObjectFileMachO::GetSegmentNameOBJC() {
static ConstString g_segment_name_OBJC("__OBJC");
return g_segment_name_OBJC;
}
ConstString ObjectFileMachO::GetSegmentNameLINKEDIT() {
static ConstString g_section_name_LINKEDIT("__LINKEDIT");
return g_section_name_LINKEDIT;
}
ConstString ObjectFileMachO::GetSegmentNameDWARF() {
static ConstString g_section_name("__DWARF");
return g_section_name;
}
ConstString ObjectFileMachO::GetSectionNameEHFrame() {
static ConstString g_section_name_eh_frame("__eh_frame");
return g_section_name_eh_frame;
}
bool ObjectFileMachO::MagicBytesMatch(DataBufferSP &data_sp,
lldb::addr_t data_offset,
lldb::addr_t data_length) {
DataExtractor data;
data.SetData(data_sp, data_offset, data_length);
lldb::offset_t offset = 0;
uint32_t magic = data.GetU32(&offset);
return MachHeaderSizeFromMagic(magic) != 0;
}
ObjectFileMachO::ObjectFileMachO(const lldb::ModuleSP &module_sp,
DataBufferSP &data_sp,
lldb::offset_t data_offset,
const FileSpec *file,
lldb::offset_t file_offset,
lldb::offset_t length)
: ObjectFile(module_sp, file, file_offset, length, data_sp, data_offset),
m_mach_segments(), m_mach_sections(), m_entry_point_address(),
m_thread_context_offsets(), m_thread_context_offsets_valid(false),
m_reexported_dylibs(), m_allow_assembly_emulation_unwind_plans(true) {
::memset(&m_header, 0, sizeof(m_header));
::memset(&m_dysymtab, 0, sizeof(m_dysymtab));
}
ObjectFileMachO::ObjectFileMachO(const lldb::ModuleSP &module_sp,
lldb::DataBufferSP &header_data_sp,
const lldb::ProcessSP &process_sp,
lldb::addr_t header_addr)
: ObjectFile(module_sp, process_sp, header_addr, header_data_sp),
m_mach_segments(), m_mach_sections(), m_entry_point_address(),
m_thread_context_offsets(), m_thread_context_offsets_valid(false),
m_reexported_dylibs(), m_allow_assembly_emulation_unwind_plans(true) {
::memset(&m_header, 0, sizeof(m_header));
::memset(&m_dysymtab, 0, sizeof(m_dysymtab));
}
bool ObjectFileMachO::ParseHeader(DataExtractor &data,
lldb::offset_t *data_offset_ptr,
llvm::MachO::mach_header &header) {
data.SetByteOrder(endian::InlHostByteOrder());
// Leave magic in the original byte order
header.magic = data.GetU32(data_offset_ptr);
bool can_parse = false;
bool is_64_bit = false;
switch (header.magic) {
case MH_MAGIC:
data.SetByteOrder(endian::InlHostByteOrder());
data.SetAddressByteSize(4);
can_parse = true;
break;
case MH_MAGIC_64:
data.SetByteOrder(endian::InlHostByteOrder());
data.SetAddressByteSize(8);
can_parse = true;
is_64_bit = true;
break;
case MH_CIGAM:
data.SetByteOrder(endian::InlHostByteOrder() == eByteOrderBig
? eByteOrderLittle
: eByteOrderBig);
data.SetAddressByteSize(4);
can_parse = true;
break;
case MH_CIGAM_64:
data.SetByteOrder(endian::InlHostByteOrder() == eByteOrderBig
? eByteOrderLittle
: eByteOrderBig);
data.SetAddressByteSize(8);
is_64_bit = true;
can_parse = true;
break;
default:
break;
}
if (can_parse) {
data.GetU32(data_offset_ptr, &header.cputype, 6);
if (is_64_bit)
*data_offset_ptr += 4;
return true;
} else {
memset(&header, 0, sizeof(header));
}
return false;
}
bool ObjectFileMachO::ParseHeader() {
ModuleSP module_sp(GetModule());
if (!module_sp)
return false;
std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
bool can_parse = false;
lldb::offset_t offset = 0;
m_data.SetByteOrder(endian::InlHostByteOrder());
// Leave magic in the original byte order
m_header.magic = m_data.GetU32(&offset);
switch (m_header.magic) {
case MH_MAGIC:
m_data.SetByteOrder(endian::InlHostByteOrder());
m_data.SetAddressByteSize(4);
can_parse = true;
break;
case MH_MAGIC_64:
m_data.SetByteOrder(endian::InlHostByteOrder());
m_data.SetAddressByteSize(8);
can_parse = true;
break;
case MH_CIGAM:
m_data.SetByteOrder(endian::InlHostByteOrder() == eByteOrderBig
? eByteOrderLittle
: eByteOrderBig);
m_data.SetAddressByteSize(4);
can_parse = true;
break;
case MH_CIGAM_64:
m_data.SetByteOrder(endian::InlHostByteOrder() == eByteOrderBig
? eByteOrderLittle
: eByteOrderBig);
m_data.SetAddressByteSize(8);
can_parse = true;
break;
default:
break;
}
if (can_parse) {
m_data.GetU32(&offset, &m_header.cputype, 6);
ModuleSpecList all_specs;
ModuleSpec base_spec;
GetAllArchSpecs(m_header, m_data, MachHeaderSizeFromMagic(m_header.magic),
base_spec, all_specs);
for (unsigned i = 0, e = all_specs.GetSize(); i != e; ++i) {
ArchSpec mach_arch =
all_specs.GetModuleSpecRefAtIndex(i).GetArchitecture();
// Check if the module has a required architecture
const ArchSpec &module_arch = module_sp->GetArchitecture();
if (module_arch.IsValid() && !module_arch.IsCompatibleMatch(mach_arch))
continue;
if (SetModulesArchitecture(mach_arch)) {
const size_t header_and_lc_size =
m_header.sizeofcmds + MachHeaderSizeFromMagic(m_header.magic);
if (m_data.GetByteSize() < header_and_lc_size) {
DataBufferSP data_sp;
ProcessSP process_sp(m_process_wp.lock());
if (process_sp) {
data_sp = ReadMemory(process_sp, m_memory_addr, header_and_lc_size);
} else {
// Read in all only the load command data from the file on disk
data_sp = MapFileData(m_file, header_and_lc_size, m_file_offset);
if (data_sp->GetByteSize() != header_and_lc_size)
continue;
}
if (data_sp)
m_data.SetData(data_sp);
}
}
return true;
}
// None found.
return false;
} else {
memset(&m_header, 0, sizeof(struct mach_header));
}
return false;
}
ByteOrder ObjectFileMachO::GetByteOrder() const {
return m_data.GetByteOrder();
}
bool ObjectFileMachO::IsExecutable() const {
return m_header.filetype == MH_EXECUTE;
}
bool ObjectFileMachO::IsDynamicLoader() const {
return m_header.filetype == MH_DYLINKER;
}
uint32_t ObjectFileMachO::GetAddressByteSize() const {
return m_data.GetAddressByteSize();
}
AddressClass ObjectFileMachO::GetAddressClass(lldb::addr_t file_addr) {
Symtab *symtab = GetSymtab();
if (!symtab)
return AddressClass::eUnknown;
Symbol *symbol = symtab->FindSymbolContainingFileAddress(file_addr);
if (symbol) {
if (symbol->ValueIsAddress()) {
SectionSP section_sp(symbol->GetAddressRef().GetSection());
if (section_sp) {
const lldb::SectionType section_type = section_sp->GetType();
switch (section_type) {
case eSectionTypeInvalid:
return AddressClass::eUnknown;
case eSectionTypeCode:
if (m_header.cputype == llvm::MachO::CPU_TYPE_ARM) {
// For ARM we have a bit in the n_desc field of the symbol that
// tells us ARM/Thumb which is bit 0x0008.
if (symbol->GetFlags() & MACHO_NLIST_ARM_SYMBOL_IS_THUMB)
return AddressClass::eCodeAlternateISA;
}
return AddressClass::eCode;
case eSectionTypeContainer:
return AddressClass::eUnknown;
case eSectionTypeData:
case eSectionTypeDataCString:
case eSectionTypeDataCStringPointers:
case eSectionTypeDataSymbolAddress:
case eSectionTypeData4:
case eSectionTypeData8:
case eSectionTypeData16:
case eSectionTypeDataPointers:
case eSectionTypeZeroFill:
case eSectionTypeDataObjCMessageRefs:
case eSectionTypeDataObjCCFStrings:
case eSectionTypeGoSymtab:
return AddressClass::eData;
case eSectionTypeDebug:
case eSectionTypeDWARFDebugAbbrev:
case eSectionTypeDWARFDebugAbbrevDwo:
case eSectionTypeDWARFDebugAddr:
case eSectionTypeDWARFDebugAranges:
case eSectionTypeDWARFDebugCuIndex:
case eSectionTypeDWARFDebugFrame:
case eSectionTypeDWARFDebugInfo:
case eSectionTypeDWARFDebugInfoDwo:
case eSectionTypeDWARFDebugLine:
case eSectionTypeDWARFDebugLineStr:
case eSectionTypeDWARFDebugLoc:
case eSectionTypeDWARFDebugLocLists:
case eSectionTypeDWARFDebugMacInfo:
case eSectionTypeDWARFDebugMacro:
case eSectionTypeDWARFDebugNames:
case eSectionTypeDWARFDebugPubNames:
case eSectionTypeDWARFDebugPubTypes:
case eSectionTypeDWARFDebugRanges:
case eSectionTypeDWARFDebugRngLists:
case eSectionTypeDWARFDebugStr:
case eSectionTypeDWARFDebugStrDwo:
case eSectionTypeDWARFDebugStrOffsets:
case eSectionTypeDWARFDebugStrOffsetsDwo:
case eSectionTypeDWARFDebugTypes:
case eSectionTypeDWARFDebugTypesDwo:
case eSectionTypeDWARFAppleNames:
case eSectionTypeDWARFAppleTypes:
case eSectionTypeDWARFAppleNamespaces:
case eSectionTypeDWARFAppleObjC:
case eSectionTypeDWARFGNUDebugAltLink:
return AddressClass::eDebug;
case eSectionTypeEHFrame:
case eSectionTypeARMexidx:
case eSectionTypeARMextab:
case eSectionTypeCompactUnwind:
return AddressClass::eRuntime;
case eSectionTypeAbsoluteAddress:
case eSectionTypeELFSymbolTable:
case eSectionTypeELFDynamicSymbols:
case eSectionTypeELFRelocationEntries:
case eSectionTypeELFDynamicLinkInfo:
case eSectionTypeOther:
return AddressClass::eUnknown;
}
}
}
const SymbolType symbol_type = symbol->GetType();
switch (symbol_type) {
case eSymbolTypeAny:
return AddressClass::eUnknown;
case eSymbolTypeAbsolute:
return AddressClass::eUnknown;
case eSymbolTypeCode:
case eSymbolTypeTrampoline:
case eSymbolTypeResolver:
if (m_header.cputype == llvm::MachO::CPU_TYPE_ARM) {
// For ARM we have a bit in the n_desc field of the symbol that tells
// us ARM/Thumb which is bit 0x0008.
if (symbol->GetFlags() & MACHO_NLIST_ARM_SYMBOL_IS_THUMB)
return AddressClass::eCodeAlternateISA;
}
return AddressClass::eCode;
case eSymbolTypeData:
return AddressClass::eData;
case eSymbolTypeRuntime:
return AddressClass::eRuntime;
case eSymbolTypeException:
return AddressClass::eRuntime;
case eSymbolTypeSourceFile:
return AddressClass::eDebug;
case eSymbolTypeHeaderFile:
return AddressClass::eDebug;
case eSymbolTypeObjectFile:
return AddressClass::eDebug;
case eSymbolTypeCommonBlock:
return AddressClass::eDebug;
case eSymbolTypeBlock:
return AddressClass::eDebug;
case eSymbolTypeLocal:
return AddressClass::eData;
case eSymbolTypeParam:
return AddressClass::eData;
case eSymbolTypeVariable:
return AddressClass::eData;
case eSymbolTypeVariableType:
return AddressClass::eDebug;
case eSymbolTypeLineEntry:
return AddressClass::eDebug;
case eSymbolTypeLineHeader:
return AddressClass::eDebug;
case eSymbolTypeScopeBegin:
return AddressClass::eDebug;
case eSymbolTypeScopeEnd:
return AddressClass::eDebug;
case eSymbolTypeAdditional:
return AddressClass::eUnknown;
case eSymbolTypeCompiler:
return AddressClass::eDebug;
case eSymbolTypeInstrumentation:
return AddressClass::eDebug;
case eSymbolTypeUndefined:
return AddressClass::eUnknown;
case eSymbolTypeObjCClass:
return AddressClass::eRuntime;
case eSymbolTypeObjCMetaClass:
return AddressClass::eRuntime;
case eSymbolTypeObjCIVar:
return AddressClass::eRuntime;
case eSymbolTypeReExported:
return AddressClass::eRuntime;
}
}
return AddressClass::eUnknown;
}
Symtab *ObjectFileMachO::GetSymtab() {
ModuleSP module_sp(GetModule());
if (module_sp) {
std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
if (m_symtab_up == nullptr) {
m_symtab_up.reset(new Symtab(this));
std::lock_guard<std::recursive_mutex> symtab_guard(
m_symtab_up->GetMutex());
ParseSymtab();
m_symtab_up->Finalize();
}
}
return m_symtab_up.get();
}
bool ObjectFileMachO::IsStripped() {
if (m_dysymtab.cmd == 0) {
ModuleSP module_sp(GetModule());
if (module_sp) {
lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
for (uint32_t i = 0; i < m_header.ncmds; ++i) {
const lldb::offset_t load_cmd_offset = offset;
load_command lc;
if (m_data.GetU32(&offset, &lc.cmd, 2) == nullptr)
break;
if (lc.cmd == LC_DYSYMTAB) {
m_dysymtab.cmd = lc.cmd;
m_dysymtab.cmdsize = lc.cmdsize;
if (m_data.GetU32(&offset, &m_dysymtab.ilocalsym,
(sizeof(m_dysymtab) / sizeof(uint32_t)) - 2) ==
nullptr) {
// Clear m_dysymtab if we were unable to read all items from the
// load command
::memset(&m_dysymtab, 0, sizeof(m_dysymtab));
}
}
offset = load_cmd_offset + lc.cmdsize;
}
}
}
if (m_dysymtab.cmd)
return m_dysymtab.nlocalsym <= 1;
return false;
}
ObjectFileMachO::EncryptedFileRanges ObjectFileMachO::GetEncryptedFileRanges() {
EncryptedFileRanges result;
lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
encryption_info_command encryption_cmd;
for (uint32_t i = 0; i < m_header.ncmds; ++i) {
const lldb::offset_t load_cmd_offset = offset;
if (m_data.GetU32(&offset, &encryption_cmd, 2) == nullptr)
break;
// LC_ENCRYPTION_INFO and LC_ENCRYPTION_INFO_64 have the same sizes for the
// 3 fields we care about, so treat them the same.
if (encryption_cmd.cmd == LC_ENCRYPTION_INFO ||
encryption_cmd.cmd == LC_ENCRYPTION_INFO_64) {
if (m_data.GetU32(&offset, &encryption_cmd.cryptoff, 3)) {
if (encryption_cmd.cryptid != 0) {
EncryptedFileRanges::Entry entry;
entry.SetRangeBase(encryption_cmd.cryptoff);
entry.SetByteSize(encryption_cmd.cryptsize);
result.Append(entry);
}
}
}
offset = load_cmd_offset + encryption_cmd.cmdsize;
}
return result;
}
void ObjectFileMachO::SanitizeSegmentCommand(segment_command_64 &seg_cmd,
uint32_t cmd_idx) {
if (m_length == 0 || seg_cmd.filesize == 0)
return;
if (seg_cmd.fileoff > m_length) {
// We have a load command that says it extends past the end of the file.
// This is likely a corrupt file. We don't have any way to return an error
// condition here (this method was likely invoked from something like
// ObjectFile::GetSectionList()), so we just null out the section contents,
// and dump a message to stdout. The most common case here is core file
// debugging with a truncated file.
const char *lc_segment_name =
seg_cmd.cmd == LC_SEGMENT_64 ? "LC_SEGMENT_64" : "LC_SEGMENT";
GetModule()->ReportWarning(
"load command %u %s has a fileoff (0x%" PRIx64
") that extends beyond the end of the file (0x%" PRIx64
"), ignoring this section",
cmd_idx, lc_segment_name, seg_cmd.fileoff, m_length);
seg_cmd.fileoff = 0;
seg_cmd.filesize = 0;
}
if (seg_cmd.fileoff + seg_cmd.filesize > m_length) {
// We have a load command that says it extends past the end of the file.
// This is likely a corrupt file. We don't have any way to return an error
// condition here (this method was likely invoked from something like
// ObjectFile::GetSectionList()), so we just null out the section contents,
// and dump a message to stdout. The most common case here is core file
// debugging with a truncated file.
const char *lc_segment_name =
seg_cmd.cmd == LC_SEGMENT_64 ? "LC_SEGMENT_64" : "LC_SEGMENT";
GetModule()->ReportWarning(
"load command %u %s has a fileoff + filesize (0x%" PRIx64
") that extends beyond the end of the file (0x%" PRIx64
"), the segment will be truncated to match",
cmd_idx, lc_segment_name, seg_cmd.fileoff + seg_cmd.filesize, m_length);
// Truncate the length
seg_cmd.filesize = m_length - seg_cmd.fileoff;
}
}
static uint32_t GetSegmentPermissions(const segment_command_64 &seg_cmd) {
uint32_t result = 0;
if (seg_cmd.initprot & VM_PROT_READ)
result |= ePermissionsReadable;
if (seg_cmd.initprot & VM_PROT_WRITE)
result |= ePermissionsWritable;
if (seg_cmd.initprot & VM_PROT_EXECUTE)
result |= ePermissionsExecutable;
return result;
}
static lldb::SectionType GetSectionType(uint32_t flags,
ConstString section_name) {
if (flags & (S_ATTR_PURE_INSTRUCTIONS | S_ATTR_SOME_INSTRUCTIONS))
return eSectionTypeCode;
uint32_t mach_sect_type = flags & SECTION_TYPE;
static ConstString g_sect_name_objc_data("__objc_data");
static ConstString g_sect_name_objc_msgrefs("__objc_msgrefs");
static ConstString g_sect_name_objc_selrefs("__objc_selrefs");
static ConstString g_sect_name_objc_classrefs("__objc_classrefs");
static ConstString g_sect_name_objc_superrefs("__objc_superrefs");
static ConstString g_sect_name_objc_const("__objc_const");
static ConstString g_sect_name_objc_classlist("__objc_classlist");
static ConstString g_sect_name_cfstring("__cfstring");
static ConstString g_sect_name_dwarf_debug_abbrev("__debug_abbrev");
static ConstString g_sect_name_dwarf_debug_aranges("__debug_aranges");
static ConstString g_sect_name_dwarf_debug_frame("__debug_frame");
static ConstString g_sect_name_dwarf_debug_info("__debug_info");
static ConstString g_sect_name_dwarf_debug_line("__debug_line");
static ConstString g_sect_name_dwarf_debug_loc("__debug_loc");
static ConstString g_sect_name_dwarf_debug_loclists("__debug_loclists");
static ConstString g_sect_name_dwarf_debug_macinfo("__debug_macinfo");
static ConstString g_sect_name_dwarf_debug_names("__debug_names");
static ConstString g_sect_name_dwarf_debug_pubnames("__debug_pubnames");
static ConstString g_sect_name_dwarf_debug_pubtypes("__debug_pubtypes");
static ConstString g_sect_name_dwarf_debug_ranges("__debug_ranges");
static ConstString g_sect_name_dwarf_debug_str("__debug_str");
static ConstString g_sect_name_dwarf_debug_types("__debug_types");
static ConstString g_sect_name_dwarf_apple_names("__apple_names");
static ConstString g_sect_name_dwarf_apple_types("__apple_types");
static ConstString g_sect_name_dwarf_apple_namespaces("__apple_namespac");
static ConstString g_sect_name_dwarf_apple_objc("__apple_objc");
static ConstString g_sect_name_eh_frame("__eh_frame");
static ConstString g_sect_name_compact_unwind("__unwind_info");
static ConstString g_sect_name_text("__text");
static ConstString g_sect_name_data("__data");
static ConstString g_sect_name_go_symtab("__gosymtab");
if (section_name == g_sect_name_dwarf_debug_abbrev)
return eSectionTypeDWARFDebugAbbrev;
if (section_name == g_sect_name_dwarf_debug_aranges)
return eSectionTypeDWARFDebugAranges;
if (section_name == g_sect_name_dwarf_debug_frame)
return eSectionTypeDWARFDebugFrame;
if (section_name == g_sect_name_dwarf_debug_info)
return eSectionTypeDWARFDebugInfo;
if (section_name == g_sect_name_dwarf_debug_line)
return eSectionTypeDWARFDebugLine;
if (section_name == g_sect_name_dwarf_debug_loc)
return eSectionTypeDWARFDebugLoc;
if (section_name == g_sect_name_dwarf_debug_loclists)
return eSectionTypeDWARFDebugLocLists;
if (section_name == g_sect_name_dwarf_debug_macinfo)
return eSectionTypeDWARFDebugMacInfo;
if (section_name == g_sect_name_dwarf_debug_names)
return eSectionTypeDWARFDebugNames;
if (section_name == g_sect_name_dwarf_debug_pubnames)
return eSectionTypeDWARFDebugPubNames;
if (section_name == g_sect_name_dwarf_debug_pubtypes)
return eSectionTypeDWARFDebugPubTypes;
if (section_name == g_sect_name_dwarf_debug_ranges)
return eSectionTypeDWARFDebugRanges;
if (section_name == g_sect_name_dwarf_debug_str)
return eSectionTypeDWARFDebugStr;
if (section_name == g_sect_name_dwarf_debug_types)
return eSectionTypeDWARFDebugTypes;
if (section_name == g_sect_name_dwarf_apple_names)
return eSectionTypeDWARFAppleNames;
if (section_name == g_sect_name_dwarf_apple_types)
return eSectionTypeDWARFAppleTypes;
if (section_name == g_sect_name_dwarf_apple_namespaces)
return eSectionTypeDWARFAppleNamespaces;
if (section_name == g_sect_name_dwarf_apple_objc)
return eSectionTypeDWARFAppleObjC;
if (section_name == g_sect_name_objc_selrefs)
return eSectionTypeDataCStringPointers;
if (section_name == g_sect_name_objc_msgrefs)
return eSectionTypeDataObjCMessageRefs;
if (section_name == g_sect_name_eh_frame)
return eSectionTypeEHFrame;
if (section_name == g_sect_name_compact_unwind)
return eSectionTypeCompactUnwind;
if (section_name == g_sect_name_cfstring)
return eSectionTypeDataObjCCFStrings;
if (section_name == g_sect_name_go_symtab)
return eSectionTypeGoSymtab;
if (section_name == g_sect_name_objc_data ||
section_name == g_sect_name_objc_classrefs ||
section_name == g_sect_name_objc_superrefs ||
section_name == g_sect_name_objc_const ||
section_name == g_sect_name_objc_classlist) {
return eSectionTypeDataPointers;
}
switch (mach_sect_type) {
// TODO: categorize sections by other flags for regular sections
case S_REGULAR:
if (section_name == g_sect_name_text)
return eSectionTypeCode;
if (section_name == g_sect_name_data)
return eSectionTypeData;
return eSectionTypeOther;
case S_ZEROFILL:
return eSectionTypeZeroFill;
case S_CSTRING_LITERALS: // section with only literal C strings
return eSectionTypeDataCString;
case S_4BYTE_LITERALS: // section with only 4 byte literals
return eSectionTypeData4;
case S_8BYTE_LITERALS: // section with only 8 byte literals
return eSectionTypeData8;
case S_LITERAL_POINTERS: // section with only pointers to literals
return eSectionTypeDataPointers;
case S_NON_LAZY_SYMBOL_POINTERS: // section with only non-lazy symbol pointers
return eSectionTypeDataPointers;
case S_LAZY_SYMBOL_POINTERS: // section with only lazy symbol pointers
return eSectionTypeDataPointers;
case S_SYMBOL_STUBS: // section with only symbol stubs, byte size of stub in
// the reserved2 field
return eSectionTypeCode;
case S_MOD_INIT_FUNC_POINTERS: // section with only function pointers for
// initialization
return eSectionTypeDataPointers;
case S_MOD_TERM_FUNC_POINTERS: // section with only function pointers for
// termination
return eSectionTypeDataPointers;
case S_COALESCED:
return eSectionTypeOther;
case S_GB_ZEROFILL:
return eSectionTypeZeroFill;
case S_INTERPOSING: // section with only pairs of function pointers for
// interposing
return eSectionTypeCode;
case S_16BYTE_LITERALS: // section with only 16 byte literals
return eSectionTypeData16;
case S_DTRACE_DOF:
return eSectionTypeDebug;
case S_LAZY_DYLIB_SYMBOL_POINTERS:
return eSectionTypeDataPointers;
default:
return eSectionTypeOther;
}
}
struct ObjectFileMachO::SegmentParsingContext {
const EncryptedFileRanges EncryptedRanges;
lldb_private::SectionList &UnifiedList;
uint32_t NextSegmentIdx = 0;
uint32_t NextSectionIdx = 0;
bool FileAddressesChanged = false;
SegmentParsingContext(EncryptedFileRanges EncryptedRanges,
lldb_private::SectionList &UnifiedList)
: EncryptedRanges(std::move(EncryptedRanges)), UnifiedList(UnifiedList) {}
};
void ObjectFileMachO::ProcessSegmentCommand(const load_command &load_cmd_,
lldb::offset_t offset,
uint32_t cmd_idx,
SegmentParsingContext &context) {
segment_command_64 load_cmd;
memcpy(&load_cmd, &load_cmd_, sizeof(load_cmd_));
if (!m_data.GetU8(&offset, (uint8_t *)load_cmd.segname, 16))
return;
ModuleSP module_sp = GetModule();
const bool is_core = GetType() == eTypeCoreFile;
const bool is_dsym = (m_header.filetype == MH_DSYM);
bool add_section = true;
bool add_to_unified = true;
ConstString const_segname(
load_cmd.segname, strnlen(load_cmd.segname, sizeof(load_cmd.segname)));
SectionSP unified_section_sp(
context.UnifiedList.FindSectionByName(const_segname));
if (is_dsym && unified_section_sp) {
if (const_segname == GetSegmentNameLINKEDIT()) {
// We need to keep the __LINKEDIT segment private to this object file
// only
add_to_unified = false;
} else {
// This is the dSYM file and this section has already been created by the
// object file, no need to create it.
add_section = false;
}
}
load_cmd.vmaddr = m_data.GetAddress(&offset);
load_cmd.vmsize = m_data.GetAddress(&offset);
load_cmd.fileoff = m_data.GetAddress(&offset);
load_cmd.filesize = m_data.GetAddress(&offset);
if (!m_data.GetU32(&offset, &load_cmd.maxprot, 4))
return;
SanitizeSegmentCommand(load_cmd, cmd_idx);
const uint32_t segment_permissions = GetSegmentPermissions(load_cmd);
const bool segment_is_encrypted =
(load_cmd.flags & SG_PROTECTED_VERSION_1) != 0;
// Keep a list of mach segments around in case we need to get at data that
// isn't stored in the abstracted Sections.
m_mach_segments.push_back(load_cmd);
// Use a segment ID of the segment index shifted left by 8 so they never
// conflict with any of the sections.
SectionSP segment_sp;
if (add_section && (const_segname || is_core)) {
segment_sp = std::make_shared<Section>(
module_sp, // Module to which this section belongs
this, // Object file to which this sections belongs
++context.NextSegmentIdx
<< 8, // Section ID is the 1 based segment index
// shifted right by 8 bits as not to collide with any of the 256
// section IDs that are possible
const_segname, // Name of this section
eSectionTypeContainer, // This section is a container of other
// sections.
load_cmd.vmaddr, // File VM address == addresses as they are
// found in the object file
load_cmd.vmsize, // VM size in bytes of this section
load_cmd.fileoff, // Offset to the data for this section in
// the file
load_cmd.filesize, // Size in bytes of this section as found
// in the file
0, // Segments have no alignment information
load_cmd.flags); // Flags for this section
segment_sp->SetIsEncrypted(segment_is_encrypted);
m_sections_up->AddSection(segment_sp);
segment_sp->SetPermissions(segment_permissions);
if (add_to_unified)
context.UnifiedList.AddSection(segment_sp);
} else if (unified_section_sp) {
if (is_dsym && unified_section_sp->GetFileAddress() != load_cmd.vmaddr) {
// Check to see if the module was read from memory?
if (module_sp->GetObjectFile()->GetBaseAddress().IsValid()) {
// We have a module that is in memory and needs to have its file
// address adjusted. We need to do this because when we load a file
// from memory, its addresses will be slid already, yet the addresses
// in the new symbol file will still be unslid. Since everything is
// stored as section offset, this shouldn't cause any problems.
// Make sure we've parsed the symbol table from the ObjectFile before
// we go around changing its Sections.
module_sp->GetObjectFile()->GetSymtab();
// eh_frame would present the same problems but we parse that on a per-
// function basis as-needed so it's more difficult to remove its use of
// the Sections. Realistically, the environments where this code path
// will be taken will not have eh_frame sections.
unified_section_sp->SetFileAddress(load_cmd.vmaddr);
// Notify the module that the section addresses have been changed once
// we're done so any file-address caches can be updated.
context.FileAddressesChanged = true;
}
}
m_sections_up->AddSection(unified_section_sp);
}
struct section_64 sect64;
::memset(§64, 0, sizeof(sect64));
// Push a section into our mach sections for the section at index zero
// (NO_SECT) if we don't have any mach sections yet...
if (m_mach_sections.empty())
m_mach_sections.push_back(sect64);
uint32_t segment_sect_idx;
const lldb::user_id_t first_segment_sectID = context.NextSectionIdx + 1;
const uint32_t num_u32s = load_cmd.cmd == LC_SEGMENT ? 7 : 8;
for (segment_sect_idx = 0; segment_sect_idx < load_cmd.nsects;
++segment_sect_idx) {
if (m_data.GetU8(&offset, (uint8_t *)sect64.sectname,
sizeof(sect64.sectname)) == nullptr)
break;
if (m_data.GetU8(&offset, (uint8_t *)sect64.segname,
sizeof(sect64.segname)) == nullptr)
break;
sect64.addr = m_data.GetAddress(&offset);
sect64.size = m_data.GetAddress(&offset);
if (m_data.GetU32(&offset, §64.offset, num_u32s) == nullptr)
break;
// Keep a list of mach sections around in case we need to get at data that
// isn't stored in the abstracted Sections.
m_mach_sections.push_back(sect64);
if (add_section) {
ConstString section_name(
sect64.sectname, strnlen(sect64.sectname, sizeof(sect64.sectname)));
if (!const_segname) {
// We have a segment with no name so we need to conjure up segments
// that correspond to the section's segname if there isn't already such
// a section. If there is such a section, we resize the section so that
// it spans all sections. We also mark these sections as fake so
// address matches don't hit if they land in the gaps between the child
// sections.
const_segname.SetTrimmedCStringWithLength(sect64.segname,
sizeof(sect64.segname));
segment_sp = context.UnifiedList.FindSectionByName(const_segname);
if (segment_sp.get()) {
Section *segment = segment_sp.get();
// Grow the section size as needed.
const lldb::addr_t sect64_min_addr = sect64.addr;
const lldb::addr_t sect64_max_addr = sect64_min_addr + sect64.size;
const lldb::addr_t curr_seg_byte_size = segment->GetByteSize();
const lldb::addr_t curr_seg_min_addr = segment->GetFileAddress();
const lldb::addr_t curr_seg_max_addr =
curr_seg_min_addr + curr_seg_byte_size;
if (sect64_min_addr >= curr_seg_min_addr) {
const lldb::addr_t new_seg_byte_size =
sect64_max_addr - curr_seg_min_addr;
// Only grow the section size if needed
if (new_seg_byte_size > curr_seg_byte_size)
segment->SetByteSize(new_seg_byte_size);
} else {
// We need to change the base address of the segment and adjust the
// child section offsets for all existing children.
const lldb::addr_t slide_amount =
sect64_min_addr - curr_seg_min_addr;
segment->Slide(slide_amount, false);
segment->GetChildren().Slide(-slide_amount, false);
segment->SetByteSize(curr_seg_max_addr - sect64_min_addr);
}
// Grow the section size as needed.
if (sect64.offset) {
const lldb::addr_t segment_min_file_offset =
segment->GetFileOffset();
const lldb::addr_t segment_max_file_offset =
segment_min_file_offset + segment->GetFileSize();
const lldb::addr_t section_min_file_offset = sect64.offset;
const lldb::addr_t section_max_file_offset =
section_min_file_offset + sect64.size;
const lldb::addr_t new_file_offset =
std::min(section_min_file_offset, segment_min_file_offset);
const lldb::addr_t new_file_size =
std::max(section_max_file_offset, segment_max_file_offset) -
new_file_offset;
segment->SetFileOffset(new_file_offset);
segment->SetFileSize(new_file_size);
}
} else {
// Create a fake section for the section's named segment
segment_sp = std::make_shared<Section>(
segment_sp, // Parent section
module_sp, // Module to which this section belongs
this, // Object file to which this section belongs
++context.NextSegmentIdx
<< 8, // Section ID is the 1 based segment index
// shifted right by 8 bits as not to
// collide with any of the 256 section IDs
// that are possible
const_segname, // Name of this section
eSectionTypeContainer, // This section is a container of
// other sections.
sect64.addr, // File VM address == addresses as they are
// found in the object file
sect64.size, // VM size in bytes of this section
sect64.offset, // Offset to the data for this section in
// the file
sect64.offset ? sect64.size : 0, // Size in bytes of
// this section as
// found in the file
sect64.align,
load_cmd.flags); // Flags for this section
segment_sp->SetIsFake(true);
segment_sp->SetPermissions(segment_permissions);
m_sections_up->AddSection(segment_sp);
if (add_to_unified)
context.UnifiedList.AddSection(segment_sp);
segment_sp->SetIsEncrypted(segment_is_encrypted);
}
}
assert(segment_sp.get());
lldb::SectionType sect_type = GetSectionType(sect64.flags, section_name);
SectionSP section_sp(new Section(
segment_sp, module_sp, this, ++context.NextSectionIdx, section_name,
sect_type, sect64.addr - segment_sp->GetFileAddress(), sect64.size,
sect64.offset, sect64.offset == 0 ? 0 : sect64.size, sect64.align,
sect64.flags));
// Set the section to be encrypted to match the segment
bool section_is_encrypted = false;
if (!segment_is_encrypted && load_cmd.filesize != 0)
section_is_encrypted = context.EncryptedRanges.FindEntryThatContains(
sect64.offset) != nullptr;
section_sp->SetIsEncrypted(segment_is_encrypted || section_is_encrypted);
section_sp->SetPermissions(segment_permissions);
segment_sp->GetChildren().AddSection(section_sp);
if (segment_sp->IsFake()) {
segment_sp.reset();
const_segname.Clear();
}
}
}
if (segment_sp && is_dsym) {
if (first_segment_sectID <= context.NextSectionIdx) {
lldb::user_id_t sect_uid;
for (sect_uid = first_segment_sectID; sect_uid <= context.NextSectionIdx;
++sect_uid) {
SectionSP curr_section_sp(
segment_sp->GetChildren().FindSectionByID(sect_uid));
SectionSP next_section_sp;
if (sect_uid + 1 <= context.NextSectionIdx)
next_section_sp =
segment_sp->GetChildren().FindSectionByID(sect_uid + 1);
if (curr_section_sp.get()) {
if (curr_section_sp->GetByteSize() == 0) {
if (next_section_sp.get() != nullptr)
curr_section_sp->SetByteSize(next_section_sp->GetFileAddress() -
curr_section_sp->GetFileAddress());
else
curr_section_sp->SetByteSize(load_cmd.vmsize);
}
}
}
}
}
}
void ObjectFileMachO::ProcessDysymtabCommand(const load_command &load_cmd,
lldb::offset_t offset) {
m_dysymtab.cmd = load_cmd.cmd;
m_dysymtab.cmdsize = load_cmd.cmdsize;
m_data.GetU32(&offset, &m_dysymtab.ilocalsym,
(sizeof(m_dysymtab) / sizeof(uint32_t)) - 2);
}
void ObjectFileMachO::CreateSections(SectionList &unified_section_list) {
if (m_sections_up)
return;
m_sections_up.reset(new SectionList());
lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
// bool dump_sections = false;
ModuleSP module_sp(GetModule());
offset = MachHeaderSizeFromMagic(m_header.magic);
SegmentParsingContext context(GetEncryptedFileRanges(), unified_section_list);
struct load_command load_cmd;
for (uint32_t i = 0; i < m_header.ncmds; ++i) {
const lldb::offset_t load_cmd_offset = offset;
if (m_data.GetU32(&offset, &load_cmd, 2) == nullptr)
break;
if (load_cmd.cmd == LC_SEGMENT || load_cmd.cmd == LC_SEGMENT_64)
ProcessSegmentCommand(load_cmd, offset, i, context);
else if (load_cmd.cmd == LC_DYSYMTAB)
ProcessDysymtabCommand(load_cmd, offset);
offset = load_cmd_offset + load_cmd.cmdsize;
}
if (context.FileAddressesChanged && module_sp)
module_sp->SectionFileAddressesChanged();
}
class MachSymtabSectionInfo {
public:
MachSymtabSectionInfo(SectionList *section_list)
: m_section_list(section_list), m_section_infos() {
// Get the number of sections down to a depth of 1 to include all segments
// and their sections, but no other sections that may be added for debug
// map or
m_section_infos.resize(section_list->GetNumSections(1));
}
SectionSP GetSection(uint8_t n_sect, addr_t file_addr) {
if (n_sect == 0)
return SectionSP();
if (n_sect < m_section_infos.size()) {
if (!m_section_infos[n_sect].section_sp) {
SectionSP section_sp(m_section_list->FindSectionByID(n_sect));
m_section_infos[n_sect].section_sp = section_sp;
if (section_sp) {
m_section_infos[n_sect].vm_range.SetBaseAddress(
section_sp->GetFileAddress());
m_section_infos[n_sect].vm_range.SetByteSize(
section_sp->GetByteSize());
} else {
Host::SystemLog(Host::eSystemLogError,
"error: unable to find section for section %u\n",
n_sect);
}
}
if (m_section_infos[n_sect].vm_range.Contains(file_addr)) {
// Symbol is in section.
return m_section_infos[n_sect].section_sp;
} else if (m_section_infos[n_sect].vm_range.GetByteSize() == 0 &&
m_section_infos[n_sect].vm_range.GetBaseAddress() ==
file_addr) {
// Symbol is in section with zero size, but has the same start address
// as the section. This can happen with linker symbols (symbols that
// start with the letter 'l' or 'L'.
return m_section_infos[n_sect].section_sp;
}
}
return m_section_list->FindSectionContainingFileAddress(file_addr);
}
protected:
struct SectionInfo {
SectionInfo() : vm_range(), section_sp() {}
VMRange vm_range;
SectionSP section_sp;
};
SectionList *m_section_list;
std::vector<SectionInfo> m_section_infos;
};
struct TrieEntry {
void Dump() const {
printf("0x%16.16llx 0x%16.16llx 0x%16.16llx \"%s\"",
static_cast<unsigned long long>(address),
static_cast<unsigned long long>(flags),
static_cast<unsigned long long>(other), name.GetCString());
if (import_name)
printf(" -> \"%s\"\n", import_name.GetCString());
else
printf("\n");
}
ConstString name;
uint64_t address = LLDB_INVALID_ADDRESS;
uint64_t flags = 0;
uint64_t other = 0;
ConstString import_name;
};
struct TrieEntryWithOffset {
lldb::offset_t nodeOffset;
TrieEntry entry;
TrieEntryWithOffset(lldb::offset_t offset) : nodeOffset(offset), entry() {}
void Dump(uint32_t idx) const {
printf("[%3u] 0x%16.16llx: ", idx,
static_cast<unsigned long long>(nodeOffset));
entry.Dump();
}
bool operator<(const TrieEntryWithOffset &other) const {
return (nodeOffset < other.nodeOffset);
}
};
static bool ParseTrieEntries(DataExtractor &data, lldb::offset_t offset,
const bool is_arm,
std::vector<llvm::StringRef> &nameSlices,
std::set<lldb::addr_t> &resolver_addresses,
std::vector<TrieEntryWithOffset> &output) {
if (!data.ValidOffset(offset))
return true;
const uint64_t terminalSize = data.GetULEB128(&offset);
lldb::offset_t children_offset = offset + terminalSize;
if (terminalSize != 0) {
TrieEntryWithOffset e(offset);
e.entry.flags = data.GetULEB128(&offset);
const char *import_name = nullptr;
if (e.entry.flags & EXPORT_SYMBOL_FLAGS_REEXPORT) {
e.entry.address = 0;
e.entry.other = data.GetULEB128(&offset); // dylib ordinal
import_name = data.GetCStr(&offset);
} else {
e.entry.address = data.GetULEB128(&offset);
if (e.entry.flags & EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER) {
e.entry.other = data.GetULEB128(&offset);
uint64_t resolver_addr = e.entry.other;
if (is_arm)
resolver_addr &= THUMB_ADDRESS_BIT_MASK;
resolver_addresses.insert(resolver_addr);
} else
e.entry.other = 0;
}
// Only add symbols that are reexport symbols with a valid import name
if (EXPORT_SYMBOL_FLAGS_REEXPORT & e.entry.flags && import_name &&
import_name[0]) {
std::string name;
if (!nameSlices.empty()) {
for (auto name_slice : nameSlices)
name.append(name_slice.data(), name_slice.size());
}
if (name.size() > 1) {
// Skip the leading '_'
e.entry.name.SetCStringWithLength(name.c_str() + 1, name.size() - 1);
}
if (import_name) {
// Skip the leading '_'
e.entry.import_name.SetCString(import_name + 1);
}
output.push_back(e);
}
}
const uint8_t childrenCount = data.GetU8(&children_offset);
for (uint8_t i = 0; i < childrenCount; ++i) {
const char *cstr = data.GetCStr(&children_offset);
if (cstr)
nameSlices.push_back(llvm::StringRef(cstr));
else
return false; // Corrupt data
lldb::offset_t childNodeOffset = data.GetULEB128(&children_offset);
if (childNodeOffset) {
if (!ParseTrieEntries(data, childNodeOffset, is_arm, nameSlices,
resolver_addresses, output)) {
return false;
}
}
nameSlices.pop_back();
}
return true;
}
// Read the UUID out of a dyld_shared_cache file on-disk.
UUID ObjectFileMachO::GetSharedCacheUUID(FileSpec dyld_shared_cache,
const ByteOrder byte_order,
const uint32_t addr_byte_size) {
UUID dsc_uuid;
DataBufferSP DscData = MapFileData(
dyld_shared_cache, sizeof(struct lldb_copy_dyld_cache_header_v1), 0);
if (!DscData)
return dsc_uuid;
DataExtractor dsc_header_data(DscData, byte_order, addr_byte_size);
char version_str[7];
lldb::offset_t offset = 0;
memcpy(version_str, dsc_header_data.GetData(&offset, 6), 6);
version_str[6] = '\0';
if (strcmp(version_str, "dyld_v") == 0) {
offset = offsetof(struct lldb_copy_dyld_cache_header_v1, uuid);
dsc_uuid = UUID::fromOptionalData(
dsc_header_data.GetData(&offset, sizeof(uuid_t)), sizeof(uuid_t));
}
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS));
if (log && dsc_uuid.IsValid()) {
LLDB_LOGF(log, "Shared cache %s has UUID %s",
dyld_shared_cache.GetPath().c_str(),
dsc_uuid.GetAsString().c_str());
}
return dsc_uuid;
}
static llvm::Optional<struct nlist_64>
ParseNList(DataExtractor &nlist_data, lldb::offset_t &nlist_data_offset,
size_t nlist_byte_size) {
struct nlist_64 nlist;
if (!nlist_data.ValidOffsetForDataOfSize(nlist_data_offset, nlist_byte_size))
return {};
nlist.n_strx = nlist_data.GetU32_unchecked(&nlist_data_offset);
nlist.n_type = nlist_data.GetU8_unchecked(&nlist_data_offset);
nlist.n_sect = nlist_data.GetU8_unchecked(&nlist_data_offset);
nlist.n_desc = nlist_data.GetU16_unchecked(&nlist_data_offset);
nlist.n_value = nlist_data.GetAddress_unchecked(&nlist_data_offset);
return nlist;
}
enum { DebugSymbols = true, NonDebugSymbols = false };
size_t ObjectFileMachO::ParseSymtab() {
static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
Timer scoped_timer(func_cat, "ObjectFileMachO::ParseSymtab () module = %s",
m_file.GetFilename().AsCString(""));
ModuleSP module_sp(GetModule());
if (!module_sp)
return 0;
struct symtab_command symtab_load_command = {0, 0, 0, 0, 0, 0};
struct linkedit_data_command function_starts_load_command = {0, 0, 0, 0};
struct dyld_info_command dyld_info = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
typedef AddressDataArray<lldb::addr_t, bool, 100> FunctionStarts;
FunctionStarts function_starts;
lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
uint32_t i;
FileSpecList dylib_files;
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS));
llvm::StringRef g_objc_v2_prefix_class("_OBJC_CLASS_$_");
llvm::StringRef g_objc_v2_prefix_metaclass("_OBJC_METACLASS_$_");
llvm::StringRef g_objc_v2_prefix_ivar("_OBJC_IVAR_$_");
for (i = 0; i < m_header.ncmds; ++i) {
const lldb::offset_t cmd_offset = offset;
// Read in the load command and load command size
struct load_command lc;
if (m_data.GetU32(&offset, &lc, 2) == nullptr)
break;
// Watch for the symbol table load command
switch (lc.cmd) {
case LC_SYMTAB:
symtab_load_command.cmd = lc.cmd;
symtab_load_command.cmdsize = lc.cmdsize;
// Read in the rest of the symtab load command
if (m_data.GetU32(&offset, &symtab_load_command.symoff, 4) ==
nullptr) // fill in symoff, nsyms, stroff, strsize fields
return 0;
if (symtab_load_command.symoff == 0) {
if (log)
module_sp->LogMessage(log, "LC_SYMTAB.symoff == 0");
return 0;
}
if (symtab_load_command.stroff == 0) {
if (log)
module_sp->LogMessage(log, "LC_SYMTAB.stroff == 0");
return 0;
}
if (symtab_load_command.nsyms == 0) {
if (log)
module_sp->LogMessage(log, "LC_SYMTAB.nsyms == 0");
return 0;
}
if (symtab_load_command.strsize == 0) {
if (log)
module_sp->LogMessage(log, "LC_SYMTAB.strsize == 0");
return 0;
}
break;
case LC_DYLD_INFO:
case LC_DYLD_INFO_ONLY:
if (m_data.GetU32(&offset, &dyld_info.rebase_off, 10)) {
dyld_info.cmd = lc.cmd;
dyld_info.cmdsize = lc.cmdsize;
} else {
memset(&dyld_info, 0, sizeof(dyld_info));
}
break;
case LC_LOAD_DYLIB:
case LC_LOAD_WEAK_DYLIB:
case LC_REEXPORT_DYLIB:
case LC_LOADFVMLIB:
case LC_LOAD_UPWARD_DYLIB: {
uint32_t name_offset = cmd_offset + m_data.GetU32(&offset);
const char *path = m_data.PeekCStr(name_offset);
if (path) {
FileSpec file_spec(path);
// Strip the path if there is @rpath, @executable, etc so we just use
// the basename
if (path[0] == '@')
file_spec.GetDirectory().Clear();
if (lc.cmd == LC_REEXPORT_DYLIB) {
m_reexported_dylibs.AppendIfUnique(file_spec);
}
dylib_files.Append(file_spec);
}
} break;
case LC_FUNCTION_STARTS:
function_starts_load_command.cmd = lc.cmd;
function_starts_load_command.cmdsize = lc.cmdsize;
if (m_data.GetU32(&offset, &function_starts_load_command.dataoff, 2) ==
nullptr) // fill in symoff, nsyms, stroff, strsize fields
memset(&function_starts_load_command, 0,
sizeof(function_starts_load_command));
break;
default:
break;
}
offset = cmd_offset + lc.cmdsize;
}
if (!symtab_load_command.cmd)
return 0;
Symtab *symtab = m_symtab_up.get();
SectionList *section_list = GetSectionList();
if (section_list == nullptr)
return 0;
const uint32_t addr_byte_size = m_data.GetAddressByteSize();
const ByteOrder byte_order = m_data.GetByteOrder();
bool bit_width_32 = addr_byte_size == 4;
const size_t nlist_byte_size =
bit_width_32 ? sizeof(struct nlist) : sizeof(struct nlist_64);
DataExtractor nlist_data(nullptr, 0, byte_order, addr_byte_size);
DataExtractor strtab_data(nullptr, 0, byte_order, addr_byte_size);
DataExtractor function_starts_data(nullptr, 0, byte_order, addr_byte_size);
DataExtractor indirect_symbol_index_data(nullptr, 0, byte_order,
addr_byte_size);
DataExtractor dyld_trie_data(nullptr, 0, byte_order, addr_byte_size);
const addr_t nlist_data_byte_size =
symtab_load_command.nsyms * nlist_byte_size;
const addr_t strtab_data_byte_size = symtab_load_command.strsize;
addr_t strtab_addr = LLDB_INVALID_ADDRESS;
ProcessSP process_sp(m_process_wp.lock());
Process *process = process_sp.get();
uint32_t memory_module_load_level = eMemoryModuleLoadLevelComplete;
if (process && m_header.filetype != llvm::MachO::MH_OBJECT) {
Target &target = process->GetTarget();
memory_module_load_level = target.GetMemoryModuleLoadLevel();
SectionSP linkedit_section_sp(
section_list->FindSectionByName(GetSegmentNameLINKEDIT()));
// Reading mach file from memory in a process or core file...
if (linkedit_section_sp) {
addr_t linkedit_load_addr =
linkedit_section_sp->GetLoadBaseAddress(&target);
if (linkedit_load_addr == LLDB_INVALID_ADDRESS) {
// We might be trying to access the symbol table before the
// __LINKEDIT's load address has been set in the target. We can't
// fail to read the symbol table, so calculate the right address
// manually
linkedit_load_addr = CalculateSectionLoadAddressForMemoryImage(
m_memory_addr, GetMachHeaderSection(), linkedit_section_sp.get());
}
const addr_t linkedit_file_offset = linkedit_section_sp->GetFileOffset();
const addr_t symoff_addr = linkedit_load_addr +
symtab_load_command.symoff -
linkedit_file_offset;
strtab_addr = linkedit_load_addr + symtab_load_command.stroff -
linkedit_file_offset;
bool data_was_read = false;
#if defined(__APPLE__) && \
(defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
if (m_header.flags & 0x80000000u &&
process->GetAddressByteSize() == sizeof(void *)) {
// This mach-o memory file is in the dyld shared cache. If this
// program is not remote and this is iOS, then this process will
// share the same shared cache as the process we are debugging and we
// can read the entire __LINKEDIT from the address space in this
// process. This is a needed optimization that is used for local iOS
// debugging only since all shared libraries in the shared cache do
// not have corresponding files that exist in the file system of the
// device. They have been combined into a single file. This means we
// always have to load these files from memory. All of the symbol and
// string tables from all of the __LINKEDIT sections from the shared
// libraries in the shared cache have been merged into a single large
// symbol and string table. Reading all of this symbol and string
// table data across can slow down debug launch times, so we optimize
// this by reading the memory for the __LINKEDIT section from this
// process.
UUID lldb_shared_cache;
addr_t lldb_shared_cache_addr;
GetLLDBSharedCacheUUID(lldb_shared_cache_addr, lldb_shared_cache);
UUID process_shared_cache;
addr_t process_shared_cache_addr;
GetProcessSharedCacheUUID(process, process_shared_cache_addr,
process_shared_cache);
bool use_lldb_cache = true;
if (lldb_shared_cache.IsValid() && process_shared_cache.IsValid() &&
(lldb_shared_cache != process_shared_cache ||
process_shared_cache_addr != lldb_shared_cache_addr)) {
use_lldb_cache = false;
}
PlatformSP platform_sp(target.GetPlatform());
if (platform_sp && platform_sp->IsHost() && use_lldb_cache) {
data_was_read = true;
nlist_data.SetData((void *)symoff_addr, nlist_data_byte_size,
eByteOrderLittle);
strtab_data.SetData((void *)strtab_addr, strtab_data_byte_size,
eByteOrderLittle);
if (function_starts_load_command.cmd) {
const addr_t func_start_addr =
linkedit_load_addr + function_starts_load_command.dataoff -
linkedit_file_offset;
function_starts_data.SetData((void *)func_start_addr,
function_starts_load_command.datasize,
eByteOrderLittle);
}
}
}
#endif
if (!data_was_read) {
// Always load dyld - the dynamic linker - from memory if we didn't
// find a binary anywhere else. lldb will not register
// dylib/framework/bundle loads/unloads if we don't have the dyld
// symbols, we force dyld to load from memory despite the user's
// target.memory-module-load-level setting.
if (memory_module_load_level == eMemoryModuleLoadLevelComplete ||
m_header.filetype == llvm::MachO::MH_DYLINKER) {
DataBufferSP nlist_data_sp(
ReadMemory(process_sp, symoff_addr, nlist_data_byte_size));
if (nlist_data_sp)
nlist_data.SetData(nlist_data_sp, 0, nlist_data_sp->GetByteSize());
if (m_dysymtab.nindirectsyms != 0) {
const addr_t indirect_syms_addr = linkedit_load_addr +
m_dysymtab.indirectsymoff -
linkedit_file_offset;
DataBufferSP indirect_syms_data_sp(ReadMemory(
process_sp, indirect_syms_addr, m_dysymtab.nindirectsyms * 4));
if (indirect_syms_data_sp)
indirect_symbol_index_data.SetData(
indirect_syms_data_sp, 0,
indirect_syms_data_sp->GetByteSize());
// If this binary is outside the shared cache,
// cache the string table.
// Binaries in the shared cache all share a giant string table,
// and we can't share the string tables across multiple
// ObjectFileMachO's, so we'd end up re-reading this mega-strtab
// for every binary in the shared cache - it would be a big perf
// problem. For binaries outside the shared cache, it's faster to
// read the entire strtab at once instead of piece-by-piece as we
// process the nlist records.
if ((m_header.flags & 0x80000000u) == 0) {
DataBufferSP strtab_data_sp(
ReadMemory(process_sp, strtab_addr, strtab_data_byte_size));
if (strtab_data_sp) {
strtab_data.SetData(strtab_data_sp, 0,
strtab_data_sp->GetByteSize());
}
}
}
}
if (memory_module_load_level >= eMemoryModuleLoadLevelPartial) {
if (function_starts_load_command.cmd) {
const addr_t func_start_addr =
linkedit_load_addr + function_starts_load_command.dataoff -
linkedit_file_offset;
DataBufferSP func_start_data_sp(
ReadMemory(process_sp, func_start_addr,
function_starts_load_command.datasize));
if (func_start_data_sp)
function_starts_data.SetData(func_start_data_sp, 0,
func_start_data_sp->GetByteSize());
}
}
}
}
} else {
nlist_data.SetData(m_data, symtab_load_command.symoff,
nlist_data_byte_size);
strtab_data.SetData(m_data, symtab_load_command.stroff,
strtab_data_byte_size);
if (dyld_info.export_size > 0) {
dyld_trie_data.SetData(m_data, dyld_info.export_off,
dyld_info.export_size);
}
if (m_dysymtab.nindirectsyms != 0) {
indirect_symbol_index_data.SetData(m_data, m_dysymtab.indirectsymoff,
m_dysymtab.nindirectsyms * 4);
}
if (function_starts_load_command.cmd) {
function_starts_data.SetData(m_data, function_starts_load_command.dataoff,
function_starts_load_command.datasize);
}
}
if (nlist_data.GetByteSize() == 0 &&
memory_module_load_level == eMemoryModuleLoadLevelComplete) {
if (log)
module_sp->LogMessage(log, "failed to read nlist data");
return 0;
}
const bool have_strtab_data = strtab_data.GetByteSize() > 0;
if (!have_strtab_data) {
if (process) {
if (strtab_addr == LLDB_INVALID_ADDRESS) {
if (log)
module_sp->LogMessage(log, "failed to locate the strtab in memory");
return 0;
}
} else {
if (log)
module_sp->LogMessage(log, "failed to read strtab data");
return 0;
}
}
ConstString g_segment_name_TEXT = GetSegmentNameTEXT();
ConstString g_segment_name_DATA = GetSegmentNameDATA();
ConstString g_segment_name_DATA_DIRTY = GetSegmentNameDATA_DIRTY();
ConstString g_segment_name_DATA_CONST = GetSegmentNameDATA_CONST();
ConstString g_segment_name_OBJC = GetSegmentNameOBJC();
ConstString g_section_name_eh_frame = GetSectionNameEHFrame();
SectionSP text_section_sp(
section_list->FindSectionByName(g_segment_name_TEXT));
SectionSP data_section_sp(
section_list->FindSectionByName(g_segment_name_DATA));
SectionSP data_dirty_section_sp(
section_list->FindSectionByName(g_segment_name_DATA_DIRTY));
SectionSP data_const_section_sp(
section_list->FindSectionByName(g_segment_name_DATA_CONST));
SectionSP objc_section_sp(
section_list->FindSectionByName(g_segment_name_OBJC));
SectionSP eh_frame_section_sp;
if (text_section_sp.get())
eh_frame_section_sp = text_section_sp->GetChildren().FindSectionByName(
g_section_name_eh_frame);
else
eh_frame_section_sp =
section_list->FindSectionByName(g_section_name_eh_frame);
const bool is_arm = (m_header.cputype == llvm::MachO::CPU_TYPE_ARM);
// lldb works best if it knows the start address of all functions in a
// module. Linker symbols or debug info are normally the best source of
// information for start addr / size but they may be stripped in a released
// binary. Two additional sources of information exist in Mach-O binaries:
// LC_FUNCTION_STARTS - a list of ULEB128 encoded offsets of each
// function's start address in the
// binary, relative to the text section.
// eh_frame - the eh_frame FDEs have the start addr & size of
// each function
// LC_FUNCTION_STARTS is the fastest source to read in, and is present on
// all modern binaries.
// Binaries built to run on older releases may need to use eh_frame
// information.
if (text_section_sp && function_starts_data.GetByteSize()) {
FunctionStarts::Entry function_start_entry;
function_start_entry.data = false;
lldb::offset_t function_start_offset = 0;
function_start_entry.addr = text_section_sp->GetFileAddress();
uint64_t delta;
while ((delta = function_starts_data.GetULEB128(&function_start_offset)) >
0) {
// Now append the current entry
function_start_entry.addr += delta;
function_starts.Append(function_start_entry);
}
} else {
// If m_type is eTypeDebugInfo, then this is a dSYM - it will have the
// load command claiming an eh_frame but it doesn't actually have the
// eh_frame content. And if we have a dSYM, we don't need to do any of
// this fill-in-the-missing-symbols works anyway - the debug info should
// give us all the functions in the module.
if (text_section_sp.get() && eh_frame_section_sp.get() &&
m_type != eTypeDebugInfo) {
DWARFCallFrameInfo eh_frame(*this, eh_frame_section_sp,
DWARFCallFrameInfo::EH);
DWARFCallFrameInfo::FunctionAddressAndSizeVector functions;
eh_frame.GetFunctionAddressAndSizeVector(functions);
addr_t text_base_addr = text_section_sp->GetFileAddress();
size_t count = functions.GetSize();
for (size_t i = 0; i < count; ++i) {
const DWARFCallFrameInfo::FunctionAddressAndSizeVector::Entry *func =
functions.GetEntryAtIndex(i);
if (func) {
FunctionStarts::Entry function_start_entry;
function_start_entry.addr = func->base - text_base_addr;
function_starts.Append(function_start_entry);
}
}
}
}
const size_t function_starts_count = function_starts.GetSize();
// For user process binaries (executables, dylibs, frameworks, bundles), if
// we don't have LC_FUNCTION_STARTS/eh_frame section in this binary, we're
// going to assume the binary has been stripped. Don't allow assembly
// language instruction emulation because we don't know proper function
// start boundaries.
//
// For all other types of binaries (kernels, stand-alone bare board
// binaries, kexts), they may not have LC_FUNCTION_STARTS / eh_frame
// sections - we should not make any assumptions about them based on that.
if (function_starts_count == 0 && CalculateStrata() == eStrataUser) {
m_allow_assembly_emulation_unwind_plans = false;
Log *unwind_or_symbol_log(lldb_private::GetLogIfAnyCategoriesSet(
LIBLLDB_LOG_SYMBOLS | LIBLLDB_LOG_UNWIND));
if (unwind_or_symbol_log)
module_sp->LogMessage(
unwind_or_symbol_log,
"no LC_FUNCTION_STARTS, will not allow assembly profiled unwinds");
}
const user_id_t TEXT_eh_frame_sectID = eh_frame_section_sp.get()
? eh_frame_section_sp->GetID()
: static_cast<user_id_t>(NO_SECT);
lldb::offset_t nlist_data_offset = 0;
uint32_t N_SO_index = UINT32_MAX;
MachSymtabSectionInfo section_info(section_list);
std::vector<uint32_t> N_FUN_indexes;
std::vector<uint32_t> N_NSYM_indexes;
std::vector<uint32_t> N_INCL_indexes;
std::vector<uint32_t> N_BRAC_indexes;
std::vector<uint32_t> N_COMM_indexes;
typedef std::multimap<uint64_t, uint32_t> ValueToSymbolIndexMap;
typedef llvm::DenseMap<uint32_t, uint32_t> NListIndexToSymbolIndexMap;
typedef llvm::DenseMap<const char *, uint32_t> ConstNameToSymbolIndexMap;
ValueToSymbolIndexMap N_FUN_addr_to_sym_idx;
ValueToSymbolIndexMap N_STSYM_addr_to_sym_idx;
ConstNameToSymbolIndexMap N_GSYM_name_to_sym_idx;
// Any symbols that get merged into another will get an entry in this map
// so we know
NListIndexToSymbolIndexMap m_nlist_idx_to_sym_idx;
uint32_t nlist_idx = 0;
Symbol *symbol_ptr = nullptr;
uint32_t sym_idx = 0;
Symbol *sym = nullptr;
size_t num_syms = 0;
std::string memory_symbol_name;
uint32_t unmapped_local_symbols_found = 0;
std::vector<TrieEntryWithOffset> trie_entries;
std::set<lldb::addr_t> resolver_addresses;
if (dyld_trie_data.GetByteSize() > 0) {
std::vector<llvm::StringRef> nameSlices;
ParseTrieEntries(dyld_trie_data, 0, is_arm, nameSlices, resolver_addresses,
trie_entries);
ConstString text_segment_name("__TEXT");
SectionSP text_segment_sp =
GetSectionList()->FindSectionByName(text_segment_name);
if (text_segment_sp) {
const lldb::addr_t text_segment_file_addr =
text_segment_sp->GetFileAddress();
if (text_segment_file_addr != LLDB_INVALID_ADDRESS) {
for (auto &e : trie_entries)
e.entry.address += text_segment_file_addr;
}
}
}
typedef std::set<ConstString> IndirectSymbols;
IndirectSymbols indirect_symbol_names;
#if defined(__APPLE__) && \
(defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
// Some recent builds of the dyld_shared_cache (hereafter: DSC) have been
// optimized by moving LOCAL symbols out of the memory mapped portion of
// the DSC. The symbol information has all been retained, but it isn't
// available in the normal nlist data. However, there *are* duplicate
// entries of *some*
// LOCAL symbols in the normal nlist data. To handle this situation
// correctly, we must first attempt
// to parse any DSC unmapped symbol information. If we find any, we set a
// flag that tells the normal nlist parser to ignore all LOCAL symbols.
if (m_header.flags & 0x80000000u) {
// Before we can start mapping the DSC, we need to make certain the
// target process is actually using the cache we can find.
// Next we need to determine the correct path for the dyld shared cache.
ArchSpec header_arch;
GetArchitecture(header_arch);
char dsc_path[PATH_MAX];
char dsc_path_development[PATH_MAX];
snprintf(
dsc_path, sizeof(dsc_path), "%s%s%s",
"/System/Library/Caches/com.apple.dyld/", /* IPHONE_DYLD_SHARED_CACHE_DIR
*/
"dyld_shared_cache_", /* DYLD_SHARED_CACHE_BASE_NAME */
header_arch.GetArchitectureName());
snprintf(
dsc_path_development, sizeof(dsc_path), "%s%s%s%s",
"/System/Library/Caches/com.apple.dyld/", /* IPHONE_DYLD_SHARED_CACHE_DIR
*/
"dyld_shared_cache_", /* DYLD_SHARED_CACHE_BASE_NAME */
header_arch.GetArchitectureName(), ".development");
FileSpec dsc_nondevelopment_filespec(dsc_path);
FileSpec dsc_development_filespec(dsc_path_development);
FileSpec dsc_filespec;
UUID dsc_uuid;
UUID process_shared_cache_uuid;
addr_t process_shared_cache_base_addr;
if (process) {
GetProcessSharedCacheUUID(process, process_shared_cache_base_addr,
process_shared_cache_uuid);
}
// First see if we can find an exact match for the inferior process
// shared cache UUID in the development or non-development shared caches
// on disk.
if (process_shared_cache_uuid.IsValid()) {
if (FileSystem::Instance().Exists(dsc_development_filespec)) {
UUID dsc_development_uuid = GetSharedCacheUUID(
dsc_development_filespec, byte_order, addr_byte_size);
if (dsc_development_uuid.IsValid() &&
dsc_development_uuid == process_shared_cache_uuid) {
dsc_filespec = dsc_development_filespec;
dsc_uuid = dsc_development_uuid;
}
}
if (!dsc_uuid.IsValid() &&
FileSystem::Instance().Exists(dsc_nondevelopment_filespec)) {
UUID dsc_nondevelopment_uuid = GetSharedCacheUUID(
dsc_nondevelopment_filespec, byte_order, addr_byte_size);
if (dsc_nondevelopment_uuid.IsValid() &&
dsc_nondevelopment_uuid == process_shared_cache_uuid) {
dsc_filespec = dsc_nondevelopment_filespec;
dsc_uuid = dsc_nondevelopment_uuid;
}
}
}
// Failing a UUID match, prefer the development dyld_shared cache if both
// are present.
if (!FileSystem::Instance().Exists(dsc_filespec)) {
if (FileSystem::Instance().Exists(dsc_development_filespec)) {
dsc_filespec = dsc_development_filespec;
} else {
dsc_filespec = dsc_nondevelopment_filespec;
}
}
/* The dyld_cache_header has a pointer to the
dyld_cache_local_symbols_info structure (localSymbolsOffset).
The dyld_cache_local_symbols_info structure gives us three things:
1. The start and count of the nlist records in the dyld_shared_cache
file
2. The start and size of the strings for these nlist records
3. The start and count of dyld_cache_local_symbols_entry entries
There is one dyld_cache_local_symbols_entry per dylib/framework in the
dyld shared cache.
The "dylibOffset" field is the Mach-O header of this dylib/framework in
the dyld shared cache.
The dyld_cache_local_symbols_entry also lists the start of this
dylib/framework's nlist records
and the count of how many nlist records there are for this
dylib/framework.
*/
// Process the dyld shared cache header to find the unmapped symbols
DataBufferSP dsc_data_sp = MapFileData(
dsc_filespec, sizeof(struct lldb_copy_dyld_cache_header_v1), 0);
if (!dsc_uuid.IsValid()) {
dsc_uuid = GetSharedCacheUUID(dsc_filespec, byte_order, addr_byte_size);
}
if (dsc_data_sp) {
DataExtractor dsc_header_data(dsc_data_sp, byte_order, addr_byte_size);
bool uuid_match = true;
if (dsc_uuid.IsValid() && process) {
if (process_shared_cache_uuid.IsValid() &&
dsc_uuid != process_shared_cache_uuid) {
// The on-disk dyld_shared_cache file is not the same as the one in
// this process' memory, don't use it.
uuid_match = false;
ModuleSP module_sp(GetModule());
if (module_sp)
module_sp->ReportWarning("process shared cache does not match "
"on-disk dyld_shared_cache file, some "
"symbol names will be missing.");
}
}
offset = offsetof(struct lldb_copy_dyld_cache_header_v1, mappingOffset);
uint32_t mappingOffset = dsc_header_data.GetU32(&offset);
// If the mappingOffset points to a location inside the header, we've
// opened an old dyld shared cache, and should not proceed further.
if (uuid_match &&
mappingOffset >= sizeof(struct lldb_copy_dyld_cache_header_v1)) {
DataBufferSP dsc_mapping_info_data_sp = MapFileData(
dsc_filespec, sizeof(struct lldb_copy_dyld_cache_mapping_info),
mappingOffset);
DataExtractor dsc_mapping_info_data(dsc_mapping_info_data_sp,
byte_order, addr_byte_size);
offset = 0;
// The File addresses (from the in-memory Mach-O load commands) for
// the shared libraries in the shared library cache need to be
// adjusted by an offset to match up with the dylibOffset identifying
// field in the dyld_cache_local_symbol_entry's. This offset is
// recorded in mapping_offset_value.
const uint64_t mapping_offset_value =
dsc_mapping_info_data.GetU64(&offset);
offset =
offsetof(struct lldb_copy_dyld_cache_header_v1, localSymbolsOffset);
uint64_t localSymbolsOffset = dsc_header_data.GetU64(&offset);
uint64_t localSymbolsSize = dsc_header_data.GetU64(&offset);
if (localSymbolsOffset && localSymbolsSize) {
// Map the local symbols
DataBufferSP dsc_local_symbols_data_sp =
MapFileData(dsc_filespec, localSymbolsSize, localSymbolsOffset);
if (dsc_local_symbols_data_sp) {
DataExtractor dsc_local_symbols_data(dsc_local_symbols_data_sp,
byte_order, addr_byte_size);
offset = 0;
typedef llvm::DenseMap<ConstString, uint16_t> UndefinedNameToDescMap;
typedef llvm::DenseMap<uint32_t, ConstString> SymbolIndexToName;
UndefinedNameToDescMap undefined_name_to_desc;
SymbolIndexToName reexport_shlib_needs_fixup;
// Read the local_symbols_infos struct in one shot
struct lldb_copy_dyld_cache_local_symbols_info local_symbols_info;
dsc_local_symbols_data.GetU32(&offset,
&local_symbols_info.nlistOffset, 6);
SectionSP text_section_sp(
section_list->FindSectionByName(GetSegmentNameTEXT()));
uint32_t header_file_offset =
(text_section_sp->GetFileAddress() - mapping_offset_value);
offset = local_symbols_info.entriesOffset;
for (uint32_t entry_index = 0;
entry_index < local_symbols_info.entriesCount; entry_index++) {
struct lldb_copy_dyld_cache_local_symbols_entry
local_symbols_entry;
local_symbols_entry.dylibOffset =
dsc_local_symbols_data.GetU32(&offset);
local_symbols_entry.nlistStartIndex =
dsc_local_symbols_data.GetU32(&offset);
local_symbols_entry.nlistCount =
dsc_local_symbols_data.GetU32(&offset);
if (header_file_offset == local_symbols_entry.dylibOffset) {
unmapped_local_symbols_found = local_symbols_entry.nlistCount;
// The normal nlist code cannot correctly size the Symbols
// array, we need to allocate it here.
sym = symtab->Resize(
symtab_load_command.nsyms + m_dysymtab.nindirectsyms +
unmapped_local_symbols_found - m_dysymtab.nlocalsym);
num_syms = symtab->GetNumSymbols();
nlist_data_offset =
local_symbols_info.nlistOffset +
(nlist_byte_size * local_symbols_entry.nlistStartIndex);
uint32_t string_table_offset = local_symbols_info.stringsOffset;
for (uint32_t nlist_index = 0;
nlist_index < local_symbols_entry.nlistCount;
nlist_index++) {
/////////////////////////////
{
llvm::Optional<struct nlist_64> nlist_maybe =
ParseNList(dsc_local_symbols_data, nlist_data_offset,
nlist_byte_size);
if (!nlist_maybe)
break;
struct nlist_64 nlist = *nlist_maybe;
SymbolType type = eSymbolTypeInvalid;
const char *symbol_name = dsc_local_symbols_data.PeekCStr(
string_table_offset + nlist.n_strx);
if (symbol_name == NULL) {
// No symbol should be NULL, even the symbols with no
// string values should have an offset zero which
// points to an empty C-string
Host::SystemLog(
Host::eSystemLogError,
"error: DSC unmapped local symbol[%u] has invalid "
"string table offset 0x%x in %s, ignoring symbol\n",
entry_index, nlist.n_strx,
module_sp->GetFileSpec().GetPath().c_str());
continue;
}
if (symbol_name[0] == '\0')
symbol_name = NULL;
const char *symbol_name_non_abi_mangled = NULL;
SectionSP symbol_section;
uint32_t symbol_byte_size = 0;
bool add_nlist = true;
bool is_debug = ((nlist.n_type & N_STAB) != 0);
bool demangled_is_synthesized = false;
bool is_gsym = false;
bool set_value = true;
assert(sym_idx < num_syms);
sym[sym_idx].SetDebug(is_debug);
if (is_debug) {
switch (nlist.n_type) {
case N_GSYM:
// global symbol: name,,NO_SECT,type,0
// Sometimes the N_GSYM value contains the address.
// FIXME: In the .o files, we have a GSYM and a debug
// symbol for all the ObjC data. They
// have the same address, but we want to ensure that
// we always find only the real symbol, 'cause we
// don't currently correctly attribute the
// GSYM one to the ObjCClass/Ivar/MetaClass
// symbol type. This is a temporary hack to make
// sure the ObjectiveC symbols get treated correctly.
// To do this right, we should coalesce all the GSYM
// & global symbols that have the same address.
is_gsym = true;
sym[sym_idx].SetExternal(true);
if (symbol_name && symbol_name[0] == '_' &&
symbol_name[1] == 'O') {
llvm::StringRef symbol_name_ref(symbol_name);
if (symbol_name_ref.startswith(
g_objc_v2_prefix_class)) {
symbol_name_non_abi_mangled = symbol_name + 1;
symbol_name =
symbol_name + g_objc_v2_prefix_class.size();
type = eSymbolTypeObjCClass;
demangled_is_synthesized = true;
} else if (symbol_name_ref.startswith(
g_objc_v2_prefix_metaclass)) {
symbol_name_non_abi_mangled = symbol_name + 1;
symbol_name =
symbol_name + g_objc_v2_prefix_metaclass.size();
type = eSymbolTypeObjCMetaClass;
demangled_is_synthesized = true;
} else if (symbol_name_ref.startswith(
g_objc_v2_prefix_ivar)) {
symbol_name_non_abi_mangled = symbol_name + 1;
symbol_name =
symbol_name + g_objc_v2_prefix_ivar.size();
type = eSymbolTypeObjCIVar;
demangled_is_synthesized = true;
}
} else {
if (nlist.n_value != 0)
symbol_section = section_info.GetSection(
nlist.n_sect, nlist.n_value);
type = eSymbolTypeData;
}
break;
case N_FNAME:
// procedure name (f77 kludge): name,,NO_SECT,0,0
type = eSymbolTypeCompiler;
break;
case N_FUN:
// procedure: name,,n_sect,linenumber,address
if (symbol_name) {
type = eSymbolTypeCode;
symbol_section = section_info.GetSection(
nlist.n_sect, nlist.n_value);
N_FUN_addr_to_sym_idx.insert(
std::make_pair(nlist.n_value, sym_idx));
// We use the current number of symbols in the
// symbol table in lieu of using nlist_idx in case
// we ever start trimming entries out
N_FUN_indexes.push_back(sym_idx);
} else {
type = eSymbolTypeCompiler;
if (!N_FUN_indexes.empty()) {
// Copy the size of the function into the
// original
// STAB entry so we don't have
// to hunt for it later
symtab->SymbolAtIndex(N_FUN_indexes.back())
->SetByteSize(nlist.n_value);
N_FUN_indexes.pop_back();
// We don't really need the end function STAB as
// it contains the size which we already placed
// with the original symbol, so don't add it if
// we want a minimal symbol table
add_nlist = false;
}
}
break;
case N_STSYM:
// static symbol: name,,n_sect,type,address
N_STSYM_addr_to_sym_idx.insert(
std::make_pair(nlist.n_value, sym_idx));
symbol_section = section_info.GetSection(nlist.n_sect,
nlist.n_value);
if (symbol_name && symbol_name[0]) {
type = ObjectFile::GetSymbolTypeFromName(
symbol_name + 1, eSymbolTypeData);
}
break;
case N_LCSYM:
// .lcomm symbol: name,,n_sect,type,address
symbol_section = section_info.GetSection(nlist.n_sect,
nlist.n_value);
type = eSymbolTypeCommonBlock;
break;
case N_BNSYM:
// We use the current number of symbols in the symbol
// table in lieu of using nlist_idx in case we ever
// start trimming entries out Skip these if we want
// minimal symbol tables
add_nlist = false;
break;
case N_ENSYM:
// Set the size of the N_BNSYM to the terminating
// index of this N_ENSYM so that we can always skip
// the entire symbol if we need to navigate more
// quickly at the source level when parsing STABS
// Skip these if we want minimal symbol tables
add_nlist = false;
break;
case N_OPT:
// emitted with gcc2_compiled and in gcc source
type = eSymbolTypeCompiler;
break;
case N_RSYM:
// register sym: name,,NO_SECT,type,register
type = eSymbolTypeVariable;
break;
case N_SLINE:
// src line: 0,,n_sect,linenumber,address
symbol_section = section_info.GetSection(nlist.n_sect,
nlist.n_value);
type = eSymbolTypeLineEntry;
break;
case N_SSYM:
// structure elt: name,,NO_SECT,type,struct_offset
type = eSymbolTypeVariableType;
break;
case N_SO:
// source file name
type = eSymbolTypeSourceFile;
if (symbol_name == NULL) {
add_nlist = false;
if (N_SO_index != UINT32_MAX) {
// Set the size of the N_SO to the terminating
// index of this N_SO so that we can always skip
// the entire N_SO if we need to navigate more
// quickly at the source level when parsing STABS
symbol_ptr = symtab->SymbolAtIndex(N_SO_index);
symbol_ptr->SetByteSize(sym_idx);
symbol_ptr->SetSizeIsSibling(true);
}
N_NSYM_indexes.clear();
N_INCL_indexes.clear();
N_BRAC_indexes.clear();
N_COMM_indexes.clear();
N_FUN_indexes.clear();
N_SO_index = UINT32_MAX;
} else {
// We use the current number of symbols in the
// symbol table in lieu of using nlist_idx in case
// we ever start trimming entries out
const bool N_SO_has_full_path = symbol_name[0] == '/';
if (N_SO_has_full_path) {
if ((N_SO_index == sym_idx - 1) &&
((sym_idx - 1) < num_syms)) {
// We have two consecutive N_SO entries where
// the first contains a directory and the
// second contains a full path.
sym[sym_idx - 1].GetMangled().SetValue(
ConstString(symbol_name), false);
m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
add_nlist = false;
} else {
// This is the first entry in a N_SO that
// contains a directory or
// a full path to the source file
N_SO_index = sym_idx;
}
} else if ((N_SO_index == sym_idx - 1) &&
((sym_idx - 1) < num_syms)) {
// This is usually the second N_SO entry that
// contains just the filename, so here we combine
// it with the first one if we are minimizing the
// symbol table
const char *so_path =
sym[sym_idx - 1]
.GetMangled()
.GetDemangledName(
lldb::eLanguageTypeUnknown)
.AsCString();
if (so_path && so_path[0]) {
std::string full_so_path(so_path);
const size_t double_slash_pos =
full_so_path.find("//");
if (double_slash_pos != std::string::npos) {
// The linker has been generating bad N_SO
// entries with doubled up paths
// in the format "%s%s" where the first
// string in the DW_AT_comp_dir, and the
// second is the directory for the source
// file so you end up with a path that looks
// like "/tmp/src//tmp/src/"
FileSpec so_dir(so_path);
if (!FileSystem::Instance().Exists(so_dir)) {
so_dir.SetFile(
&full_so_path[double_slash_pos + 1],
FileSpec::Style::native);
if (FileSystem::Instance().Exists(so_dir)) {
// Trim off the incorrect path
full_so_path.erase(0, double_slash_pos + 1);
}
}
}
if (*full_so_path.rbegin() != '/')
full_so_path += '/';
full_so_path += symbol_name;
sym[sym_idx - 1].GetMangled().SetValue(
ConstString(full_so_path.c_str()), false);
add_nlist = false;
m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
}
} else {
// This could be a relative path to a N_SO
N_SO_index = sym_idx;
}
}
break;
case N_OSO:
// object file name: name,,0,0,st_mtime
type = eSymbolTypeObjectFile;
break;
case N_LSYM:
// local sym: name,,NO_SECT,type,offset
type = eSymbolTypeLocal;
break;
// INCL scopes
case N_BINCL:
// include file beginning: name,,NO_SECT,0,sum We use
// the current number of symbols in the symbol table
// in lieu of using nlist_idx in case we ever start
// trimming entries out
N_INCL_indexes.push_back(sym_idx);
type = eSymbolTypeScopeBegin;
break;
case N_EINCL:
// include file end: name,,NO_SECT,0,0
// Set the size of the N_BINCL to the terminating
// index of this N_EINCL so that we can always skip
// the entire symbol if we need to navigate more
// quickly at the source level when parsing STABS
if (!N_INCL_indexes.empty()) {
symbol_ptr =
symtab->SymbolAtIndex(N_INCL_indexes.back());
symbol_ptr->SetByteSize(sym_idx + 1);
symbol_ptr->SetSizeIsSibling(true);
N_INCL_indexes.pop_back();
}
type = eSymbolTypeScopeEnd;
break;
case N_SOL:
// #included file name: name,,n_sect,0,address
type = eSymbolTypeHeaderFile;
// We currently don't use the header files on darwin
add_nlist = false;
break;
case N_PARAMS:
// compiler parameters: name,,NO_SECT,0,0
type = eSymbolTypeCompiler;
break;
case N_VERSION:
// compiler version: name,,NO_SECT,0,0
type = eSymbolTypeCompiler;
break;
case N_OLEVEL:
// compiler -O level: name,,NO_SECT,0,0
type = eSymbolTypeCompiler;
break;
case N_PSYM:
// parameter: name,,NO_SECT,type,offset
type = eSymbolTypeVariable;
break;
case N_ENTRY:
// alternate entry: name,,n_sect,linenumber,address
symbol_section = section_info.GetSection(nlist.n_sect,
nlist.n_value);
type = eSymbolTypeLineEntry;
break;
// Left and Right Braces
case N_LBRAC:
// left bracket: 0,,NO_SECT,nesting level,address We
// use the current number of symbols in the symbol
// table in lieu of using nlist_idx in case we ever
// start trimming entries out
symbol_section = section_info.GetSection(nlist.n_sect,
nlist.n_value);
N_BRAC_indexes.push_back(sym_idx);
type = eSymbolTypeScopeBegin;
break;
case N_RBRAC:
// right bracket: 0,,NO_SECT,nesting level,address
// Set the size of the N_LBRAC to the terminating
// index of this N_RBRAC so that we can always skip
// the entire symbol if we need to navigate more
// quickly at the source level when parsing STABS
symbol_section = section_info.GetSection(nlist.n_sect,
nlist.n_value);
if (!N_BRAC_indexes.empty()) {
symbol_ptr =
symtab->SymbolAtIndex(N_BRAC_indexes.back());
symbol_ptr->SetByteSize(sym_idx + 1);
symbol_ptr->SetSizeIsSibling(true);
N_BRAC_indexes.pop_back();
}
type = eSymbolTypeScopeEnd;
break;
case N_EXCL:
// deleted include file: name,,NO_SECT,0,sum
type = eSymbolTypeHeaderFile;
break;
// COMM scopes
case N_BCOMM:
// begin common: name,,NO_SECT,0,0
// We use the current number of symbols in the symbol
// table in lieu of using nlist_idx in case we ever
// start trimming entries out
type = eSymbolTypeScopeBegin;
N_COMM_indexes.push_back(sym_idx);
break;
case N_ECOML:
// end common (local name): 0,,n_sect,0,address
symbol_section = section_info.GetSection(nlist.n_sect,
nlist.n_value);
// Fall through
case N_ECOMM:
// end common: name,,n_sect,0,0
// Set the size of the N_BCOMM to the terminating
// index of this N_ECOMM/N_ECOML so that we can
// always skip the entire symbol if we need to
// navigate more quickly at the source level when
// parsing STABS
if (!N_COMM_indexes.empty()) {
symbol_ptr =
symtab->SymbolAtIndex(N_COMM_indexes.back());
symbol_ptr->SetByteSize(sym_idx + 1);
symbol_ptr->SetSizeIsSibling(true);
N_COMM_indexes.pop_back();
}
type = eSymbolTypeScopeEnd;
break;
case N_LENG:
// second stab entry with length information
type = eSymbolTypeAdditional;
break;
default:
break;
}
} else {
// uint8_t n_pext = N_PEXT & nlist.n_type;
uint8_t n_type = N_TYPE & nlist.n_type;
sym[sym_idx].SetExternal((N_EXT & nlist.n_type) != 0);
switch (n_type) {
case N_INDR: {
const char *reexport_name_cstr =
strtab_data.PeekCStr(nlist.n_value);
if (reexport_name_cstr && reexport_name_cstr[0]) {
type = eSymbolTypeReExported;
ConstString reexport_name(
reexport_name_cstr +
((reexport_name_cstr[0] == '_') ? 1 : 0));
sym[sym_idx].SetReExportedSymbolName(reexport_name);
set_value = false;
reexport_shlib_needs_fixup[sym_idx] = reexport_name;
indirect_symbol_names.insert(ConstString(
symbol_name + ((symbol_name[0] == '_') ? 1 : 0)));
} else
type = eSymbolTypeUndefined;
} break;
case N_UNDF:
if (symbol_name && symbol_name[0]) {
ConstString undefined_name(
symbol_name + ((symbol_name[0] == '_') ? 1 : 0));
undefined_name_to_desc[undefined_name] = nlist.n_desc;
}
// Fall through
case N_PBUD:
type = eSymbolTypeUndefined;
break;
case N_ABS:
type = eSymbolTypeAbsolute;
break;
case N_SECT: {
symbol_section = section_info.GetSection(nlist.n_sect,
nlist.n_value);
if (symbol_section == NULL) {
// TODO: warn about this?
add_nlist = false;
break;
}
if (TEXT_eh_frame_sectID == nlist.n_sect) {
type = eSymbolTypeException;
} else {
uint32_t section_type =
symbol_section->Get() & SECTION_TYPE;
switch (section_type) {
case S_CSTRING_LITERALS:
type = eSymbolTypeData;
break; // section with only literal C strings
case S_4BYTE_LITERALS:
type = eSymbolTypeData;
break; // section with only 4 byte literals
case S_8BYTE_LITERALS:
type = eSymbolTypeData;
break; // section with only 8 byte literals
case S_LITERAL_POINTERS:
type = eSymbolTypeTrampoline;
break; // section with only pointers to literals
case S_NON_LAZY_SYMBOL_POINTERS:
type = eSymbolTypeTrampoline;
break; // section with only non-lazy symbol
// pointers
case S_LAZY_SYMBOL_POINTERS:
type = eSymbolTypeTrampoline;
break; // section with only lazy symbol pointers
case S_SYMBOL_STUBS:
type = eSymbolTypeTrampoline;
break; // section with only symbol stubs, byte
// size of stub in the reserved2 field
case S_MOD_INIT_FUNC_POINTERS:
type = eSymbolTypeCode;
break; // section with only function pointers for
// initialization
case S_MOD_TERM_FUNC_POINTERS:
type = eSymbolTypeCode;
break; // section with only function pointers for
// termination
case S_INTERPOSING:
type = eSymbolTypeTrampoline;
break; // section with only pairs of function
// pointers for interposing
case S_16BYTE_LITERALS:
type = eSymbolTypeData;
break; // section with only 16 byte literals
case S_DTRACE_DOF:
type = eSymbolTypeInstrumentation;
break;
case S_LAZY_DYLIB_SYMBOL_POINTERS:
type = eSymbolTypeTrampoline;
break;
default:
switch (symbol_section->GetType()) {
case lldb::eSectionTypeCode:
type = eSymbolTypeCode;
break;
case eSectionTypeData:
case eSectionTypeDataCString: // Inlined C string
// data
case eSectionTypeDataCStringPointers: // Pointers
// to C
// string
// data
case eSectionTypeDataSymbolAddress: // Address of
// a symbol in
// the symbol
// table
case eSectionTypeData4:
case eSectionTypeData8:
case eSectionTypeData16:
type = eSymbolTypeData;
break;
default:
break;
}
break;
}
if (type == eSymbolTypeInvalid) {
const char *symbol_sect_name =
symbol_section->GetName().AsCString();
if (symbol_section->IsDescendant(
text_section_sp.get())) {
if (symbol_section->IsClear(
S_ATTR_PURE_INSTRUCTIONS |
S_ATTR_SELF_MODIFYING_CODE |
S_ATTR_SOME_INSTRUCTIONS))
type = eSymbolTypeData;
else
type = eSymbolTypeCode;
} else if (symbol_section->IsDescendant(
data_section_sp.get()) ||
symbol_section->IsDescendant(
data_dirty_section_sp.get()) ||
symbol_section->IsDescendant(
data_const_section_sp.get())) {
if (symbol_sect_name &&
::strstr(symbol_sect_name, "__objc") ==
symbol_sect_name) {
type = eSymbolTypeRuntime;
if (symbol_name) {
llvm::StringRef symbol_name_ref(symbol_name);
if (symbol_name_ref.startswith("_OBJC_")) {
llvm::StringRef
g_objc_v2_prefix_class(
"_OBJC_CLASS_$_");
llvm::StringRef
g_objc_v2_prefix_metaclass(
"_OBJC_METACLASS_$_");
llvm::StringRef
g_objc_v2_prefix_ivar("_OBJC_IVAR_$_");
if (symbol_name_ref.startswith(
g_objc_v2_prefix_class)) {
symbol_name_non_abi_mangled =
symbol_name + 1;
symbol_name =
symbol_name +
g_objc_v2_prefix_class.size();
type = eSymbolTypeObjCClass;
demangled_is_synthesized = true;
} else if (
symbol_name_ref.startswith(
g_objc_v2_prefix_metaclass)) {
symbol_name_non_abi_mangled =
symbol_name + 1;
symbol_name =
symbol_name +
g_objc_v2_prefix_metaclass.size();
type = eSymbolTypeObjCMetaClass;
demangled_is_synthesized = true;
} else if (symbol_name_ref.startswith(
g_objc_v2_prefix_ivar)) {
symbol_name_non_abi_mangled =
symbol_name + 1;
symbol_name =
symbol_name +
g_objc_v2_prefix_ivar.size();
type = eSymbolTypeObjCIVar;
demangled_is_synthesized = true;
}
}
}
} else if (symbol_sect_name &&
::strstr(symbol_sect_name,
"__gcc_except_tab") ==
symbol_sect_name) {
type = eSymbolTypeException;
} else {
type = eSymbolTypeData;
}
} else if (symbol_sect_name &&
::strstr(symbol_sect_name, "__IMPORT") ==
symbol_sect_name) {
type = eSymbolTypeTrampoline;
} else if (symbol_section->IsDescendant(
objc_section_sp.get())) {
type = eSymbolTypeRuntime;
if (symbol_name && symbol_name[0] == '.') {
llvm::StringRef symbol_name_ref(symbol_name);
llvm::StringRef
g_objc_v1_prefix_class(".objc_class_name_");
if (symbol_name_ref.startswith(
g_objc_v1_prefix_class)) {
symbol_name_non_abi_mangled = symbol_name;
symbol_name = symbol_name +
g_objc_v1_prefix_class.size();
type = eSymbolTypeObjCClass;
demangled_is_synthesized = true;
}
}
}
}
}
} break;
}
}
if (add_nlist) {
uint64_t symbol_value = nlist.n_value;
if (symbol_name_non_abi_mangled) {
sym[sym_idx].GetMangled().SetMangledName(
ConstString(symbol_name_non_abi_mangled));
sym[sym_idx].GetMangled().SetDemangledName(
ConstString(symbol_name));
} else {
bool symbol_name_is_mangled = false;
if (symbol_name && symbol_name[0] == '_') {
symbol_name_is_mangled = symbol_name[1] == '_';
symbol_name++; // Skip the leading underscore
}
if (symbol_name) {
ConstString const_symbol_name(symbol_name);
sym[sym_idx].GetMangled().SetValue(
const_symbol_name, symbol_name_is_mangled);
if (is_gsym && is_debug) {
const char *gsym_name =
sym[sym_idx]
.GetMangled()
.GetName(lldb::eLanguageTypeUnknown,
Mangled::ePreferMangled)
.GetCString();
if (gsym_name)
N_GSYM_name_to_sym_idx[gsym_name] = sym_idx;
}
}
}
if (symbol_section) {
const addr_t section_file_addr =
symbol_section->GetFileAddress();
if (symbol_byte_size == 0 &&
function_starts_count > 0) {
addr_t symbol_lookup_file_addr = nlist.n_value;
// Do an exact address match for non-ARM addresses,
// else get the closest since the symbol might be a
// thumb symbol which has an address with bit zero
// set
FunctionStarts::Entry *func_start_entry =
function_starts.FindEntry(symbol_lookup_file_addr,
!is_arm);
if (is_arm && func_start_entry) {
// Verify that the function start address is the
// symbol address (ARM) or the symbol address + 1
// (thumb)
if (func_start_entry->addr !=
symbol_lookup_file_addr &&
func_start_entry->addr !=
(symbol_lookup_file_addr + 1)) {
// Not the right entry, NULL it out...
func_start_entry = NULL;
}
}
if (func_start_entry) {
func_start_entry->data = true;
addr_t symbol_file_addr = func_start_entry->addr;
uint32_t symbol_flags = 0;
if (is_arm) {
if (symbol_file_addr & 1)
symbol_flags = MACHO_NLIST_ARM_SYMBOL_IS_THUMB;
symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
}
const FunctionStarts::Entry *next_func_start_entry =
function_starts.FindNextEntry(func_start_entry);
const addr_t section_end_file_addr =
section_file_addr +
symbol_section->GetByteSize();
if (next_func_start_entry) {
addr_t next_symbol_file_addr =
next_func_start_entry->addr;
// Be sure the clear the Thumb address bit when
// we calculate the size from the current and
// next address
if (is_arm)
next_symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
symbol_byte_size = std::min<lldb::addr_t>(
next_symbol_file_addr - symbol_file_addr,
section_end_file_addr - symbol_file_addr);
} else {
symbol_byte_size =
section_end_file_addr - symbol_file_addr;
}
}
}
symbol_value -= section_file_addr;
}
if (is_debug == false) {
if (type == eSymbolTypeCode) {
// See if we can find a N_FUN entry for any code
// symbols. If we do find a match, and the name
// matches, then we can merge the two into just the
// function symbol to avoid duplicate entries in
// the symbol table
auto range =
N_FUN_addr_to_sym_idx.equal_range(nlist.n_value);
if (range.first != range.second) {
bool found_it = false;
for (const auto pos = range.first;
pos != range.second; ++pos) {
if (sym[sym_idx].GetMangled().GetName(
lldb::eLanguageTypeUnknown,
Mangled::ePreferMangled) ==
sym[pos->second].GetMangled().GetName(
lldb::eLanguageTypeUnknown,
Mangled::ePreferMangled)) {
m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
// We just need the flags from the linker
// symbol, so put these flags
// into the N_FUN flags to avoid duplicate
// symbols in the symbol table
sym[pos->second].SetExternal(
sym[sym_idx].IsExternal());
sym[pos->second].SetFlags(nlist.n_type << 16 |
nlist.n_desc);
if (resolver_addresses.find(nlist.n_value) !=
resolver_addresses.end())
sym[pos->second].SetType(eSymbolTypeResolver);
sym[sym_idx].Clear();
found_it = true;
break;
}
}
if (found_it)
continue;
} else {
if (resolver_addresses.find(nlist.n_value) !=
resolver_addresses.end())
type = eSymbolTypeResolver;
}
} else if (type == eSymbolTypeData ||
type == eSymbolTypeObjCClass ||
type == eSymbolTypeObjCMetaClass ||
type == eSymbolTypeObjCIVar) {
// See if we can find a N_STSYM entry for any data
// symbols. If we do find a match, and the name
// matches, then we can merge the two into just the
// Static symbol to avoid duplicate entries in the
// symbol table
auto range = N_STSYM_addr_to_sym_idx.equal_range(
nlist.n_value);
if (range.first != range.second) {
bool found_it = false;
for (const auto pos = range.first;
pos != range.second; ++pos) {
if (sym[sym_idx].GetMangled().GetName(
lldb::eLanguageTypeUnknown,
Mangled::ePreferMangled) ==
sym[pos->second].GetMangled().GetName(
lldb::eLanguageTypeUnknown,
Mangled::ePreferMangled)) {
m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
// We just need the flags from the linker
// symbol, so put these flags
// into the N_STSYM flags to avoid duplicate
// symbols in the symbol table
sym[pos->second].SetExternal(
sym[sym_idx].IsExternal());
sym[pos->second].SetFlags(nlist.n_type << 16 |
nlist.n_desc);
sym[sym_idx].Clear();
found_it = true;
break;
}
}
if (found_it)
continue;
} else {
const char *gsym_name =
sym[sym_idx]
.GetMangled()
.GetName(lldb::eLanguageTypeUnknown,
Mangled::ePreferMangled)
.GetCString();
if (gsym_name) {
// Combine N_GSYM stab entries with the non
// stab symbol
ConstNameToSymbolIndexMap::const_iterator pos =
N_GSYM_name_to_sym_idx.find(gsym_name);
if (pos != N_GSYM_name_to_sym_idx.end()) {
const uint32_t GSYM_sym_idx = pos->second;
m_nlist_idx_to_sym_idx[nlist_idx] =
GSYM_sym_idx;
// Copy the address, because often the N_GSYM
// address has an invalid address of zero
// when the global is a common symbol
sym[GSYM_sym_idx].GetAddressRef().SetSection(
symbol_section);
sym[GSYM_sym_idx].GetAddressRef().SetOffset(
symbol_value);
// We just need the flags from the linker
// symbol, so put these flags
// into the N_GSYM flags to avoid duplicate
// symbols in the symbol table
sym[GSYM_sym_idx].SetFlags(nlist.n_type << 16 |
nlist.n_desc);
sym[sym_idx].Clear();
continue;
}
}
}
}
}
sym[sym_idx].SetID(nlist_idx);
sym[sym_idx].SetType(type);
if (set_value) {
sym[sym_idx].GetAddressRef().SetSection(symbol_section);
sym[sym_idx].GetAddressRef().SetOffset(symbol_value);
}
sym[sym_idx].SetFlags(nlist.n_type << 16 | nlist.n_desc);
if (symbol_byte_size > 0)
sym[sym_idx].SetByteSize(symbol_byte_size);
if (demangled_is_synthesized)
sym[sym_idx].SetDemangledNameIsSynthesized(true);
++sym_idx;
} else {
sym[sym_idx].Clear();
}
}
/////////////////////////////
}
break; // No more entries to consider
}
}
for (const auto &pos : reexport_shlib_needs_fixup) {
const auto undef_pos = undefined_name_to_desc.find(pos.second);
if (undef_pos != undefined_name_to_desc.end()) {
const uint8_t dylib_ordinal =
llvm::MachO::GET_LIBRARY_ORDINAL(undef_pos->second);
if (dylib_ordinal > 0 && dylib_ordinal < dylib_files.GetSize())
sym[pos.first].SetReExportedSymbolSharedLibrary(
dylib_files.GetFileSpecAtIndex(dylib_ordinal - 1));
}
}
}
}
}
}
}
// Must reset this in case it was mutated above!
nlist_data_offset = 0;
#endif
if (nlist_data.GetByteSize() > 0) {
// If the sym array was not created while parsing the DSC unmapped
// symbols, create it now.
if (sym == nullptr) {
sym =
symtab->Resize(symtab_load_command.nsyms + m_dysymtab.nindirectsyms);
num_syms = symtab->GetNumSymbols();
}
if (unmapped_local_symbols_found) {
assert(m_dysymtab.ilocalsym == 0);
nlist_data_offset += (m_dysymtab.nlocalsym * nlist_byte_size);
nlist_idx = m_dysymtab.nlocalsym;
} else {
nlist_idx = 0;
}
typedef llvm::DenseMap<ConstString, uint16_t> UndefinedNameToDescMap;
typedef llvm::DenseMap<uint32_t, ConstString> SymbolIndexToName;
UndefinedNameToDescMap undefined_name_to_desc;
SymbolIndexToName reexport_shlib_needs_fixup;
// Symtab parsing is a huge mess. Everything is entangled and the code
// requires access to a ridiculous amount of variables. LLDB depends
// heavily on the proper merging of symbols and to get that right we need
// to make sure we have parsed all the debug symbols first. Therefore we
// invoke the lambda twice, once to parse only the debug symbols and then
// once more to parse the remaining symbols.
auto ParseSymbolLambda = [&](struct nlist_64 &nlist, uint32_t nlist_idx,
bool debug_only) {
const bool is_debug = ((nlist.n_type & N_STAB) != 0);
if (is_debug != debug_only)
return true;
const char *symbol_name_non_abi_mangled = nullptr;
const char *symbol_name = nullptr;
if (have_strtab_data) {
symbol_name = strtab_data.PeekCStr(nlist.n_strx);
if (symbol_name == nullptr) {
// No symbol should be NULL, even the symbols with no string values
// should have an offset zero which points to an empty C-string
Host::SystemLog(Host::eSystemLogError,
"error: symbol[%u] has invalid string table offset "
"0x%x in %s, ignoring symbol\n",
nlist_idx, nlist.n_strx,
module_sp->GetFileSpec().GetPath().c_str());
return true;
}
if (symbol_name[0] == '\0')
symbol_name = nullptr;
} else {
const addr_t str_addr = strtab_addr + nlist.n_strx;
Status str_error;
if (process->ReadCStringFromMemory(str_addr, memory_symbol_name,
str_error))
symbol_name = memory_symbol_name.c_str();
}
SymbolType type = eSymbolTypeInvalid;
SectionSP symbol_section;
lldb::addr_t symbol_byte_size = 0;
bool add_nlist = true;
bool is_gsym = false;
bool demangled_is_synthesized = false;
bool set_value = true;
assert(sym_idx < num_syms);
sym[sym_idx].SetDebug(is_debug);
if (is_debug) {
switch (nlist.n_type) {
case N_GSYM:
// global symbol: name,,NO_SECT,type,0
// Sometimes the N_GSYM value contains the address.
// FIXME: In the .o files, we have a GSYM and a debug symbol for all
// the ObjC data. They
// have the same address, but we want to ensure that we always find
// only the real symbol, 'cause we don't currently correctly
// attribute the GSYM one to the ObjCClass/Ivar/MetaClass symbol
// type. This is a temporary hack to make sure the ObjectiveC
// symbols get treated correctly. To do this right, we should
// coalesce all the GSYM & global symbols that have the same
// address.
is_gsym = true;
sym[sym_idx].SetExternal(true);
if (symbol_name && symbol_name[0] == '_' && symbol_name[1] == 'O') {
llvm::StringRef symbol_name_ref(symbol_name);
if (symbol_name_ref.startswith(g_objc_v2_prefix_class)) {
symbol_name_non_abi_mangled = symbol_name + 1;
symbol_name = symbol_name + g_objc_v2_prefix_class.size();
type = eSymbolTypeObjCClass;
demangled_is_synthesized = true;
} else if (symbol_name_ref.startswith(g_objc_v2_prefix_metaclass)) {
symbol_name_non_abi_mangled = symbol_name + 1;
symbol_name = symbol_name + g_objc_v2_prefix_metaclass.size();
type = eSymbolTypeObjCMetaClass;
demangled_is_synthesized = true;
} else if (symbol_name_ref.startswith(g_objc_v2_prefix_ivar)) {
symbol_name_non_abi_mangled = symbol_name + 1;
symbol_name = symbol_name + g_objc_v2_prefix_ivar.size();
type = eSymbolTypeObjCIVar;
demangled_is_synthesized = true;
}
} else {
if (nlist.n_value != 0)
symbol_section =
section_info.GetSection(nlist.n_sect, nlist.n_value);
type = eSymbolTypeData;
}
break;
case N_FNAME:
// procedure name (f77 kludge): name,,NO_SECT,0,0
type = eSymbolTypeCompiler;
break;
case N_FUN:
// procedure: name,,n_sect,linenumber,address
if (symbol_name) {
type = eSymbolTypeCode;
symbol_section =
section_info.GetSection(nlist.n_sect, nlist.n_value);
N_FUN_addr_to_sym_idx.insert(
std::make_pair(nlist.n_value, sym_idx));
// We use the current number of symbols in the symbol table in
// lieu of using nlist_idx in case we ever start trimming entries
// out
N_FUN_indexes.push_back(sym_idx);
} else {
type = eSymbolTypeCompiler;
if (!N_FUN_indexes.empty()) {
// Copy the size of the function into the original STAB entry
// so we don't have to hunt for it later
symtab->SymbolAtIndex(N_FUN_indexes.back())
->SetByteSize(nlist.n_value);
N_FUN_indexes.pop_back();
// We don't really need the end function STAB as it contains
// the size which we already placed with the original symbol,
// so don't add it if we want a minimal symbol table
add_nlist = false;
}
}
break;
case N_STSYM:
// static symbol: name,,n_sect,type,address
N_STSYM_addr_to_sym_idx.insert(
std::make_pair(nlist.n_value, sym_idx));
symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
if (symbol_name && symbol_name[0]) {
type = ObjectFile::GetSymbolTypeFromName(symbol_name + 1,
eSymbolTypeData);
}
break;
case N_LCSYM:
// .lcomm symbol: name,,n_sect,type,address
symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
type = eSymbolTypeCommonBlock;
break;
case N_BNSYM:
// We use the current number of symbols in the symbol table in lieu
// of using nlist_idx in case we ever start trimming entries out
// Skip these if we want minimal symbol tables
add_nlist = false;
break;
case N_ENSYM:
// Set the size of the N_BNSYM to the terminating index of this
// N_ENSYM so that we can always skip the entire symbol if we need
// to navigate more quickly at the source level when parsing STABS
// Skip these if we want minimal symbol tables
add_nlist = false;
break;
case N_OPT:
// emitted with gcc2_compiled and in gcc source
type = eSymbolTypeCompiler;
break;
case N_RSYM:
// register sym: name,,NO_SECT,type,register
type = eSymbolTypeVariable;
break;
case N_SLINE:
// src line: 0,,n_sect,linenumber,address
symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
type = eSymbolTypeLineEntry;
break;
case N_SSYM:
// structure elt: name,,NO_SECT,type,struct_offset
type = eSymbolTypeVariableType;
break;
case N_SO:
// source file name
type = eSymbolTypeSourceFile;
if (symbol_name == nullptr) {
add_nlist = false;
if (N_SO_index != UINT32_MAX) {
// Set the size of the N_SO to the terminating index of this
// N_SO so that we can always skip the entire N_SO if we need
// to navigate more quickly at the source level when parsing
// STABS
symbol_ptr = symtab->SymbolAtIndex(N_SO_index);
symbol_ptr->SetByteSize(sym_idx);
symbol_ptr->SetSizeIsSibling(true);
}
N_NSYM_indexes.clear();
N_INCL_indexes.clear();
N_BRAC_indexes.clear();
N_COMM_indexes.clear();
N_FUN_indexes.clear();
N_SO_index = UINT32_MAX;
} else {
// We use the current number of symbols in the symbol table in
// lieu of using nlist_idx in case we ever start trimming entries
// out
const bool N_SO_has_full_path = symbol_name[0] == '/';
if (N_SO_has_full_path) {
if ((N_SO_index == sym_idx - 1) && ((sym_idx - 1) < num_syms)) {
// We have two consecutive N_SO entries where the first
// contains a directory and the second contains a full path.
sym[sym_idx - 1].GetMangled().SetValue(ConstString(symbol_name),
false);
m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
add_nlist = false;
} else {
// This is the first entry in a N_SO that contains a
// directory or a full path to the source file
N_SO_index = sym_idx;
}
} else if ((N_SO_index == sym_idx - 1) &&
((sym_idx - 1) < num_syms)) {
// This is usually the second N_SO entry that contains just the
// filename, so here we combine it with the first one if we are
// minimizing the symbol table
const char *so_path =
sym[sym_idx - 1]
.GetMangled()
.GetDemangledName(lldb::eLanguageTypeUnknown)
.AsCString();
if (so_path && so_path[0]) {
std::string full_so_path(so_path);
const size_t double_slash_pos = full_so_path.find("//");
if (double_slash_pos != std::string::npos) {
// The linker has been generating bad N_SO entries with
// doubled up paths in the format "%s%s" where the first
// string in the DW_AT_comp_dir, and the second is the
// directory for the source file so you end up with a path
// that looks like "/tmp/src//tmp/src/"
FileSpec so_dir(so_path);
if (!FileSystem::Instance().Exists(so_dir)) {
so_dir.SetFile(&full_so_path[double_slash_pos + 1],
FileSpec::Style::native);
if (FileSystem::Instance().Exists(so_dir)) {
// Trim off the incorrect path
full_so_path.erase(0, double_slash_pos + 1);
}
}
}
if (*full_so_path.rbegin() != '/')
full_so_path += '/';
full_so_path += symbol_name;
sym[sym_idx - 1].GetMangled().SetValue(
ConstString(full_so_path.c_str()), false);
add_nlist = false;
m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
}
} else {
// This could be a relative path to a N_SO
N_SO_index = sym_idx;
}
}
break;
case N_OSO:
// object file name: name,,0,0,st_mtime
type = eSymbolTypeObjectFile;
break;
case N_LSYM:
// local sym: name,,NO_SECT,type,offset
type = eSymbolTypeLocal;
break;
// INCL scopes
case N_BINCL:
// include file beginning: name,,NO_SECT,0,sum We use the current
// number of symbols in the symbol table in lieu of using nlist_idx
// in case we ever start trimming entries out
N_INCL_indexes.push_back(sym_idx);
type = eSymbolTypeScopeBegin;
break;
case N_EINCL:
// include file end: name,,NO_SECT,0,0
// Set the size of the N_BINCL to the terminating index of this
// N_EINCL so that we can always skip the entire symbol if we need
// to navigate more quickly at the source level when parsing STABS
if (!N_INCL_indexes.empty()) {
symbol_ptr = symtab->SymbolAtIndex(N_INCL_indexes.back());
symbol_ptr->SetByteSize(sym_idx + 1);
symbol_ptr->SetSizeIsSibling(true);
N_INCL_indexes.pop_back();
}
type = eSymbolTypeScopeEnd;
break;
case N_SOL:
// #included file name: name,,n_sect,0,address
type = eSymbolTypeHeaderFile;
// We currently don't use the header files on darwin
add_nlist = false;
break;
case N_PARAMS:
// compiler parameters: name,,NO_SECT,0,0
type = eSymbolTypeCompiler;
break;
case N_VERSION:
// compiler version: name,,NO_SECT,0,0
type = eSymbolTypeCompiler;
break;
case N_OLEVEL:
// compiler -O level: name,,NO_SECT,0,0
type = eSymbolTypeCompiler;
break;
case N_PSYM:
// parameter: name,,NO_SECT,type,offset
type = eSymbolTypeVariable;
break;
case N_ENTRY:
// alternate entry: name,,n_sect,linenumber,address
symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
type = eSymbolTypeLineEntry;
break;
// Left and Right Braces
case N_LBRAC:
// left bracket: 0,,NO_SECT,nesting level,address We use the
// current number of symbols in the symbol table in lieu of using
// nlist_idx in case we ever start trimming entries out
symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
N_BRAC_indexes.push_back(sym_idx);
type = eSymbolTypeScopeBegin;
break;
case N_RBRAC:
// right bracket: 0,,NO_SECT,nesting level,address Set the size of
// the N_LBRAC to the terminating index of this N_RBRAC so that we
// can always skip the entire symbol if we need to navigate more
// quickly at the source level when parsing STABS
symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
if (!N_BRAC_indexes.empty()) {
symbol_ptr = symtab->SymbolAtIndex(N_BRAC_indexes.back());
symbol_ptr->SetByteSize(sym_idx + 1);
symbol_ptr->SetSizeIsSibling(true);
N_BRAC_indexes.pop_back();
}
type = eSymbolTypeScopeEnd;
break;
case N_EXCL:
// deleted include file: name,,NO_SECT,0,sum
type = eSymbolTypeHeaderFile;
break;
// COMM scopes
case N_BCOMM:
// begin common: name,,NO_SECT,0,0
// We use the current number of symbols in the symbol table in lieu
// of using nlist_idx in case we ever start trimming entries out
type = eSymbolTypeScopeBegin;
N_COMM_indexes.push_back(sym_idx);
break;
case N_ECOML:
// end common (local name): 0,,n_sect,0,address
symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
LLVM_FALLTHROUGH;
case N_ECOMM:
// end common: name,,n_sect,0,0
// Set the size of the N_BCOMM to the terminating index of this
// N_ECOMM/N_ECOML so that we can always skip the entire symbol if
// we need to navigate more quickly at the source level when
// parsing STABS
if (!N_COMM_indexes.empty()) {
symbol_ptr = symtab->SymbolAtIndex(N_COMM_indexes.back());
symbol_ptr->SetByteSize(sym_idx + 1);
symbol_ptr->SetSizeIsSibling(true);
N_COMM_indexes.pop_back();
}
type = eSymbolTypeScopeEnd;
break;
case N_LENG:
// second stab entry with length information
type = eSymbolTypeAdditional;
break;
default:
break;
}
} else {
uint8_t n_type = N_TYPE & nlist.n_type;
sym[sym_idx].SetExternal((N_EXT & nlist.n_type) != 0);
switch (n_type) {
case N_INDR: {
const char *reexport_name_cstr = strtab_data.PeekCStr(nlist.n_value);
if (reexport_name_cstr && reexport_name_cstr[0]) {
type = eSymbolTypeReExported;
ConstString reexport_name(reexport_name_cstr +
((reexport_name_cstr[0] == '_') ? 1 : 0));
sym[sym_idx].SetReExportedSymbolName(reexport_name);
set_value = false;
reexport_shlib_needs_fixup[sym_idx] = reexport_name;
indirect_symbol_names.insert(
ConstString(symbol_name + ((symbol_name[0] == '_') ? 1 : 0)));
} else
type = eSymbolTypeUndefined;
} break;
case N_UNDF:
if (symbol_name && symbol_name[0]) {
ConstString undefined_name(symbol_name +
((symbol_name[0] == '_') ? 1 : 0));
undefined_name_to_desc[undefined_name] = nlist.n_desc;
}
LLVM_FALLTHROUGH;
case N_PBUD:
type = eSymbolTypeUndefined;
break;
case N_ABS:
type = eSymbolTypeAbsolute;
break;
case N_SECT: {
symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
if (!symbol_section) {
// TODO: warn about this?
add_nlist = false;
break;
}
if (TEXT_eh_frame_sectID == nlist.n_sect) {
type = eSymbolTypeException;
} else {
uint32_t section_type = symbol_section->Get() & SECTION_TYPE;
switch (section_type) {
case S_CSTRING_LITERALS:
type = eSymbolTypeData;
break; // section with only literal C strings
case S_4BYTE_LITERALS:
type = eSymbolTypeData;
break; // section with only 4 byte literals
case S_8BYTE_LITERALS:
type = eSymbolTypeData;
break; // section with only 8 byte literals
case S_LITERAL_POINTERS:
type = eSymbolTypeTrampoline;
break; // section with only pointers to literals
case S_NON_LAZY_SYMBOL_POINTERS:
type = eSymbolTypeTrampoline;
break; // section with only non-lazy symbol pointers
case S_LAZY_SYMBOL_POINTERS:
type = eSymbolTypeTrampoline;
break; // section with only lazy symbol pointers
case S_SYMBOL_STUBS:
type = eSymbolTypeTrampoline;
break; // section with only symbol stubs, byte size of stub in
// the reserved2 field
case S_MOD_INIT_FUNC_POINTERS:
type = eSymbolTypeCode;
break; // section with only function pointers for initialization
case S_MOD_TERM_FUNC_POINTERS:
type = eSymbolTypeCode;
break; // section with only function pointers for termination
case S_INTERPOSING:
type = eSymbolTypeTrampoline;
break; // section with only pairs of function pointers for
// interposing
case S_16BYTE_LITERALS:
type = eSymbolTypeData;
break; // section with only 16 byte literals
case S_DTRACE_DOF:
type = eSymbolTypeInstrumentation;
break;
case S_LAZY_DYLIB_SYMBOL_POINTERS:
type = eSymbolTypeTrampoline;
break;
default:
switch (symbol_section->GetType()) {
case lldb::eSectionTypeCode:
type = eSymbolTypeCode;
break;
case eSectionTypeData:
case eSectionTypeDataCString: // Inlined C string data
case eSectionTypeDataCStringPointers: // Pointers to C string
// data
case eSectionTypeDataSymbolAddress: // Address of a symbol in
// the symbol table
case eSectionTypeData4:
case eSectionTypeData8:
case eSectionTypeData16:
type = eSymbolTypeData;
break;
default:
break;
}
break;
}
if (type == eSymbolTypeInvalid) {
const char *symbol_sect_name =
symbol_section->GetName().AsCString();
if (symbol_section->IsDescendant(text_section_sp.get())) {
if (symbol_section->IsClear(S_ATTR_PURE_INSTRUCTIONS |
S_ATTR_SELF_MODIFYING_CODE |
S_ATTR_SOME_INSTRUCTIONS))
type = eSymbolTypeData;
else
type = eSymbolTypeCode;
} else if (symbol_section->IsDescendant(data_section_sp.get()) ||
symbol_section->IsDescendant(
data_dirty_section_sp.get()) ||
symbol_section->IsDescendant(
data_const_section_sp.get())) {
if (symbol_sect_name &&
::strstr(symbol_sect_name, "__objc") == symbol_sect_name) {
type = eSymbolTypeRuntime;
if (symbol_name) {
llvm::StringRef symbol_name_ref(symbol_name);
if (symbol_name_ref.startswith("_OBJC_")) {
llvm::StringRef g_objc_v2_prefix_class(
"_OBJC_CLASS_$_");
llvm::StringRef g_objc_v2_prefix_metaclass(
"_OBJC_METACLASS_$_");
llvm::StringRef g_objc_v2_prefix_ivar(
"_OBJC_IVAR_$_");
if (symbol_name_ref.startswith(g_objc_v2_prefix_class)) {
symbol_name_non_abi_mangled = symbol_name + 1;
symbol_name =
symbol_name + g_objc_v2_prefix_class.size();
type = eSymbolTypeObjCClass;
demangled_is_synthesized = true;
} else if (symbol_name_ref.startswith(
g_objc_v2_prefix_metaclass)) {
symbol_name_non_abi_mangled = symbol_name + 1;
symbol_name =
symbol_name + g_objc_v2_prefix_metaclass.size();
type = eSymbolTypeObjCMetaClass;
demangled_is_synthesized = true;
} else if (symbol_name_ref.startswith(
g_objc_v2_prefix_ivar)) {
symbol_name_non_abi_mangled = symbol_name + 1;
symbol_name =
symbol_name + g_objc_v2_prefix_ivar.size();
type = eSymbolTypeObjCIVar;
demangled_is_synthesized = true;
}
}
}
} else if (symbol_sect_name &&
::strstr(symbol_sect_name, "__gcc_except_tab") ==
symbol_sect_name) {
type = eSymbolTypeException;
} else {
type = eSymbolTypeData;
}
} else if (symbol_sect_name &&
::strstr(symbol_sect_name, "__IMPORT") ==
symbol_sect_name) {
type = eSymbolTypeTrampoline;
} else if (symbol_section->IsDescendant(objc_section_sp.get())) {
type = eSymbolTypeRuntime;
if (symbol_name && symbol_name[0] == '.') {
llvm::StringRef symbol_name_ref(symbol_name);
llvm::StringRef g_objc_v1_prefix_class(
".objc_class_name_");
if (symbol_name_ref.startswith(g_objc_v1_prefix_class)) {
symbol_name_non_abi_mangled = symbol_name;
symbol_name = symbol_name + g_objc_v1_prefix_class.size();
type = eSymbolTypeObjCClass;
demangled_is_synthesized = true;
}
}
}
}
}
} break;
}
}
if (!add_nlist) {
sym[sym_idx].Clear();
return true;
}
uint64_t symbol_value = nlist.n_value;
if (symbol_name_non_abi_mangled) {
sym[sym_idx].GetMangled().SetMangledName(
ConstString(symbol_name_non_abi_mangled));
sym[sym_idx].GetMangled().SetDemangledName(ConstString(symbol_name));
} else {
bool symbol_name_is_mangled = false;
if (symbol_name && symbol_name[0] == '_') {
symbol_name_is_mangled = symbol_name[1] == '_';
symbol_name++; // Skip the leading underscore
}
if (symbol_name) {
ConstString const_symbol_name(symbol_name);
sym[sym_idx].GetMangled().SetValue(const_symbol_name,
symbol_name_is_mangled);
}
}
if (is_gsym) {
const char *gsym_name =
sym[sym_idx]
.GetMangled()
.GetName(lldb::eLanguageTypeUnknown, Mangled::ePreferMangled)
.GetCString();
if (gsym_name)
N_GSYM_name_to_sym_idx[gsym_name] = sym_idx;
}
if (symbol_section) {
const addr_t section_file_addr = symbol_section->GetFileAddress();
if (symbol_byte_size == 0 && function_starts_count > 0) {
addr_t symbol_lookup_file_addr = nlist.n_value;
// Do an exact address match for non-ARM addresses, else get the
// closest since the symbol might be a thumb symbol which has an
// address with bit zero set.
FunctionStarts::Entry *func_start_entry =
function_starts.FindEntry(symbol_lookup_file_addr, !is_arm);
if (is_arm && func_start_entry) {
// Verify that the function start address is the symbol address
// (ARM) or the symbol address + 1 (thumb).
if (func_start_entry->addr != symbol_lookup_file_addr &&
func_start_entry->addr != (symbol_lookup_file_addr + 1)) {
// Not the right entry, NULL it out...
func_start_entry = nullptr;
}
}
if (func_start_entry) {
func_start_entry->data = true;
addr_t symbol_file_addr = func_start_entry->addr;
if (is_arm)
symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
const FunctionStarts::Entry *next_func_start_entry =
function_starts.FindNextEntry(func_start_entry);
const addr_t section_end_file_addr =
section_file_addr + symbol_section->GetByteSize();
if (next_func_start_entry) {
addr_t next_symbol_file_addr = next_func_start_entry->addr;
// Be sure the clear the Thumb address bit when we calculate the
// size from the current and next address
if (is_arm)
next_symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
symbol_byte_size = std::min<lldb::addr_t>(
next_symbol_file_addr - symbol_file_addr,
section_end_file_addr - symbol_file_addr);
} else {
symbol_byte_size = section_end_file_addr - symbol_file_addr;
}
}
}
symbol_value -= section_file_addr;
}
if (!is_debug) {
if (type == eSymbolTypeCode) {
// See if we can find a N_FUN entry for any code symbols. If we do
// find a match, and the name matches, then we can merge the two into
// just the function symbol to avoid duplicate entries in the symbol
// table.
std::pair<ValueToSymbolIndexMap::const_iterator,
ValueToSymbolIndexMap::const_iterator>
range;
range = N_FUN_addr_to_sym_idx.equal_range(nlist.n_value);
if (range.first != range.second) {
for (ValueToSymbolIndexMap::const_iterator pos = range.first;
pos != range.second; ++pos) {
if (sym[sym_idx].GetMangled().GetName(lldb::eLanguageTypeUnknown,
Mangled::ePreferMangled) ==
sym[pos->second].GetMangled().GetName(
lldb::eLanguageTypeUnknown, Mangled::ePreferMangled)) {
m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
// We just need the flags from the linker symbol, so put these
// flags into the N_FUN flags to avoid duplicate symbols in the
// symbol table.
sym[pos->second].SetExternal(sym[sym_idx].IsExternal());
sym[pos->second].SetFlags(nlist.n_type << 16 | nlist.n_desc);
if (resolver_addresses.find(nlist.n_value) !=
resolver_addresses.end())
sym[pos->second].SetType(eSymbolTypeResolver);
sym[sym_idx].Clear();
return true;
}
}
} else {
if (resolver_addresses.find(nlist.n_value) !=
resolver_addresses.end())
type = eSymbolTypeResolver;
}
} else if (type == eSymbolTypeData || type == eSymbolTypeObjCClass ||
type == eSymbolTypeObjCMetaClass ||
type == eSymbolTypeObjCIVar) {
// See if we can find a N_STSYM entry for any data symbols. If we do
// find a match, and the name matches, then we can merge the two into
// just the Static symbol to avoid duplicate entries in the symbol
// table.
std::pair<ValueToSymbolIndexMap::const_iterator,
ValueToSymbolIndexMap::const_iterator>
range;
range = N_STSYM_addr_to_sym_idx.equal_range(nlist.n_value);
if (range.first != range.second) {
for (ValueToSymbolIndexMap::const_iterator pos = range.first;
pos != range.second; ++pos) {
if (sym[sym_idx].GetMangled().GetName(lldb::eLanguageTypeUnknown,
Mangled::ePreferMangled) ==
sym[pos->second].GetMangled().GetName(
lldb::eLanguageTypeUnknown, Mangled::ePreferMangled)) {
m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
// We just need the flags from the linker symbol, so put these
// flags into the N_STSYM flags to avoid duplicate symbols in
// the symbol table.
sym[pos->second].SetExternal(sym[sym_idx].IsExternal());
sym[pos->second].SetFlags(nlist.n_type << 16 | nlist.n_desc);
sym[sym_idx].Clear();
return true;
}
}
} else {
// Combine N_GSYM stab entries with the non stab symbol.
const char *gsym_name = sym[sym_idx]
.GetMangled()
.GetName(lldb::eLanguageTypeUnknown,
Mangled::ePreferMangled)
.GetCString();
if (gsym_name) {
ConstNameToSymbolIndexMap::const_iterator pos =
N_GSYM_name_to_sym_idx.find(gsym_name);
if (pos != N_GSYM_name_to_sym_idx.end()) {
const uint32_t GSYM_sym_idx = pos->second;
m_nlist_idx_to_sym_idx[nlist_idx] = GSYM_sym_idx;
// Copy the address, because often the N_GSYM address has an
// invalid address of zero when the global is a common symbol.
sym[GSYM_sym_idx].GetAddressRef().SetSection(symbol_section);
sym[GSYM_sym_idx].GetAddressRef().SetOffset(symbol_value);
// We just need the flags from the linker symbol, so put these
// flags into the N_GSYM flags to avoid duplicate symbols in
// the symbol table.
sym[GSYM_sym_idx].SetFlags(nlist.n_type << 16 | nlist.n_desc);
sym[sym_idx].Clear();
return true;
}
}
}
}
}
sym[sym_idx].SetID(nlist_idx);
sym[sym_idx].SetType(type);
if (set_value) {
sym[sym_idx].GetAddressRef().SetSection(symbol_section);
sym[sym_idx].GetAddressRef().SetOffset(symbol_value);
}
sym[sym_idx].SetFlags(nlist.n_type << 16 | nlist.n_desc);
if (nlist.n_desc & N_WEAK_REF)
sym[sym_idx].SetIsWeak(true);
if (symbol_byte_size > 0)
sym[sym_idx].SetByteSize(symbol_byte_size);
if (demangled_is_synthesized)
sym[sym_idx].SetDemangledNameIsSynthesized(true);
++sym_idx;
return true;
};
// First parse all the nlists but don't process them yet. See the next
// comment for an explanation why.
std::vector<struct nlist_64> nlists;
nlists.reserve(symtab_load_command.nsyms);
for (; nlist_idx < symtab_load_command.nsyms; ++nlist_idx) {
if (auto nlist =
ParseNList(nlist_data, nlist_data_offset, nlist_byte_size))
nlists.push_back(*nlist);
else
break;
}
// Now parse all the debug symbols. This is needed to merge non-debug
// symbols in the next step. Non-debug symbols are always coalesced into
// the debug symbol. Doing this in one step would mean that some symbols
// won't be merged.
nlist_idx = 0;
for (auto &nlist : nlists) {
if (!ParseSymbolLambda(nlist, nlist_idx++, DebugSymbols))
break;
}
// Finally parse all the non debug symbols.
nlist_idx = 0;
for (auto &nlist : nlists) {
if (!ParseSymbolLambda(nlist, nlist_idx++, NonDebugSymbols))
break;
}
for (const auto &pos : reexport_shlib_needs_fixup) {
const auto undef_pos = undefined_name_to_desc.find(pos.second);
if (undef_pos != undefined_name_to_desc.end()) {
const uint8_t dylib_ordinal =
llvm::MachO::GET_LIBRARY_ORDINAL(undef_pos->second);
if (dylib_ordinal > 0 && dylib_ordinal < dylib_files.GetSize())
sym[pos.first].SetReExportedSymbolSharedLibrary(
dylib_files.GetFileSpecAtIndex(dylib_ordinal - 1));
}
}
}
uint32_t synthetic_sym_id = symtab_load_command.nsyms;
if (function_starts_count > 0) {
uint32_t num_synthetic_function_symbols = 0;
for (i = 0; i < function_starts_count; ++i) {
if (!function_starts.GetEntryRef(i).data)
++num_synthetic_function_symbols;
}
if (num_synthetic_function_symbols > 0) {
if (num_syms < sym_idx + num_synthetic_function_symbols) {
num_syms = sym_idx + num_synthetic_function_symbols;
sym = symtab->Resize(num_syms);
}
for (i = 0; i < function_starts_count; ++i) {
const FunctionStarts::Entry *func_start_entry =
function_starts.GetEntryAtIndex(i);
if (!func_start_entry->data) {
addr_t symbol_file_addr = func_start_entry->addr;
uint32_t symbol_flags = 0;
if (is_arm) {
if (symbol_file_addr & 1)
symbol_flags = MACHO_NLIST_ARM_SYMBOL_IS_THUMB;
symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
}
Address symbol_addr;
if (module_sp->ResolveFileAddress(symbol_file_addr, symbol_addr)) {
SectionSP symbol_section(symbol_addr.GetSection());
uint32_t symbol_byte_size = 0;
if (symbol_section) {
const addr_t section_file_addr = symbol_section->GetFileAddress();
const FunctionStarts::Entry *next_func_start_entry =
function_starts.FindNextEntry(func_start_entry);
const addr_t section_end_file_addr =
section_file_addr + symbol_section->GetByteSize();
if (next_func_start_entry) {
addr_t next_symbol_file_addr = next_func_start_entry->addr;
if (is_arm)
next_symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
symbol_byte_size = std::min<lldb::addr_t>(
next_symbol_file_addr - symbol_file_addr,
section_end_file_addr - symbol_file_addr);
} else {
symbol_byte_size = section_end_file_addr - symbol_file_addr;
}
sym[sym_idx].SetID(synthetic_sym_id++);
sym[sym_idx].GetMangled().SetDemangledName(
GetNextSyntheticSymbolName());
sym[sym_idx].SetType(eSymbolTypeCode);
sym[sym_idx].SetIsSynthetic(true);
sym[sym_idx].GetAddressRef() = symbol_addr;
if (symbol_flags)
sym[sym_idx].SetFlags(symbol_flags);
if (symbol_byte_size)
sym[sym_idx].SetByteSize(symbol_byte_size);
++sym_idx;
}
}
}
}
}
}
// Trim our symbols down to just what we ended up with after removing any
// symbols.
if (sym_idx < num_syms) {
num_syms = sym_idx;
sym = symtab->Resize(num_syms);
}
// Now synthesize indirect symbols
if (m_dysymtab.nindirectsyms != 0) {
if (indirect_symbol_index_data.GetByteSize()) {
NListIndexToSymbolIndexMap::const_iterator end_index_pos =
m_nlist_idx_to_sym_idx.end();
for (uint32_t sect_idx = 1; sect_idx < m_mach_sections.size();
++sect_idx) {
if ((m_mach_sections[sect_idx].flags & SECTION_TYPE) ==
S_SYMBOL_STUBS) {
uint32_t symbol_stub_byte_size = m_mach_sections[sect_idx].reserved2;
if (symbol_stub_byte_size == 0)
continue;
const uint32_t num_symbol_stubs =
m_mach_sections[sect_idx].size / symbol_stub_byte_size;
if (num_symbol_stubs == 0)
continue;
const uint32_t symbol_stub_index_offset =
m_mach_sections[sect_idx].reserved1;
for (uint32_t stub_idx = 0; stub_idx < num_symbol_stubs; ++stub_idx) {
const uint32_t symbol_stub_index =
symbol_stub_index_offset + stub_idx;
const lldb::addr_t symbol_stub_addr =
m_mach_sections[sect_idx].addr +
(stub_idx * symbol_stub_byte_size);
lldb::offset_t symbol_stub_offset = symbol_stub_index * 4;
if (indirect_symbol_index_data.ValidOffsetForDataOfSize(
symbol_stub_offset, 4)) {
const uint32_t stub_sym_id =
indirect_symbol_index_data.GetU32(&symbol_stub_offset);
if (stub_sym_id & (INDIRECT_SYMBOL_ABS | INDIRECT_SYMBOL_LOCAL))
continue;
NListIndexToSymbolIndexMap::const_iterator index_pos =
m_nlist_idx_to_sym_idx.find(stub_sym_id);
Symbol *stub_symbol = nullptr;
if (index_pos != end_index_pos) {
// We have a remapping from the original nlist index to a
// current symbol index, so just look this up by index
stub_symbol = symtab->SymbolAtIndex(index_pos->second);
} else {
// We need to lookup a symbol using the original nlist symbol
// index since this index is coming from the S_SYMBOL_STUBS
stub_symbol = symtab->FindSymbolByID(stub_sym_id);
}
if (stub_symbol) {
Address so_addr(symbol_stub_addr, section_list);
if (stub_symbol->GetType() == eSymbolTypeUndefined) {
// Change the external symbol into a trampoline that makes
// sense These symbols were N_UNDF N_EXT, and are useless
// to us, so we can re-use them so we don't have to make up
// a synthetic symbol for no good reason.
if (resolver_addresses.find(symbol_stub_addr) ==
resolver_addresses.end())
stub_symbol->SetType(eSymbolTypeTrampoline);
else
stub_symbol->SetType(eSymbolTypeResolver);
stub_symbol->SetExternal(false);
stub_symbol->GetAddressRef() = so_addr;
stub_symbol->SetByteSize(symbol_stub_byte_size);
} else {
// Make a synthetic symbol to describe the trampoline stub
Mangled stub_symbol_mangled_name(stub_symbol->GetMangled());
if (sym_idx >= num_syms) {
sym = symtab->Resize(++num_syms);
stub_symbol = nullptr; // this pointer no longer valid
}
sym[sym_idx].SetID(synthetic_sym_id++);
sym[sym_idx].GetMangled() = stub_symbol_mangled_name;
if (resolver_addresses.find(symbol_stub_addr) ==
resolver_addresses.end())
sym[sym_idx].SetType(eSymbolTypeTrampoline);
else
sym[sym_idx].SetType(eSymbolTypeResolver);
sym[sym_idx].SetIsSynthetic(true);
sym[sym_idx].GetAddressRef() = so_addr;
sym[sym_idx].SetByteSize(symbol_stub_byte_size);
++sym_idx;
}
} else {
if (log)
log->Warning("symbol stub referencing symbol table symbol "
"%u that isn't in our minimal symbol table, "
"fix this!!!",
stub_sym_id);
}
}
}
}
}
}
}
if (!trie_entries.empty()) {
for (const auto &e : trie_entries) {
if (e.entry.import_name) {
// Only add indirect symbols from the Trie entries if we didn't have
// a N_INDR nlist entry for this already
if (indirect_symbol_names.find(e.entry.name) ==
indirect_symbol_names.end()) {
// Make a synthetic symbol to describe re-exported symbol.
if (sym_idx >= num_syms)
sym = symtab->Resize(++num_syms);
sym[sym_idx].SetID(synthetic_sym_id++);
sym[sym_idx].GetMangled() = Mangled(e.entry.name);
sym[sym_idx].SetType(eSymbolTypeReExported);
sym[sym_idx].SetIsSynthetic(true);
sym[sym_idx].SetReExportedSymbolName(e.entry.import_name);
if (e.entry.other > 0 && e.entry.other <= dylib_files.GetSize()) {
sym[sym_idx].SetReExportedSymbolSharedLibrary(
dylib_files.GetFileSpecAtIndex(e.entry.other - 1));
}
++sym_idx;
}
}
}
}
// StreamFile s(stdout, false);
// s.Printf ("Symbol table before CalculateSymbolSizes():\n");
// symtab->Dump(&s, NULL, eSortOrderNone);
// Set symbol byte sizes correctly since mach-o nlist entries don't have
// sizes
symtab->CalculateSymbolSizes();
// s.Printf ("Symbol table after CalculateSymbolSizes():\n");
// symtab->Dump(&s, NULL, eSortOrderNone);
return symtab->GetNumSymbols();
}
void ObjectFileMachO::Dump(Stream *s) {
ModuleSP module_sp(GetModule());
if (module_sp) {
std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
s->Printf("%p: ", static_cast<void *>(this));
s->Indent();
if (m_header.magic == MH_MAGIC_64 || m_header.magic == MH_CIGAM_64)
s->PutCString("ObjectFileMachO64");
else
s->PutCString("ObjectFileMachO32");
*s << ", file = '" << m_file;
ModuleSpecList all_specs;
ModuleSpec base_spec;
GetAllArchSpecs(m_header, m_data, MachHeaderSizeFromMagic(m_header.magic),
base_spec, all_specs);
for (unsigned i = 0, e = all_specs.GetSize(); i != e; ++i) {
*s << "', triple";
if (e)
s->Printf("[%d]", i);
*s << " = ";
*s << all_specs.GetModuleSpecRefAtIndex(i)
.GetArchitecture()
.GetTriple()
.getTriple();
}
*s << "\n";
SectionList *sections = GetSectionList();
if (sections)
sections->Dump(s, nullptr, true, UINT32_MAX);
if (m_symtab_up)
m_symtab_up->Dump(s, nullptr, eSortOrderNone);
}
}
UUID ObjectFileMachO::GetUUID(const llvm::MachO::mach_header &header,
const lldb_private::DataExtractor &data,
lldb::offset_t lc_offset) {
uint32_t i;
struct uuid_command load_cmd;
lldb::offset_t offset = lc_offset;
for (i = 0; i < header.ncmds; ++i) {
const lldb::offset_t cmd_offset = offset;
if (data.GetU32(&offset, &load_cmd, 2) == nullptr)
break;
if (load_cmd.cmd == LC_UUID) {
const uint8_t *uuid_bytes = data.PeekData(offset, 16);
if (uuid_bytes) {
// OpenCL on Mac OS X uses the same UUID for each of its object files.
// We pretend these object files have no UUID to prevent crashing.
const uint8_t opencl_uuid[] = {0x8c, 0x8e, 0xb3, 0x9b, 0x3b, 0xa8,
0x4b, 0x16, 0xb6, 0xa4, 0x27, 0x63,
0xbb, 0x14, 0xf0, 0x0d};
if (!memcmp(uuid_bytes, opencl_uuid, 16))
return UUID();
return UUID::fromOptionalData(uuid_bytes, 16);
}
return UUID();
}
offset = cmd_offset + load_cmd.cmdsize;
}
return UUID();
}
static llvm::StringRef GetOSName(uint32_t cmd) {
switch (cmd) {
case llvm::MachO::LC_VERSION_MIN_IPHONEOS:
return llvm::Triple::getOSTypeName(llvm::Triple::IOS);
case llvm::MachO::LC_VERSION_MIN_MACOSX:
return llvm::Triple::getOSTypeName(llvm::Triple::MacOSX);
case llvm::MachO::LC_VERSION_MIN_TVOS:
return llvm::Triple::getOSTypeName(llvm::Triple::TvOS);
case llvm::MachO::LC_VERSION_MIN_WATCHOS:
return llvm::Triple::getOSTypeName(llvm::Triple::WatchOS);
default:
llvm_unreachable("unexpected LC_VERSION load command");
}
}
namespace {
struct OSEnv {
llvm::StringRef os_type;
llvm::StringRef environment;
OSEnv(uint32_t cmd) {
switch (cmd) {
case llvm::MachO::PLATFORM_MACOS:
os_type = llvm::Triple::getOSTypeName(llvm::Triple::MacOSX);
return;
case llvm::MachO::PLATFORM_IOS:
os_type = llvm::Triple::getOSTypeName(llvm::Triple::IOS);
return;
case llvm::MachO::PLATFORM_TVOS:
os_type = llvm::Triple::getOSTypeName(llvm::Triple::TvOS);
return;
case llvm::MachO::PLATFORM_WATCHOS:
os_type = llvm::Triple::getOSTypeName(llvm::Triple::WatchOS);
return;
// NEED_BRIDGEOS_TRIPLE case llvm::MachO::PLATFORM_BRIDGEOS:
// NEED_BRIDGEOS_TRIPLE os_type =
// llvm::Triple::getOSTypeName(llvm::Triple::BridgeOS);
// NEED_BRIDGEOS_TRIPLE return;
case llvm::MachO::PLATFORM_MACCATALYST:
os_type = llvm::Triple::getOSTypeName(llvm::Triple::IOS);
environment = llvm::Triple::getEnvironmentTypeName(llvm::Triple::MacABI);
return;
case llvm::MachO::PLATFORM_IOSSIMULATOR:
os_type = llvm::Triple::getOSTypeName(llvm::Triple::IOS);
environment =
llvm::Triple::getEnvironmentTypeName(llvm::Triple::Simulator);
return;
case llvm::MachO::PLATFORM_TVOSSIMULATOR:
os_type = llvm::Triple::getOSTypeName(llvm::Triple::TvOS);
environment =
llvm::Triple::getEnvironmentTypeName(llvm::Triple::Simulator);
return;
case llvm::MachO::PLATFORM_WATCHOSSIMULATOR:
os_type = llvm::Triple::getOSTypeName(llvm::Triple::WatchOS);
environment =
llvm::Triple::getEnvironmentTypeName(llvm::Triple::Simulator);
return;
default: {
Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS |
LIBLLDB_LOG_PROCESS));
LLDB_LOGF(log, "unsupported platform in LC_BUILD_VERSION");
}
}
}
};
struct MinOS {
uint32_t major_version, minor_version, patch_version;
MinOS(uint32_t version)
: major_version(version >> 16), minor_version((version >> 8) & 0xffu),
patch_version(version & 0xffu) {}
};
} // namespace
void ObjectFileMachO::GetAllArchSpecs(const llvm::MachO::mach_header &header,
const lldb_private::DataExtractor &data,
lldb::offset_t lc_offset,
ModuleSpec &base_spec,
lldb_private::ModuleSpecList &all_specs) {
auto &base_arch = base_spec.GetArchitecture();
base_arch.SetArchitecture(eArchTypeMachO, header.cputype, header.cpusubtype);
if (!base_arch.IsValid())
return;
bool found_any = false;
auto add_triple = [&](const llvm::Triple &triple) {
auto spec = base_spec;
spec.GetArchitecture().GetTriple() = triple;
if (spec.GetArchitecture().IsValid()) {
spec.GetUUID() = ObjectFileMachO::GetUUID(header, data, lc_offset);
all_specs.Append(spec);
found_any = true;
}
};
// Set OS to an unspecified unknown or a "*" so it can match any OS
llvm::Triple base_triple = base_arch.GetTriple();
base_triple.setOS(llvm::Triple::UnknownOS);
base_triple.setOSName(llvm::StringRef());
if (header.filetype == MH_PRELOAD) {
if (header.cputype == CPU_TYPE_ARM) {
// If this is a 32-bit arm binary, and it's a standalone binary, force
// the Vendor to Apple so we don't accidentally pick up the generic
// armv7 ABI at runtime. Apple's armv7 ABI always uses r7 for the
// frame pointer register; most other armv7 ABIs use a combination of
// r7 and r11.
base_triple.setVendor(llvm::Triple::Apple);
} else {
// Set vendor to an unspecified unknown or a "*" so it can match any
// vendor This is required for correct behavior of EFI debugging on
// x86_64
base_triple.setVendor(llvm::Triple::UnknownVendor);
base_triple.setVendorName(llvm::StringRef());
}
return add_triple(base_triple);
}
struct load_command load_cmd;
// See if there is an LC_VERSION_MIN_* load command that can give
// us the OS type.
lldb::offset_t offset = lc_offset;
for (uint32_t i = 0; i < header.ncmds; ++i) {
const lldb::offset_t cmd_offset = offset;
if (data.GetU32(&offset, &load_cmd, 2) == NULL)
break;
struct version_min_command version_min;
switch (load_cmd.cmd) {
case llvm::MachO::LC_VERSION_MIN_IPHONEOS:
case llvm::MachO::LC_VERSION_MIN_MACOSX:
case llvm::MachO::LC_VERSION_MIN_TVOS:
case llvm::MachO::LC_VERSION_MIN_WATCHOS: {
if (load_cmd.cmdsize != sizeof(version_min))
break;
if (data.ExtractBytes(cmd_offset, sizeof(version_min),
data.GetByteOrder(), &version_min) == 0)
break;
MinOS min_os(version_min.version);
llvm::SmallString<32> os_name;
llvm::raw_svector_ostream os(os_name);
os << GetOSName(load_cmd.cmd) << min_os.major_version << '.'
<< min_os.minor_version << '.' << min_os.patch_version;
auto triple = base_triple;
triple.setOSName(os.str());
os_name.clear();
add_triple(triple);
break;
}
default:
break;
}
offset = cmd_offset + load_cmd.cmdsize;
}
// See if there are LC_BUILD_VERSION load commands that can give
// us the OS type.
offset = lc_offset;
for (uint32_t i = 0; i < header.ncmds; ++i) {
const lldb::offset_t cmd_offset = offset;
if (data.GetU32(&offset, &load_cmd, 2) == NULL)
break;
do {
if (load_cmd.cmd == llvm::MachO::LC_BUILD_VERSION) {
struct build_version_command build_version;
if (load_cmd.cmdsize < sizeof(build_version)) {
// Malformed load command.
break;
}
if (data.ExtractBytes(cmd_offset, sizeof(build_version),
data.GetByteOrder(), &build_version) == 0)
break;
MinOS min_os(build_version.minos);
OSEnv os_env(build_version.platform);
llvm::SmallString<16> os_name;
llvm::raw_svector_ostream os(os_name);
os << os_env.os_type << min_os.major_version << '.'
<< min_os.minor_version << '.' << min_os.patch_version;
auto triple = base_triple;
triple.setOSName(os.str());
os_name.clear();
if (!os_env.environment.empty())
triple.setEnvironmentName(os_env.environment);
add_triple(triple);
}
} while (0);
offset = cmd_offset + load_cmd.cmdsize;
}
if (!found_any) {
if (header.filetype == MH_KEXT_BUNDLE) {
base_triple.setVendor(llvm::Triple::Apple);
add_triple(base_triple);
} else {
// We didn't find a LC_VERSION_MIN load command and this isn't a KEXT
// so lets not say our Vendor is Apple, leave it as an unspecified
// unknown.
base_triple.setVendor(llvm::Triple::UnknownVendor);
base_triple.setVendorName(llvm::StringRef());
add_triple(base_triple);
}
}
}
ArchSpec ObjectFileMachO::GetArchitecture(
ModuleSP module_sp, const llvm::MachO::mach_header &header,
const lldb_private::DataExtractor &data, lldb::offset_t lc_offset) {
ModuleSpecList all_specs;
ModuleSpec base_spec;
GetAllArchSpecs(header, data, MachHeaderSizeFromMagic(header.magic),
base_spec, all_specs);
// If the object file offers multiple alternative load commands,
// pick the one that matches the module.
if (module_sp) {
const ArchSpec &module_arch = module_sp->GetArchitecture();
for (unsigned i = 0, e = all_specs.GetSize(); i != e; ++i) {
ArchSpec mach_arch =
all_specs.GetModuleSpecRefAtIndex(i).GetArchitecture();
if (module_arch.IsCompatibleMatch(mach_arch))
return mach_arch;
}
}
// Return the first arch we found.
if (all_specs.GetSize() == 0)
return {};
return all_specs.GetModuleSpecRefAtIndex(0).GetArchitecture();
}
UUID ObjectFileMachO::GetUUID() {
ModuleSP module_sp(GetModule());
if (module_sp) {
std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
return GetUUID(m_header, m_data, offset);
}
return UUID();
}
uint32_t ObjectFileMachO::GetDependentModules(FileSpecList &files) {
uint32_t count = 0;
ModuleSP module_sp(GetModule());
if (module_sp) {
std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
struct load_command load_cmd;
lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
std::vector<std::string> rpath_paths;
std::vector<std::string> rpath_relative_paths;
std::vector<std::string> at_exec_relative_paths;
uint32_t i;
for (i = 0; i < m_header.ncmds; ++i) {
const uint32_t cmd_offset = offset;
if (m_data.GetU32(&offset, &load_cmd, 2) == nullptr)
break;
switch (load_cmd.cmd) {
case LC_RPATH:
case LC_LOAD_DYLIB:
case LC_LOAD_WEAK_DYLIB:
case LC_REEXPORT_DYLIB:
case LC_LOAD_DYLINKER:
case LC_LOADFVMLIB:
case LC_LOAD_UPWARD_DYLIB: {
uint32_t name_offset = cmd_offset + m_data.GetU32(&offset);
const char *path = m_data.PeekCStr(name_offset);
if (path) {
if (load_cmd.cmd == LC_RPATH)
rpath_paths.push_back(path);
else {
if (path[0] == '@') {
if (strncmp(path, "@rpath", strlen("@rpath")) == 0)
rpath_relative_paths.push_back(path + strlen("@rpath"));
else if (strncmp(path, "@executable_path",
strlen("@executable_path")) == 0)
at_exec_relative_paths.push_back(path +
strlen("@executable_path"));
} else {
FileSpec file_spec(path);
if (files.AppendIfUnique(file_spec))
count++;
}
}
}
} break;
default:
break;
}
offset = cmd_offset + load_cmd.cmdsize;
}
FileSpec this_file_spec(m_file);
FileSystem::Instance().Resolve(this_file_spec);
if (!rpath_paths.empty()) {
// Fixup all LC_RPATH values to be absolute paths
std::string loader_path("@loader_path");
std::string executable_path("@executable_path");
for (auto &rpath : rpath_paths) {
if (rpath.find(loader_path) == 0) {
rpath.erase(0, loader_path.size());
rpath.insert(0, this_file_spec.GetDirectory().GetCString());
} else if (rpath.find(executable_path) == 0) {
rpath.erase(0, executable_path.size());
rpath.insert(0, this_file_spec.GetDirectory().GetCString());
}
}
for (const auto &rpath_relative_path : rpath_relative_paths) {
for (const auto &rpath : rpath_paths) {
std::string path = rpath;
path += rpath_relative_path;
// It is OK to resolve this path because we must find a file on disk
// for us to accept it anyway if it is rpath relative.
FileSpec file_spec(path);
FileSystem::Instance().Resolve(file_spec);
if (FileSystem::Instance().Exists(file_spec) &&
files.AppendIfUnique(file_spec)) {
count++;
break;
}
}
}
}
// We may have @executable_paths but no RPATHS. Figure those out here.
// Only do this if this object file is the executable. We have no way to
// get back to the actual executable otherwise, so we won't get the right
// path.
if (!at_exec_relative_paths.empty() && CalculateType() == eTypeExecutable) {
FileSpec exec_dir = this_file_spec.CopyByRemovingLastPathComponent();
for (const auto &at_exec_relative_path : at_exec_relative_paths) {
FileSpec file_spec =
exec_dir.CopyByAppendingPathComponent(at_exec_relative_path);
if (FileSystem::Instance().Exists(file_spec) &&
files.AppendIfUnique(file_spec))
count++;
}
}
}
return count;
}
lldb_private::Address ObjectFileMachO::GetEntryPointAddress() {
// If the object file is not an executable it can't hold the entry point.
// m_entry_point_address is initialized to an invalid address, so we can just
// return that. If m_entry_point_address is valid it means we've found it
// already, so return the cached value.
if ((!IsExecutable() && !IsDynamicLoader()) ||
m_entry_point_address.IsValid()) {
return m_entry_point_address;
}
// Otherwise, look for the UnixThread or Thread command. The data for the
// Thread command is given in /usr/include/mach-o.h, but it is basically:
//
// uint32_t flavor - this is the flavor argument you would pass to
// thread_get_state
// uint32_t count - this is the count of longs in the thread state data
// struct XXX_thread_state state - this is the structure from
// <machine/thread_status.h> corresponding to the flavor.
// <repeat this trio>
//
// So we just keep reading the various register flavors till we find the GPR
// one, then read the PC out of there.
// FIXME: We will need to have a "RegisterContext data provider" class at some
// point that can get all the registers
// out of data in this form & attach them to a given thread. That should
// underlie the MacOS X User process plugin, and we'll also need it for the
// MacOS X Core File process plugin. When we have that we can also use it
// here.
//
// For now we hard-code the offsets and flavors we need:
//
//
ModuleSP module_sp(GetModule());
if (module_sp) {
std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
struct load_command load_cmd;
lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
uint32_t i;
lldb::addr_t start_address = LLDB_INVALID_ADDRESS;
bool done = false;
for (i = 0; i < m_header.ncmds; ++i) {
const lldb::offset_t cmd_offset = offset;
if (m_data.GetU32(&offset, &load_cmd, 2) == nullptr)
break;
switch (load_cmd.cmd) {
case LC_UNIXTHREAD:
case LC_THREAD: {
while (offset < cmd_offset + load_cmd.cmdsize) {
uint32_t flavor = m_data.GetU32(&offset);
uint32_t count = m_data.GetU32(&offset);
if (count == 0) {
// We've gotten off somehow, log and exit;
return m_entry_point_address;
}
switch (m_header.cputype) {
case llvm::MachO::CPU_TYPE_ARM:
if (flavor == 1 ||
flavor == 9) // ARM_THREAD_STATE/ARM_THREAD_STATE32
// from mach/arm/thread_status.h
{
offset += 60; // This is the offset of pc in the GPR thread state
// data structure.
start_address = m_data.GetU32(&offset);
done = true;
}
break;
case llvm::MachO::CPU_TYPE_ARM64:
case llvm::MachO::CPU_TYPE_ARM64_32:
if (flavor == 6) // ARM_THREAD_STATE64 from mach/arm/thread_status.h
{
offset += 256; // This is the offset of pc in the GPR thread state
// data structure.
start_address = m_data.GetU64(&offset);
done = true;
}
break;
case llvm::MachO::CPU_TYPE_I386:
if (flavor ==
1) // x86_THREAD_STATE32 from mach/i386/thread_status.h
{
offset += 40; // This is the offset of eip in the GPR thread state
// data structure.
start_address = m_data.GetU32(&offset);
done = true;
}
break;
case llvm::MachO::CPU_TYPE_X86_64:
if (flavor ==
4) // x86_THREAD_STATE64 from mach/i386/thread_status.h
{
offset += 16 * 8; // This is the offset of rip in the GPR thread
// state data structure.
start_address = m_data.GetU64(&offset);
done = true;
}
break;
default:
return m_entry_point_address;
}
// Haven't found the GPR flavor yet, skip over the data for this
// flavor:
if (done)
break;
offset += count * 4;
}
} break;
case LC_MAIN: {
ConstString text_segment_name("__TEXT");
uint64_t entryoffset = m_data.GetU64(&offset);
SectionSP text_segment_sp =
GetSectionList()->FindSectionByName(text_segment_name);
if (text_segment_sp) {
done = true;
start_address = text_segment_sp->GetFileAddress() + entryoffset;
}
} break;
default:
break;
}
if (done)
break;
// Go to the next load command:
offset = cmd_offset + load_cmd.cmdsize;
}
if (start_address == LLDB_INVALID_ADDRESS && IsDynamicLoader()) {
if (GetSymtab()) {
Symbol *dyld_start_sym = GetSymtab()->FindFirstSymbolWithNameAndType(
ConstString("_dyld_start"), SymbolType::eSymbolTypeCode,
Symtab::eDebugAny, Symtab::eVisibilityAny);
if (dyld_start_sym && dyld_start_sym->GetAddress().IsValid()) {
start_address = dyld_start_sym->GetAddress().GetFileAddress();
}
}
}
if (start_address != LLDB_INVALID_ADDRESS) {
// We got the start address from the load commands, so now resolve that
// address in the sections of this ObjectFile:
if (!m_entry_point_address.ResolveAddressUsingFileSections(
start_address, GetSectionList())) {
m_entry_point_address.Clear();
}
} else {
// We couldn't read the UnixThread load command - maybe it wasn't there.
// As a fallback look for the "start" symbol in the main executable.
ModuleSP module_sp(GetModule());
if (module_sp) {
SymbolContextList contexts;
SymbolContext context;
module_sp->FindSymbolsWithNameAndType(ConstString("start"),
eSymbolTypeCode, contexts);
if (contexts.GetSize()) {
if (contexts.GetContextAtIndex(0, context))
m_entry_point_address = context.symbol->GetAddress();
}
}
}
}
return m_entry_point_address;
}
lldb_private::Address ObjectFileMachO::GetBaseAddress() {
lldb_private::Address header_addr;
SectionList *section_list = GetSectionList();
if (section_list) {
SectionSP text_segment_sp(
section_list->FindSectionByName(GetSegmentNameTEXT()));
if (text_segment_sp) {
header_addr.SetSection(text_segment_sp);
header_addr.SetOffset(0);
}
}
return header_addr;
}
uint32_t ObjectFileMachO::GetNumThreadContexts() {
ModuleSP module_sp(GetModule());
if (module_sp) {
std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
if (!m_thread_context_offsets_valid) {
m_thread_context_offsets_valid = true;
lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
FileRangeArray::Entry file_range;
thread_command thread_cmd;
for (uint32_t i = 0; i < m_header.ncmds; ++i) {
const uint32_t cmd_offset = offset;
if (m_data.GetU32(&offset, &thread_cmd, 2) == nullptr)
break;
if (thread_cmd.cmd == LC_THREAD) {
file_range.SetRangeBase(offset);
file_range.SetByteSize(thread_cmd.cmdsize - 8);
m_thread_context_offsets.Append(file_range);
}
offset = cmd_offset + thread_cmd.cmdsize;
}
}
}
return m_thread_context_offsets.GetSize();
}
std::string ObjectFileMachO::GetIdentifierString() {
std::string result;
ModuleSP module_sp(GetModule());
if (module_sp) {
std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
// First, look over the load commands for an LC_NOTE load command with
// data_owner string "kern ver str" & use that if found.
lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
for (uint32_t i = 0; i < m_header.ncmds; ++i) {
const uint32_t cmd_offset = offset;
load_command lc;
if (m_data.GetU32(&offset, &lc.cmd, 2) == nullptr)
break;
if (lc.cmd == LC_NOTE) {
char data_owner[17];
m_data.CopyData(offset, 16, data_owner);
data_owner[16] = '\0';
offset += 16;
uint64_t fileoff = m_data.GetU64_unchecked(&offset);
uint64_t size = m_data.GetU64_unchecked(&offset);
// "kern ver str" has a uint32_t version and then a nul terminated
// c-string.
if (strcmp("kern ver str", data_owner) == 0) {
offset = fileoff;
uint32_t version;
if (m_data.GetU32(&offset, &version, 1) != nullptr) {
if (version == 1) {
uint32_t strsize = size - sizeof(uint32_t);
char *buf = (char *)malloc(strsize);
if (buf) {
m_data.CopyData(offset, strsize, buf);
buf[strsize - 1] = '\0';
result = buf;
if (buf)
free(buf);
return result;
}
}
}
}
}
offset = cmd_offset + lc.cmdsize;
}
// Second, make a pass over the load commands looking for an obsolete
// LC_IDENT load command.
offset = MachHeaderSizeFromMagic(m_header.magic);
for (uint32_t i = 0; i < m_header.ncmds; ++i) {
const uint32_t cmd_offset = offset;
struct ident_command ident_command;
if (m_data.GetU32(&offset, &ident_command, 2) == nullptr)
break;
if (ident_command.cmd == LC_IDENT && ident_command.cmdsize != 0) {
char *buf = (char *)malloc(ident_command.cmdsize);
if (buf != nullptr && m_data.CopyData(offset, ident_command.cmdsize,
buf) == ident_command.cmdsize) {
buf[ident_command.cmdsize - 1] = '\0';
result = buf;
}
if (buf)
free(buf);
}
offset = cmd_offset + ident_command.cmdsize;
}
}
return result;
}
bool ObjectFileMachO::GetCorefileMainBinaryInfo(addr_t &address, UUID &uuid) {
address = LLDB_INVALID_ADDRESS;
uuid.Clear();
ModuleSP module_sp(GetModule());
if (module_sp) {
std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
for (uint32_t i = 0; i < m_header.ncmds; ++i) {
const uint32_t cmd_offset = offset;
load_command lc;
if (m_data.GetU32(&offset, &lc.cmd, 2) == nullptr)
break;
if (lc.cmd == LC_NOTE) {
char data_owner[17];
memset(data_owner, 0, sizeof(data_owner));
m_data.CopyData(offset, 16, data_owner);
offset += 16;
uint64_t fileoff = m_data.GetU64_unchecked(&offset);
uint64_t size = m_data.GetU64_unchecked(&offset);
// "main bin spec" (main binary specification) data payload is
// formatted:
// uint32_t version [currently 1]
// uint32_t type [0 == unspecified, 1 == kernel, 2 == user
// process] uint64_t address [ UINT64_MAX if address not
// specified ] uuid_t uuid [ all zero's if uuid not
// specified ] uint32_t log2_pagesize [ process page size in log base
// 2, e.g. 4k pages are 12. 0 for unspecified ]
if (strcmp("main bin spec", data_owner) == 0 && size >= 32) {
offset = fileoff;
uint32_t version;
if (m_data.GetU32(&offset, &version, 1) != nullptr && version == 1) {
uint32_t type = 0;
uuid_t raw_uuid;
memset(raw_uuid, 0, sizeof(uuid_t));
if (m_data.GetU32(&offset, &type, 1) &&
m_data.GetU64(&offset, &address, 1) &&
m_data.CopyData(offset, sizeof(uuid_t), raw_uuid) != 0) {
uuid = UUID::fromOptionalData(raw_uuid, sizeof(uuid_t));
return true;
}
}
}
}
offset = cmd_offset + lc.cmdsize;
}
}
return false;
}
lldb::RegisterContextSP
ObjectFileMachO::GetThreadContextAtIndex(uint32_t idx,
lldb_private::Thread &thread) {
lldb::RegisterContextSP reg_ctx_sp;
ModuleSP module_sp(GetModule());
if (module_sp) {
std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
if (!m_thread_context_offsets_valid)
GetNumThreadContexts();
const FileRangeArray::Entry *thread_context_file_range =
m_thread_context_offsets.GetEntryAtIndex(idx);
if (thread_context_file_range) {
DataExtractor data(m_data, thread_context_file_range->GetRangeBase(),
thread_context_file_range->GetByteSize());
switch (m_header.cputype) {
case llvm::MachO::CPU_TYPE_ARM64:
case llvm::MachO::CPU_TYPE_ARM64_32:
reg_ctx_sp =
std::make_shared<RegisterContextDarwin_arm64_Mach>(thread, data);
break;
case llvm::MachO::CPU_TYPE_ARM:
reg_ctx_sp =
std::make_shared<RegisterContextDarwin_arm_Mach>(thread, data);
break;
case llvm::MachO::CPU_TYPE_I386:
reg_ctx_sp =
std::make_shared<RegisterContextDarwin_i386_Mach>(thread, data);
break;
case llvm::MachO::CPU_TYPE_X86_64:
reg_ctx_sp =
std::make_shared<RegisterContextDarwin_x86_64_Mach>(thread, data);
break;
}
}
}
return reg_ctx_sp;
}
ObjectFile::Type ObjectFileMachO::CalculateType() {
switch (m_header.filetype) {
case MH_OBJECT: // 0x1u
if (GetAddressByteSize() == 4) {
// 32 bit kexts are just object files, but they do have a valid
// UUID load command.
if (GetUUID()) {
// this checking for the UUID load command is not enough we could
// eventually look for the symbol named "OSKextGetCurrentIdentifier" as
// this is required of kexts
if (m_strata == eStrataInvalid)
m_strata = eStrataKernel;
return eTypeSharedLibrary;
}
}
return eTypeObjectFile;
case MH_EXECUTE:
return eTypeExecutable; // 0x2u
case MH_FVMLIB:
return eTypeSharedLibrary; // 0x3u
case MH_CORE:
return eTypeCoreFile; // 0x4u
case MH_PRELOAD:
return eTypeSharedLibrary; // 0x5u
case MH_DYLIB:
return eTypeSharedLibrary; // 0x6u
case MH_DYLINKER:
return eTypeDynamicLinker; // 0x7u
case MH_BUNDLE:
return eTypeSharedLibrary; // 0x8u
case MH_DYLIB_STUB:
return eTypeStubLibrary; // 0x9u
case MH_DSYM:
return eTypeDebugInfo; // 0xAu
case MH_KEXT_BUNDLE:
return eTypeSharedLibrary; // 0xBu
default:
break;
}
return eTypeUnknown;
}
ObjectFile::Strata ObjectFileMachO::CalculateStrata() {
switch (m_header.filetype) {
case MH_OBJECT: // 0x1u
{
// 32 bit kexts are just object files, but they do have a valid
// UUID load command.
if (GetUUID()) {
// this checking for the UUID load command is not enough we could
// eventually look for the symbol named "OSKextGetCurrentIdentifier" as
// this is required of kexts
if (m_type == eTypeInvalid)
m_type = eTypeSharedLibrary;
return eStrataKernel;
}
}
return eStrataUnknown;
case MH_EXECUTE: // 0x2u
// Check for the MH_DYLDLINK bit in the flags
if (m_header.flags & MH_DYLDLINK) {
return eStrataUser;
} else {
SectionList *section_list = GetSectionList();
if (section_list) {
static ConstString g_kld_section_name("__KLD");
if (section_list->FindSectionByName(g_kld_section_name))
return eStrataKernel;
}
}
return eStrataRawImage;
case MH_FVMLIB:
return eStrataUser; // 0x3u
case MH_CORE:
return eStrataUnknown; // 0x4u
case MH_PRELOAD:
return eStrataRawImage; // 0x5u
case MH_DYLIB:
return eStrataUser; // 0x6u
case MH_DYLINKER:
return eStrataUser; // 0x7u
case MH_BUNDLE:
return eStrataUser; // 0x8u
case MH_DYLIB_STUB:
return eStrataUser; // 0x9u
case MH_DSYM:
return eStrataUnknown; // 0xAu
case MH_KEXT_BUNDLE:
return eStrataKernel; // 0xBu
default:
break;
}
return eStrataUnknown;
}
llvm::VersionTuple ObjectFileMachO::GetVersion() {
ModuleSP module_sp(GetModule());
if (module_sp) {
std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
struct dylib_command load_cmd;
lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
uint32_t version_cmd = 0;
uint64_t version = 0;
uint32_t i;
for (i = 0; i < m_header.ncmds; ++i) {
const lldb::offset_t cmd_offset = offset;
if (m_data.GetU32(&offset, &load_cmd, 2) == nullptr)
break;
if (load_cmd.cmd == LC_ID_DYLIB) {
if (version_cmd == 0) {
version_cmd = load_cmd.cmd;
if (m_data.GetU32(&offset, &load_cmd.dylib, 4) == nullptr)
break;
version = load_cmd.dylib.current_version;
}
break; // Break for now unless there is another more complete version
// number load command in the future.
}
offset = cmd_offset + load_cmd.cmdsize;
}
if (version_cmd == LC_ID_DYLIB) {
unsigned major = (version & 0xFFFF0000ull) >> 16;
unsigned minor = (version & 0x0000FF00ull) >> 8;
unsigned subminor = (version & 0x000000FFull);
return llvm::VersionTuple(major, minor, subminor);
}
}
return llvm::VersionTuple();
}
ArchSpec ObjectFileMachO::GetArchitecture() {
ModuleSP module_sp(GetModule());
ArchSpec arch;
if (module_sp) {
std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
return GetArchitecture(module_sp, m_header, m_data,
MachHeaderSizeFromMagic(m_header.magic));
}
return arch;
}
void ObjectFileMachO::GetProcessSharedCacheUUID(Process *process,
addr_t &base_addr, UUID &uuid) {
uuid.Clear();
base_addr = LLDB_INVALID_ADDRESS;
if (process && process->GetDynamicLoader()) {
DynamicLoader *dl = process->GetDynamicLoader();
LazyBool using_shared_cache;
LazyBool private_shared_cache;
dl->GetSharedCacheInformation(base_addr, uuid, using_shared_cache,
private_shared_cache);
}
Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS |
LIBLLDB_LOG_PROCESS));
LLDB_LOGF(
log,
"inferior process shared cache has a UUID of %s, base address 0x%" PRIx64,
uuid.GetAsString().c_str(), base_addr);
}
// From dyld SPI header dyld_process_info.h
typedef void *dyld_process_info;
struct lldb_copy__dyld_process_cache_info {
uuid_t cacheUUID; // UUID of cache used by process
uint64_t cacheBaseAddress; // load address of dyld shared cache
bool noCache; // process is running without a dyld cache
bool privateCache; // process is using a private copy of its dyld cache
};
// #including mach/mach.h pulls in machine.h & CPU_TYPE_ARM etc conflicts with
// llvm enum definitions llvm::MachO::CPU_TYPE_ARM turning them into compile
// errors. So we need to use the actual underlying types of task_t and
// kern_return_t below.
extern "C" unsigned int /*task_t*/ mach_task_self();
void ObjectFileMachO::GetLLDBSharedCacheUUID(addr_t &base_addr, UUID &uuid) {
uuid.Clear();
base_addr = LLDB_INVALID_ADDRESS;
#if defined(__APPLE__) && \
(defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
uint8_t *(*dyld_get_all_image_infos)(void);
dyld_get_all_image_infos =
(uint8_t * (*)()) dlsym(RTLD_DEFAULT, "_dyld_get_all_image_infos");
if (dyld_get_all_image_infos) {
uint8_t *dyld_all_image_infos_address = dyld_get_all_image_infos();
if (dyld_all_image_infos_address) {
uint32_t *version = (uint32_t *)
dyld_all_image_infos_address; // version <mach-o/dyld_images.h>
if (*version >= 13) {
uuid_t *sharedCacheUUID_address = 0;
int wordsize = sizeof(uint8_t *);
if (wordsize == 8) {
sharedCacheUUID_address =
(uuid_t *)((uint8_t *)dyld_all_image_infos_address +
160); // sharedCacheUUID <mach-o/dyld_images.h>
if (*version >= 15)
base_addr =
*(uint64_t
*)((uint8_t *)dyld_all_image_infos_address +
176); // sharedCacheBaseAddress <mach-o/dyld_images.h>
} else {
sharedCacheUUID_address =
(uuid_t *)((uint8_t *)dyld_all_image_infos_address +
84); // sharedCacheUUID <mach-o/dyld_images.h>
if (*version >= 15) {
base_addr = 0;
base_addr =
*(uint32_t
*)((uint8_t *)dyld_all_image_infos_address +
100); // sharedCacheBaseAddress <mach-o/dyld_images.h>
}
}
uuid = UUID::fromOptionalData(sharedCacheUUID_address, sizeof(uuid_t));
}
}
} else {
// Exists in macOS 10.12 and later, iOS 10.0 and later - dyld SPI
dyld_process_info (*dyld_process_info_create)(
unsigned int /* task_t */ task, uint64_t timestamp,
unsigned int /*kern_return_t*/ *kernelError);
void (*dyld_process_info_get_cache)(void *info, void *cacheInfo);
void (*dyld_process_info_release)(dyld_process_info info);
dyld_process_info_create = (void *(*)(unsigned int /* task_t */, uint64_t,
unsigned int /*kern_return_t*/ *))
dlsym(RTLD_DEFAULT, "_dyld_process_info_create");
dyld_process_info_get_cache = (void (*)(void *, void *))dlsym(
RTLD_DEFAULT, "_dyld_process_info_get_cache");
dyld_process_info_release =
(void (*)(void *))dlsym(RTLD_DEFAULT, "_dyld_process_info_release");
if (dyld_process_info_create && dyld_process_info_get_cache) {
unsigned int /*kern_return_t */ kern_ret;
dyld_process_info process_info =
dyld_process_info_create(::mach_task_self(), 0, &kern_ret);
if (process_info) {
struct lldb_copy__dyld_process_cache_info sc_info;
memset(&sc_info, 0, sizeof(struct lldb_copy__dyld_process_cache_info));
dyld_process_info_get_cache(process_info, &sc_info);
if (sc_info.cacheBaseAddress != 0) {
base_addr = sc_info.cacheBaseAddress;
uuid = UUID::fromOptionalData(sc_info.cacheUUID, sizeof(uuid_t));
}
dyld_process_info_release(process_info);
}
}
}
Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS |
LIBLLDB_LOG_PROCESS));
if (log && uuid.IsValid())
LLDB_LOGF(log,
"lldb's in-memory shared cache has a UUID of %s base address of "
"0x%" PRIx64,
uuid.GetAsString().c_str(), base_addr);
#endif
}
llvm::VersionTuple ObjectFileMachO::GetMinimumOSVersion() {
if (!m_min_os_version) {
lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
for (uint32_t i = 0; i < m_header.ncmds; ++i) {
const lldb::offset_t load_cmd_offset = offset;
version_min_command lc;
if (m_data.GetU32(&offset, &lc.cmd, 2) == nullptr)
break;
if (lc.cmd == llvm::MachO::LC_VERSION_MIN_MACOSX ||
lc.cmd == llvm::MachO::LC_VERSION_MIN_IPHONEOS ||
lc.cmd == llvm::MachO::LC_VERSION_MIN_TVOS ||
lc.cmd == llvm::MachO::LC_VERSION_MIN_WATCHOS) {
if (m_data.GetU32(&offset, &lc.version,
(sizeof(lc) / sizeof(uint32_t)) - 2)) {
const uint32_t xxxx = lc.version >> 16;
const uint32_t yy = (lc.version >> 8) & 0xffu;
const uint32_t zz = lc.version & 0xffu;
if (xxxx) {
m_min_os_version = llvm::VersionTuple(xxxx, yy, zz);
break;
}
}
} else if (lc.cmd == llvm::MachO::LC_BUILD_VERSION) {
// struct build_version_command {
// uint32_t cmd; /* LC_BUILD_VERSION */
// uint32_t cmdsize; /* sizeof(struct
// build_version_command) plus */
// /* ntools * sizeof(struct
// build_tool_version) */
// uint32_t platform; /* platform */
// uint32_t minos; /* X.Y.Z is encoded in nibbles
// xxxx.yy.zz */ uint32_t sdk; /* X.Y.Z is encoded in
// nibbles xxxx.yy.zz */ uint32_t ntools; /* number of
// tool entries following this */
// };
offset += 4; // skip platform
uint32_t minos = m_data.GetU32(&offset);
const uint32_t xxxx = minos >> 16;
const uint32_t yy = (minos >> 8) & 0xffu;
const uint32_t zz = minos & 0xffu;
if (xxxx) {
m_min_os_version = llvm::VersionTuple(xxxx, yy, zz);
break;
}
}
offset = load_cmd_offset + lc.cmdsize;
}
if (!m_min_os_version) {
// Set version to an empty value so we don't keep trying to
m_min_os_version = llvm::VersionTuple();
}
}
return *m_min_os_version;
}
llvm::VersionTuple ObjectFileMachO::GetSDKVersion() {
if (!m_sdk_versions.hasValue()) {
lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
for (uint32_t i = 0; i < m_header.ncmds; ++i) {
const lldb::offset_t load_cmd_offset = offset;
version_min_command lc;
if (m_data.GetU32(&offset, &lc.cmd, 2) == nullptr)
break;
if (lc.cmd == llvm::MachO::LC_VERSION_MIN_MACOSX ||
lc.cmd == llvm::MachO::LC_VERSION_MIN_IPHONEOS ||
lc.cmd == llvm::MachO::LC_VERSION_MIN_TVOS ||
lc.cmd == llvm::MachO::LC_VERSION_MIN_WATCHOS) {
if (m_data.GetU32(&offset, &lc.version,
(sizeof(lc) / sizeof(uint32_t)) - 2)) {
const uint32_t xxxx = lc.sdk >> 16;
const uint32_t yy = (lc.sdk >> 8) & 0xffu;
const uint32_t zz = lc.sdk & 0xffu;
if (xxxx) {
m_sdk_versions = llvm::VersionTuple(xxxx, yy, zz);
break;
} else {
GetModule()->ReportWarning("minimum OS version load command with "
"invalid (0) version found.");
}
}
}
offset = load_cmd_offset + lc.cmdsize;
}
if (!m_sdk_versions.hasValue()) {
offset = MachHeaderSizeFromMagic(m_header.magic);
for (uint32_t i = 0; i < m_header.ncmds; ++i) {
const lldb::offset_t load_cmd_offset = offset;
version_min_command lc;
if (m_data.GetU32(&offset, &lc.cmd, 2) == nullptr)
break;
if (lc.cmd == llvm::MachO::LC_BUILD_VERSION) {
// struct build_version_command {
// uint32_t cmd; /* LC_BUILD_VERSION */
// uint32_t cmdsize; /* sizeof(struct
// build_version_command) plus */
// /* ntools * sizeof(struct
// build_tool_version) */
// uint32_t platform; /* platform */
// uint32_t minos; /* X.Y.Z is encoded in nibbles
// xxxx.yy.zz */ uint32_t sdk; /* X.Y.Z is encoded
// in nibbles xxxx.yy.zz */ uint32_t ntools; /* number
// of tool entries following this */
// };
offset += 4; // skip platform
uint32_t minos = m_data.GetU32(&offset);
const uint32_t xxxx = minos >> 16;
const uint32_t yy = (minos >> 8) & 0xffu;
const uint32_t zz = minos & 0xffu;
if (xxxx) {
m_sdk_versions = llvm::VersionTuple(xxxx, yy, zz);
break;
}
}
offset = load_cmd_offset + lc.cmdsize;
}
}
if (!m_sdk_versions.hasValue())
m_sdk_versions = llvm::VersionTuple();
}
return m_sdk_versions.getValue();
}
bool ObjectFileMachO::GetIsDynamicLinkEditor() {
return m_header.filetype == llvm::MachO::MH_DYLINKER;
}
bool ObjectFileMachO::AllowAssemblyEmulationUnwindPlans() {
return m_allow_assembly_emulation_unwind_plans;
}
// PluginInterface protocol
lldb_private::ConstString ObjectFileMachO::GetPluginName() {
return GetPluginNameStatic();
}
uint32_t ObjectFileMachO::GetPluginVersion() { return 1; }
Section *ObjectFileMachO::GetMachHeaderSection() {
// Find the first address of the mach header which is the first non-zero file
// sized section whose file offset is zero. This is the base file address of
// the mach-o file which can be subtracted from the vmaddr of the other
// segments found in memory and added to the load address
ModuleSP module_sp = GetModule();
if (!module_sp)
return nullptr;
SectionList *section_list = GetSectionList();
if (!section_list)
return nullptr;
const size_t num_sections = section_list->GetSize();
for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
Section *section = section_list->GetSectionAtIndex(sect_idx).get();
if (section->GetFileOffset() == 0 && SectionIsLoadable(section))
return section;
}
return nullptr;
}
bool ObjectFileMachO::SectionIsLoadable(const Section *section) {
if (!section)
return false;
const bool is_dsym = (m_header.filetype == MH_DSYM);
if (section->GetFileSize() == 0 && !is_dsym)
return false;
if (section->IsThreadSpecific())
return false;
if (GetModule().get() != section->GetModule().get())
return false;
// Be careful with __LINKEDIT and __DWARF segments
if (section->GetName() == GetSegmentNameLINKEDIT() ||
section->GetName() == GetSegmentNameDWARF()) {
// Only map __LINKEDIT and __DWARF if we have an in memory image and
// this isn't a kernel binary like a kext or mach_kernel.
const bool is_memory_image = (bool)m_process_wp.lock();
const Strata strata = GetStrata();
if (is_memory_image == false || strata == eStrataKernel)
return false;
}
return true;
}
lldb::addr_t ObjectFileMachO::CalculateSectionLoadAddressForMemoryImage(
lldb::addr_t header_load_address, const Section *header_section,
const Section *section) {
ModuleSP module_sp = GetModule();
if (module_sp && header_section && section &&
header_load_address != LLDB_INVALID_ADDRESS) {
lldb::addr_t file_addr = header_section->GetFileAddress();
if (file_addr != LLDB_INVALID_ADDRESS && SectionIsLoadable(section))
return section->GetFileAddress() - file_addr + header_load_address;
}
return LLDB_INVALID_ADDRESS;
}
bool ObjectFileMachO::SetLoadAddress(Target &target, lldb::addr_t value,
bool value_is_offset) {
ModuleSP module_sp = GetModule();
if (!module_sp)
return false;
SectionList *section_list = GetSectionList();
if (!section_list)
return false;
size_t num_loaded_sections = 0;
const size_t num_sections = section_list->GetSize();
if (value_is_offset) {
// "value" is an offset to apply to each top level segment
for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
// Iterate through the object file sections to find all of the
// sections that size on disk (to avoid __PAGEZERO) and load them
SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));
if (SectionIsLoadable(section_sp.get()))
if (target.GetSectionLoadList().SetSectionLoadAddress(
section_sp, section_sp->GetFileAddress() + value))
++num_loaded_sections;
}
} else {
// "value" is the new base address of the mach_header, adjust each
// section accordingly
Section *mach_header_section = GetMachHeaderSection();
if (mach_header_section) {
for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));
lldb::addr_t section_load_addr =
CalculateSectionLoadAddressForMemoryImage(
value, mach_header_section, section_sp.get());
if (section_load_addr != LLDB_INVALID_ADDRESS) {
if (target.GetSectionLoadList().SetSectionLoadAddress(
section_sp, section_load_addr))
++num_loaded_sections;
}
}
}
}
return num_loaded_sections > 0;
}
bool ObjectFileMachO::SaveCore(const lldb::ProcessSP &process_sp,
const FileSpec &outfile, Status &error) {
if (!process_sp)
return false;
Target &target = process_sp->GetTarget();
const ArchSpec target_arch = target.GetArchitecture();
const llvm::Triple &target_triple = target_arch.GetTriple();
if (target_triple.getVendor() == llvm::Triple::Apple &&
(target_triple.getOS() == llvm::Triple::MacOSX ||
target_triple.getOS() == llvm::Triple::IOS ||
target_triple.getOS() == llvm::Triple::WatchOS ||
target_triple.getOS() == llvm::Triple::TvOS)) {
// NEED_BRIDGEOS_TRIPLE target_triple.getOS() == llvm::Triple::BridgeOS))
// {
bool make_core = false;
switch (target_arch.GetMachine()) {
case llvm::Triple::aarch64:
case llvm::Triple::aarch64_32:
case llvm::Triple::arm:
case llvm::Triple::thumb:
case llvm::Triple::x86:
case llvm::Triple::x86_64:
make_core = true;
break;
default:
error.SetErrorStringWithFormat("unsupported core architecture: %s",
target_triple.str().c_str());
break;
}
if (make_core) {
std::vector<segment_command_64> segment_load_commands;
// uint32_t range_info_idx = 0;
MemoryRegionInfo range_info;
Status range_error = process_sp->GetMemoryRegionInfo(0, range_info);
const uint32_t addr_byte_size = target_arch.GetAddressByteSize();
const ByteOrder byte_order = target_arch.GetByteOrder();
if (range_error.Success()) {
while (range_info.GetRange().GetRangeBase() != LLDB_INVALID_ADDRESS) {
const addr_t addr = range_info.GetRange().GetRangeBase();
const addr_t size = range_info.GetRange().GetByteSize();
if (size == 0)
break;
// Calculate correct protections
uint32_t prot = 0;
if (range_info.GetReadable() == MemoryRegionInfo::eYes)
prot |= VM_PROT_READ;
if (range_info.GetWritable() == MemoryRegionInfo::eYes)
prot |= VM_PROT_WRITE;
if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
prot |= VM_PROT_EXECUTE;
if (prot != 0) {
uint32_t cmd_type = LC_SEGMENT_64;
uint32_t segment_size = sizeof(segment_command_64);
if (addr_byte_size == 4) {
cmd_type = LC_SEGMENT;
segment_size = sizeof(segment_command);
}
segment_command_64 segment = {
cmd_type, // uint32_t cmd;
segment_size, // uint32_t cmdsize;
{0}, // char segname[16];
addr, // uint64_t vmaddr; // uint32_t for 32-bit Mach-O
size, // uint64_t vmsize; // uint32_t for 32-bit Mach-O
0, // uint64_t fileoff; // uint32_t for 32-bit Mach-O
size, // uint64_t filesize; // uint32_t for 32-bit Mach-O
prot, // uint32_t maxprot;
prot, // uint32_t initprot;
0, // uint32_t nsects;
0}; // uint32_t flags;
segment_load_commands.push_back(segment);
} else {
// No protections and a size of 1 used to be returned from old
// debugservers when we asked about a region that was past the
// last memory region and it indicates the end...
if (size == 1)
break;
}
range_error = process_sp->GetMemoryRegionInfo(
range_info.GetRange().GetRangeEnd(), range_info);
if (range_error.Fail())
break;
}
StreamString buffer(Stream::eBinary, addr_byte_size, byte_order);
mach_header_64 mach_header;
if (addr_byte_size == 8) {
mach_header.magic = MH_MAGIC_64;
} else {
mach_header.magic = MH_MAGIC;
}
mach_header.cputype = target_arch.GetMachOCPUType();
mach_header.cpusubtype = target_arch.GetMachOCPUSubType();
mach_header.filetype = MH_CORE;
mach_header.ncmds = segment_load_commands.size();
mach_header.flags = 0;
mach_header.reserved = 0;
ThreadList &thread_list = process_sp->GetThreadList();
const uint32_t num_threads = thread_list.GetSize();
// Make an array of LC_THREAD data items. Each one contains the
// contents of the LC_THREAD load command. The data doesn't contain
// the load command + load command size, we will add the load command
// and load command size as we emit the data.
std::vector<StreamString> LC_THREAD_datas(num_threads);
for (auto &LC_THREAD_data : LC_THREAD_datas) {
LC_THREAD_data.GetFlags().Set(Stream::eBinary);
LC_THREAD_data.SetAddressByteSize(addr_byte_size);
LC_THREAD_data.SetByteOrder(byte_order);
}
for (uint32_t thread_idx = 0; thread_idx < num_threads; ++thread_idx) {
ThreadSP thread_sp(thread_list.GetThreadAtIndex(thread_idx));
if (thread_sp) {
switch (mach_header.cputype) {
case llvm::MachO::CPU_TYPE_ARM64:
case llvm::MachO::CPU_TYPE_ARM64_32:
RegisterContextDarwin_arm64_Mach::Create_LC_THREAD(
thread_sp.get(), LC_THREAD_datas[thread_idx]);
break;
case llvm::MachO::CPU_TYPE_ARM:
RegisterContextDarwin_arm_Mach::Create_LC_THREAD(
thread_sp.get(), LC_THREAD_datas[thread_idx]);
break;
case llvm::MachO::CPU_TYPE_I386:
RegisterContextDarwin_i386_Mach::Create_LC_THREAD(
thread_sp.get(), LC_THREAD_datas[thread_idx]);
break;
case llvm::MachO::CPU_TYPE_X86_64:
RegisterContextDarwin_x86_64_Mach::Create_LC_THREAD(
thread_sp.get(), LC_THREAD_datas[thread_idx]);
break;
}
}
}
// The size of the load command is the size of the segments...
if (addr_byte_size == 8) {
mach_header.sizeofcmds =
segment_load_commands.size() * sizeof(struct segment_command_64);
} else {
mach_header.sizeofcmds =
segment_load_commands.size() * sizeof(struct segment_command);
}
// and the size of all LC_THREAD load command
for (const auto &LC_THREAD_data : LC_THREAD_datas) {
++mach_header.ncmds;
mach_header.sizeofcmds += 8 + LC_THREAD_data.GetSize();
}
// Write the mach header
buffer.PutHex32(mach_header.magic);
buffer.PutHex32(mach_header.cputype);
buffer.PutHex32(mach_header.cpusubtype);
buffer.PutHex32(mach_header.filetype);
buffer.PutHex32(mach_header.ncmds);
buffer.PutHex32(mach_header.sizeofcmds);
buffer.PutHex32(mach_header.flags);
if (addr_byte_size == 8) {
buffer.PutHex32(mach_header.reserved);
}
// Skip the mach header and all load commands and align to the next
// 0x1000 byte boundary
addr_t file_offset = buffer.GetSize() + mach_header.sizeofcmds;
if (file_offset & 0x00000fff) {
file_offset += 0x00001000ull;
file_offset &= (~0x00001000ull + 1);
}
for (auto &segment : segment_load_commands) {
segment.fileoff = file_offset;
file_offset += segment.filesize;
}
// Write out all of the LC_THREAD load commands
for (const auto &LC_THREAD_data : LC_THREAD_datas) {
const size_t LC_THREAD_data_size = LC_THREAD_data.GetSize();
buffer.PutHex32(LC_THREAD);
buffer.PutHex32(8 + LC_THREAD_data_size); // cmd + cmdsize + data
buffer.Write(LC_THREAD_data.GetString().data(), LC_THREAD_data_size);
}
// Write out all of the segment load commands
for (const auto &segment : segment_load_commands) {
printf("0x%8.8x 0x%8.8x [0x%16.16" PRIx64 " - 0x%16.16" PRIx64
") [0x%16.16" PRIx64 " 0x%16.16" PRIx64
") 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x]\n",
segment.cmd, segment.cmdsize, segment.vmaddr,
segment.vmaddr + segment.vmsize, segment.fileoff,
segment.filesize, segment.maxprot, segment.initprot,
segment.nsects, segment.flags);
buffer.PutHex32(segment.cmd);
buffer.PutHex32(segment.cmdsize);
buffer.PutRawBytes(segment.segname, sizeof(segment.segname));
if (addr_byte_size == 8) {
buffer.PutHex64(segment.vmaddr);
buffer.PutHex64(segment.vmsize);
buffer.PutHex64(segment.fileoff);
buffer.PutHex64(segment.filesize);
} else {
buffer.PutHex32(static_cast<uint32_t>(segment.vmaddr));
buffer.PutHex32(static_cast<uint32_t>(segment.vmsize));
buffer.PutHex32(static_cast<uint32_t>(segment.fileoff));
buffer.PutHex32(static_cast<uint32_t>(segment.filesize));
}
buffer.PutHex32(segment.maxprot);
buffer.PutHex32(segment.initprot);
buffer.PutHex32(segment.nsects);
buffer.PutHex32(segment.flags);
}
std::string core_file_path(outfile.GetPath());
auto core_file = FileSystem::Instance().Open(
outfile, File::eOpenOptionWrite | File::eOpenOptionTruncate |
File::eOpenOptionCanCreate);
if (!core_file) {
error = core_file.takeError();
} else {
// Read 1 page at a time
uint8_t bytes[0x1000];
// Write the mach header and load commands out to the core file
size_t bytes_written = buffer.GetString().size();
error =
core_file.get()->Write(buffer.GetString().data(), bytes_written);
if (error.Success()) {
// Now write the file data for all memory segments in the process
for (const auto &segment : segment_load_commands) {
if (core_file.get()->SeekFromStart(segment.fileoff) == -1) {
error.SetErrorStringWithFormat(
"unable to seek to offset 0x%" PRIx64 " in '%s'",
segment.fileoff, core_file_path.c_str());
break;
}
printf("Saving %" PRId64
" bytes of data for memory region at 0x%" PRIx64 "\n",
segment.vmsize, segment.vmaddr);
addr_t bytes_left = segment.vmsize;
addr_t addr = segment.vmaddr;
Status memory_read_error;
while (bytes_left > 0 && error.Success()) {
const size_t bytes_to_read =
bytes_left > sizeof(bytes) ? sizeof(bytes) : bytes_left;
// In a savecore setting, we don't really care about caching,
// as the data is dumped and very likely never read again,
// so we call ReadMemoryFromInferior to bypass it.
const size_t bytes_read = process_sp->ReadMemoryFromInferior(
addr, bytes, bytes_to_read, memory_read_error);
if (bytes_read == bytes_to_read) {
size_t bytes_written = bytes_read;
error = core_file.get()->Write(bytes, bytes_written);
bytes_left -= bytes_read;
addr += bytes_read;
} else {
// Some pages within regions are not readable, those should
// be zero filled
memset(bytes, 0, bytes_to_read);
size_t bytes_written = bytes_to_read;
error = core_file.get()->Write(bytes, bytes_written);
bytes_left -= bytes_to_read;
addr += bytes_to_read;
}
}
}
}
}
} else {
error.SetErrorString(
"process doesn't support getting memory region info");
}
}
return true; // This is the right plug to handle saving core files for
// this process
}
return false;
}
|