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
|
pub const Atom = @import("MachO/Atom.zig");
pub const DebugSymbols = @import("MachO/DebugSymbols.zig");
pub const Relocation = @import("MachO/Relocation.zig");
base: link.File,
rpath_list: []const []const u8,
/// Debug symbols bundle (or dSym).
d_sym: ?DebugSymbols = null,
/// A list of all input files.
/// Index of each input file also encodes the priority or precedence of one input file
/// over another.
files: std.MultiArrayList(File.Entry) = .{},
/// Long-lived list of all file descriptors.
/// We store them globally rather than per actual File so that we can re-use
/// one file handle per every object file within an archive.
file_handles: std.ArrayListUnmanaged(File.Handle) = .empty,
zig_object: ?File.Index = null,
internal_object: ?File.Index = null,
objects: std.ArrayListUnmanaged(File.Index) = .empty,
dylibs: std.ArrayListUnmanaged(File.Index) = .empty,
segments: std.ArrayListUnmanaged(macho.segment_command_64) = .empty,
sections: std.MultiArrayList(Section) = .{},
resolver: SymbolResolver = .{},
/// This table will be populated after `scanRelocs` has run.
/// Key is symbol index.
undefs: std.AutoArrayHashMapUnmanaged(SymbolResolver.Index, UndefRefs) = .empty,
undefs_mutex: std.Thread.Mutex = .{},
dupes: std.AutoArrayHashMapUnmanaged(SymbolResolver.Index, std.ArrayListUnmanaged(File.Index)) = .empty,
dupes_mutex: std.Thread.Mutex = .{},
dyld_info_cmd: macho.dyld_info_command = .{},
symtab_cmd: macho.symtab_command = .{},
dysymtab_cmd: macho.dysymtab_command = .{},
function_starts_cmd: macho.linkedit_data_command = .{ .cmd = .FUNCTION_STARTS },
data_in_code_cmd: macho.linkedit_data_command = .{ .cmd = .DATA_IN_CODE },
uuid_cmd: macho.uuid_command = .{ .uuid = [_]u8{0} ** 16 },
codesig_cmd: macho.linkedit_data_command = .{ .cmd = .CODE_SIGNATURE },
pagezero_seg_index: ?u8 = null,
text_seg_index: ?u8 = null,
linkedit_seg_index: ?u8 = null,
text_sect_index: ?u8 = null,
data_sect_index: ?u8 = null,
got_sect_index: ?u8 = null,
stubs_sect_index: ?u8 = null,
stubs_helper_sect_index: ?u8 = null,
la_symbol_ptr_sect_index: ?u8 = null,
tlv_ptr_sect_index: ?u8 = null,
eh_frame_sect_index: ?u8 = null,
unwind_info_sect_index: ?u8 = null,
objc_stubs_sect_index: ?u8 = null,
thunks: std.ArrayListUnmanaged(Thunk) = .empty,
/// Output synthetic sections
symtab: std.ArrayListUnmanaged(macho.nlist_64) = .empty,
strtab: std.ArrayListUnmanaged(u8) = .empty,
indsymtab: Indsymtab = .{},
got: GotSection = .{},
stubs: StubsSection = .{},
stubs_helper: StubsHelperSection = .{},
objc_stubs: ObjcStubsSection = .{},
la_symbol_ptr: LaSymbolPtrSection = .{},
tlv_ptr: TlvPtrSection = .{},
rebase_section: Rebase = .{},
bind_section: Bind = .{},
weak_bind_section: WeakBind = .{},
lazy_bind_section: LazyBind = .{},
export_trie: ExportTrie = .{},
unwind_info: UnwindInfo = .{},
data_in_code: DataInCode = .{},
/// Tracked loadable segments during incremental linking.
zig_text_seg_index: ?u8 = null,
zig_const_seg_index: ?u8 = null,
zig_data_seg_index: ?u8 = null,
zig_bss_seg_index: ?u8 = null,
/// Tracked section headers with incremental updates to Zig object.
zig_text_sect_index: ?u8 = null,
zig_const_sect_index: ?u8 = null,
zig_data_sect_index: ?u8 = null,
zig_bss_sect_index: ?u8 = null,
/// Tracked DWARF section headers that apply only when we emit relocatable.
/// For executable and loadable images, DWARF is tracked directly by dSYM bundle object.
debug_info_sect_index: ?u8 = null,
debug_abbrev_sect_index: ?u8 = null,
debug_str_sect_index: ?u8 = null,
debug_aranges_sect_index: ?u8 = null,
debug_line_sect_index: ?u8 = null,
debug_line_str_sect_index: ?u8 = null,
debug_loclists_sect_index: ?u8 = null,
debug_rnglists_sect_index: ?u8 = null,
has_tlv: AtomicBool = AtomicBool.init(false),
binds_to_weak: AtomicBool = AtomicBool.init(false),
weak_defines: AtomicBool = AtomicBool.init(false),
/// Options
/// SDK layout
sdk_layout: ?SdkLayout,
/// Size of the __PAGEZERO segment.
pagezero_size: ?u64,
/// Minimum space for future expansion of the load commands.
headerpad_size: ?u32,
/// Set enough space as if all paths were MATPATHLEN.
headerpad_max_install_names: bool,
/// Remove dylibs that are unreachable by the entry point or exported symbols.
dead_strip_dylibs: bool,
/// Treatment of undefined symbols
undefined_treatment: UndefinedTreatment,
/// TODO: delete this, libraries need to be resolved by the frontend instead
lib_directories: []const Directory,
/// Resolved list of framework search directories
framework_dirs: []const []const u8,
/// List of input frameworks
frameworks: []const Framework,
/// Install name for the dylib.
/// TODO: unify with soname
install_name: ?[]const u8,
/// Path to entitlements file.
entitlements: ?[]const u8,
compatibility_version: ?std.SemanticVersion,
/// Entry name
entry_name: ?[]const u8,
platform: Platform,
sdk_version: ?std.SemanticVersion,
/// When set to true, the linker will hoist all dylibs including system dependent dylibs.
no_implicit_dylibs: bool = false,
/// Whether the linker should parse and always force load objects containing ObjC in archives.
// TODO: in Zig we currently take -ObjC as always on
force_load_objc: bool = true,
/// Whether local symbols should be discarded from the symbol table.
discard_local_symbols: bool = false,
/// Hot-code swapping state.
hot_state: if (is_hot_update_compatible) HotUpdateState else struct {} = .{},
/// When adding a new field, remember to update `hashAddFrameworks`.
pub const Framework = struct {
needed: bool = false,
weak: bool = false,
path: Path,
};
pub fn hashAddFrameworks(man: *Cache.Manifest, hm: []const Framework) !void {
for (hm) |value| {
man.hash.add(value.needed);
man.hash.add(value.weak);
_ = try man.addFilePath(value.path, null);
}
}
pub fn createEmpty(
arena: Allocator,
comp: *Compilation,
emit: Path,
options: link.File.OpenOptions,
) !*MachO {
const target = &comp.root_mod.resolved_target.result;
assert(target.ofmt == .macho);
const gpa = comp.gpa;
const use_llvm = comp.config.use_llvm;
const opt_zcu = comp.zcu;
const optimize_mode = comp.root_mod.optimize_mode;
const output_mode = comp.config.output_mode;
const link_mode = comp.config.link_mode;
const allow_shlib_undefined = options.allow_shlib_undefined orelse false;
const self = try arena.create(MachO);
self.* = .{
.base = .{
.tag = .macho,
.comp = comp,
.emit = emit,
.zcu_object_basename = if (use_llvm)
try std.fmt.allocPrint(arena, "{s}_zcu.o", .{fs.path.stem(emit.sub_path)})
else
null,
.gc_sections = options.gc_sections orelse (optimize_mode != .Debug),
.print_gc_sections = options.print_gc_sections,
.stack_size = options.stack_size orelse 16777216,
.allow_shlib_undefined = allow_shlib_undefined,
.file = null,
.build_id = options.build_id,
},
.rpath_list = options.rpath_list,
.pagezero_size = options.pagezero_size,
.headerpad_size = options.headerpad_size,
.headerpad_max_install_names = options.headerpad_max_install_names,
.dead_strip_dylibs = options.dead_strip_dylibs,
.sdk_layout = options.darwin_sdk_layout,
.frameworks = options.frameworks,
.install_name = options.install_name,
.entitlements = options.entitlements,
.compatibility_version = options.compatibility_version,
.entry_name = switch (options.entry) {
.disabled => null,
.default => if (output_mode != .Exe) null else default_entry_symbol_name,
.enabled => default_entry_symbol_name,
.named => |name| name,
},
.platform = Platform.fromTarget(target),
.sdk_version = if (options.darwin_sdk_layout) |layout| inferSdkVersion(comp, layout) else null,
.undefined_treatment = if (allow_shlib_undefined) .dynamic_lookup else .@"error",
// TODO delete this, directories must instead be resolved by the frontend
.lib_directories = options.lib_directories,
.framework_dirs = options.framework_dirs,
.force_load_objc = options.force_load_objc,
.discard_local_symbols = options.discard_local_symbols,
};
errdefer self.base.destroy();
self.base.file = try emit.root_dir.handle.createFile(emit.sub_path, .{
.truncate = true,
.read = true,
.mode = link.File.determineMode(output_mode, link_mode),
});
// Append null file
try self.files.append(gpa, .null);
// Append empty string to string tables
try self.strtab.append(gpa, 0);
if (opt_zcu) |zcu| {
if (!use_llvm) {
const index: File.Index = @intCast(try self.files.addOne(gpa));
self.files.set(index, .{ .zig_object = .{
.index = index,
.basename = try std.fmt.allocPrint(arena, "{s}.o", .{
fs.path.stem(zcu.main_mod.root_src_path),
}),
} });
self.zig_object = index;
const zo = self.getZigObject().?;
try zo.init(self);
try self.initMetadata(.{
.emit = emit,
.zo = zo,
.symbol_count_hint = options.symbol_count_hint,
.program_code_size_hint = options.program_code_size_hint,
});
}
}
return self;
}
pub fn open(
arena: Allocator,
comp: *Compilation,
emit: Path,
options: link.File.OpenOptions,
) !*MachO {
// TODO: restore saved linker state, don't truncate the file, and
// participate in incremental compilation.
return createEmpty(arena, comp, emit, options);
}
pub fn deinit(self: *MachO) void {
const gpa = self.base.comp.gpa;
if (self.d_sym) |*d_sym| {
d_sym.deinit();
}
for (self.file_handles.items) |handle| {
handle.close();
}
self.file_handles.deinit(gpa);
for (self.files.items(.tags), self.files.items(.data)) |tag, *data| switch (tag) {
.null => {},
.zig_object => data.zig_object.deinit(gpa),
.internal => data.internal.deinit(gpa),
.object => data.object.deinit(gpa),
.dylib => data.dylib.deinit(gpa),
};
self.files.deinit(gpa);
self.objects.deinit(gpa);
self.dylibs.deinit(gpa);
self.segments.deinit(gpa);
for (
self.sections.items(.atoms),
self.sections.items(.out),
self.sections.items(.thunks),
self.sections.items(.relocs),
) |*atoms, *out, *thnks, *relocs| {
atoms.deinit(gpa);
out.deinit(gpa);
thnks.deinit(gpa);
relocs.deinit(gpa);
}
self.sections.deinit(gpa);
self.resolver.deinit(gpa);
for (self.undefs.values()) |*val| {
val.deinit(gpa);
}
self.undefs.deinit(gpa);
for (self.dupes.values()) |*val| {
val.deinit(gpa);
}
self.dupes.deinit(gpa);
self.symtab.deinit(gpa);
self.strtab.deinit(gpa);
self.got.deinit(gpa);
self.stubs.deinit(gpa);
self.objc_stubs.deinit(gpa);
self.tlv_ptr.deinit(gpa);
self.rebase_section.deinit(gpa);
self.bind_section.deinit(gpa);
self.weak_bind_section.deinit(gpa);
self.lazy_bind_section.deinit(gpa);
self.export_trie.deinit(gpa);
self.unwind_info.deinit(gpa);
self.data_in_code.deinit(gpa);
self.thunks.deinit(gpa);
}
pub fn flush(
self: *MachO,
arena: Allocator,
tid: Zcu.PerThread.Id,
prog_node: std.Progress.Node,
) link.File.FlushError!void {
const tracy = trace(@src());
defer tracy.end();
const comp = self.base.comp;
const gpa = comp.gpa;
const diags = &self.base.comp.link_diags;
const sub_prog_node = prog_node.start("MachO Flush", 0);
defer sub_prog_node.end();
const zcu_obj_path: ?Path = if (self.base.zcu_object_basename) |raw| p: {
break :p try comp.resolveEmitPathFlush(arena, .temp, raw);
} else null;
// --verbose-link
if (comp.verbose_link) try self.dumpArgv(comp);
if (self.getZigObject()) |zo| try zo.flush(self, tid);
if (self.base.isStaticLib()) return relocatable.flushStaticLib(self, comp, zcu_obj_path);
if (self.base.isObject()) return relocatable.flushObject(self, comp, zcu_obj_path);
var positionals = std.ArrayList(link.Input).init(gpa);
defer positionals.deinit();
try positionals.ensureUnusedCapacity(comp.link_inputs.len);
for (comp.link_inputs) |link_input| switch (link_input) {
.dso => continue, // handled below
.object, .archive => positionals.appendAssumeCapacity(link_input),
.dso_exact => @panic("TODO"),
.res => unreachable,
};
// This is a set of object files emitted by clang in a single `build-exe` invocation.
// For instance, the implicit `a.o` as compiled by `zig build-exe a.c` will end up
// in this set.
try positionals.ensureUnusedCapacity(comp.c_object_table.keys().len);
for (comp.c_object_table.keys()) |key| {
positionals.appendAssumeCapacity(try link.openObjectInput(diags, key.status.success.object_path));
}
if (zcu_obj_path) |path| try positionals.append(try link.openObjectInput(diags, path));
if (comp.config.any_sanitize_thread) {
try positionals.append(try link.openObjectInput(diags, comp.tsan_lib.?.full_object_path));
}
if (comp.config.any_fuzz) {
try positionals.append(try link.openArchiveInput(diags, comp.fuzzer_lib.?.full_object_path, false, false));
}
if (comp.ubsan_rt_lib) |crt_file| {
const path = crt_file.full_object_path;
self.classifyInputFile(try link.openArchiveInput(diags, path, false, false)) catch |err|
diags.addParseError(path, "failed to parse archive: {s}", .{@errorName(err)});
} else if (comp.ubsan_rt_obj) |crt_file| {
const path = crt_file.full_object_path;
self.classifyInputFile(try link.openObjectInput(diags, path)) catch |err|
diags.addParseError(path, "failed to parse archive: {s}", .{@errorName(err)});
}
for (positionals.items) |link_input| {
self.classifyInputFile(link_input) catch |err|
diags.addParseError(link_input.path().?, "failed to read input file: {s}", .{@errorName(err)});
}
var system_libs = std.ArrayList(SystemLib).init(gpa);
defer system_libs.deinit();
// frameworks
try system_libs.ensureUnusedCapacity(self.frameworks.len);
for (self.frameworks) |info| {
system_libs.appendAssumeCapacity(.{
.needed = info.needed,
.weak = info.weak,
.path = info.path,
});
}
// libc++ dep
if (comp.config.link_libcpp) {
try system_libs.ensureUnusedCapacity(2);
system_libs.appendAssumeCapacity(.{ .path = comp.libcxxabi_static_lib.?.full_object_path });
system_libs.appendAssumeCapacity(.{ .path = comp.libcxx_static_lib.?.full_object_path });
}
const is_exe_or_dyn_lib = comp.config.output_mode == .Exe or
(comp.config.output_mode == .Lib and comp.config.link_mode == .dynamic);
if (comp.config.link_libc and is_exe_or_dyn_lib) {
if (comp.zigc_static_lib) |zigc| {
const path = zigc.full_object_path;
self.classifyInputFile(try link.openArchiveInput(diags, path, false, false)) catch |err|
diags.addParseError(path, "failed to parse archive: {s}", .{@errorName(err)});
}
}
// libc/libSystem dep
self.resolveLibSystem(arena, comp, &system_libs) catch |err| switch (err) {
error.MissingLibSystem => {}, // already reported
else => |e| return diags.fail("failed to resolve libSystem: {s}", .{@errorName(e)}),
};
for (comp.link_inputs) |link_input| switch (link_input) {
.object, .archive, .dso_exact => continue,
.res => unreachable,
.dso => {
self.classifyInputFile(link_input) catch |err|
diags.addParseError(link_input.path().?, "failed to parse input file: {s}", .{@errorName(err)});
},
};
for (system_libs.items) |lib| {
switch (Compilation.classifyFileExt(lib.path.sub_path)) {
.shared_library => {
const dso_input = try link.openDsoInput(diags, lib.path, lib.needed, lib.weak, lib.reexport);
self.classifyInputFile(dso_input) catch |err|
diags.addParseError(lib.path, "failed to parse input file: {s}", .{@errorName(err)});
},
.static_library => {
const archive_input = try link.openArchiveInput(diags, lib.path, lib.must_link, lib.hidden);
self.classifyInputFile(archive_input) catch |err|
diags.addParseError(lib.path, "failed to parse input file: {s}", .{@errorName(err)});
},
else => unreachable,
}
}
// Finally, link against compiler_rt.
if (comp.compiler_rt_lib) |crt_file| {
const path = crt_file.full_object_path;
self.classifyInputFile(try link.openArchiveInput(diags, path, false, false)) catch |err|
diags.addParseError(path, "failed to parse archive: {s}", .{@errorName(err)});
} else if (comp.compiler_rt_obj) |crt_file| {
const path = crt_file.full_object_path;
self.classifyInputFile(try link.openObjectInput(diags, path)) catch |err|
diags.addParseError(path, "failed to parse archive: {s}", .{@errorName(err)});
}
try self.parseInputFiles();
self.parseDependentDylibs() catch |err| {
switch (err) {
error.MissingLibraryDependencies => {},
else => |e| return diags.fail("failed to parse dependent libraries: {s}", .{@errorName(e)}),
}
};
if (diags.hasErrors()) return error.LinkFailure;
{
const index = @as(File.Index, @intCast(try self.files.addOne(gpa)));
self.files.set(index, .{ .internal = .{ .index = index } });
self.internal_object = index;
const object = self.getInternalObject().?;
try object.init(gpa);
try object.initSymbols(self);
}
try self.resolveSymbols();
try self.convertTentativeDefsAndResolveSpecialSymbols();
self.dedupLiterals() catch |err| switch (err) {
error.LinkFailure => return error.LinkFailure,
else => |e| return diags.fail("failed to deduplicate literals: {s}", .{@errorName(e)}),
};
if (self.base.gc_sections) {
try dead_strip.gcAtoms(self);
}
self.checkDuplicates() catch |err| switch (err) {
error.HasDuplicates => return error.LinkFailure,
else => |e| return diags.fail("failed to check for duplicate symbol definitions: {s}", .{@errorName(e)}),
};
self.markImportsAndExports();
self.deadStripDylibs();
for (self.dylibs.items, 1..) |index, ord| {
const dylib = self.getFile(index).?.dylib;
dylib.ordinal = @intCast(ord);
}
self.claimUnresolved();
self.scanRelocs() catch |err| switch (err) {
error.HasUndefinedSymbols => return error.LinkFailure,
else => |e| return diags.fail("failed to scan relocations: {s}", .{@errorName(e)}),
};
try self.initOutputSections();
try self.initSyntheticSections();
try self.sortSections();
try self.addAtomsToSections();
try self.calcSectionSizes();
try self.generateUnwindInfo();
try self.initSegments();
self.allocateSections() catch |err| switch (err) {
error.LinkFailure => return error.LinkFailure,
else => |e| return diags.fail("failed to allocate sections: {s}", .{@errorName(e)}),
};
self.allocateSegments();
self.allocateSyntheticSymbols();
if (build_options.enable_logging) {
state_log.debug("{f}", .{self.dumpState()});
}
// Beyond this point, everything has been allocated a virtual address and we can resolve
// the relocations, and commit objects to file.
try self.resizeSections();
if (self.getZigObject()) |zo| {
zo.resolveRelocs(self) catch |err| switch (err) {
error.ResolveFailed => return error.LinkFailure,
else => |e| return e,
};
}
try self.writeSectionsAndUpdateLinkeditSizes();
try self.writeSectionsToFile();
try self.allocateLinkeditSegment();
self.writeLinkeditSectionsToFile() catch |err| switch (err) {
error.OutOfMemory => return error.OutOfMemory,
error.LinkFailure => return error.LinkFailure,
else => |e| return diags.fail("failed to write linkedit sections to file: {s}", .{@errorName(e)}),
};
var codesig: ?CodeSignature = if (self.requiresCodeSig()) blk: {
// Preallocate space for the code signature.
// We need to do this at this stage so that we have the load commands with proper values
// written out to the file.
// The most important here is to have the correct vm and filesize of the __LINKEDIT segment
// where the code signature goes into.
var codesig = CodeSignature.init(self.getPageSize());
codesig.code_directory.ident = fs.path.basename(self.base.emit.sub_path);
if (self.entitlements) |path| codesig.addEntitlements(gpa, path) catch |err|
return diags.fail("failed to add entitlements from {s}: {s}", .{ path, @errorName(err) });
try self.writeCodeSignaturePadding(&codesig);
break :blk codesig;
} else null;
defer if (codesig) |*csig| csig.deinit(gpa);
self.getLinkeditSegment().vmsize = mem.alignForward(
u64,
self.getLinkeditSegment().filesize,
self.getPageSize(),
);
const ncmds, const sizeofcmds, const uuid_cmd_offset = self.writeLoadCommands() catch |err| switch (err) {
error.NoSpaceLeft => unreachable,
error.OutOfMemory => return error.OutOfMemory,
error.LinkFailure => return error.LinkFailure,
};
try self.writeHeader(ncmds, sizeofcmds);
self.writeUuid(uuid_cmd_offset, self.requiresCodeSig()) catch |err| switch (err) {
error.OutOfMemory => return error.OutOfMemory,
error.LinkFailure => return error.LinkFailure,
else => |e| return diags.fail("failed to calculate and write uuid: {s}", .{@errorName(e)}),
};
if (self.getDebugSymbols()) |dsym| dsym.flush(self) catch |err| switch (err) {
error.OutOfMemory => return error.OutOfMemory,
else => |e| return diags.fail("failed to get debug symbols: {s}", .{@errorName(e)}),
};
// Code signing always comes last.
if (codesig) |*csig| {
self.writeCodeSignature(csig) catch |err| switch (err) {
error.OutOfMemory => return error.OutOfMemory,
error.LinkFailure => return error.LinkFailure,
else => |e| return diags.fail("failed to write code signature: {s}", .{@errorName(e)}),
};
const emit = self.base.emit;
invalidateKernelCache(emit.root_dir.handle, emit.sub_path) catch |err| switch (err) {
error.OutOfMemory => return error.OutOfMemory,
else => |e| return diags.fail("failed to invalidate kernel cache: {s}", .{@errorName(e)}),
};
}
}
/// --verbose-link output
fn dumpArgv(self: *MachO, comp: *Compilation) !void {
const gpa = self.base.comp.gpa;
var arena_allocator = std.heap.ArenaAllocator.init(gpa);
defer arena_allocator.deinit();
const arena = arena_allocator.allocator();
const directory = self.base.emit.root_dir;
const full_out_path = try directory.join(arena, &[_][]const u8{self.base.emit.sub_path});
const zcu_obj_path: ?[]const u8 = if (self.base.zcu_object_basename) |raw| p: {
const p = try comp.resolveEmitPathFlush(arena, .temp, raw);
break :p try p.toString(arena);
} else null;
var argv = std.ArrayList([]const u8).init(arena);
try argv.append("zig");
if (self.base.isStaticLib()) {
try argv.append("ar");
} else {
try argv.append("ld");
}
if (self.base.isObject()) {
try argv.append("-r");
}
if (self.base.isRelocatable()) {
for (comp.link_inputs) |link_input| switch (link_input) {
.object, .archive => |obj| try argv.append(try obj.path.toString(arena)),
.res => |res| try argv.append(try res.path.toString(arena)),
.dso => |dso| try argv.append(try dso.path.toString(arena)),
.dso_exact => |dso_exact| try argv.appendSlice(&.{ "-l", dso_exact.name }),
};
for (comp.c_object_table.keys()) |key| {
try argv.append(try key.status.success.object_path.toString(arena));
}
if (zcu_obj_path) |p| {
try argv.append(p);
}
} else {
if (!self.base.isStatic()) {
try argv.append("-dynamic");
}
if (self.base.isDynLib()) {
try argv.append("-dylib");
if (self.install_name) |install_name| {
try argv.append("-install_name");
try argv.append(install_name);
}
}
try argv.append("-platform_version");
try argv.append(@tagName(self.platform.os_tag));
try argv.append(try std.fmt.allocPrint(arena, "{f}", .{self.platform.version}));
if (self.sdk_version) |ver| {
try argv.append(try std.fmt.allocPrint(arena, "{d}.{d}", .{ ver.major, ver.minor }));
} else {
try argv.append(try std.fmt.allocPrint(arena, "{f}", .{self.platform.version}));
}
if (comp.sysroot) |syslibroot| {
try argv.append("-syslibroot");
try argv.append(syslibroot);
}
for (self.rpath_list) |rpath| {
try argv.appendSlice(&.{ "-rpath", rpath });
}
if (self.pagezero_size) |size| {
try argv.append("-pagezero_size");
try argv.append(try std.fmt.allocPrint(arena, "0x{x}", .{size}));
}
if (self.headerpad_size) |size| {
try argv.append("-headerpad_size");
try argv.append(try std.fmt.allocPrint(arena, "0x{x}", .{size}));
}
if (self.headerpad_max_install_names) {
try argv.append("-headerpad_max_install_names");
}
if (self.base.gc_sections) {
try argv.append("-dead_strip");
}
if (self.dead_strip_dylibs) {
try argv.append("-dead_strip_dylibs");
}
if (self.force_load_objc) {
try argv.append("-ObjC");
}
if (self.discard_local_symbols) {
try argv.append("-x");
}
if (self.entry_name) |entry_name| {
try argv.appendSlice(&.{ "-e", entry_name });
}
try argv.append("-o");
try argv.append(full_out_path);
if (self.base.isDynLib() and self.base.allow_shlib_undefined) {
try argv.append("-undefined");
try argv.append("dynamic_lookup");
}
for (comp.link_inputs) |link_input| switch (link_input) {
.dso => continue, // handled below
.res => unreachable, // windows only
.object, .archive => |obj| {
if (obj.must_link) try argv.append("-force_load"); // TODO: verify this
try argv.append(try obj.path.toString(arena));
},
.dso_exact => |dso_exact| try argv.appendSlice(&.{ "-l", dso_exact.name }),
};
for (comp.c_object_table.keys()) |key| {
try argv.append(try key.status.success.object_path.toString(arena));
}
if (zcu_obj_path) |p| {
try argv.append(p);
}
if (comp.config.any_sanitize_thread) {
const path = try comp.tsan_lib.?.full_object_path.toString(arena);
try argv.appendSlice(&.{ path, "-rpath", std.fs.path.dirname(path) orelse "." });
}
if (comp.config.any_fuzz) {
try argv.append(try comp.fuzzer_lib.?.full_object_path.toString(arena));
}
for (self.lib_directories) |lib_directory| {
// TODO delete this, directories must instead be resolved by the frontend
const arg = try std.fmt.allocPrint(arena, "-L{s}", .{lib_directory.path orelse "."});
try argv.append(arg);
}
for (comp.link_inputs) |link_input| switch (link_input) {
.object, .archive, .dso_exact => continue, // handled above
.res => unreachable, // windows only
.dso => |dso| {
if (dso.needed) {
try argv.appendSlice(&.{ "-needed-l", try dso.path.toString(arena) });
} else if (dso.weak) {
try argv.appendSlice(&.{ "-weak-l", try dso.path.toString(arena) });
} else {
try argv.appendSlice(&.{ "-l", try dso.path.toString(arena) });
}
},
};
for (self.framework_dirs) |f_dir| {
try argv.append("-F");
try argv.append(f_dir);
}
for (self.frameworks) |framework| {
const name = framework.path.stem();
const arg = if (framework.needed)
try std.fmt.allocPrint(arena, "-needed_framework {s}", .{name})
else if (framework.weak)
try std.fmt.allocPrint(arena, "-weak_framework {s}", .{name})
else
try std.fmt.allocPrint(arena, "-framework {s}", .{name});
try argv.append(arg);
}
if (comp.config.link_libcpp) {
try argv.appendSlice(&.{
try comp.libcxxabi_static_lib.?.full_object_path.toString(arena),
try comp.libcxx_static_lib.?.full_object_path.toString(arena),
});
}
try argv.append("-lSystem");
if (comp.zigc_static_lib) |lib| try argv.append(try lib.full_object_path.toString(arena));
if (comp.compiler_rt_lib) |lib| try argv.append(try lib.full_object_path.toString(arena));
if (comp.compiler_rt_obj) |obj| try argv.append(try obj.full_object_path.toString(arena));
if (comp.ubsan_rt_lib) |lib| try argv.append(try lib.full_object_path.toString(arena));
if (comp.ubsan_rt_obj) |obj| try argv.append(try obj.full_object_path.toString(arena));
}
Compilation.dump_argv(argv.items);
}
/// TODO delete this, libsystem must be resolved when setting up the compilation pipeline
pub fn resolveLibSystem(
self: *MachO,
arena: Allocator,
comp: *Compilation,
out_libs: anytype,
) !void {
const diags = &self.base.comp.link_diags;
var test_path = std.ArrayList(u8).init(arena);
var checked_paths = std.ArrayList([]const u8).init(arena);
success: {
if (self.sdk_layout) |sdk_layout| switch (sdk_layout) {
.sdk => {
const dir = try fs.path.join(arena, &.{ comp.sysroot.?, "usr", "lib" });
if (try accessLibPath(arena, &test_path, &checked_paths, dir, "System")) break :success;
},
.vendored => {
const dir = try comp.dirs.zig_lib.join(arena, &.{ "libc", "darwin" });
if (try accessLibPath(arena, &test_path, &checked_paths, dir, "System")) break :success;
},
};
for (self.lib_directories) |directory| {
if (try accessLibPath(arena, &test_path, &checked_paths, directory.path orelse ".", "System")) break :success;
}
diags.addMissingLibraryError(checked_paths.items, "unable to find libSystem system library", .{});
return error.MissingLibSystem;
}
const libsystem_path = Path.initCwd(try arena.dupe(u8, test_path.items));
try out_libs.append(.{
.needed = true,
.path = libsystem_path,
});
}
pub fn classifyInputFile(self: *MachO, input: link.Input) !void {
const tracy = trace(@src());
defer tracy.end();
const path, const file = input.pathAndFile().?;
// TODO don't classify now, it's too late. The input file has already been classified
log.debug("classifying input file {f}", .{path});
const fh = try self.addFileHandle(file);
var buffer: [Archive.SARMAG]u8 = undefined;
const fat_arch: ?fat.Arch = try self.parseFatFile(file, path);
const offset = if (fat_arch) |fa| fa.offset else 0;
if (readMachHeader(file, offset) catch null) |h| blk: {
if (h.magic != macho.MH_MAGIC_64) break :blk;
switch (h.filetype) {
macho.MH_OBJECT => try self.addObject(path, fh, offset),
macho.MH_DYLIB => _ = try self.addDylib(.fromLinkInput(input), true, fh, offset),
else => return error.UnknownFileType,
}
return;
}
if (readArMagic(file, offset, &buffer) catch null) |ar_magic| blk: {
if (!mem.eql(u8, ar_magic, Archive.ARMAG)) break :blk;
try self.addArchive(input.archive, fh, fat_arch);
return;
}
_ = try self.addTbd(.fromLinkInput(input), true, fh);
}
fn parseFatFile(self: *MachO, file: std.fs.File, path: Path) !?fat.Arch {
const diags = &self.base.comp.link_diags;
const fat_h = fat.readFatHeader(file) catch return null;
if (fat_h.magic != macho.FAT_MAGIC and fat_h.magic != macho.FAT_MAGIC_64) return null;
var fat_archs_buffer: [2]fat.Arch = undefined;
const fat_archs = try fat.parseArchs(file, fat_h, &fat_archs_buffer);
const cpu_arch = self.getTarget().cpu.arch;
for (fat_archs) |arch| {
if (arch.tag == cpu_arch) return arch;
}
return diags.failParse(path, "missing arch in universal file: expected {s}", .{@tagName(cpu_arch)});
}
pub fn readMachHeader(file: std.fs.File, offset: usize) !macho.mach_header_64 {
var buffer: [@sizeOf(macho.mach_header_64)]u8 = undefined;
const nread = try file.preadAll(&buffer, offset);
if (nread != buffer.len) return error.InputOutput;
const hdr = @as(*align(1) const macho.mach_header_64, @ptrCast(&buffer)).*;
return hdr;
}
pub fn readArMagic(file: std.fs.File, offset: usize, buffer: *[Archive.SARMAG]u8) ![]const u8 {
const nread = try file.preadAll(buffer, offset);
if (nread != buffer.len) return error.InputOutput;
return buffer[0..Archive.SARMAG];
}
fn addObject(self: *MachO, path: Path, handle: File.HandleIndex, offset: u64) !void {
const tracy = trace(@src());
defer tracy.end();
const gpa = self.base.comp.gpa;
const mtime: u64 = mtime: {
const file = self.getFileHandle(handle);
const stat = file.stat() catch break :mtime 0;
break :mtime @as(u64, @intCast(@divFloor(stat.mtime, 1_000_000_000)));
};
const index = @as(File.Index, @intCast(try self.files.addOne(gpa)));
self.files.set(index, .{ .object = .{
.offset = offset,
.path = .{
.root_dir = path.root_dir,
.sub_path = try gpa.dupe(u8, path.sub_path),
},
.file_handle = handle,
.mtime = mtime,
.index = index,
} });
try self.objects.append(gpa, index);
}
pub fn parseInputFiles(self: *MachO) !void {
const tracy = trace(@src());
defer tracy.end();
const diags = &self.base.comp.link_diags;
{
for (self.objects.items) |index| {
parseInputFileWorker(self, self.getFile(index).?);
}
for (self.dylibs.items) |index| {
parseInputFileWorker(self, self.getFile(index).?);
}
}
if (diags.hasErrors()) return error.LinkFailure;
}
fn parseInputFileWorker(self: *MachO, file: File) void {
file.parse(self) catch |err| {
switch (err) {
error.MalformedObject,
error.MalformedDylib,
error.MalformedTbd,
error.InvalidMachineType,
error.InvalidTarget,
=> {}, // already reported
else => |e| self.reportParseError2(file.getIndex(), "unexpected error: parsing input file failed with error {s}", .{@errorName(e)}) catch {},
}
};
}
fn addArchive(self: *MachO, lib: link.Input.Object, handle: File.HandleIndex, fat_arch: ?fat.Arch) !void {
const tracy = trace(@src());
defer tracy.end();
const gpa = self.base.comp.gpa;
var archive: Archive = .{};
defer archive.deinit(gpa);
try archive.unpack(self, lib.path, handle, fat_arch);
for (archive.objects.items) |unpacked| {
const index: File.Index = @intCast(try self.files.addOne(gpa));
self.files.set(index, .{ .object = unpacked });
const object = &self.files.items(.data)[index].object;
object.index = index;
object.alive = lib.must_link; // TODO: or self.options.all_load;
object.hidden = lib.hidden;
try self.objects.append(gpa, index);
}
}
fn addDylib(self: *MachO, lib: SystemLib, explicit: bool, handle: File.HandleIndex, offset: u64) !File.Index {
const tracy = trace(@src());
defer tracy.end();
const gpa = self.base.comp.gpa;
const index: File.Index = @intCast(try self.files.addOne(gpa));
self.files.set(index, .{ .dylib = .{
.offset = offset,
.file_handle = handle,
.tag = .dylib,
.path = .{
.root_dir = lib.path.root_dir,
.sub_path = try gpa.dupe(u8, lib.path.sub_path),
},
.index = index,
.needed = lib.needed,
.weak = lib.weak,
.reexport = lib.reexport,
.explicit = explicit,
.umbrella = index,
} });
try self.dylibs.append(gpa, index);
return index;
}
fn addTbd(self: *MachO, lib: SystemLib, explicit: bool, handle: File.HandleIndex) !File.Index {
const tracy = trace(@src());
defer tracy.end();
const gpa = self.base.comp.gpa;
const index: File.Index = @intCast(try self.files.addOne(gpa));
self.files.set(index, .{ .dylib = .{
.offset = 0,
.file_handle = handle,
.tag = .tbd,
.path = .{
.root_dir = lib.path.root_dir,
.sub_path = try gpa.dupe(u8, lib.path.sub_path),
},
.index = index,
.needed = lib.needed,
.weak = lib.weak,
.reexport = lib.reexport,
.explicit = explicit,
.umbrella = index,
} });
try self.dylibs.append(gpa, index);
return index;
}
/// According to ld64's manual, public (i.e., system) dylibs/frameworks are hoisted into the final
/// image unless overriden by -no_implicit_dylibs.
fn isHoisted(self: *MachO, install_name: []const u8) bool {
if (self.no_implicit_dylibs) return true;
if (fs.path.dirname(install_name)) |dirname| {
if (mem.startsWith(u8, dirname, "/usr/lib")) return true;
if (eatPrefix(dirname, "/System/Library/Frameworks/")) |path| {
const basename = fs.path.basename(install_name);
if (mem.indexOfScalar(u8, path, '.')) |index| {
if (mem.eql(u8, basename, path[0..index])) return true;
}
}
}
return false;
}
/// TODO delete this, libraries must be instead resolved when instantiating the compilation pipeline
fn accessLibPath(
arena: Allocator,
test_path: *std.ArrayList(u8),
checked_paths: *std.ArrayList([]const u8),
search_dir: []const u8,
name: []const u8,
) !bool {
const sep = fs.path.sep_str;
for (&[_][]const u8{ ".tbd", ".dylib", "" }) |ext| {
test_path.clearRetainingCapacity();
try test_path.writer().print("{s}" ++ sep ++ "lib{s}{s}", .{ search_dir, name, ext });
try checked_paths.append(try arena.dupe(u8, test_path.items));
fs.cwd().access(test_path.items, .{}) catch |err| switch (err) {
error.FileNotFound => continue,
else => |e| return e,
};
return true;
}
return false;
}
fn accessFrameworkPath(
arena: Allocator,
test_path: *std.ArrayList(u8),
checked_paths: *std.ArrayList([]const u8),
search_dir: []const u8,
name: []const u8,
) !bool {
const sep = fs.path.sep_str;
for (&[_][]const u8{ ".tbd", ".dylib", "" }) |ext| {
test_path.clearRetainingCapacity();
try test_path.writer().print("{s}" ++ sep ++ "{s}.framework" ++ sep ++ "{s}{s}", .{
search_dir,
name,
name,
ext,
});
try checked_paths.append(try arena.dupe(u8, test_path.items));
fs.cwd().access(test_path.items, .{}) catch |err| switch (err) {
error.FileNotFound => continue,
else => |e| return e,
};
return true;
}
return false;
}
fn parseDependentDylibs(self: *MachO) !void {
const tracy = trace(@src());
defer tracy.end();
if (self.dylibs.items.len == 0) return;
const gpa = self.base.comp.gpa;
const framework_dirs = self.framework_dirs;
// TODO delete this, directories must instead be resolved by the frontend
const lib_directories = self.lib_directories;
var arena_alloc = std.heap.ArenaAllocator.init(gpa);
defer arena_alloc.deinit();
const arena = arena_alloc.allocator();
// TODO handle duplicate dylibs - it is not uncommon to have the same dylib loaded multiple times
// in which case we should track that and return File.Index immediately instead re-parsing paths.
var has_errors = false;
var index: usize = 0;
while (index < self.dylibs.items.len) : (index += 1) {
const dylib_index = self.dylibs.items[index];
var dependents = std.ArrayList(File.Index).init(gpa);
defer dependents.deinit();
try dependents.ensureTotalCapacityPrecise(self.getFile(dylib_index).?.dylib.dependents.items.len);
const is_weak = self.getFile(dylib_index).?.dylib.weak;
for (self.getFile(dylib_index).?.dylib.dependents.items) |id| {
// We will search for the dependent dylibs in the following order:
// 1. Basename is in search lib directories or framework directories
// 2. If name is an absolute path, search as-is optionally prepending a syslibroot
// if specified.
// 3. If name is a relative path, substitute @rpath, @loader_path, @executable_path with
// dependees list of rpaths, and search there.
// 4. Finally, just search the provided relative path directly in CWD.
var test_path = std.ArrayList(u8).init(arena);
var checked_paths = std.ArrayList([]const u8).init(arena);
const full_path = full_path: {
{
const stem = fs.path.stem(id.name);
// Framework
for (framework_dirs) |dir| {
test_path.clearRetainingCapacity();
if (try accessFrameworkPath(arena, &test_path, &checked_paths, dir, stem)) break :full_path test_path.items;
}
// Library
const lib_name = eatPrefix(stem, "lib") orelse stem;
for (lib_directories) |lib_directory| {
test_path.clearRetainingCapacity();
if (try accessLibPath(arena, &test_path, &checked_paths, lib_directory.path orelse ".", lib_name)) break :full_path test_path.items;
}
}
if (fs.path.isAbsolute(id.name)) {
const existing_ext = fs.path.extension(id.name);
const path = if (existing_ext.len > 0) id.name[0 .. id.name.len - existing_ext.len] else id.name;
for (&[_][]const u8{ ".tbd", ".dylib", "" }) |ext| {
test_path.clearRetainingCapacity();
if (self.base.comp.sysroot) |root| {
try test_path.writer().print("{s}" ++ fs.path.sep_str ++ "{s}{s}", .{ root, path, ext });
} else {
try test_path.writer().print("{s}{s}", .{ path, ext });
}
try checked_paths.append(try arena.dupe(u8, test_path.items));
fs.cwd().access(test_path.items, .{}) catch |err| switch (err) {
error.FileNotFound => continue,
else => |e| return e,
};
break :full_path test_path.items;
}
}
if (eatPrefix(id.name, "@rpath/")) |path| {
const dylib = self.getFile(dylib_index).?.dylib;
for (self.getFile(dylib.umbrella).?.dylib.rpaths.keys()) |rpath| {
const prefix = eatPrefix(rpath, "@loader_path/") orelse rpath;
const rel_path = try fs.path.join(arena, &.{ prefix, path });
try checked_paths.append(rel_path);
var buffer: [fs.max_path_bytes]u8 = undefined;
const full_path = fs.realpath(rel_path, &buffer) catch continue;
break :full_path try arena.dupe(u8, full_path);
}
} else if (eatPrefix(id.name, "@loader_path/")) |_| {
try self.reportParseError2(dylib_index, "TODO handle install_name '{s}'", .{id.name});
return error.Unhandled;
} else if (eatPrefix(id.name, "@executable_path/")) |_| {
try self.reportParseError2(dylib_index, "TODO handle install_name '{s}'", .{id.name});
return error.Unhandled;
}
try checked_paths.append(try arena.dupe(u8, id.name));
var buffer: [fs.max_path_bytes]u8 = undefined;
if (fs.realpath(id.name, &buffer)) |full_path| {
break :full_path try arena.dupe(u8, full_path);
} else |_| {
try self.reportMissingDependencyError(
self.getFile(dylib_index).?.dylib.getUmbrella(self).index,
id.name,
checked_paths.items,
"unable to resolve dependency",
.{},
);
has_errors = true;
continue;
}
};
const lib: SystemLib = .{
.path = Path.initCwd(full_path),
.weak = is_weak,
};
const file = try lib.path.root_dir.handle.openFile(lib.path.sub_path, .{});
const fh = try self.addFileHandle(file);
const fat_arch = try self.parseFatFile(file, lib.path);
const offset = if (fat_arch) |fa| fa.offset else 0;
const file_index = file_index: {
if (readMachHeader(file, offset) catch null) |h| blk: {
if (h.magic != macho.MH_MAGIC_64) break :blk;
switch (h.filetype) {
macho.MH_DYLIB => break :file_index try self.addDylib(lib, false, fh, offset),
else => break :file_index @as(File.Index, 0),
}
}
break :file_index try self.addTbd(lib, false, fh);
};
dependents.appendAssumeCapacity(file_index);
}
const dylib = self.getFile(dylib_index).?.dylib;
for (dylib.dependents.items, dependents.items) |id, file_index| {
if (self.getFile(file_index)) |file| {
const dep_dylib = file.dylib;
try dep_dylib.parse(self); // TODO in parallel
dep_dylib.hoisted = self.isHoisted(id.name);
dep_dylib.umbrella = dylib.umbrella;
if (!dep_dylib.hoisted) {
const umbrella = dep_dylib.getUmbrella(self);
for (dep_dylib.exports.items(.name), dep_dylib.exports.items(.flags)) |off, flags| {
// TODO rethink this entire algorithm
try umbrella.addExport(gpa, dep_dylib.getString(off), flags);
}
try umbrella.rpaths.ensureUnusedCapacity(gpa, dep_dylib.rpaths.keys().len);
for (dep_dylib.rpaths.keys()) |rpath| {
umbrella.rpaths.putAssumeCapacity(try gpa.dupe(u8, rpath), {});
}
}
} else try self.reportDependencyError(
dylib.getUmbrella(self).index,
id.name,
"unable to resolve dependency",
.{},
);
has_errors = true;
}
}
if (has_errors) return error.MissingLibraryDependencies;
}
/// When resolving symbols, we approach the problem similarly to `mold`.
/// 1. Resolve symbols across all objects (including those preemptively extracted archives).
/// 2. Resolve symbols across all shared objects.
/// 3. Mark live objects (see `MachO.markLive`)
/// 4. Reset state of all resolved globals since we will redo this bit on the pruned set.
/// 5. Remove references to dead objects/shared objects
/// 6. Re-run symbol resolution on pruned objects and shared objects sets.
pub fn resolveSymbols(self: *MachO) !void {
const tracy = trace(@src());
defer tracy.end();
// Resolve symbols in the ZigObject. For now, we assume that it's always live.
if (self.getZigObject()) |zo| try zo.asFile().resolveSymbols(self);
// Resolve symbols on the set of all objects and shared objects (even if some are unneeded).
for (self.objects.items) |index| try self.getFile(index).?.resolveSymbols(self);
for (self.dylibs.items) |index| try self.getFile(index).?.resolveSymbols(self);
if (self.getInternalObject()) |obj| try obj.resolveSymbols(self);
// Mark live objects.
self.markLive();
// Reset state of all globals after marking live objects.
self.resolver.reset();
// Prune dead objects.
var i: usize = 0;
while (i < self.objects.items.len) {
const index = self.objects.items[i];
if (!self.getFile(index).?.object.alive) {
_ = self.objects.orderedRemove(i);
self.files.items(.data)[index].object.deinit(self.base.comp.gpa);
self.files.set(index, .null);
} else i += 1;
}
// Re-resolve the symbols.
if (self.getZigObject()) |zo| try zo.resolveSymbols(self);
for (self.objects.items) |index| try self.getFile(index).?.resolveSymbols(self);
for (self.dylibs.items) |index| try self.getFile(index).?.resolveSymbols(self);
if (self.getInternalObject()) |obj| try obj.resolveSymbols(self);
// Merge symbol visibility
if (self.getZigObject()) |zo| zo.mergeSymbolVisibility(self);
for (self.objects.items) |index| self.getFile(index).?.object.mergeSymbolVisibility(self);
}
fn markLive(self: *MachO) void {
const tracy = trace(@src());
defer tracy.end();
if (self.getZigObject()) |zo| zo.markLive(self);
for (self.objects.items) |index| {
const object = self.getFile(index).?.object;
if (object.alive) object.markLive(self);
}
if (self.getInternalObject()) |obj| obj.markLive(self);
}
fn convertTentativeDefsAndResolveSpecialSymbols(self: *MachO) !void {
const diags = &self.base.comp.link_diags;
{
for (self.objects.items) |index| {
convertTentativeDefinitionsWorker(self, self.getFile(index).?.object);
}
if (self.getInternalObject()) |obj| {
resolveSpecialSymbolsWorker(self, obj);
}
}
if (diags.hasErrors()) return error.LinkFailure;
}
fn convertTentativeDefinitionsWorker(self: *MachO, object: *Object) void {
const tracy = trace(@src());
defer tracy.end();
object.convertTentativeDefinitions(self) catch |err| {
self.reportParseError2(
object.index,
"unexpected error occurred while converting tentative symbols into defined symbols: {s}",
.{@errorName(err)},
) catch {};
};
}
fn resolveSpecialSymbolsWorker(self: *MachO, obj: *InternalObject) void {
const tracy = trace(@src());
defer tracy.end();
const diags = &self.base.comp.link_diags;
obj.resolveBoundarySymbols(self) catch |err|
return diags.addError("failed to resolve boundary symbols: {s}", .{@errorName(err)});
obj.resolveObjcMsgSendSymbols(self) catch |err|
return diags.addError("failed to resolve ObjC msgsend stubs: {s}", .{@errorName(err)});
}
pub fn dedupLiterals(self: *MachO) !void {
const tracy = trace(@src());
defer tracy.end();
const gpa = self.base.comp.gpa;
var lp: LiteralPool = .{};
defer lp.deinit(gpa);
if (self.getZigObject()) |zo| {
try zo.resolveLiterals(&lp, self);
}
for (self.objects.items) |index| {
try self.getFile(index).?.object.resolveLiterals(&lp, self);
}
if (self.getInternalObject()) |object| {
try object.resolveLiterals(&lp, self);
}
{
if (self.getZigObject()) |zo| {
File.dedupLiterals(zo.asFile(), lp, self);
}
for (self.objects.items) |index| {
File.dedupLiterals(self.getFile(index).?, lp, self);
}
if (self.getInternalObject()) |object| {
File.dedupLiterals(object.asFile(), lp, self);
}
}
}
fn claimUnresolved(self: *MachO) void {
if (self.getZigObject()) |zo| {
zo.asFile().claimUnresolved(self);
}
for (self.objects.items) |index| {
self.getFile(index).?.claimUnresolved(self);
}
}
fn checkDuplicates(self: *MachO) !void {
const tracy = trace(@src());
defer tracy.end();
const diags = &self.base.comp.link_diags;
{
if (self.getZigObject()) |zo| {
checkDuplicatesWorker(self, zo.asFile());
}
for (self.objects.items) |index| {
checkDuplicatesWorker(self, self.getFile(index).?);
}
if (self.getInternalObject()) |obj| {
checkDuplicatesWorker(self, obj.asFile());
}
}
if (diags.hasErrors()) return error.LinkFailure;
try self.reportDuplicates();
}
fn checkDuplicatesWorker(self: *MachO, file: File) void {
const tracy = trace(@src());
defer tracy.end();
file.checkDuplicates(self) catch |err| {
self.reportParseError2(file.getIndex(), "failed to check for duplicate definitions: {s}", .{
@errorName(err),
}) catch {};
};
}
fn markImportsAndExports(self: *MachO) void {
const tracy = trace(@src());
defer tracy.end();
if (self.getZigObject()) |zo| {
zo.asFile().markImportsExports(self);
}
for (self.objects.items) |index| {
self.getFile(index).?.markImportsExports(self);
}
if (self.getInternalObject()) |obj| {
obj.asFile().markImportsExports(self);
}
}
fn deadStripDylibs(self: *MachO) void {
const tracy = trace(@src());
defer tracy.end();
for (self.dylibs.items) |index| {
self.getFile(index).?.dylib.markReferenced(self);
}
var i: usize = 0;
while (i < self.dylibs.items.len) {
const index = self.dylibs.items[i];
if (!self.getFile(index).?.dylib.isAlive(self)) {
_ = self.dylibs.orderedRemove(i);
self.files.items(.data)[index].dylib.deinit(self.base.comp.gpa);
self.files.set(index, .null);
} else i += 1;
}
}
fn scanRelocs(self: *MachO) !void {
const tracy = trace(@src());
defer tracy.end();
const diags = &self.base.comp.link_diags;
{
if (self.getZigObject()) |zo| {
scanRelocsWorker(self, zo.asFile());
}
for (self.objects.items) |index| {
scanRelocsWorker(self, self.getFile(index).?);
}
if (self.getInternalObject()) |obj| {
scanRelocsWorker(self, obj.asFile());
}
}
if (diags.hasErrors()) return error.LinkFailure;
if (self.getInternalObject()) |obj| {
try obj.checkUndefs(self);
}
try self.reportUndefs();
if (self.getZigObject()) |zo| {
try zo.asFile().createSymbolIndirection(self);
}
for (self.objects.items) |index| {
try self.getFile(index).?.createSymbolIndirection(self);
}
for (self.dylibs.items) |index| {
try self.getFile(index).?.createSymbolIndirection(self);
}
if (self.getInternalObject()) |obj| {
try obj.asFile().createSymbolIndirection(self);
}
}
fn scanRelocsWorker(self: *MachO, file: File) void {
file.scanRelocs(self) catch |err| {
self.reportParseError2(file.getIndex(), "failed to scan relocations: {s}", .{
@errorName(err),
}) catch {};
};
}
fn sortGlobalSymbolsByName(self: *MachO, symbols: []SymbolResolver.Index) void {
const lessThan = struct {
fn lessThan(ctx: *MachO, lhs: SymbolResolver.Index, rhs: SymbolResolver.Index) bool {
const lhs_name = ctx.resolver.keys.items[lhs - 1].getName(ctx);
const rhs_name = ctx.resolver.keys.items[rhs - 1].getName(ctx);
return mem.order(u8, lhs_name, rhs_name) == .lt;
}
}.lessThan;
mem.sort(SymbolResolver.Index, symbols, self, lessThan);
}
fn reportUndefs(self: *MachO) !void {
const tracy = trace(@src());
defer tracy.end();
if (self.undefined_treatment == .suppress or
self.undefined_treatment == .dynamic_lookup) return;
if (self.undefs.keys().len == 0) return; // Nothing to do
const gpa = self.base.comp.gpa;
const diags = &self.base.comp.link_diags;
const max_notes = 4;
// We will sort by name, and then by file to ensure deterministic output.
var keys = try std.ArrayList(SymbolResolver.Index).initCapacity(gpa, self.undefs.keys().len);
defer keys.deinit();
keys.appendSliceAssumeCapacity(self.undefs.keys());
self.sortGlobalSymbolsByName(keys.items);
const refLessThan = struct {
fn lessThan(ctx: void, lhs: Ref, rhs: Ref) bool {
_ = ctx;
return lhs.lessThan(rhs);
}
}.lessThan;
for (self.undefs.values()) |*undefs| switch (undefs.*) {
.refs => |refs| mem.sort(Ref, refs.items, {}, refLessThan),
else => {},
};
for (keys.items) |key| {
const undef_sym = self.resolver.keys.items[key - 1];
const notes = self.undefs.get(key).?;
const nnotes = nnotes: {
const nnotes = switch (notes) {
.refs => |refs| refs.items.len,
else => 1,
};
break :nnotes @min(nnotes, max_notes) + @intFromBool(nnotes > max_notes);
};
var err = try diags.addErrorWithNotes(nnotes);
try err.addMsg("undefined symbol: {s}", .{undef_sym.getName(self)});
switch (notes) {
.force_undefined => err.addNote("referenced with linker flag -u", .{}),
.entry => err.addNote("referenced with linker flag -e", .{}),
.dyld_stub_binder, .objc_msgsend => err.addNote("referenced implicitly", .{}),
.refs => |refs| {
var inote: usize = 0;
while (inote < @min(refs.items.len, max_notes)) : (inote += 1) {
const ref = refs.items[inote];
const file = self.getFile(ref.file).?;
const atom = ref.getAtom(self).?;
err.addNote("referenced by {f}:{s}", .{ file.fmtPath(), atom.getName(self) });
}
if (refs.items.len > max_notes) {
const remaining = refs.items.len - max_notes;
err.addNote("referenced {d} more times", .{remaining});
}
},
}
}
return error.HasUndefinedSymbols;
}
fn initOutputSections(self: *MachO) !void {
const tracy = trace(@src());
defer tracy.end();
for (self.objects.items) |index| {
try self.getFile(index).?.initOutputSections(self);
}
if (self.getInternalObject()) |obj| {
try obj.asFile().initOutputSections(self);
}
self.text_sect_index = self.getSectionByName("__TEXT", "__text") orelse
try self.addSection("__TEXT", "__text", .{
.alignment = switch (self.getTarget().cpu.arch) {
.x86_64 => 0,
.aarch64 => 2,
else => unreachable,
},
.flags = macho.S_REGULAR |
macho.S_ATTR_PURE_INSTRUCTIONS | macho.S_ATTR_SOME_INSTRUCTIONS,
});
self.data_sect_index = self.getSectionByName("__DATA", "__data") orelse
try self.addSection("__DATA", "__data", .{});
}
fn initSyntheticSections(self: *MachO) !void {
const cpu_arch = self.getTarget().cpu.arch;
if (self.got.symbols.items.len > 0) {
self.got_sect_index = try self.addSection("__DATA_CONST", "__got", .{
.flags = macho.S_NON_LAZY_SYMBOL_POINTERS,
.reserved1 = @intCast(self.stubs.symbols.items.len),
});
}
if (self.stubs.symbols.items.len > 0) {
self.stubs_sect_index = try self.addSection("__TEXT", "__stubs", .{
.flags = macho.S_SYMBOL_STUBS |
macho.S_ATTR_PURE_INSTRUCTIONS | macho.S_ATTR_SOME_INSTRUCTIONS,
.reserved1 = 0,
.reserved2 = switch (cpu_arch) {
.x86_64 => 6,
.aarch64 => 3 * @sizeOf(u32),
else => 0,
},
});
self.stubs_helper_sect_index = try self.addSection("__TEXT", "__stub_helper", .{
.flags = macho.S_ATTR_PURE_INSTRUCTIONS | macho.S_ATTR_SOME_INSTRUCTIONS,
});
self.la_symbol_ptr_sect_index = try self.addSection("__DATA", "__la_symbol_ptr", .{
.flags = macho.S_LAZY_SYMBOL_POINTERS,
.reserved1 = @intCast(self.stubs.symbols.items.len + self.got.symbols.items.len),
});
}
if (self.objc_stubs.symbols.items.len > 0) {
self.objc_stubs_sect_index = try self.addSection("__TEXT", "__objc_stubs", .{
.flags = macho.S_ATTR_PURE_INSTRUCTIONS | macho.S_ATTR_SOME_INSTRUCTIONS,
});
}
if (self.tlv_ptr.symbols.items.len > 0) {
self.tlv_ptr_sect_index = try self.addSection("__DATA", "__thread_ptrs", .{
.flags = macho.S_THREAD_LOCAL_VARIABLE_POINTERS,
});
}
const needs_unwind_info = for (self.objects.items) |index| {
if (self.getFile(index).?.object.hasUnwindRecords()) break true;
} else false;
if (needs_unwind_info) {
self.unwind_info_sect_index = try self.addSection("__TEXT", "__unwind_info", .{});
}
const needs_eh_frame = for (self.objects.items) |index| {
if (self.getFile(index).?.object.hasEhFrameRecords()) break true;
} else false;
if (needs_eh_frame) {
assert(needs_unwind_info);
self.eh_frame_sect_index = try self.addSection("__TEXT", "__eh_frame", .{});
}
if (self.getInternalObject()) |obj| {
const gpa = self.base.comp.gpa;
for (obj.boundary_symbols.items) |sym_index| {
const ref = obj.getSymbolRef(sym_index, self);
const sym = ref.getSymbol(self).?;
const name = sym.getName(self);
if (eatPrefix(name, "segment$start$")) |segname| {
if (self.getSegmentByName(segname) == null) { // TODO check segname is valid
const prot = getSegmentProt(segname);
_ = try self.segments.append(gpa, .{
.cmdsize = @sizeOf(macho.segment_command_64),
.segname = makeStaticString(segname),
.initprot = prot,
.maxprot = prot,
});
}
} else if (eatPrefix(name, "segment$end$")) |segname| {
if (self.getSegmentByName(segname) == null) { // TODO check segname is valid
const prot = getSegmentProt(segname);
_ = try self.segments.append(gpa, .{
.cmdsize = @sizeOf(macho.segment_command_64),
.segname = makeStaticString(segname),
.initprot = prot,
.maxprot = prot,
});
}
} else if (eatPrefix(name, "section$start$")) |actual_name| {
const sep = mem.indexOfScalar(u8, actual_name, '$').?; // TODO error rather than a panic
const segname = actual_name[0..sep]; // TODO check segname is valid
const sectname = actual_name[sep + 1 ..]; // TODO check sectname is valid
if (self.getSectionByName(segname, sectname) == null) {
_ = try self.addSection(segname, sectname, .{});
}
} else if (eatPrefix(name, "section$end$")) |actual_name| {
const sep = mem.indexOfScalar(u8, actual_name, '$').?; // TODO error rather than a panic
const segname = actual_name[0..sep]; // TODO check segname is valid
const sectname = actual_name[sep + 1 ..]; // TODO check sectname is valid
if (self.getSectionByName(segname, sectname) == null) {
_ = try self.addSection(segname, sectname, .{});
}
} else unreachable;
}
}
}
fn getSegmentProt(segname: []const u8) macho.vm_prot_t {
if (mem.eql(u8, segname, "__PAGEZERO")) return macho.PROT.NONE;
if (mem.eql(u8, segname, "__TEXT")) return macho.PROT.READ | macho.PROT.EXEC;
if (mem.eql(u8, segname, "__LINKEDIT")) return macho.PROT.READ;
return macho.PROT.READ | macho.PROT.WRITE;
}
fn getSegmentRank(segname: []const u8) u8 {
if (mem.eql(u8, segname, "__PAGEZERO")) return 0x0;
if (mem.eql(u8, segname, "__LINKEDIT")) return 0xf;
if (mem.indexOf(u8, segname, "ZIG")) |_| return 0xe;
if (mem.startsWith(u8, segname, "__TEXT")) return 0x1;
if (mem.startsWith(u8, segname, "__DATA_CONST")) return 0x2;
if (mem.startsWith(u8, segname, "__DATA")) return 0x3;
return 0x4;
}
fn segmentLessThan(ctx: void, lhs: []const u8, rhs: []const u8) bool {
_ = ctx;
const lhs_rank = getSegmentRank(lhs);
const rhs_rank = getSegmentRank(rhs);
if (lhs_rank == rhs_rank) {
return mem.order(u8, lhs, rhs) == .lt;
}
return lhs_rank < rhs_rank;
}
fn getSectionRank(section: macho.section_64) u8 {
if (section.isCode()) {
if (mem.eql(u8, "__text", section.sectName())) return 0x0;
if (section.type() == macho.S_SYMBOL_STUBS) return 0x1;
return 0x2;
}
switch (section.type()) {
macho.S_NON_LAZY_SYMBOL_POINTERS,
macho.S_LAZY_SYMBOL_POINTERS,
=> return 0x0,
macho.S_MOD_INIT_FUNC_POINTERS => return 0x1,
macho.S_MOD_TERM_FUNC_POINTERS => return 0x2,
macho.S_ZEROFILL => return 0xf,
macho.S_THREAD_LOCAL_REGULAR => return 0xd,
macho.S_THREAD_LOCAL_ZEROFILL => return 0xe,
else => {
if (mem.eql(u8, "__unwind_info", section.sectName())) return 0xe;
if (mem.eql(u8, "__compact_unwind", section.sectName())) return 0xe;
if (mem.eql(u8, "__eh_frame", section.sectName())) return 0xf;
return 0x3;
},
}
}
fn sectionLessThan(ctx: void, lhs: macho.section_64, rhs: macho.section_64) bool {
if (mem.eql(u8, lhs.segName(), rhs.segName())) {
const lhs_rank = getSectionRank(lhs);
const rhs_rank = getSectionRank(rhs);
if (lhs_rank == rhs_rank) {
return mem.order(u8, lhs.sectName(), rhs.sectName()) == .lt;
}
return lhs_rank < rhs_rank;
}
return segmentLessThan(ctx, lhs.segName(), rhs.segName());
}
pub fn sortSections(self: *MachO) !void {
const Entry = struct {
index: u8,
pub fn lessThan(macho_file: *MachO, lhs: @This(), rhs: @This()) bool {
return sectionLessThan(
{},
macho_file.sections.items(.header)[lhs.index],
macho_file.sections.items(.header)[rhs.index],
);
}
};
const gpa = self.base.comp.gpa;
var entries = try std.ArrayList(Entry).initCapacity(gpa, self.sections.slice().len);
defer entries.deinit();
for (0..self.sections.slice().len) |index| {
entries.appendAssumeCapacity(.{ .index = @intCast(index) });
}
mem.sort(Entry, entries.items, self, Entry.lessThan);
const backlinks = try gpa.alloc(u8, entries.items.len);
defer gpa.free(backlinks);
for (entries.items, 0..) |entry, i| {
backlinks[entry.index] = @intCast(i);
}
var slice = self.sections.toOwnedSlice();
defer slice.deinit(gpa);
try self.sections.ensureTotalCapacity(gpa, slice.len);
for (entries.items) |sorted| {
self.sections.appendAssumeCapacity(slice.get(sorted.index));
}
for (&[_]*?u8{
&self.data_sect_index,
&self.got_sect_index,
&self.zig_text_sect_index,
&self.zig_const_sect_index,
&self.zig_data_sect_index,
&self.zig_bss_sect_index,
&self.stubs_sect_index,
&self.stubs_helper_sect_index,
&self.la_symbol_ptr_sect_index,
&self.tlv_ptr_sect_index,
&self.eh_frame_sect_index,
&self.unwind_info_sect_index,
&self.objc_stubs_sect_index,
&self.debug_str_sect_index,
&self.debug_info_sect_index,
&self.debug_abbrev_sect_index,
&self.debug_aranges_sect_index,
&self.debug_line_sect_index,
&self.debug_line_str_sect_index,
&self.debug_loclists_sect_index,
&self.debug_rnglists_sect_index,
}) |maybe_index| {
if (maybe_index.*) |*index| {
index.* = backlinks[index.*];
}
}
if (self.getZigObject()) |zo| {
for (zo.getAtoms()) |atom_index| {
const atom = zo.getAtom(atom_index) orelse continue;
if (!atom.isAlive()) continue;
atom.out_n_sect = backlinks[atom.out_n_sect];
}
if (zo.dwarf) |*dwarf| dwarf.reloadSectionMetadata();
}
for (self.objects.items) |index| {
const file = self.getFile(index).?;
for (file.getAtoms()) |atom_index| {
const atom = file.getAtom(atom_index) orelse continue;
if (!atom.isAlive()) continue;
atom.out_n_sect = backlinks[atom.out_n_sect];
}
}
if (self.getInternalObject()) |object| {
for (object.getAtoms()) |atom_index| {
const atom = object.getAtom(atom_index) orelse continue;
if (!atom.isAlive()) continue;
atom.out_n_sect = backlinks[atom.out_n_sect];
}
}
}
pub fn addAtomsToSections(self: *MachO) !void {
const tracy = trace(@src());
defer tracy.end();
const gpa = self.base.comp.gpa;
if (self.getZigObject()) |zo| {
for (zo.getAtoms()) |atom_index| {
const atom = zo.getAtom(atom_index) orelse continue;
if (!atom.isAlive()) continue;
if (self.isZigSection(atom.out_n_sect)) continue;
const atoms = &self.sections.items(.atoms)[atom.out_n_sect];
try atoms.append(gpa, .{ .index = atom_index, .file = zo.index });
}
}
for (self.objects.items) |index| {
const file = self.getFile(index).?;
for (file.getAtoms()) |atom_index| {
const atom = file.getAtom(atom_index) orelse continue;
if (!atom.isAlive()) continue;
const atoms = &self.sections.items(.atoms)[atom.out_n_sect];
try atoms.append(gpa, .{ .index = atom_index, .file = index });
}
}
if (self.getInternalObject()) |object| {
for (object.getAtoms()) |atom_index| {
const atom = object.getAtom(atom_index) orelse continue;
if (!atom.isAlive()) continue;
const atoms = &self.sections.items(.atoms)[atom.out_n_sect];
try atoms.append(gpa, .{ .index = atom_index, .file = object.index });
}
}
}
fn calcSectionSizes(self: *MachO) !void {
const tracy = trace(@src());
defer tracy.end();
const diags = &self.base.comp.link_diags;
const cpu_arch = self.getTarget().cpu.arch;
if (self.data_sect_index) |idx| {
const header = &self.sections.items(.header)[idx];
header.size += @sizeOf(u64);
header.@"align" = 3;
}
{
const slice = self.sections.slice();
for (slice.items(.header), slice.items(.atoms), 0..) |header, atoms, i| {
if (atoms.items.len == 0) continue;
if (self.requiresThunks() and header.isCode()) continue;
calcSectionSizeWorker(self, @as(u8, @intCast(i)));
}
if (self.requiresThunks()) {
for (slice.items(.header), slice.items(.atoms), 0..) |header, atoms, i| {
if (!header.isCode()) continue;
if (atoms.items.len == 0) continue;
createThunksWorker(self, @as(u8, @intCast(i)));
}
}
// At this point, we can also calculate most of the symtab and data-in-code linkedit section sizes
if (self.getZigObject()) |zo| {
File.calcSymtabSize(zo.asFile(), self);
}
for (self.objects.items) |index| {
File.calcSymtabSize(self.getFile(index).?, self);
}
for (self.dylibs.items) |index| {
File.calcSymtabSize(self.getFile(index).?, self);
}
if (self.getInternalObject()) |obj| {
File.calcSymtabSize(obj.asFile(), self);
}
}
if (diags.hasErrors()) return error.LinkFailure;
try self.calcSymtabSize();
if (self.got_sect_index) |idx| {
const header = &self.sections.items(.header)[idx];
header.size = self.got.size();
header.@"align" = 3;
}
if (self.stubs_sect_index) |idx| {
const header = &self.sections.items(.header)[idx];
header.size = self.stubs.size(self);
header.@"align" = switch (cpu_arch) {
.x86_64 => 1,
.aarch64 => 2,
else => 0,
};
}
if (self.stubs_helper_sect_index) |idx| {
const header = &self.sections.items(.header)[idx];
header.size = self.stubs_helper.size(self);
header.@"align" = 2;
}
if (self.la_symbol_ptr_sect_index) |idx| {
const header = &self.sections.items(.header)[idx];
header.size = self.la_symbol_ptr.size(self);
header.@"align" = 3;
}
if (self.tlv_ptr_sect_index) |idx| {
const header = &self.sections.items(.header)[idx];
header.size = self.tlv_ptr.size();
header.@"align" = 3;
}
if (self.objc_stubs_sect_index) |idx| {
const header = &self.sections.items(.header)[idx];
header.size = self.objc_stubs.size(self);
header.@"align" = switch (cpu_arch) {
.x86_64 => 0,
.aarch64 => 2,
else => 0,
};
}
}
fn calcSectionSizeWorker(self: *MachO, sect_id: u8) void {
const tracy = trace(@src());
defer tracy.end();
const diags = &self.base.comp.link_diags;
const doWork = struct {
fn doWork(macho_file: *MachO, header: *macho.section_64, atoms: []const Ref) !void {
for (atoms) |ref| {
const atom = ref.getAtom(macho_file).?;
const atom_alignment = atom.alignment.toByteUnits() orelse 1;
const offset = mem.alignForward(u64, header.size, atom_alignment);
const padding = offset - header.size;
atom.value = offset;
header.size += padding + atom.size;
header.@"align" = @max(header.@"align", atom.alignment.toLog2Units());
}
}
}.doWork;
const slice = self.sections.slice();
const header = &slice.items(.header)[sect_id];
const atoms = slice.items(.atoms)[sect_id].items;
doWork(self, header, atoms) catch |err| {
try diags.addError("failed to calculate size of section '{s},{s}': {s}", .{
header.segName(), header.sectName(), @errorName(err),
});
};
}
fn createThunksWorker(self: *MachO, sect_id: u8) void {
const tracy = trace(@src());
defer tracy.end();
const diags = &self.base.comp.link_diags;
self.createThunks(sect_id) catch |err| {
const header = self.sections.items(.header)[sect_id];
diags.addError("failed to create thunks and calculate size of section '{s},{s}': {s}", .{
header.segName(), header.sectName(), @errorName(err),
});
};
}
fn generateUnwindInfo(self: *MachO) !void {
const tracy = trace(@src());
defer tracy.end();
const diags = &self.base.comp.link_diags;
if (self.eh_frame_sect_index) |index| {
const sect = &self.sections.items(.header)[index];
sect.size = try eh_frame.calcSize(self);
sect.@"align" = 3;
}
if (self.unwind_info_sect_index) |index| {
const sect = &self.sections.items(.header)[index];
self.unwind_info.generate(self) catch |err| switch (err) {
error.TooManyPersonalities => return diags.fail("too many personalities in unwind info", .{}),
else => |e| return e,
};
sect.size = self.unwind_info.calcSize();
sect.@"align" = 2;
}
}
fn initSegments(self: *MachO) !void {
const gpa = self.base.comp.gpa;
const slice = self.sections.slice();
// Add __PAGEZERO if required
const pagezero_size = self.pagezero_size orelse default_pagezero_size;
const aligned_pagezero_size = mem.alignBackward(u64, pagezero_size, self.getPageSize());
if (!self.base.isDynLib() and aligned_pagezero_size > 0) {
if (aligned_pagezero_size != pagezero_size) {
// TODO convert into a warning
log.warn("requested __PAGEZERO size (0x{x}) is not page aligned", .{pagezero_size});
log.warn(" rounding down to 0x{x}", .{aligned_pagezero_size});
}
self.pagezero_seg_index = try self.addSegment("__PAGEZERO", .{ .vmsize = aligned_pagezero_size });
}
// __TEXT segment is non-optional
self.text_seg_index = try self.addSegment("__TEXT", .{ .prot = getSegmentProt("__TEXT") });
// Next, create segments required by sections
for (slice.items(.header)) |header| {
const segname = header.segName();
if (self.getSegmentByName(segname) == null) {
_ = try self.addSegment(segname, .{ .prot = getSegmentProt(segname) });
}
}
// Add __LINKEDIT
self.linkedit_seg_index = try self.addSegment("__LINKEDIT", .{ .prot = getSegmentProt("__LINKEDIT") });
// Sort segments
const Entry = struct {
index: u8,
pub fn lessThan(macho_file: *MachO, lhs: @This(), rhs: @This()) bool {
return segmentLessThan(
{},
macho_file.segments.items[lhs.index].segName(),
macho_file.segments.items[rhs.index].segName(),
);
}
};
var entries = try std.ArrayList(Entry).initCapacity(gpa, self.segments.items.len);
defer entries.deinit();
for (0..self.segments.items.len) |index| {
entries.appendAssumeCapacity(.{ .index = @intCast(index) });
}
mem.sort(Entry, entries.items, self, Entry.lessThan);
const backlinks = try gpa.alloc(u8, entries.items.len);
defer gpa.free(backlinks);
for (entries.items, 0..) |entry, i| {
backlinks[entry.index] = @intCast(i);
}
const segments = try self.segments.toOwnedSlice(gpa);
defer gpa.free(segments);
try self.segments.ensureTotalCapacityPrecise(gpa, segments.len);
for (entries.items) |sorted| {
self.segments.appendAssumeCapacity(segments[sorted.index]);
}
for (&[_]*?u8{
&self.pagezero_seg_index,
&self.text_seg_index,
&self.linkedit_seg_index,
&self.zig_text_seg_index,
&self.zig_const_seg_index,
&self.zig_data_seg_index,
&self.zig_bss_seg_index,
}) |maybe_index| {
if (maybe_index.*) |*index| {
index.* = backlinks[index.*];
}
}
// Attach sections to segments
for (slice.items(.header), slice.items(.segment_id)) |header, *seg_id| {
const segname = header.segName();
const segment_id = self.getSegmentByName(segname) orelse blk: {
const segment_id = @as(u8, @intCast(self.segments.items.len));
const protection = getSegmentProt(segname);
try self.segments.append(gpa, .{
.cmdsize = @sizeOf(macho.segment_command_64),
.segname = makeStaticString(segname),
.maxprot = protection,
.initprot = protection,
});
break :blk segment_id;
};
const segment = &self.segments.items[segment_id];
segment.cmdsize += @sizeOf(macho.section_64);
segment.nsects += 1;
seg_id.* = segment_id;
}
// Set __DATA_CONST as READ_ONLY
if (self.getSegmentByName("__DATA_CONST")) |seg_id| {
const seg = &self.segments.items[seg_id];
seg.flags |= macho.SG_READ_ONLY;
}
}
fn allocateSections(self: *MachO) !void {
const headerpad = try load_commands.calcMinHeaderPadSize(self);
var vmaddr: u64 = if (self.pagezero_seg_index) |index|
self.segments.items[index].vmaddr + self.segments.items[index].vmsize
else
0;
vmaddr += headerpad;
var fileoff = headerpad;
var prev_seg_id: u8 = if (self.pagezero_seg_index) |index| index + 1 else 0;
const page_size = self.getPageSize();
const slice = self.sections.slice();
const last_index = for (0..slice.items(.header).len) |i| {
if (self.isZigSection(@intCast(i))) break i;
} else slice.items(.header).len;
for (slice.items(.header)[0..last_index], slice.items(.segment_id)[0..last_index]) |*header, curr_seg_id| {
if (prev_seg_id != curr_seg_id) {
vmaddr = mem.alignForward(u64, vmaddr, page_size);
fileoff = mem.alignForward(u32, fileoff, page_size);
}
const alignment = try self.alignPow(header.@"align");
vmaddr = mem.alignForward(u64, vmaddr, alignment);
header.addr = vmaddr;
vmaddr += header.size;
if (!header.isZerofill()) {
fileoff = mem.alignForward(u32, fileoff, alignment);
header.offset = fileoff;
fileoff += @intCast(header.size);
}
prev_seg_id = curr_seg_id;
}
fileoff = mem.alignForward(u32, fileoff, page_size);
for (slice.items(.header)[last_index..], slice.items(.segment_id)[last_index..]) |*header, seg_id| {
if (header.isZerofill()) continue;
if (header.offset < fileoff) {
const existing_size = header.size;
header.size = 0;
// Must move the entire section.
const new_offset = try self.findFreeSpace(existing_size, page_size);
log.debug("moving '{s},{s}' from 0x{x} to 0x{x}", .{
header.segName(),
header.sectName(),
header.offset,
new_offset,
});
try self.copyRangeAllZeroOut(header.offset, new_offset, existing_size);
header.offset = @intCast(new_offset);
header.size = existing_size;
self.segments.items[seg_id].fileoff = new_offset;
}
}
}
/// We allocate segments in a separate step to also consider segments that have no sections.
fn allocateSegments(self: *MachO) void {
const first_index = if (self.pagezero_seg_index) |index| index + 1 else 0;
const last_index = for (0..self.segments.items.len) |i| {
if (self.isZigSegment(@intCast(i))) break i;
} else self.segments.items.len;
var vmaddr: u64 = if (self.pagezero_seg_index) |index|
self.segments.items[index].vmaddr + self.segments.items[index].vmsize
else
0;
var fileoff: u64 = 0;
const page_size = self.getPageSize();
const slice = self.sections.slice();
var next_sect_id: u8 = 0;
for (self.segments.items[first_index..last_index], first_index..last_index) |*seg, seg_id| {
seg.vmaddr = vmaddr;
seg.fileoff = fileoff;
while (next_sect_id < slice.items(.header).len) : (next_sect_id += 1) {
const header = slice.items(.header)[next_sect_id];
const sid = slice.items(.segment_id)[next_sect_id];
if (seg_id != sid) break;
vmaddr = header.addr + header.size;
if (!header.isZerofill()) {
fileoff = header.offset + header.size;
}
}
seg.vmsize = vmaddr - seg.vmaddr;
seg.filesize = fileoff - seg.fileoff;
vmaddr = mem.alignForward(u64, vmaddr, page_size);
fileoff = mem.alignForward(u64, fileoff, page_size);
}
}
fn allocateSyntheticSymbols(self: *MachO) void {
if (self.getInternalObject()) |obj| {
obj.allocateSyntheticSymbols(self);
const text_seg = self.getTextSegment();
for (obj.boundary_symbols.items) |sym_index| {
const ref = obj.getSymbolRef(sym_index, self);
const sym = ref.getSymbol(self).?;
const name = sym.getName(self);
sym.value = text_seg.vmaddr;
if (mem.startsWith(u8, name, "segment$start$")) {
const segname = name["segment$start$".len..];
if (self.getSegmentByName(segname)) |seg_id| {
const seg = self.segments.items[seg_id];
sym.value = seg.vmaddr;
}
} else if (mem.startsWith(u8, name, "segment$end$")) {
const segname = name["segment$end$".len..];
if (self.getSegmentByName(segname)) |seg_id| {
const seg = self.segments.items[seg_id];
sym.value = seg.vmaddr + seg.vmsize;
}
} else if (mem.startsWith(u8, name, "section$start$")) {
const actual_name = name["section$start$".len..];
const sep = mem.indexOfScalar(u8, actual_name, '$').?; // TODO error rather than a panic
const segname = actual_name[0..sep];
const sectname = actual_name[sep + 1 ..];
if (self.getSectionByName(segname, sectname)) |sect_id| {
const sect = self.sections.items(.header)[sect_id];
sym.value = sect.addr;
sym.out_n_sect = sect_id;
}
} else if (mem.startsWith(u8, name, "section$end$")) {
const actual_name = name["section$end$".len..];
const sep = mem.indexOfScalar(u8, actual_name, '$').?; // TODO error rather than a panic
const segname = actual_name[0..sep];
const sectname = actual_name[sep + 1 ..];
if (self.getSectionByName(segname, sectname)) |sect_id| {
const sect = self.sections.items(.header)[sect_id];
sym.value = sect.addr + sect.size;
sym.out_n_sect = sect_id;
}
} else unreachable;
}
if (self.objc_stubs.symbols.items.len > 0) {
const addr = self.sections.items(.header)[self.objc_stubs_sect_index.?].addr;
for (self.objc_stubs.symbols.items, 0..) |ref, idx| {
const sym = ref.getSymbol(self).?;
sym.value = addr + idx * ObjcStubsSection.entrySize(self.getTarget().cpu.arch);
sym.out_n_sect = self.objc_stubs_sect_index.?;
}
}
}
}
fn allocateLinkeditSegment(self: *MachO) !void {
var fileoff: u64 = 0;
var vmaddr: u64 = 0;
for (self.segments.items) |seg| {
if (fileoff < seg.fileoff + seg.filesize) fileoff = seg.fileoff + seg.filesize;
if (vmaddr < seg.vmaddr + seg.vmsize) vmaddr = seg.vmaddr + seg.vmsize;
}
const page_size = self.getPageSize();
const seg = self.getLinkeditSegment();
seg.vmaddr = mem.alignForward(u64, vmaddr, page_size);
seg.fileoff = mem.alignForward(u64, fileoff, page_size);
var off = try self.cast(u32, seg.fileoff);
// DYLD_INFO_ONLY
{
const cmd = &self.dyld_info_cmd;
cmd.rebase_off = off;
off += cmd.rebase_size;
cmd.bind_off = off;
off += cmd.bind_size;
cmd.weak_bind_off = off;
off += cmd.weak_bind_size;
cmd.lazy_bind_off = off;
off += cmd.lazy_bind_size;
cmd.export_off = off;
off += cmd.export_size;
off = mem.alignForward(u32, off, @alignOf(u64));
}
// FUNCTION_STARTS
{
const cmd = &self.function_starts_cmd;
cmd.dataoff = off;
off += cmd.datasize;
off = mem.alignForward(u32, off, @alignOf(u64));
}
// DATA_IN_CODE
{
const cmd = &self.data_in_code_cmd;
cmd.dataoff = off;
off += cmd.datasize;
off = mem.alignForward(u32, off, @alignOf(u64));
}
// SYMTAB (symtab)
{
const cmd = &self.symtab_cmd;
cmd.symoff = off;
off += cmd.nsyms * @sizeOf(macho.nlist_64);
off = mem.alignForward(u32, off, @alignOf(u32));
}
// DYSYMTAB
{
const cmd = &self.dysymtab_cmd;
cmd.indirectsymoff = off;
off += cmd.nindirectsyms * @sizeOf(u32);
off = mem.alignForward(u32, off, @alignOf(u64));
}
// SYMTAB (strtab)
{
const cmd = &self.symtab_cmd;
cmd.stroff = off;
off += cmd.strsize;
}
seg.filesize = off - seg.fileoff;
}
fn resizeSections(self: *MachO) !void {
const slice = self.sections.slice();
for (slice.items(.header), slice.items(.out), 0..) |header, *out, n_sect| {
if (header.isZerofill()) continue;
if (self.isZigSection(@intCast(n_sect))) continue; // TODO this is horrible
const cpu_arch = self.getTarget().cpu.arch;
const size = try self.cast(usize, header.size);
try out.resize(self.base.comp.gpa, size);
const padding_byte: u8 = if (header.isCode() and cpu_arch == .x86_64) 0xcc else 0;
@memset(out.items, padding_byte);
}
}
fn writeSectionsAndUpdateLinkeditSizes(self: *MachO) !void {
const tracy = trace(@src());
defer tracy.end();
const gpa = self.base.comp.gpa;
const diags = &self.base.comp.link_diags;
const cmd = self.symtab_cmd;
try self.symtab.resize(gpa, cmd.nsyms);
try self.strtab.resize(gpa, cmd.strsize);
self.strtab.items[0] = 0;
{
for (self.objects.items) |index| {
writeAtomsWorker(self, self.getFile(index).?);
}
if (self.getZigObject()) |zo| {
writeAtomsWorker(self, zo.asFile());
}
if (self.getInternalObject()) |obj| {
writeAtomsWorker(self, obj.asFile());
}
for (self.thunks.items) |thunk| {
writeThunkWorker(self, thunk);
}
const slice = self.sections.slice();
for (&[_]?u8{
self.eh_frame_sect_index,
self.unwind_info_sect_index,
self.got_sect_index,
self.stubs_sect_index,
self.la_symbol_ptr_sect_index,
self.tlv_ptr_sect_index,
self.objc_stubs_sect_index,
}) |maybe_sect_id| {
if (maybe_sect_id) |sect_id| {
const out = slice.items(.out)[sect_id].items;
writeSyntheticSectionWorker(self, sect_id, out);
}
}
if (self.la_symbol_ptr_sect_index) |_| {
updateLazyBindSizeWorker(self);
}
updateLinkeditSizeWorker(self, .rebase);
updateLinkeditSizeWorker(self, .bind);
updateLinkeditSizeWorker(self, .weak_bind);
updateLinkeditSizeWorker(self, .export_trie);
updateLinkeditSizeWorker(self, .data_in_code);
if (self.getZigObject()) |zo| {
File.writeSymtab(zo.asFile(), self, self);
}
for (self.objects.items) |index| {
File.writeSymtab(self.getFile(index).?, self, self);
}
for (self.dylibs.items) |index| {
File.writeSymtab(self.getFile(index).?, self, self);
}
if (self.getInternalObject()) |obj| {
File.writeSymtab(obj.asFile(), self, self);
}
if (self.requiresThunks()) for (self.thunks.items) |th| {
Thunk.writeSymtab(th, self, self);
};
}
if (diags.hasErrors()) return error.LinkFailure;
}
fn writeAtomsWorker(self: *MachO, file: File) void {
const tracy = trace(@src());
defer tracy.end();
file.writeAtoms(self) catch |err| {
self.reportParseError2(file.getIndex(), "failed to resolve relocations and write atoms: {s}", .{
@errorName(err),
}) catch {};
};
}
fn writeThunkWorker(self: *MachO, thunk: Thunk) void {
const tracy = trace(@src());
defer tracy.end();
const diags = &self.base.comp.link_diags;
const doWork = struct {
fn doWork(th: Thunk, buffer: []u8, macho_file: *MachO) !void {
const off = try macho_file.cast(usize, th.value);
const size = th.size();
var stream = std.io.fixedBufferStream(buffer[off..][0..size]);
try th.write(macho_file, stream.writer());
}
}.doWork;
const out = self.sections.items(.out)[thunk.out_n_sect].items;
doWork(thunk, out, self) catch |err| {
diags.addError("failed to write contents of thunk: {s}", .{@errorName(err)});
};
}
fn writeSyntheticSectionWorker(self: *MachO, sect_id: u8, out: []u8) void {
const tracy = trace(@src());
defer tracy.end();
const diags = &self.base.comp.link_diags;
const Tag = enum {
eh_frame,
unwind_info,
got,
stubs,
la_symbol_ptr,
tlv_ptr,
objc_stubs,
};
const doWork = struct {
fn doWork(macho_file: *MachO, tag: Tag, buffer: []u8) !void {
var stream = std.io.fixedBufferStream(buffer);
switch (tag) {
.eh_frame => eh_frame.write(macho_file, buffer),
.unwind_info => try macho_file.unwind_info.write(macho_file, buffer),
.got => try macho_file.got.write(macho_file, stream.writer()),
.stubs => try macho_file.stubs.write(macho_file, stream.writer()),
.la_symbol_ptr => try macho_file.la_symbol_ptr.write(macho_file, stream.writer()),
.tlv_ptr => try macho_file.tlv_ptr.write(macho_file, stream.writer()),
.objc_stubs => try macho_file.objc_stubs.write(macho_file, stream.writer()),
}
}
}.doWork;
const header = self.sections.items(.header)[sect_id];
const tag: Tag = tag: {
if (self.eh_frame_sect_index != null and
self.eh_frame_sect_index.? == sect_id) break :tag .eh_frame;
if (self.unwind_info_sect_index != null and
self.unwind_info_sect_index.? == sect_id) break :tag .unwind_info;
if (self.got_sect_index != null and
self.got_sect_index.? == sect_id) break :tag .got;
if (self.stubs_sect_index != null and
self.stubs_sect_index.? == sect_id) break :tag .stubs;
if (self.la_symbol_ptr_sect_index != null and
self.la_symbol_ptr_sect_index.? == sect_id) break :tag .la_symbol_ptr;
if (self.tlv_ptr_sect_index != null and
self.tlv_ptr_sect_index.? == sect_id) break :tag .tlv_ptr;
if (self.objc_stubs_sect_index != null and
self.objc_stubs_sect_index.? == sect_id) break :tag .objc_stubs;
unreachable;
};
doWork(self, tag, out) catch |err| {
diags.addError("could not write section '{s},{s}': {s}", .{
header.segName(), header.sectName(), @errorName(err),
});
};
}
fn updateLazyBindSizeWorker(self: *MachO) void {
const tracy = trace(@src());
defer tracy.end();
const diags = &self.base.comp.link_diags;
const doWork = struct {
fn doWork(macho_file: *MachO) !void {
try macho_file.lazy_bind_section.updateSize(macho_file);
const sect_id = macho_file.stubs_helper_sect_index.?;
const out = &macho_file.sections.items(.out)[sect_id];
var stream = std.io.fixedBufferStream(out.items);
try macho_file.stubs_helper.write(macho_file, stream.writer());
}
}.doWork;
doWork(self) catch |err|
diags.addError("could not calculate size of lazy binding section: {s}", .{@errorName(err)});
}
pub fn updateLinkeditSizeWorker(self: *MachO, tag: enum {
rebase,
bind,
weak_bind,
export_trie,
data_in_code,
}) void {
const diags = &self.base.comp.link_diags;
const res = switch (tag) {
.rebase => self.rebase_section.updateSize(self),
.bind => self.bind_section.updateSize(self),
.weak_bind => self.weak_bind_section.updateSize(self),
.export_trie => self.export_trie.updateSize(self),
.data_in_code => self.data_in_code.updateSize(self),
};
res catch |err|
diags.addError("could not calculate size of {s} section: {s}", .{ @tagName(tag), @errorName(err) });
}
fn writeSectionsToFile(self: *MachO) !void {
const tracy = trace(@src());
defer tracy.end();
const slice = self.sections.slice();
for (slice.items(.header), slice.items(.out)) |header, out| {
try self.pwriteAll(out.items, header.offset);
}
}
fn writeLinkeditSectionsToFile(self: *MachO) !void {
const tracy = trace(@src());
defer tracy.end();
try self.writeDyldInfo();
try self.writeDataInCode();
try self.writeSymtabToFile();
try self.writeIndsymtab();
}
fn writeDyldInfo(self: *MachO) !void {
const tracy = trace(@src());
defer tracy.end();
const gpa = self.base.comp.gpa;
const base_off = self.getLinkeditSegment().fileoff;
const cmd = self.dyld_info_cmd;
var needed_size: u32 = 0;
needed_size += cmd.rebase_size;
needed_size += cmd.bind_size;
needed_size += cmd.weak_bind_size;
needed_size += cmd.lazy_bind_size;
needed_size += cmd.export_size;
const buffer = try gpa.alloc(u8, needed_size);
defer gpa.free(buffer);
@memset(buffer, 0);
var stream = std.io.fixedBufferStream(buffer);
const writer = stream.writer();
try self.rebase_section.write(writer);
try stream.seekTo(cmd.bind_off - base_off);
try self.bind_section.write(writer);
try stream.seekTo(cmd.weak_bind_off - base_off);
try self.weak_bind_section.write(writer);
try stream.seekTo(cmd.lazy_bind_off - base_off);
try self.lazy_bind_section.write(writer);
try stream.seekTo(cmd.export_off - base_off);
try self.export_trie.write(writer);
try self.pwriteAll(buffer, cmd.rebase_off);
}
pub fn writeDataInCode(self: *MachO) !void {
const tracy = trace(@src());
defer tracy.end();
const gpa = self.base.comp.gpa;
const cmd = self.data_in_code_cmd;
var buffer = try std.ArrayList(u8).initCapacity(gpa, self.data_in_code.size());
defer buffer.deinit();
try self.data_in_code.write(self, buffer.writer());
try self.pwriteAll(buffer.items, cmd.dataoff);
}
fn writeIndsymtab(self: *MachO) !void {
const tracy = trace(@src());
defer tracy.end();
const gpa = self.base.comp.gpa;
const cmd = self.dysymtab_cmd;
const needed_size = cmd.nindirectsyms * @sizeOf(u32);
var buffer = try std.ArrayList(u8).initCapacity(gpa, needed_size);
defer buffer.deinit();
try self.indsymtab.write(self, buffer.writer());
try self.pwriteAll(buffer.items, cmd.indirectsymoff);
}
pub fn writeSymtabToFile(self: *MachO) !void {
const tracy = trace(@src());
defer tracy.end();
const cmd = self.symtab_cmd;
try self.pwriteAll(mem.sliceAsBytes(self.symtab.items), cmd.symoff);
try self.pwriteAll(self.strtab.items, cmd.stroff);
}
fn writeUnwindInfo(self: *MachO) !void {
const tracy = trace(@src());
defer tracy.end();
const gpa = self.base.comp.gpa;
if (self.eh_frame_sect_index) |index| {
const header = self.sections.items(.header)[index];
const size = try self.cast(usize, header.size);
const buffer = try gpa.alloc(u8, size);
defer gpa.free(buffer);
eh_frame.write(self, buffer);
try self.pwriteAll(buffer, header.offset);
}
if (self.unwind_info_sect_index) |index| {
const header = self.sections.items(.header)[index];
const size = try self.cast(usize, header.size);
const buffer = try gpa.alloc(u8, size);
defer gpa.free(buffer);
try self.unwind_info.write(self, buffer);
try self.pwriteAll(buffer, header.offset);
}
}
fn calcSymtabSize(self: *MachO) !void {
const tracy = trace(@src());
defer tracy.end();
const gpa = self.base.comp.gpa;
var files = std.ArrayList(File.Index).init(gpa);
defer files.deinit();
try files.ensureTotalCapacityPrecise(self.objects.items.len + self.dylibs.items.len + 2);
if (self.zig_object) |index| files.appendAssumeCapacity(index);
for (self.objects.items) |index| files.appendAssumeCapacity(index);
for (self.dylibs.items) |index| files.appendAssumeCapacity(index);
if (self.internal_object) |index| files.appendAssumeCapacity(index);
var nlocals: u32 = 0;
var nstabs: u32 = 0;
var nexports: u32 = 0;
var nimports: u32 = 0;
var strsize: u32 = 1;
if (self.requiresThunks()) for (self.thunks.items) |*th| {
th.output_symtab_ctx.ilocal = nlocals;
th.output_symtab_ctx.stroff = strsize;
th.calcSymtabSize(self);
nlocals += th.output_symtab_ctx.nlocals;
strsize += th.output_symtab_ctx.strsize;
};
for (files.items) |index| {
const file = self.getFile(index).?;
const ctx = switch (file) {
inline else => |x| &x.output_symtab_ctx,
};
ctx.ilocal = nlocals;
ctx.istab = nstabs;
ctx.iexport = nexports;
ctx.iimport = nimports;
ctx.stroff = strsize;
nlocals += ctx.nlocals;
nstabs += ctx.nstabs;
nexports += ctx.nexports;
nimports += ctx.nimports;
strsize += ctx.strsize;
}
for (files.items) |index| {
const file = self.getFile(index).?;
const ctx = switch (file) {
inline else => |x| &x.output_symtab_ctx,
};
ctx.istab += nlocals;
ctx.iexport += nlocals + nstabs;
ctx.iimport += nlocals + nstabs + nexports;
}
try self.indsymtab.updateSize(self);
{
const cmd = &self.symtab_cmd;
cmd.nsyms = nlocals + nstabs + nexports + nimports;
cmd.strsize = strsize;
}
{
const cmd = &self.dysymtab_cmd;
cmd.ilocalsym = 0;
cmd.nlocalsym = nlocals + nstabs;
cmd.iextdefsym = nlocals + nstabs;
cmd.nextdefsym = nexports;
cmd.iundefsym = nlocals + nstabs + nexports;
cmd.nundefsym = nimports;
}
}
fn writeLoadCommands(self: *MachO) !struct { usize, usize, u64 } {
const comp = self.base.comp;
const gpa = comp.gpa;
const needed_size = try load_commands.calcLoadCommandsSize(self, false);
const buffer = try gpa.alloc(u8, needed_size);
defer gpa.free(buffer);
var stream = std.io.fixedBufferStream(buffer);
const writer = stream.writer();
var ncmds: usize = 0;
// Segment and section load commands
{
const slice = self.sections.slice();
var sect_id: usize = 0;
for (self.segments.items) |seg| {
try writer.writeStruct(seg);
for (slice.items(.header)[sect_id..][0..seg.nsects]) |header| {
try writer.writeStruct(header);
}
sect_id += seg.nsects;
}
ncmds += self.segments.items.len;
}
try writer.writeStruct(self.dyld_info_cmd);
ncmds += 1;
try writer.writeStruct(self.function_starts_cmd);
ncmds += 1;
try writer.writeStruct(self.data_in_code_cmd);
ncmds += 1;
try writer.writeStruct(self.symtab_cmd);
ncmds += 1;
try writer.writeStruct(self.dysymtab_cmd);
ncmds += 1;
try load_commands.writeDylinkerLC(writer);
ncmds += 1;
if (self.getInternalObject()) |obj| {
if (obj.getEntryRef(self)) |ref| {
const sym = ref.getSymbol(self).?;
const seg = self.getTextSegment();
const entryoff: u32 = if (sym.getFile(self) == null)
0
else
@as(u32, @intCast(sym.getAddress(.{ .stubs = true }, self) - seg.vmaddr));
try writer.writeStruct(macho.entry_point_command{
.entryoff = entryoff,
.stacksize = self.base.stack_size,
});
ncmds += 1;
}
}
if (self.base.isDynLib()) {
try load_commands.writeDylibIdLC(self, writer);
ncmds += 1;
}
for (self.rpath_list) |rpath| {
try load_commands.writeRpathLC(rpath, writer);
ncmds += 1;
}
if (comp.config.any_sanitize_thread) {
const path = try comp.tsan_lib.?.full_object_path.toString(gpa);
defer gpa.free(path);
const rpath = std.fs.path.dirname(path) orelse ".";
try load_commands.writeRpathLC(rpath, writer);
ncmds += 1;
}
try writer.writeStruct(macho.source_version_command{ .version = 0 });
ncmds += 1;
if (self.platform.isBuildVersionCompatible()) {
try load_commands.writeBuildVersionLC(self.platform, self.sdk_version, writer);
ncmds += 1;
} else {
try load_commands.writeVersionMinLC(self.platform, self.sdk_version, writer);
ncmds += 1;
}
const uuid_cmd_offset = @sizeOf(macho.mach_header_64) + stream.pos;
try writer.writeStruct(self.uuid_cmd);
ncmds += 1;
for (self.dylibs.items) |index| {
const dylib = self.getFile(index).?.dylib;
assert(dylib.isAlive(self));
const dylib_id = dylib.id.?;
try load_commands.writeDylibLC(.{
.cmd = if (dylib.weak)
.LOAD_WEAK_DYLIB
else if (dylib.reexport)
.REEXPORT_DYLIB
else
.LOAD_DYLIB,
.name = dylib_id.name,
.timestamp = dylib_id.timestamp,
.current_version = dylib_id.current_version,
.compatibility_version = dylib_id.compatibility_version,
}, writer);
ncmds += 1;
}
if (self.requiresCodeSig()) {
try writer.writeStruct(self.codesig_cmd);
ncmds += 1;
}
assert(stream.pos == needed_size);
try self.pwriteAll(buffer, @sizeOf(macho.mach_header_64));
return .{ ncmds, buffer.len, uuid_cmd_offset };
}
fn writeHeader(self: *MachO, ncmds: usize, sizeofcmds: usize) !void {
var header: macho.mach_header_64 = .{};
header.flags = macho.MH_NOUNDEFS | macho.MH_DYLDLINK;
// TODO: if (self.options.namespace == .two_level) {
header.flags |= macho.MH_TWOLEVEL;
// }
switch (self.getTarget().cpu.arch) {
.aarch64 => {
header.cputype = macho.CPU_TYPE_ARM64;
header.cpusubtype = macho.CPU_SUBTYPE_ARM_ALL;
},
.x86_64 => {
header.cputype = macho.CPU_TYPE_X86_64;
header.cpusubtype = macho.CPU_SUBTYPE_X86_64_ALL;
},
else => {},
}
if (self.base.isDynLib()) {
header.filetype = macho.MH_DYLIB;
} else {
header.filetype = macho.MH_EXECUTE;
header.flags |= macho.MH_PIE;
}
const has_reexports = for (self.dylibs.items) |index| {
if (self.getFile(index).?.dylib.reexport) break true;
} else false;
if (!has_reexports) {
header.flags |= macho.MH_NO_REEXPORTED_DYLIBS;
}
if (self.has_tlv.load(.seq_cst)) {
header.flags |= macho.MH_HAS_TLV_DESCRIPTORS;
}
if (self.binds_to_weak.load(.seq_cst)) {
header.flags |= macho.MH_BINDS_TO_WEAK;
}
if (self.weak_defines.load(.seq_cst)) {
header.flags |= macho.MH_WEAK_DEFINES;
}
header.ncmds = @intCast(ncmds);
header.sizeofcmds = @intCast(sizeofcmds);
log.debug("writing Mach-O header {}", .{header});
try self.pwriteAll(mem.asBytes(&header), 0);
}
fn writeUuid(self: *MachO, uuid_cmd_offset: u64, has_codesig: bool) !void {
const file_size = if (!has_codesig) blk: {
const seg = self.getLinkeditSegment();
break :blk seg.fileoff + seg.filesize;
} else self.codesig_cmd.dataoff;
try calcUuid(self.base.comp, self.base.file.?, file_size, &self.uuid_cmd.uuid);
const offset = uuid_cmd_offset + @sizeOf(macho.load_command);
try self.pwriteAll(&self.uuid_cmd.uuid, offset);
}
pub fn writeCodeSignaturePadding(self: *MachO, code_sig: *CodeSignature) !void {
const seg = self.getLinkeditSegment();
// Code signature data has to be 16-bytes aligned for Apple tools to recognize the file
// https://github.com/opensource-apple/cctools/blob/fdb4825f303fd5c0751be524babd32958181b3ed/libstuff/checkout.c#L271
const offset = mem.alignForward(u64, seg.fileoff + seg.filesize, 16);
const needed_size = code_sig.estimateSize(offset);
seg.filesize = offset + needed_size - seg.fileoff;
seg.vmsize = mem.alignForward(u64, seg.filesize, self.getPageSize());
log.debug("writing code signature padding from 0x{x} to 0x{x}", .{ offset, offset + needed_size });
// Pad out the space. We need to do this to calculate valid hashes for everything in the file
// except for code signature data.
try self.pwriteAll(&[_]u8{0}, offset + needed_size - 1);
self.codesig_cmd.dataoff = @as(u32, @intCast(offset));
self.codesig_cmd.datasize = @as(u32, @intCast(needed_size));
}
pub fn writeCodeSignature(self: *MachO, code_sig: *CodeSignature) !void {
const seg = self.getTextSegment();
const offset = self.codesig_cmd.dataoff;
var buffer = std.ArrayList(u8).init(self.base.comp.gpa);
defer buffer.deinit();
try buffer.ensureTotalCapacityPrecise(code_sig.size());
try code_sig.writeAdhocSignature(self, .{
.file = self.base.file.?,
.exec_seg_base = seg.fileoff,
.exec_seg_limit = seg.filesize,
.file_size = offset,
.dylib = self.base.isDynLib(),
}, buffer.writer());
assert(buffer.items.len == code_sig.size());
log.debug("writing code signature from 0x{x} to 0x{x}", .{
offset,
offset + buffer.items.len,
});
try self.pwriteAll(buffer.items, offset);
}
pub fn updateFunc(
self: *MachO,
pt: Zcu.PerThread,
func_index: InternPool.Index,
mir: *const codegen.AnyMir,
) link.File.UpdateNavError!void {
if (build_options.skip_non_native and builtin.object_format != .macho) {
@panic("Attempted to compile for object format that was disabled by build configuration");
}
return self.getZigObject().?.updateFunc(self, pt, func_index, mir);
}
pub fn updateNav(self: *MachO, pt: Zcu.PerThread, nav: InternPool.Nav.Index) link.File.UpdateNavError!void {
if (build_options.skip_non_native and builtin.object_format != .macho) {
@panic("Attempted to compile for object format that was disabled by build configuration");
}
return self.getZigObject().?.updateNav(self, pt, nav);
}
pub fn updateLineNumber(self: *MachO, pt: Zcu.PerThread, ti_id: InternPool.TrackedInst.Index) !void {
return self.getZigObject().?.updateLineNumber(pt, ti_id);
}
pub fn updateExports(
self: *MachO,
pt: Zcu.PerThread,
exported: Zcu.Exported,
export_indices: []const Zcu.Export.Index,
) link.File.UpdateExportsError!void {
if (build_options.skip_non_native and builtin.object_format != .macho) {
@panic("Attempted to compile for object format that was disabled by build configuration");
}
return self.getZigObject().?.updateExports(self, pt, exported, export_indices);
}
pub fn deleteExport(
self: *MachO,
exported: Zcu.Exported,
name: InternPool.NullTerminatedString,
) void {
return self.getZigObject().?.deleteExport(self, exported, name);
}
pub fn freeNav(self: *MachO, nav: InternPool.Nav.Index) void {
return self.getZigObject().?.freeNav(nav);
}
pub fn getNavVAddr(self: *MachO, pt: Zcu.PerThread, nav_index: InternPool.Nav.Index, reloc_info: link.File.RelocInfo) !u64 {
return self.getZigObject().?.getNavVAddr(self, pt, nav_index, reloc_info);
}
pub fn lowerUav(
self: *MachO,
pt: Zcu.PerThread,
uav: InternPool.Index,
explicit_alignment: InternPool.Alignment,
src_loc: Zcu.LazySrcLoc,
) !codegen.SymbolResult {
return self.getZigObject().?.lowerUav(self, pt, uav, explicit_alignment, src_loc);
}
pub fn getUavVAddr(self: *MachO, uav: InternPool.Index, reloc_info: link.File.RelocInfo) !u64 {
return self.getZigObject().?.getUavVAddr(self, uav, reloc_info);
}
pub fn getGlobalSymbol(self: *MachO, name: []const u8, lib_name: ?[]const u8) !u32 {
return self.getZigObject().?.getGlobalSymbol(self, name, lib_name);
}
pub fn padToIdeal(actual_size: anytype) @TypeOf(actual_size) {
return actual_size +| (actual_size / ideal_factor);
}
fn detectAllocCollision(self: *MachO, start: u64, size: u64) !?u64 {
// Conservatively commit one page size as reserved space for the headers as we
// expect it to grow and everything else be moved in flush anyhow.
const header_size = self.getPageSize();
if (start < header_size)
return header_size;
var at_end = true;
const end = start + padToIdeal(size);
for (self.sections.items(.header)) |header| {
if (header.isZerofill()) continue;
const increased_size = padToIdeal(header.size);
const test_end = header.offset +| increased_size;
if (start < test_end) {
if (end > header.offset) return test_end;
if (test_end < std.math.maxInt(u64)) at_end = false;
}
}
for (self.segments.items) |seg| {
const increased_size = padToIdeal(seg.filesize);
const test_end = seg.fileoff +| increased_size;
if (start < test_end) {
if (end > seg.fileoff) return test_end;
if (test_end < std.math.maxInt(u64)) at_end = false;
}
}
if (at_end) try self.base.file.?.setEndPos(end);
return null;
}
fn detectAllocCollisionVirtual(self: *MachO, start: u64, size: u64) ?u64 {
// Conservatively commit one page size as reserved space for the headers as we
// expect it to grow and everything else be moved in flush anyhow.
const header_size = self.getPageSize();
if (start < header_size)
return header_size;
const end = start + padToIdeal(size);
for (self.sections.items(.header)) |header| {
const increased_size = padToIdeal(header.size);
const test_end = header.addr +| increased_size;
if (end > header.addr and start < test_end) {
return test_end;
}
}
for (self.segments.items) |seg| {
const increased_size = padToIdeal(seg.vmsize);
const test_end = seg.vmaddr +| increased_size;
if (end > seg.vmaddr and start < test_end) {
return test_end;
}
}
return null;
}
pub fn allocatedSize(self: *MachO, start: u64) u64 {
if (start == 0) return 0;
var min_pos: u64 = std.math.maxInt(u64);
for (self.sections.items(.header)) |header| {
if (header.offset <= start) continue;
if (header.offset < min_pos) min_pos = header.offset;
}
for (self.segments.items) |seg| {
if (seg.fileoff <= start) continue;
if (seg.fileoff < min_pos) min_pos = seg.fileoff;
}
return min_pos - start;
}
pub fn allocatedSizeVirtual(self: *MachO, start: u64) u64 {
if (start == 0) return 0;
var min_pos: u64 = std.math.maxInt(u64);
for (self.sections.items(.header)) |header| {
if (header.addr <= start) continue;
if (header.addr < min_pos) min_pos = header.addr;
}
for (self.segments.items) |seg| {
if (seg.vmaddr <= start) continue;
if (seg.vmaddr < min_pos) min_pos = seg.vmaddr;
}
return min_pos - start;
}
pub fn findFreeSpace(self: *MachO, object_size: u64, min_alignment: u32) !u64 {
var start: u64 = 0;
while (try self.detectAllocCollision(start, object_size)) |item_end| {
start = mem.alignForward(u64, item_end, min_alignment);
}
return start;
}
pub fn findFreeSpaceVirtual(self: *MachO, object_size: u64, min_alignment: u32) u64 {
var start: u64 = 0;
while (self.detectAllocCollisionVirtual(start, object_size)) |item_end| {
start = mem.alignForward(u64, item_end, min_alignment);
}
return start;
}
pub fn copyRangeAll(self: *MachO, old_offset: u64, new_offset: u64, size: u64) !void {
const file = self.base.file.?;
const amt = try file.copyRangeAll(old_offset, file, new_offset, size);
if (amt != size) return error.InputOutput;
}
/// Like File.copyRangeAll but also ensures the source region is zeroed out after copy.
/// This is so that we guarantee zeroed out regions for mapping of zerofill sections by the loader.
fn copyRangeAllZeroOut(self: *MachO, old_offset: u64, new_offset: u64, size: u64) !void {
const gpa = self.base.comp.gpa;
try self.copyRangeAll(old_offset, new_offset, size);
const size_u = math.cast(usize, size) orelse return error.Overflow;
const zeroes = try gpa.alloc(u8, size_u); // TODO no need to allocate here.
defer gpa.free(zeroes);
@memset(zeroes, 0);
try self.base.file.?.pwriteAll(zeroes, old_offset);
}
const InitMetadataOptions = struct {
emit: Path,
zo: *ZigObject,
symbol_count_hint: u64,
program_code_size_hint: u64,
};
pub fn closeDebugInfo(self: *MachO) bool {
const d_sym = &(self.d_sym orelse return false);
d_sym.file.?.close();
d_sym.file = null;
return true;
}
pub fn reopenDebugInfo(self: *MachO) !void {
assert(self.d_sym.?.file == null);
assert(!self.base.comp.config.use_llvm);
assert(self.base.comp.config.debug_format == .dwarf);
const gpa = self.base.comp.gpa;
const sep = fs.path.sep_str;
const d_sym_path = try std.fmt.allocPrint(
gpa,
"{s}.dSYM" ++ sep ++ "Contents" ++ sep ++ "Resources" ++ sep ++ "DWARF",
.{self.base.emit.sub_path},
);
defer gpa.free(d_sym_path);
var d_sym_bundle = try self.base.emit.root_dir.handle.makeOpenPath(d_sym_path, .{});
defer d_sym_bundle.close();
self.d_sym.?.file = try d_sym_bundle.createFile(fs.path.basename(self.base.emit.sub_path), .{
.truncate = false,
.read = true,
});
}
// TODO: move to ZigObject
fn initMetadata(self: *MachO, options: InitMetadataOptions) !void {
if (!self.base.isRelocatable()) {
const base_vmaddr = blk: {
const pagezero_size = self.pagezero_size orelse default_pagezero_size;
break :blk mem.alignBackward(u64, pagezero_size, self.getPageSize());
};
{
const filesize = options.program_code_size_hint;
const off = try self.findFreeSpace(filesize, self.getPageSize());
self.zig_text_seg_index = try self.addSegment("__TEXT_ZIG", .{
.fileoff = off,
.filesize = filesize,
.vmaddr = base_vmaddr + 0x4000000,
.vmsize = filesize,
.prot = macho.PROT.READ | macho.PROT.EXEC,
});
}
{
const filesize: u64 = 1024;
const off = try self.findFreeSpace(filesize, self.getPageSize());
self.zig_const_seg_index = try self.addSegment("__CONST_ZIG", .{
.fileoff = off,
.filesize = filesize,
.vmaddr = base_vmaddr + 0xc000000,
.vmsize = filesize,
.prot = macho.PROT.READ | macho.PROT.WRITE,
});
}
{
const filesize: u64 = 1024;
const off = try self.findFreeSpace(filesize, self.getPageSize());
self.zig_data_seg_index = try self.addSegment("__DATA_ZIG", .{
.fileoff = off,
.filesize = filesize,
.vmaddr = base_vmaddr + 0x10000000,
.vmsize = filesize,
.prot = macho.PROT.READ | macho.PROT.WRITE,
});
}
{
const memsize: u64 = 1024;
self.zig_bss_seg_index = try self.addSegment("__BSS_ZIG", .{
.vmaddr = base_vmaddr + 0x14000000,
.vmsize = memsize,
.prot = macho.PROT.READ | macho.PROT.WRITE,
});
}
if (options.zo.dwarf) |*dwarf| {
// Create dSYM bundle.
log.debug("creating {s}.dSYM bundle", .{options.emit.sub_path});
self.d_sym = .{ .allocator = self.base.comp.gpa, .file = null };
try self.reopenDebugInfo();
try self.d_sym.?.initMetadata(self);
try dwarf.initMetadata();
}
}
const appendSect = struct {
fn appendSect(macho_file: *MachO, sect_id: u8, seg_id: u8) void {
const sect = &macho_file.sections.items(.header)[sect_id];
const seg = macho_file.segments.items[seg_id];
sect.addr = seg.vmaddr;
sect.offset = @intCast(seg.fileoff);
sect.size = seg.vmsize;
macho_file.sections.items(.segment_id)[sect_id] = seg_id;
}
}.appendSect;
const allocSect = struct {
fn allocSect(macho_file: *MachO, sect_id: u8, size: u64) !void {
const sect = &macho_file.sections.items(.header)[sect_id];
const alignment = try macho_file.alignPow(sect.@"align");
if (!sect.isZerofill()) {
sect.offset = try macho_file.cast(u32, try macho_file.findFreeSpace(size, alignment));
}
sect.addr = macho_file.findFreeSpaceVirtual(size, alignment);
sect.size = size;
}
}.allocSect;
{
self.zig_text_sect_index = try self.addSection("__TEXT_ZIG", "__text_zig", .{
.alignment = switch (self.getTarget().cpu.arch) {
.aarch64 => 2,
.x86_64 => 0,
else => unreachable,
},
.flags = macho.S_REGULAR | macho.S_ATTR_PURE_INSTRUCTIONS | macho.S_ATTR_SOME_INSTRUCTIONS,
});
if (self.base.isRelocatable()) {
try allocSect(self, self.zig_text_sect_index.?, options.program_code_size_hint);
} else {
appendSect(self, self.zig_text_sect_index.?, self.zig_text_seg_index.?);
}
}
{
self.zig_const_sect_index = try self.addSection("__CONST_ZIG", "__const_zig", .{});
if (self.base.isRelocatable()) {
try allocSect(self, self.zig_const_sect_index.?, 1024);
} else {
appendSect(self, self.zig_const_sect_index.?, self.zig_const_seg_index.?);
}
}
{
self.zig_data_sect_index = try self.addSection("__DATA_ZIG", "__data_zig", .{});
if (self.base.isRelocatable()) {
try allocSect(self, self.zig_data_sect_index.?, 1024);
} else {
appendSect(self, self.zig_data_sect_index.?, self.zig_data_seg_index.?);
}
}
{
self.zig_bss_sect_index = try self.addSection("__BSS_ZIG", "__bss_zig", .{
.flags = macho.S_ZEROFILL,
});
if (self.base.isRelocatable()) {
try allocSect(self, self.zig_bss_sect_index.?, 1024);
} else {
appendSect(self, self.zig_bss_sect_index.?, self.zig_bss_seg_index.?);
}
}
if (self.base.isRelocatable()) if (options.zo.dwarf) |*dwarf| {
self.debug_str_sect_index = try self.addSection("__DWARF", "__debug_str", .{
.flags = macho.S_ATTR_DEBUG,
});
self.debug_info_sect_index = try self.addSection("__DWARF", "__debug_info", .{
.flags = macho.S_ATTR_DEBUG,
});
self.debug_abbrev_sect_index = try self.addSection("__DWARF", "__debug_abbrev", .{
.flags = macho.S_ATTR_DEBUG,
});
self.debug_aranges_sect_index = try self.addSection("__DWARF", "__debug_aranges", .{
.alignment = 4,
.flags = macho.S_ATTR_DEBUG,
});
self.debug_line_sect_index = try self.addSection("__DWARF", "__debug_line", .{
.flags = macho.S_ATTR_DEBUG,
});
self.debug_line_str_sect_index = try self.addSection("__DWARF", "__debug_line_str", .{
.flags = macho.S_ATTR_DEBUG,
});
self.debug_loclists_sect_index = try self.addSection("__DWARF", "__debug_loclists", .{
.flags = macho.S_ATTR_DEBUG,
});
self.debug_rnglists_sect_index = try self.addSection("__DWARF", "__debug_rnglists", .{
.flags = macho.S_ATTR_DEBUG,
});
try dwarf.initMetadata();
};
}
pub fn growSection(self: *MachO, sect_index: u8, needed_size: u64) !void {
if (self.base.isRelocatable()) {
try self.growSectionRelocatable(sect_index, needed_size);
} else {
try self.growSectionNonRelocatable(sect_index, needed_size);
}
}
fn growSectionNonRelocatable(self: *MachO, sect_index: u8, needed_size: u64) !void {
const diags = &self.base.comp.link_diags;
const sect = &self.sections.items(.header)[sect_index];
const seg_id = self.sections.items(.segment_id)[sect_index];
const seg = &self.segments.items[seg_id];
if (!sect.isZerofill()) {
const allocated_size = self.allocatedSize(sect.offset);
if (needed_size > allocated_size) {
const existing_size = sect.size;
sect.size = 0;
// Must move the entire section.
const alignment = self.getPageSize();
const new_offset = try self.findFreeSpace(needed_size, alignment);
log.debug("moving '{s},{s}' from 0x{x} to 0x{x}", .{
sect.segName(),
sect.sectName(),
sect.offset,
new_offset,
});
try self.copyRangeAllZeroOut(sect.offset, new_offset, existing_size);
sect.offset = @intCast(new_offset);
} else if (sect.offset + allocated_size == std.math.maxInt(u64)) {
try self.base.file.?.setEndPos(sect.offset + needed_size);
}
seg.filesize = needed_size;
}
sect.size = needed_size;
seg.fileoff = sect.offset;
const mem_capacity = self.allocatedSizeVirtual(seg.vmaddr);
if (needed_size > mem_capacity) {
var err = try diags.addErrorWithNotes(2);
try err.addMsg("fatal linker error: cannot expand segment seg({d})({s}) in virtual memory", .{
seg_id,
seg.segName(),
});
err.addNote("TODO: emit relocations to memory locations in self-hosted backends", .{});
err.addNote("as a workaround, try increasing pre-allocated virtual memory of each segment", .{});
}
seg.vmsize = needed_size;
}
fn growSectionRelocatable(self: *MachO, sect_index: u8, needed_size: u64) !void {
const sect = &self.sections.items(.header)[sect_index];
if (!sect.isZerofill()) {
const allocated_size = self.allocatedSize(sect.offset);
if (needed_size > allocated_size) {
const existing_size = sect.size;
sect.size = 0;
// Must move the entire section.
const alignment = try math.powi(u32, 2, sect.@"align");
const new_offset = try self.findFreeSpace(needed_size, alignment);
const new_addr = self.findFreeSpaceVirtual(needed_size, alignment);
log.debug("new '{s},{s}' file offset 0x{x} to 0x{x} (0x{x} - 0x{x})", .{
sect.segName(),
sect.sectName(),
new_offset,
new_offset + existing_size,
new_addr,
new_addr + existing_size,
});
try self.copyRangeAll(sect.offset, new_offset, existing_size);
sect.offset = @intCast(new_offset);
sect.addr = new_addr;
} else if (sect.offset + allocated_size == std.math.maxInt(u64)) {
try self.base.file.?.setEndPos(sect.offset + needed_size);
}
}
sect.size = needed_size;
}
pub fn markDirty(self: *MachO, sect_index: u8) void {
if (self.getZigObject()) |zo| {
if (self.debug_info_sect_index.? == sect_index) {
zo.debug_info_header_dirty = true;
} else if (self.debug_line_sect_index.? == sect_index) {
zo.debug_line_header_dirty = true;
} else if (self.debug_abbrev_sect_index.? == sect_index) {
zo.debug_abbrev_dirty = true;
} else if (self.debug_str_sect_index.? == sect_index) {
zo.debug_strtab_dirty = true;
} else if (self.debug_aranges_sect_index.? == sect_index) {
zo.debug_aranges_dirty = true;
}
}
}
pub fn getTarget(self: *const MachO) *const std.Target {
return &self.base.comp.root_mod.resolved_target.result;
}
/// XNU starting with Big Sur running on arm64 is caching inodes of running binaries.
/// Any change to the binary will effectively invalidate the kernel's cache
/// resulting in a SIGKILL on each subsequent run. Since when doing incremental
/// linking we're modifying a binary in-place, this will end up with the kernel
/// killing it on every subsequent run. To circumvent it, we will copy the file
/// into a new inode, remove the original file, and rename the copy to match
/// the original file. This is super messy, but there doesn't seem any other
/// way to please the XNU.
pub fn invalidateKernelCache(dir: fs.Dir, sub_path: []const u8) !void {
const tracy = trace(@src());
defer tracy.end();
if (builtin.target.os.tag.isDarwin() and builtin.target.cpu.arch == .aarch64) {
try dir.copyFile(sub_path, dir, sub_path, .{});
}
}
inline fn conformUuid(out: *[Md5.digest_length]u8) void {
// LC_UUID uuids should conform to RFC 4122 UUID version 4 & UUID version 5 formats
out[6] = (out[6] & 0x0F) | (3 << 4);
out[8] = (out[8] & 0x3F) | 0x80;
}
pub inline fn getPageSize(self: MachO) u16 {
return switch (self.getTarget().cpu.arch) {
.aarch64 => 0x4000,
.x86_64 => 0x1000,
else => unreachable,
};
}
pub fn requiresCodeSig(self: MachO) bool {
if (self.entitlements) |_| return true;
// TODO: enable once we support this linker option
// if (self.options.adhoc_codesign) |cs| return cs;
const target = self.getTarget();
return switch (target.cpu.arch) {
.aarch64 => switch (target.os.tag) {
.driverkit, .macos => true,
.ios, .tvos, .visionos, .watchos => target.abi == .simulator,
else => false,
},
.x86_64 => false,
else => unreachable,
};
}
inline fn requiresThunks(self: MachO) bool {
return self.getTarget().cpu.arch == .aarch64;
}
pub fn isZigSegment(self: MachO, seg_id: u8) bool {
inline for (&[_]?u8{
self.zig_text_seg_index,
self.zig_const_seg_index,
self.zig_data_seg_index,
self.zig_bss_seg_index,
}) |maybe_index| {
if (maybe_index) |index| {
if (index == seg_id) return true;
}
}
return false;
}
pub fn isZigSection(self: MachO, sect_id: u8) bool {
inline for (&[_]?u8{
self.zig_text_sect_index,
self.zig_const_sect_index,
self.zig_data_sect_index,
self.zig_bss_sect_index,
}) |maybe_index| {
if (maybe_index) |index| {
if (index == sect_id) return true;
}
}
return false;
}
pub fn isDebugSection(self: MachO, sect_id: u8) bool {
inline for (&[_]?u8{
self.debug_info_sect_index,
self.debug_abbrev_sect_index,
self.debug_str_sect_index,
self.debug_aranges_sect_index,
self.debug_line_sect_index,
}) |maybe_index| {
if (maybe_index) |index| {
if (index == sect_id) return true;
}
}
return false;
}
pub fn addSegment(self: *MachO, name: []const u8, opts: struct {
vmaddr: u64 = 0,
vmsize: u64 = 0,
fileoff: u64 = 0,
filesize: u64 = 0,
prot: macho.vm_prot_t = macho.PROT.NONE,
}) error{OutOfMemory}!u8 {
const gpa = self.base.comp.gpa;
const index = @as(u8, @intCast(self.segments.items.len));
try self.segments.append(gpa, .{
.segname = makeStaticString(name),
.vmaddr = opts.vmaddr,
.vmsize = opts.vmsize,
.fileoff = opts.fileoff,
.filesize = opts.filesize,
.maxprot = opts.prot,
.initprot = opts.prot,
.nsects = 0,
.cmdsize = @sizeOf(macho.segment_command_64),
});
return index;
}
const AddSectionOpts = struct {
alignment: u32 = 0,
flags: u32 = macho.S_REGULAR,
reserved1: u32 = 0,
reserved2: u32 = 0,
};
pub fn addSection(
self: *MachO,
segname: []const u8,
sectname: []const u8,
opts: AddSectionOpts,
) !u8 {
const gpa = self.base.comp.gpa;
const index = @as(u8, @intCast(try self.sections.addOne(gpa)));
self.sections.set(index, .{
.segment_id = 0, // Segments will be created automatically later down the pipeline.
.header = .{
.sectname = makeStaticString(sectname),
.segname = makeStaticString(segname),
.@"align" = opts.alignment,
.flags = opts.flags,
.reserved1 = opts.reserved1,
.reserved2 = opts.reserved2,
},
});
return index;
}
pub fn makeStaticString(bytes: []const u8) [16]u8 {
var buf = [_]u8{0} ** 16;
@memcpy(buf[0..bytes.len], bytes);
return buf;
}
pub fn getSegmentByName(self: MachO, segname: []const u8) ?u8 {
for (self.segments.items, 0..) |seg, i| {
if (mem.eql(u8, segname, seg.segName())) return @as(u8, @intCast(i));
} else return null;
}
pub fn getSectionByName(self: MachO, segname: []const u8, sectname: []const u8) ?u8 {
for (self.sections.items(.header), 0..) |header, i| {
if (mem.eql(u8, header.segName(), segname) and mem.eql(u8, header.sectName(), sectname))
return @as(u8, @intCast(i));
} else return null;
}
pub fn getTlsAddress(self: MachO) u64 {
for (self.sections.items(.header)) |header| switch (header.type()) {
macho.S_THREAD_LOCAL_REGULAR,
macho.S_THREAD_LOCAL_ZEROFILL,
=> return header.addr,
else => {},
};
return 0;
}
pub inline fn getTextSegment(self: *MachO) *macho.segment_command_64 {
return &self.segments.items[self.text_seg_index.?];
}
pub inline fn getLinkeditSegment(self: *MachO) *macho.segment_command_64 {
return &self.segments.items[self.linkedit_seg_index.?];
}
pub fn getFile(self: *MachO, index: File.Index) ?File {
const tag = self.files.items(.tags)[index];
return switch (tag) {
.null => null,
.zig_object => .{ .zig_object = &self.files.items(.data)[index].zig_object },
.internal => .{ .internal = &self.files.items(.data)[index].internal },
.object => .{ .object = &self.files.items(.data)[index].object },
.dylib => .{ .dylib = &self.files.items(.data)[index].dylib },
};
}
pub fn getZigObject(self: *MachO) ?*ZigObject {
const index = self.zig_object orelse return null;
return self.getFile(index).?.zig_object;
}
pub fn getInternalObject(self: *MachO) ?*InternalObject {
const index = self.internal_object orelse return null;
return self.getFile(index).?.internal;
}
pub fn addFileHandle(self: *MachO, file: fs.File) !File.HandleIndex {
const gpa = self.base.comp.gpa;
const index: File.HandleIndex = @intCast(self.file_handles.items.len);
const fh = try self.file_handles.addOne(gpa);
fh.* = file;
return index;
}
pub fn getFileHandle(self: MachO, index: File.HandleIndex) File.Handle {
assert(index < self.file_handles.items.len);
return self.file_handles.items[index];
}
pub fn addThunk(self: *MachO) !Thunk.Index {
const index = @as(Thunk.Index, @intCast(self.thunks.items.len));
const thunk = try self.thunks.addOne(self.base.comp.gpa);
thunk.* = .{};
return index;
}
pub fn getThunk(self: *MachO, index: Thunk.Index) *Thunk {
assert(index < self.thunks.items.len);
return &self.thunks.items[index];
}
pub fn eatPrefix(path: []const u8, prefix: []const u8) ?[]const u8 {
if (mem.startsWith(u8, path, prefix)) return path[prefix.len..];
return null;
}
pub fn reportParseError2(
self: *MachO,
file_index: File.Index,
comptime format: []const u8,
args: anytype,
) error{OutOfMemory}!void {
const diags = &self.base.comp.link_diags;
var err = try diags.addErrorWithNotes(1);
try err.addMsg(format, args);
err.addNote("while parsing {f}", .{self.getFile(file_index).?.fmtPath()});
}
fn reportMissingDependencyError(
self: *MachO,
parent: File.Index,
path: []const u8,
checked_paths: []const []const u8,
comptime format: []const u8,
args: anytype,
) error{OutOfMemory}!void {
const diags = &self.base.comp.link_diags;
var err = try diags.addErrorWithNotes(2 + checked_paths.len);
try err.addMsg(format, args);
err.addNote("while resolving {s}", .{path});
err.addNote("a dependency of {f}", .{self.getFile(parent).?.fmtPath()});
for (checked_paths) |p| {
err.addNote("tried {s}", .{p});
}
}
fn reportDependencyError(
self: *MachO,
parent: File.Index,
path: []const u8,
comptime format: []const u8,
args: anytype,
) error{OutOfMemory}!void {
const diags = &self.base.comp.link_diags;
var err = try diags.addErrorWithNotes(2);
try err.addMsg(format, args);
err.addNote("while parsing {s}", .{path});
err.addNote("a dependency of {f}", .{self.getFile(parent).?.fmtPath()});
}
fn reportDuplicates(self: *MachO) error{ HasDuplicates, OutOfMemory }!void {
const tracy = trace(@src());
defer tracy.end();
if (self.dupes.keys().len == 0) return; // Nothing to do
const gpa = self.base.comp.gpa;
const diags = &self.base.comp.link_diags;
const max_notes = 3;
// We will sort by name, and then by file to ensure deterministic output.
var keys = try std.ArrayList(SymbolResolver.Index).initCapacity(gpa, self.dupes.keys().len);
defer keys.deinit();
keys.appendSliceAssumeCapacity(self.dupes.keys());
self.sortGlobalSymbolsByName(keys.items);
for (self.dupes.values()) |*refs| {
mem.sort(File.Index, refs.items, {}, std.sort.asc(File.Index));
}
for (keys.items) |key| {
const sym = self.resolver.keys.items[key - 1];
const notes = self.dupes.get(key).?;
const nnotes = @min(notes.items.len, max_notes) + @intFromBool(notes.items.len > max_notes);
var err = try diags.addErrorWithNotes(nnotes + 1);
try err.addMsg("duplicate symbol definition: {s}", .{sym.getName(self)});
err.addNote("defined by {f}", .{sym.getFile(self).?.fmtPath()});
var inote: usize = 0;
while (inote < @min(notes.items.len, max_notes)) : (inote += 1) {
const file = self.getFile(notes.items[inote]).?;
err.addNote("defined by {f}", .{file.fmtPath()});
}
if (notes.items.len > max_notes) {
const remaining = notes.items.len - max_notes;
err.addNote("defined {d} more times", .{remaining});
}
}
return error.HasDuplicates;
}
pub fn getDebugSymbols(self: *MachO) ?*DebugSymbols {
if (self.d_sym) |*ds| return ds;
return null;
}
pub fn ptraceAttach(self: *MachO, pid: std.posix.pid_t) !void {
if (!is_hot_update_compatible) return;
const mach_task = try machTaskForPid(pid);
log.debug("Mach task for pid {d}: {any}", .{ pid, mach_task });
self.hot_state.mach_task = mach_task;
// TODO start exception handler in another thread
// TODO enable ones we register for exceptions
// try std.os.ptrace(std.os.darwin.PT.ATTACHEXC, pid, 0, 0);
}
pub fn ptraceDetach(self: *MachO, pid: std.posix.pid_t) !void {
if (!is_hot_update_compatible) return;
_ = pid;
// TODO stop exception handler
// TODO see comment in ptraceAttach
// try std.os.ptrace(std.os.darwin.PT.DETACH, pid, 0, 0);
self.hot_state.mach_task = null;
}
pub fn dumpState(self: *MachO) std.fmt.Formatter(*MachO, fmtDumpState) {
return .{ .data = self };
}
fn fmtDumpState(self: *MachO, w: *Writer) Writer.Error!void {
if (self.getZigObject()) |zo| {
try w.print("zig_object({d}) : {s}\n", .{ zo.index, zo.basename });
try w.print("{f}{f}\n", .{
zo.fmtAtoms(self),
zo.fmtSymtab(self),
});
}
for (self.objects.items) |index| {
const object = self.getFile(index).?.object;
try w.print("object({d}) : {f} : has_debug({})", .{
index,
object.fmtPath(),
object.hasDebugInfo(),
});
if (!object.alive) try w.writeAll(" : ([*])");
try w.writeByte('\n');
try w.print("{f}{f}{f}{f}{f}\n", .{
object.fmtAtoms(self),
object.fmtCies(self),
object.fmtFdes(self),
object.fmtUnwindRecords(self),
object.fmtSymtab(self),
});
}
for (self.dylibs.items) |index| {
const dylib = self.getFile(index).?.dylib;
try w.print("dylib({d}) : {f} : needed({}) : weak({})", .{
index,
@as(Path, dylib.path),
dylib.needed,
dylib.weak,
});
if (!dylib.isAlive(self)) try w.writeAll(" : ([*])");
try w.writeByte('\n');
try w.print("{f}\n", .{dylib.fmtSymtab(self)});
}
if (self.getInternalObject()) |internal| {
try w.print("internal({d}) : internal\n", .{internal.index});
try w.print("{f}{f}\n", .{ internal.fmtAtoms(self), internal.fmtSymtab(self) });
}
try w.writeAll("thunks\n");
for (self.thunks.items, 0..) |thunk, index| {
try w.print("thunk({d}) : {f}\n", .{ index, thunk.fmt(self) });
}
try w.print("stubs\n{f}\n", .{self.stubs.fmt(self)});
try w.print("objc_stubs\n{f}\n", .{self.objc_stubs.fmt(self)});
try w.print("got\n{f}\n", .{self.got.fmt(self)});
try w.print("tlv_ptr\n{f}\n", .{self.tlv_ptr.fmt(self)});
try w.writeByte('\n');
try w.print("sections\n{f}\n", .{self.fmtSections()});
try w.print("segments\n{f}\n", .{self.fmtSegments()});
}
fn fmtSections(self: *MachO) std.fmt.Formatter(*MachO, formatSections) {
return .{ .data = self };
}
fn formatSections(self: *MachO, w: *Writer) Writer.Error!void {
const slice = self.sections.slice();
for (slice.items(.header), slice.items(.segment_id), 0..) |header, seg_id, i| {
try w.print(
"sect({d}) : seg({d}) : {s},{s} : @{x} ({x}) : align({x}) : size({x}) : relocs({x};{d})\n",
.{
i, seg_id, header.segName(), header.sectName(), header.addr, header.offset,
header.@"align", header.size, header.reloff, header.nreloc,
},
);
}
}
fn fmtSegments(self: *MachO) std.fmt.Formatter(*MachO, formatSegments) {
return .{ .data = self };
}
fn formatSegments(self: *MachO, w: *Writer) Writer.Error!void {
for (self.segments.items, 0..) |seg, i| {
try w.print("seg({d}) : {s} : @{x}-{x} ({x}-{x})\n", .{
i, seg.segName(), seg.vmaddr, seg.vmaddr + seg.vmsize,
seg.fileoff, seg.fileoff + seg.filesize,
});
}
}
pub fn fmtSectType(tt: u8) std.fmt.Formatter(u8, formatSectType) {
return .{ .data = tt };
}
fn formatSectType(tt: u8, w: *Writer) Writer.Error!void {
const name = switch (tt) {
macho.S_REGULAR => "REGULAR",
macho.S_ZEROFILL => "ZEROFILL",
macho.S_CSTRING_LITERALS => "CSTRING_LITERALS",
macho.S_4BYTE_LITERALS => "4BYTE_LITERALS",
macho.S_8BYTE_LITERALS => "8BYTE_LITERALS",
macho.S_16BYTE_LITERALS => "16BYTE_LITERALS",
macho.S_LITERAL_POINTERS => "LITERAL_POINTERS",
macho.S_NON_LAZY_SYMBOL_POINTERS => "NON_LAZY_SYMBOL_POINTERS",
macho.S_LAZY_SYMBOL_POINTERS => "LAZY_SYMBOL_POINTERS",
macho.S_SYMBOL_STUBS => "SYMBOL_STUBS",
macho.S_MOD_INIT_FUNC_POINTERS => "MOD_INIT_FUNC_POINTERS",
macho.S_MOD_TERM_FUNC_POINTERS => "MOD_TERM_FUNC_POINTERS",
macho.S_COALESCED => "COALESCED",
macho.S_GB_ZEROFILL => "GB_ZEROFILL",
macho.S_INTERPOSING => "INTERPOSING",
macho.S_DTRACE_DOF => "DTRACE_DOF",
macho.S_THREAD_LOCAL_REGULAR => "THREAD_LOCAL_REGULAR",
macho.S_THREAD_LOCAL_ZEROFILL => "THREAD_LOCAL_ZEROFILL",
macho.S_THREAD_LOCAL_VARIABLES => "THREAD_LOCAL_VARIABLES",
macho.S_THREAD_LOCAL_VARIABLE_POINTERS => "THREAD_LOCAL_VARIABLE_POINTERS",
macho.S_THREAD_LOCAL_INIT_FUNCTION_POINTERS => "THREAD_LOCAL_INIT_FUNCTION_POINTERS",
macho.S_INIT_FUNC_OFFSETS => "INIT_FUNC_OFFSETS",
else => |x| return w.print("UNKNOWN({x})", .{x}),
};
try w.print("{s}", .{name});
}
const is_hot_update_compatible = switch (builtin.target.os.tag) {
.macos => true,
else => false,
};
const default_entry_symbol_name = "_main";
const Section = struct {
header: macho.section_64,
segment_id: u8,
atoms: std.ArrayListUnmanaged(Ref) = .empty,
free_list: std.ArrayListUnmanaged(Atom.Index) = .empty,
last_atom_index: Atom.Index = 0,
thunks: std.ArrayListUnmanaged(Thunk.Index) = .empty,
out: std.ArrayListUnmanaged(u8) = .empty,
relocs: std.ArrayListUnmanaged(macho.relocation_info) = .empty,
};
pub const LiteralPool = struct {
table: std.AutoArrayHashMapUnmanaged(void, void) = .empty,
keys: std.ArrayListUnmanaged(Key) = .empty,
values: std.ArrayListUnmanaged(MachO.Ref) = .empty,
data: std.ArrayListUnmanaged(u8) = .empty,
pub fn deinit(lp: *LiteralPool, allocator: Allocator) void {
lp.table.deinit(allocator);
lp.keys.deinit(allocator);
lp.values.deinit(allocator);
lp.data.deinit(allocator);
}
const InsertResult = struct {
found_existing: bool,
index: Index,
ref: *MachO.Ref,
};
pub fn getSymbolRef(lp: LiteralPool, index: Index) MachO.Ref {
assert(index < lp.values.items.len);
return lp.values.items[index];
}
pub fn getSymbol(lp: LiteralPool, index: Index, macho_file: *MachO) *Symbol {
return lp.getSymbolRef(index).getSymbol(macho_file).?;
}
pub fn insert(lp: *LiteralPool, allocator: Allocator, @"type": u8, string: []const u8) !InsertResult {
const size: u32 = @intCast(string.len);
try lp.data.ensureUnusedCapacity(allocator, size);
const off: u32 = @intCast(lp.data.items.len);
lp.data.appendSliceAssumeCapacity(string);
const adapter = Adapter{ .lp = lp };
const key = Key{ .off = off, .size = size, .seed = @"type" };
const gop = try lp.table.getOrPutAdapted(allocator, key, adapter);
if (!gop.found_existing) {
try lp.keys.append(allocator, key);
_ = try lp.values.addOne(allocator);
}
return .{
.found_existing = gop.found_existing,
.index = @intCast(gop.index),
.ref = &lp.values.items[gop.index],
};
}
const Key = struct {
off: u32,
size: u32,
seed: u8,
fn getData(key: Key, lp: *const LiteralPool) []const u8 {
return lp.data.items[key.off..][0..key.size];
}
fn eql(key: Key, other: Key, lp: *const LiteralPool) bool {
const key_data = key.getData(lp);
const other_data = other.getData(lp);
return mem.eql(u8, key_data, other_data);
}
fn hash(key: Key, lp: *const LiteralPool) u32 {
const data = key.getData(lp);
return @truncate(Hash.hash(key.seed, data));
}
};
const Adapter = struct {
lp: *const LiteralPool,
pub fn eql(ctx: @This(), key: Key, b_void: void, b_map_index: usize) bool {
_ = b_void;
const other = ctx.lp.keys.items[b_map_index];
return key.eql(other, ctx.lp);
}
pub fn hash(ctx: @This(), key: Key) u32 {
return key.hash(ctx.lp);
}
};
pub const Index = u32;
};
const HotUpdateState = struct {
mach_task: ?MachTask = null,
};
pub const SymtabCtx = struct {
ilocal: u32 = 0,
istab: u32 = 0,
iexport: u32 = 0,
iimport: u32 = 0,
nlocals: u32 = 0,
nstabs: u32 = 0,
nexports: u32 = 0,
nimports: u32 = 0,
stroff: u32 = 0,
strsize: u32 = 0,
};
pub const null_sym = macho.nlist_64{
.n_strx = 0,
.n_type = 0,
.n_sect = 0,
.n_desc = 0,
.n_value = 0,
};
pub const Platform = struct {
os_tag: std.Target.Os.Tag,
abi: std.Target.Abi,
version: std.SemanticVersion,
/// Using Apple's ld64 as our blueprint, `min_version` as well as `sdk_version` are set to
/// the extracted minimum platform version.
pub fn fromLoadCommand(lc: macho.LoadCommandIterator.LoadCommand) Platform {
switch (lc.cmd()) {
.BUILD_VERSION => {
const cmd = lc.cast(macho.build_version_command).?;
return .{
.os_tag = switch (cmd.platform) {
.DRIVERKIT => .driverkit,
.IOS, .IOSSIMULATOR => .ios,
.MACCATALYST => .ios,
.MACOS => .macos,
.TVOS, .TVOSSIMULATOR => .tvos,
.VISIONOS, .VISIONOSSIMULATOR => .visionos,
.WATCHOS, .WATCHOSSIMULATOR => .watchos,
else => @panic("TODO"),
},
.abi = switch (cmd.platform) {
.MACCATALYST => .macabi,
.IOSSIMULATOR,
.TVOSSIMULATOR,
.VISIONOSSIMULATOR,
.WATCHOSSIMULATOR,
=> .simulator,
else => .none,
},
.version = appleVersionToSemanticVersion(cmd.minos),
};
},
.VERSION_MIN_IPHONEOS,
.VERSION_MIN_MACOSX,
.VERSION_MIN_TVOS,
.VERSION_MIN_WATCHOS,
=> {
const cmd = lc.cast(macho.version_min_command).?;
return .{
.os_tag = switch (lc.cmd()) {
.VERSION_MIN_IPHONEOS => .ios,
.VERSION_MIN_MACOSX => .macos,
.VERSION_MIN_TVOS => .tvos,
.VERSION_MIN_WATCHOS => .watchos,
else => unreachable,
},
.abi = .none,
.version = appleVersionToSemanticVersion(cmd.version),
};
},
else => unreachable,
}
}
pub fn fromTarget(target: *const std.Target) Platform {
return .{
.os_tag = target.os.tag,
.abi = target.abi,
.version = target.os.version_range.semver.min,
};
}
pub fn toAppleVersion(plat: Platform) u32 {
return semanticVersionToAppleVersion(plat.version);
}
pub fn toApplePlatform(plat: Platform) macho.PLATFORM {
return switch (plat.os_tag) {
.driverkit => .DRIVERKIT,
.ios => switch (plat.abi) {
.macabi => .MACCATALYST,
.simulator => .IOSSIMULATOR,
else => .IOS,
},
.macos => .MACOS,
.tvos => if (plat.abi == .simulator) .TVOSSIMULATOR else .TVOS,
.visionos => if (plat.abi == .simulator) .VISIONOSSIMULATOR else .VISIONOS,
.watchos => if (plat.abi == .simulator) .WATCHOSSIMULATOR else .WATCHOS,
else => unreachable,
};
}
pub fn isBuildVersionCompatible(plat: Platform) bool {
inline for (supported_platforms) |sup_plat| {
if (sup_plat[0] == plat.os_tag and sup_plat[1] == plat.abi) {
return sup_plat[2] <= plat.toAppleVersion();
}
}
return false;
}
pub fn isVersionMinCompatible(plat: Platform) bool {
inline for (supported_platforms) |sup_plat| {
if (sup_plat[0] == plat.os_tag and sup_plat[1] == plat.abi) {
return sup_plat[3] <= plat.toAppleVersion();
}
}
return false;
}
pub fn fmtTarget(plat: Platform, cpu_arch: std.Target.Cpu.Arch) std.fmt.Formatter(Format, Format.target) {
return .{ .data = .{ .platform = plat, .cpu_arch = cpu_arch } };
}
const Format = struct {
platform: Platform,
cpu_arch: std.Target.Cpu.Arch,
pub fn target(f: Format, w: *Writer) Writer.Error!void {
try w.print("{s}-{s}", .{ @tagName(f.cpu_arch), @tagName(f.platform.os_tag) });
if (f.platform.abi != .none) {
try w.print("-{s}", .{@tagName(f.platform.abi)});
}
}
};
/// Caller owns the memory.
pub fn allocPrintTarget(plat: Platform, gpa: Allocator, cpu_arch: std.Target.Cpu.Arch) error{OutOfMemory}![]u8 {
var buffer = std.ArrayList(u8).init(gpa);
defer buffer.deinit();
try buffer.writer().print("{f}", .{plat.fmtTarget(cpu_arch)});
return buffer.toOwnedSlice();
}
pub fn eqlTarget(plat: Platform, other: Platform) bool {
return plat.os_tag == other.os_tag and plat.abi == other.abi;
}
};
const SupportedPlatforms = struct {
std.Target.Os.Tag,
std.Target.Abi,
u32, // Min platform version for which to emit LC_BUILD_VERSION
u32, // Min supported platform version
};
// Source: https://github.com/apple-oss-distributions/ld64/blob/59a99ab60399c5e6c49e6945a9e1049c42b71135/src/ld/PlatformSupport.cpp#L52
// zig fmt: off
const supported_platforms = [_]SupportedPlatforms{
.{ .driverkit, .none, 0x130000, 0x130000 },
.{ .ios, .none, 0x0C0000, 0x070000 },
.{ .ios, .macabi, 0x0D0000, 0x0D0000 },
.{ .ios, .simulator, 0x0D0000, 0x080000 },
.{ .macos, .none, 0x0A0E00, 0x0A0800 },
.{ .tvos, .none, 0x0C0000, 0x070000 },
.{ .tvos, .simulator, 0x0D0000, 0x080000 },
.{ .visionos, .none, 0x010000, 0x010000 },
.{ .visionos, .simulator, 0x010000, 0x010000 },
.{ .watchos, .none, 0x050000, 0x020000 },
.{ .watchos, .simulator, 0x060000, 0x020000 },
};
// zig fmt: on
pub inline fn semanticVersionToAppleVersion(version: std.SemanticVersion) u32 {
const major = version.major;
const minor = version.minor;
const patch = version.patch;
return (@as(u32, @intCast(major)) << 16) | (@as(u32, @intCast(minor)) << 8) | @as(u32, @intCast(patch));
}
pub inline fn appleVersionToSemanticVersion(version: u32) std.SemanticVersion {
return .{
.major = @as(u16, @truncate(version >> 16)),
.minor = @as(u8, @truncate(version >> 8)),
.patch = @as(u8, @truncate(version)),
};
}
fn inferSdkVersion(comp: *Compilation, sdk_layout: SdkLayout) ?std.SemanticVersion {
const gpa = comp.gpa;
var arena_allocator = std.heap.ArenaAllocator.init(gpa);
defer arena_allocator.deinit();
const arena = arena_allocator.allocator();
const sdk_dir = switch (sdk_layout) {
.sdk => comp.sysroot.?,
.vendored => fs.path.join(arena, &.{ comp.dirs.zig_lib.path.?, "libc", "darwin" }) catch return null,
};
if (readSdkVersionFromSettings(arena, sdk_dir)) |ver| {
return parseSdkVersion(ver);
} else |_| {
// Read from settings should always succeed when vendored.
// TODO: convert to fatal linker error
if (sdk_layout == .vendored) @panic("zig installation bug: unable to parse SDK version");
}
// infer from pathname
const stem = fs.path.stem(sdk_dir);
const start = for (stem, 0..) |c, i| {
if (std.ascii.isDigit(c)) break i;
} else stem.len;
const end = for (stem[start..], start..) |c, i| {
if (std.ascii.isDigit(c) or c == '.') continue;
break i;
} else stem.len;
return parseSdkVersion(stem[start..end]);
}
// Official Apple SDKs ship with a `SDKSettings.json` located at the top of SDK fs layout.
// Use property `MinimalDisplayName` to determine version.
// The file/property is also available with vendored libc.
fn readSdkVersionFromSettings(arena: Allocator, dir: []const u8) ![]const u8 {
const sdk_path = try fs.path.join(arena, &.{ dir, "SDKSettings.json" });
const contents = try fs.cwd().readFileAlloc(arena, sdk_path, std.math.maxInt(u16));
const parsed = try std.json.parseFromSlice(std.json.Value, arena, contents, .{});
if (parsed.value.object.get("MinimalDisplayName")) |ver| return ver.string;
return error.SdkVersionFailure;
}
// Versions reported by Apple aren't exactly semantically valid as they usually omit
// the patch component, so we parse SDK value by hand.
fn parseSdkVersion(raw: []const u8) ?std.SemanticVersion {
var parsed: std.SemanticVersion = .{
.major = 0,
.minor = 0,
.patch = 0,
};
const parseNext = struct {
fn parseNext(it: anytype) ?u16 {
const nn = it.next() orelse return null;
return std.fmt.parseInt(u16, nn, 10) catch null;
}
}.parseNext;
var it = std.mem.splitAny(u8, raw, ".");
parsed.major = parseNext(&it) orelse return null;
parsed.minor = parseNext(&it) orelse return null;
parsed.patch = parseNext(&it) orelse 0;
return parsed;
}
/// When allocating, the ideal_capacity is calculated by
/// actual_capacity + (actual_capacity / ideal_factor)
const ideal_factor = 3;
/// In order for a slice of bytes to be considered eligible to keep metadata pointing at
/// it as a possible place to put new symbols, it must have enough room for this many bytes
/// (plus extra for reserved capacity).
const minimum_text_block_size = 64;
pub const min_text_capacity = padToIdeal(minimum_text_block_size);
/// Default virtual memory offset corresponds to the size of __PAGEZERO segment and
/// start of __TEXT segment.
pub const default_pagezero_size: u64 = 0x100000000;
/// We commit 0x1000 = 4096 bytes of space to the header and
/// the table of load commands. This should be plenty for any
/// potential future extensions.
pub const default_headerpad_size: u32 = 0x1000;
const SystemLib = struct {
path: Path,
needed: bool = false,
weak: bool = false,
hidden: bool = false,
reexport: bool = false,
must_link: bool = false,
fn fromLinkInput(link_input: link.Input) SystemLib {
return switch (link_input) {
.dso_exact => unreachable,
.res => unreachable,
.object, .archive => |obj| .{
.path = obj.path,
.must_link = obj.must_link,
.hidden = obj.hidden,
},
.dso => |dso| .{
.path = dso.path,
.needed = dso.needed,
.weak = dso.weak,
.reexport = dso.reexport,
},
};
}
};
pub const SdkLayout = std.zig.LibCDirs.DarwinSdkLayout;
const UndefinedTreatment = enum {
@"error",
warn,
suppress,
dynamic_lookup,
};
/// A reference to atom or symbol in an input file.
/// If file == 0, symbol is an undefined global.
pub const Ref = struct {
index: u32,
file: File.Index,
pub fn eql(ref: Ref, other: Ref) bool {
return ref.index == other.index and ref.file == other.file;
}
pub fn lessThan(ref: Ref, other: Ref) bool {
if (ref.file == other.file) {
return ref.index < other.index;
}
return ref.file < other.file;
}
pub fn getFile(ref: Ref, macho_file: *MachO) ?File {
return macho_file.getFile(ref.file);
}
pub fn getAtom(ref: Ref, macho_file: *MachO) ?*Atom {
const file = ref.getFile(macho_file) orelse return null;
return file.getAtom(ref.index);
}
pub fn getSymbol(ref: Ref, macho_file: *MachO) ?*Symbol {
const file = ref.getFile(macho_file) orelse return null;
return switch (file) {
inline else => |x| &x.symbols.items[ref.index],
};
}
pub fn format(ref: Ref, bw: *Writer) Writer.Error!void {
try bw.print("%{d} in file({d})", .{ ref.index, ref.file });
}
};
pub const SymbolResolver = struct {
keys: std.ArrayListUnmanaged(Key) = .empty,
values: std.ArrayListUnmanaged(Ref) = .empty,
table: std.AutoArrayHashMapUnmanaged(void, void) = .empty,
const Result = struct {
found_existing: bool,
index: Index,
ref: *Ref,
};
pub fn deinit(resolver: *SymbolResolver, allocator: Allocator) void {
resolver.keys.deinit(allocator);
resolver.values.deinit(allocator);
resolver.table.deinit(allocator);
}
pub fn getOrPut(
resolver: *SymbolResolver,
allocator: Allocator,
ref: Ref,
macho_file: *MachO,
) !Result {
const adapter = Adapter{ .keys = resolver.keys.items, .macho_file = macho_file };
const key = Key{ .index = ref.index, .file = ref.file };
const gop = try resolver.table.getOrPutAdapted(allocator, key, adapter);
if (!gop.found_existing) {
try resolver.keys.append(allocator, key);
_ = try resolver.values.addOne(allocator);
}
return .{
.found_existing = gop.found_existing,
.index = @intCast(gop.index + 1),
.ref = &resolver.values.items[gop.index],
};
}
pub fn get(resolver: SymbolResolver, index: Index) ?Ref {
if (index == 0) return null;
return resolver.values.items[index - 1];
}
pub fn reset(resolver: *SymbolResolver) void {
resolver.keys.clearRetainingCapacity();
resolver.values.clearRetainingCapacity();
resolver.table.clearRetainingCapacity();
}
const Key = struct {
index: Symbol.Index,
file: File.Index,
fn getName(key: Key, macho_file: *MachO) [:0]const u8 {
const ref = Ref{ .index = key.index, .file = key.file };
return ref.getSymbol(macho_file).?.getName(macho_file);
}
pub fn getFile(key: Key, macho_file: *MachO) ?File {
const ref = Ref{ .index = key.index, .file = key.file };
return ref.getFile(macho_file);
}
fn eql(key: Key, other: Key, macho_file: *MachO) bool {
const key_name = key.getName(macho_file);
const other_name = other.getName(macho_file);
return mem.eql(u8, key_name, other_name);
}
fn hash(key: Key, macho_file: *MachO) u32 {
const name = key.getName(macho_file);
return @truncate(Hash.hash(0, name));
}
};
const Adapter = struct {
keys: []const Key,
macho_file: *MachO,
pub fn eql(ctx: @This(), key: Key, b_void: void, b_map_index: usize) bool {
_ = b_void;
const other = ctx.keys[b_map_index];
return key.eql(other, ctx.macho_file);
}
pub fn hash(ctx: @This(), key: Key) u32 {
return key.hash(ctx.macho_file);
}
};
pub const Index = u32;
};
pub const String = struct {
pos: u32 = 0,
len: u32 = 0,
};
pub const UndefRefs = union(enum) {
force_undefined,
entry,
dyld_stub_binder,
objc_msgsend,
refs: std.ArrayListUnmanaged(Ref),
pub fn deinit(self: *UndefRefs, allocator: Allocator) void {
switch (self.*) {
.refs => |*refs| refs.deinit(allocator),
else => {},
}
}
};
pub const MachError = error{
/// Not enough permissions held to perform the requested kernel
/// call.
PermissionDenied,
} || std.posix.UnexpectedError;
pub const MachTask = extern struct {
port: std.c.mach_port_name_t,
pub fn isValid(self: MachTask) bool {
return self.port != std.c.TASK_NULL;
}
pub fn pidForTask(self: MachTask) MachError!std.c.pid_t {
var pid: std.c.pid_t = undefined;
switch (getKernError(std.c.pid_for_task(self.port, &pid))) {
.SUCCESS => return pid,
.FAILURE => return error.PermissionDenied,
else => |err| return unexpectedKernError(err),
}
}
pub fn allocatePort(self: MachTask, right: std.c.MACH_PORT_RIGHT) MachError!MachTask {
var out_port: std.c.mach_port_name_t = undefined;
switch (getKernError(std.c.mach_port_allocate(
self.port,
@intFromEnum(right),
&out_port,
))) {
.SUCCESS => return .{ .port = out_port },
.FAILURE => return error.PermissionDenied,
else => |err| return unexpectedKernError(err),
}
}
pub fn deallocatePort(self: MachTask, port: MachTask) void {
_ = getKernError(std.c.mach_port_deallocate(self.port, port.port));
}
pub fn insertRight(self: MachTask, port: MachTask, msg: std.c.MACH_MSG_TYPE) !void {
switch (getKernError(std.c.mach_port_insert_right(
self.port,
port.port,
port.port,
@intFromEnum(msg),
))) {
.SUCCESS => return,
.FAILURE => return error.PermissionDenied,
else => |err| return unexpectedKernError(err),
}
}
pub const PortInfo = struct {
mask: std.c.exception_mask_t,
masks: [std.c.EXC.TYPES_COUNT]std.c.exception_mask_t,
ports: [std.c.EXC.TYPES_COUNT]std.c.mach_port_t,
behaviors: [std.c.EXC.TYPES_COUNT]std.c.exception_behavior_t,
flavors: [std.c.EXC.TYPES_COUNT]std.c.thread_state_flavor_t,
count: std.c.mach_msg_type_number_t,
};
pub fn getExceptionPorts(self: MachTask, mask: std.c.exception_mask_t) !PortInfo {
var info: PortInfo = .{
.mask = mask,
.masks = undefined,
.ports = undefined,
.behaviors = undefined,
.flavors = undefined,
.count = 0,
};
info.count = info.ports.len / @sizeOf(std.c.mach_port_t);
switch (getKernError(std.c.task_get_exception_ports(
self.port,
info.mask,
&info.masks,
&info.count,
&info.ports,
&info.behaviors,
&info.flavors,
))) {
.SUCCESS => return info,
.FAILURE => return error.PermissionDenied,
else => |err| return unexpectedKernError(err),
}
}
pub fn setExceptionPorts(
self: MachTask,
mask: std.c.exception_mask_t,
new_port: MachTask,
behavior: std.c.exception_behavior_t,
new_flavor: std.c.thread_state_flavor_t,
) !void {
switch (getKernError(std.c.task_set_exception_ports(
self.port,
mask,
new_port.port,
behavior,
new_flavor,
))) {
.SUCCESS => return,
.FAILURE => return error.PermissionDenied,
else => |err| return unexpectedKernError(err),
}
}
pub const RegionInfo = struct {
pub const Tag = enum {
basic,
extended,
top,
};
base_addr: u64,
tag: Tag,
info: union {
basic: std.c.vm_region_basic_info_64,
extended: std.c.vm_region_extended_info,
top: std.c.vm_region_top_info,
},
};
pub fn getRegionInfo(
task: MachTask,
address: u64,
len: usize,
tag: RegionInfo.Tag,
) MachError!RegionInfo {
var info: RegionInfo = .{
.base_addr = address,
.tag = tag,
.info = undefined,
};
switch (tag) {
.basic => info.info = .{ .basic = undefined },
.extended => info.info = .{ .extended = undefined },
.top => info.info = .{ .top = undefined },
}
var base_len: std.c.mach_vm_size_t = if (len == 1) 2 else len;
var objname: std.c.mach_port_t = undefined;
var count: std.c.mach_msg_type_number_t = switch (tag) {
.basic => std.c.VM.REGION.BASIC_INFO_COUNT,
.extended => std.c.VM.REGION.EXTENDED_INFO_COUNT,
.top => std.c.VM.REGION.TOP_INFO_COUNT,
};
switch (getKernError(std.c.mach_vm_region(
task.port,
&info.base_addr,
&base_len,
switch (tag) {
.basic => std.c.VM.REGION.BASIC_INFO_64,
.extended => std.c.VM.REGION.EXTENDED_INFO,
.top => std.c.VM.REGION.TOP_INFO,
},
switch (tag) {
.basic => @as(std.c.vm_region_info_t, @ptrCast(&info.info.basic)),
.extended => @as(std.c.vm_region_info_t, @ptrCast(&info.info.extended)),
.top => @as(std.c.vm_region_info_t, @ptrCast(&info.info.top)),
},
&count,
&objname,
))) {
.SUCCESS => return info,
.FAILURE => return error.PermissionDenied,
else => |err| return unexpectedKernError(err),
}
}
pub const RegionSubmapInfo = struct {
pub const Tag = enum {
short,
full,
};
tag: Tag,
base_addr: u64,
info: union {
short: std.c.vm_region_submap_short_info_64,
full: std.c.vm_region_submap_info_64,
},
};
pub fn getRegionSubmapInfo(
task: MachTask,
address: u64,
len: usize,
nesting_depth: u32,
tag: RegionSubmapInfo.Tag,
) MachError!RegionSubmapInfo {
var info: RegionSubmapInfo = .{
.base_addr = address,
.tag = tag,
.info = undefined,
};
switch (tag) {
.short => info.info = .{ .short = undefined },
.full => info.info = .{ .full = undefined },
}
var nesting = nesting_depth;
var base_len: std.c.mach_vm_size_t = if (len == 1) 2 else len;
var count: std.c.mach_msg_type_number_t = switch (tag) {
.short => std.c.VM.REGION.SUBMAP_SHORT_INFO_COUNT_64,
.full => std.c.VM.REGION.SUBMAP_INFO_COUNT_64,
};
switch (getKernError(std.c.mach_vm_region_recurse(
task.port,
&info.base_addr,
&base_len,
&nesting,
switch (tag) {
.short => @as(std.c.vm_region_recurse_info_t, @ptrCast(&info.info.short)),
.full => @as(std.c.vm_region_recurse_info_t, @ptrCast(&info.info.full)),
},
&count,
))) {
.SUCCESS => return info,
.FAILURE => return error.PermissionDenied,
else => |err| return unexpectedKernError(err),
}
}
pub fn getCurrProtection(task: MachTask, address: u64, len: usize) MachError!std.c.vm_prot_t {
const info = try task.getRegionSubmapInfo(address, len, 0, .short);
return info.info.short.protection;
}
pub fn setMaxProtection(task: MachTask, address: u64, len: usize, prot: std.c.vm_prot_t) MachError!void {
return task.setProtectionImpl(address, len, true, prot);
}
pub fn setCurrProtection(task: MachTask, address: u64, len: usize, prot: std.c.vm_prot_t) MachError!void {
return task.setProtectionImpl(address, len, false, prot);
}
fn setProtectionImpl(task: MachTask, address: u64, len: usize, set_max: bool, prot: std.c.vm_prot_t) MachError!void {
switch (getKernError(std.c.mach_vm_protect(task.port, address, len, @intFromBool(set_max), prot))) {
.SUCCESS => return,
.FAILURE => return error.PermissionDenied,
else => |err| return unexpectedKernError(err),
}
}
/// Will write to VM even if current protection attributes specifically prohibit
/// us from doing so, by temporarily setting protection level to a level with VM_PROT_COPY
/// variant, and resetting after a successful or unsuccessful write.
pub fn writeMemProtected(task: MachTask, address: u64, buf: []const u8, arch: std.Target.Cpu.Arch) MachError!usize {
const curr_prot = try task.getCurrProtection(address, buf.len);
try task.setCurrProtection(
address,
buf.len,
std.c.PROT.READ | std.c.PROT.WRITE | std.c.PROT.COPY,
);
defer {
task.setCurrProtection(address, buf.len, curr_prot) catch {};
}
return task.writeMem(address, buf, arch);
}
pub fn writeMem(task: MachTask, address: u64, buf: []const u8, arch: std.Target.Cpu.Arch) MachError!usize {
const count = buf.len;
var total_written: usize = 0;
var curr_addr = address;
const page_size = try MachTask.getPageSize(task); // TODO we probably can assume value here
var out_buf = buf[0..];
while (total_written < count) {
const curr_size = maxBytesLeftInPage(page_size, curr_addr, count - total_written);
switch (getKernError(std.c.mach_vm_write(
task.port,
curr_addr,
@intFromPtr(out_buf.ptr),
@as(std.c.mach_msg_type_number_t, @intCast(curr_size)),
))) {
.SUCCESS => {},
.FAILURE => return error.PermissionDenied,
else => |err| return unexpectedKernError(err),
}
switch (arch) {
.aarch64 => {
var mattr_value: std.c.vm_machine_attribute_val_t = std.c.MATTR.VAL_CACHE_FLUSH;
switch (getKernError(std.c.vm_machine_attribute(
task.port,
curr_addr,
curr_size,
std.c.MATTR.CACHE,
&mattr_value,
))) {
.SUCCESS => {},
.FAILURE => return error.PermissionDenied,
else => |err| return unexpectedKernError(err),
}
},
.x86_64 => {},
else => unreachable,
}
out_buf = out_buf[curr_size..];
total_written += curr_size;
curr_addr += curr_size;
}
return total_written;
}
pub fn readMem(task: MachTask, address: u64, buf: []u8) MachError!usize {
const count = buf.len;
var total_read: usize = 0;
var curr_addr = address;
const page_size = try MachTask.getPageSize(task); // TODO we probably can assume value here
var out_buf = buf[0..];
while (total_read < count) {
const curr_size = maxBytesLeftInPage(page_size, curr_addr, count - total_read);
var curr_bytes_read: std.c.mach_msg_type_number_t = 0;
var vm_memory: std.c.vm_offset_t = undefined;
switch (getKernError(std.c.mach_vm_read(task.port, curr_addr, curr_size, &vm_memory, &curr_bytes_read))) {
.SUCCESS => {},
.FAILURE => return error.PermissionDenied,
else => |err| return unexpectedKernError(err),
}
@memcpy(out_buf[0..curr_bytes_read], @as([*]const u8, @ptrFromInt(vm_memory)));
_ = std.c.vm_deallocate(std.c.mach_task_self(), vm_memory, curr_bytes_read);
out_buf = out_buf[curr_bytes_read..];
curr_addr += curr_bytes_read;
total_read += curr_bytes_read;
}
return total_read;
}
fn maxBytesLeftInPage(page_size: usize, address: u64, count: usize) usize {
var left = count;
if (page_size > 0) {
const page_offset = address % page_size;
const bytes_left_in_page = page_size - page_offset;
if (count > bytes_left_in_page) {
left = bytes_left_in_page;
}
}
return left;
}
fn getPageSize(task: MachTask) MachError!usize {
if (task.isValid()) {
var info_count = std.c.TASK_VM_INFO_COUNT;
var vm_info: std.c.task_vm_info_data_t = undefined;
switch (getKernError(std.c.task_info(
task.port,
std.c.TASK_VM_INFO,
@as(std.c.task_info_t, @ptrCast(&vm_info)),
&info_count,
))) {
.SUCCESS => return @as(usize, @intCast(vm_info.page_size)),
else => {},
}
}
var page_size: std.c.vm_size_t = undefined;
switch (getKernError(std.c._host_page_size(std.c.mach_host_self(), &page_size))) {
.SUCCESS => return page_size,
else => |err| return unexpectedKernError(err),
}
}
pub fn basicTaskInfo(task: MachTask) MachError!std.c.mach_task_basic_info {
var info: std.c.mach_task_basic_info = undefined;
var count = std.c.MACH_TASK_BASIC_INFO_COUNT;
switch (getKernError(std.c.task_info(
task.port,
std.c.MACH_TASK_BASIC_INFO,
@as(std.c.task_info_t, @ptrCast(&info)),
&count,
))) {
.SUCCESS => return info,
else => |err| return unexpectedKernError(err),
}
}
pub fn @"resume"(task: MachTask) MachError!void {
switch (getKernError(std.c.task_resume(task.port))) {
.SUCCESS => {},
else => |err| return unexpectedKernError(err),
}
}
pub fn @"suspend"(task: MachTask) MachError!void {
switch (getKernError(std.c.task_suspend(task.port))) {
.SUCCESS => {},
else => |err| return unexpectedKernError(err),
}
}
const ThreadList = struct {
buf: []MachThread,
pub fn deinit(list: ThreadList) void {
const self_task = machTaskForSelf();
_ = std.c.vm_deallocate(
self_task.port,
@intFromPtr(list.buf.ptr),
@as(std.c.vm_size_t, @intCast(list.buf.len * @sizeOf(std.c.mach_port_t))),
);
}
};
pub fn getThreads(task: MachTask) MachError!ThreadList {
var thread_list: std.c.mach_port_array_t = undefined;
var thread_count: std.c.mach_msg_type_number_t = undefined;
switch (getKernError(std.c.task_threads(task.port, &thread_list, &thread_count))) {
.SUCCESS => return ThreadList{ .buf = @as([*]MachThread, @ptrCast(thread_list))[0..thread_count] },
else => |err| return unexpectedKernError(err),
}
}
};
pub const MachThread = extern struct {
port: std.c.mach_port_t,
pub fn isValid(thread: MachThread) bool {
return thread.port != std.c.THREAD_NULL;
}
pub fn getBasicInfo(thread: MachThread) MachError!std.c.thread_basic_info {
var info: std.c.thread_basic_info = undefined;
var count = std.c.THREAD_BASIC_INFO_COUNT;
switch (getKernError(std.c.thread_info(
thread.port,
std.c.THREAD_BASIC_INFO,
@as(std.c.thread_info_t, @ptrCast(&info)),
&count,
))) {
.SUCCESS => return info,
else => |err| return unexpectedKernError(err),
}
}
pub fn getIdentifierInfo(thread: MachThread) MachError!std.c.thread_identifier_info {
var info: std.c.thread_identifier_info = undefined;
var count = std.c.THREAD_IDENTIFIER_INFO_COUNT;
switch (getKernError(std.c.thread_info(
thread.port,
std.c.THREAD_IDENTIFIER_INFO,
@as(std.c.thread_info_t, @ptrCast(&info)),
&count,
))) {
.SUCCESS => return info,
else => |err| return unexpectedKernError(err),
}
}
};
pub fn machTaskForPid(pid: std.c.pid_t) MachError!MachTask {
var port: std.c.mach_port_name_t = undefined;
switch (getKernError(std.c.task_for_pid(std.c.mach_task_self(), pid, &port))) {
.SUCCESS => {},
.FAILURE => return error.PermissionDenied,
else => |err| return unexpectedKernError(err),
}
return MachTask{ .port = port };
}
pub fn machTaskForSelf() MachTask {
return .{ .port = std.c.mach_task_self() };
}
pub fn getKernError(err: std.c.kern_return_t) KernE {
return @as(KernE, @enumFromInt(@as(u32, @truncate(@as(usize, @intCast(err))))));
}
pub fn unexpectedKernError(err: KernE) std.posix.UnexpectedError {
if (std.posix.unexpected_error_tracing) {
std.debug.print("unexpected error: {d}\n", .{@intFromEnum(err)});
std.debug.dumpCurrentStackTrace(null);
}
return error.Unexpected;
}
/// Kernel return values
pub const KernE = enum(u32) {
SUCCESS = 0,
/// Specified address is not currently valid
INVALID_ADDRESS = 1,
/// Specified memory is valid, but does not permit the
/// required forms of access.
PROTECTION_FAILURE = 2,
/// The address range specified is already in use, or
/// no address range of the size specified could be
/// found.
NO_SPACE = 3,
/// The function requested was not applicable to this
/// type of argument, or an argument is invalid
INVALID_ARGUMENT = 4,
/// The function could not be performed. A catch-all.
FAILURE = 5,
/// A system resource could not be allocated to fulfill
/// this request. This failure may not be permanent.
RESOURCE_SHORTAGE = 6,
/// The task in question does not hold receive rights
/// for the port argument.
NOT_RECEIVER = 7,
/// Bogus access restriction.
NO_ACCESS = 8,
/// During a page fault, the target address refers to a
/// memory object that has been destroyed. This
/// failure is permanent.
MEMORY_FAILURE = 9,
/// During a page fault, the memory object indicated
/// that the data could not be returned. This failure
/// may be temporary; future attempts to access this
/// same data may succeed, as defined by the memory
/// object.
MEMORY_ERROR = 10,
/// The receive right is already a member of the portset.
ALREADY_IN_SET = 11,
/// The receive right is not a member of a port set.
NOT_IN_SET = 12,
/// The name already denotes a right in the task.
NAME_EXISTS = 13,
/// The operation was aborted. Ipc code will
/// catch this and reflect it as a message error.
ABORTED = 14,
/// The name doesn't denote a right in the task.
INVALID_NAME = 15,
/// Target task isn't an active task.
INVALID_TASK = 16,
/// The name denotes a right, but not an appropriate right.
INVALID_RIGHT = 17,
/// A blatant range error.
INVALID_VALUE = 18,
/// Operation would overflow limit on user-references.
UREFS_OVERFLOW = 19,
/// The supplied (port) capability is improper.
INVALID_CAPABILITY = 20,
/// The task already has send or receive rights
/// for the port under another name.
RIGHT_EXISTS = 21,
/// Target host isn't actually a host.
INVALID_HOST = 22,
/// An attempt was made to supply "precious" data
/// for memory that is already present in a
/// memory object.
MEMORY_PRESENT = 23,
/// A page was requested of a memory manager via
/// memory_object_data_request for an object using
/// a MEMORY_OBJECT_COPY_CALL strategy, with the
/// VM_PROT_WANTS_COPY flag being used to specify
/// that the page desired is for a copy of the
/// object, and the memory manager has detected
/// the page was pushed into a copy of the object
/// while the kernel was walking the shadow chain
/// from the copy to the object. This error code
/// is delivered via memory_object_data_error
/// and is handled by the kernel (it forces the
/// kernel to restart the fault). It will not be
/// seen by users.
MEMORY_DATA_MOVED = 24,
/// A strategic copy was attempted of an object
/// upon which a quicker copy is now possible.
/// The caller should retry the copy using
/// vm_object_copy_quickly. This error code
/// is seen only by the kernel.
MEMORY_RESTART_COPY = 25,
/// An argument applied to assert processor set privilege
/// was not a processor set control port.
INVALID_PROCESSOR_SET = 26,
/// The specified scheduling attributes exceed the thread's
/// limits.
POLICY_LIMIT = 27,
/// The specified scheduling policy is not currently
/// enabled for the processor set.
INVALID_POLICY = 28,
/// The external memory manager failed to initialize the
/// memory object.
INVALID_OBJECT = 29,
/// A thread is attempting to wait for an event for which
/// there is already a waiting thread.
ALREADY_WAITING = 30,
/// An attempt was made to destroy the default processor
/// set.
DEFAULT_SET = 31,
/// An attempt was made to fetch an exception port that is
/// protected, or to abort a thread while processing a
/// protected exception.
EXCEPTION_PROTECTED = 32,
/// A ledger was required but not supplied.
INVALID_LEDGER = 33,
/// The port was not a memory cache control port.
INVALID_MEMORY_CONTROL = 34,
/// An argument supplied to assert security privilege
/// was not a host security port.
INVALID_SECURITY = 35,
/// thread_depress_abort was called on a thread which
/// was not currently depressed.
NOT_DEPRESSED = 36,
/// Object has been terminated and is no longer available
TERMINATED = 37,
/// Lock set has been destroyed and is no longer available.
LOCK_SET_DESTROYED = 38,
/// The thread holding the lock terminated before releasing
/// the lock
LOCK_UNSTABLE = 39,
/// The lock is already owned by another thread
LOCK_OWNED = 40,
/// The lock is already owned by the calling thread
LOCK_OWNED_SELF = 41,
/// Semaphore has been destroyed and is no longer available.
SEMAPHORE_DESTROYED = 42,
/// Return from RPC indicating the target server was
/// terminated before it successfully replied
RPC_SERVER_TERMINATED = 43,
/// Terminate an orphaned activation.
RPC_TERMINATE_ORPHAN = 44,
/// Allow an orphaned activation to continue executing.
RPC_CONTINUE_ORPHAN = 45,
/// Empty thread activation (No thread linked to it)
NOT_SUPPORTED = 46,
/// Remote node down or inaccessible.
NODE_DOWN = 47,
/// A signalled thread was not actually waiting.
NOT_WAITING = 48,
/// Some thread-oriented operation (semaphore_wait) timed out
OPERATION_TIMED_OUT = 49,
/// During a page fault, indicates that the page was rejected
/// as a result of a signature check.
CODESIGN_ERROR = 50,
/// The requested property cannot be changed at this time.
POLICY_STATIC = 51,
/// The provided buffer is of insufficient size for the requested data.
INSUFFICIENT_BUFFER_SIZE = 52,
/// Denied by security policy
DENIED = 53,
/// The KC on which the function is operating is missing
MISSING_KC = 54,
/// The KC on which the function is operating is invalid
INVALID_KC = 55,
/// A search or query operation did not return a result
NOT_FOUND = 56,
_,
};
fn createThunks(macho_file: *MachO, sect_id: u8) !void {
const tracy = trace(@src());
defer tracy.end();
const gpa = macho_file.base.comp.gpa;
const slice = macho_file.sections.slice();
const header = &slice.items(.header)[sect_id];
const thnks = &slice.items(.thunks)[sect_id];
const atoms = slice.items(.atoms)[sect_id].items;
assert(atoms.len > 0);
for (atoms) |ref| {
ref.getAtom(macho_file).?.value = @bitCast(@as(i64, -1));
}
var i: usize = 0;
while (i < atoms.len) {
const start = i;
const start_atom = atoms[start].getAtom(macho_file).?;
assert(start_atom.isAlive());
start_atom.value = advanceSection(header, start_atom.size, start_atom.alignment);
i += 1;
while (i < atoms.len and
header.size - start_atom.value < max_allowed_distance) : (i += 1)
{
const atom = atoms[i].getAtom(macho_file).?;
assert(atom.isAlive());
atom.value = advanceSection(header, atom.size, atom.alignment);
}
// Insert a thunk at the group end
const thunk_index = try macho_file.addThunk();
const thunk = macho_file.getThunk(thunk_index);
thunk.out_n_sect = sect_id;
try thnks.append(gpa, thunk_index);
// Scan relocs in the group and create trampolines for any unreachable callsite
try scanThunkRelocs(thunk_index, gpa, atoms[start..i], macho_file);
thunk.value = advanceSection(header, thunk.size(), .@"4");
log.debug("thunk({d}) : {f}", .{ thunk_index, thunk.fmt(macho_file) });
}
}
fn advanceSection(sect: *macho.section_64, adv_size: u64, alignment: Atom.Alignment) u64 {
const offset = alignment.forward(sect.size);
const padding = offset - sect.size;
sect.size += padding + adv_size;
sect.@"align" = @max(sect.@"align", alignment.toLog2Units());
return offset;
}
fn scanThunkRelocs(thunk_index: Thunk.Index, gpa: Allocator, atoms: []const MachO.Ref, macho_file: *MachO) !void {
const tracy = trace(@src());
defer tracy.end();
const thunk = macho_file.getThunk(thunk_index);
for (atoms) |ref| {
const atom = ref.getAtom(macho_file).?;
log.debug("atom({d}) {s}", .{ atom.atom_index, atom.getName(macho_file) });
for (atom.getRelocs(macho_file)) |rel| {
if (rel.type != .branch) continue;
if (isReachable(atom, rel, macho_file)) continue;
try thunk.symbols.put(gpa, rel.getTargetSymbolRef(atom.*, macho_file), {});
}
atom.addExtra(.{ .thunk = thunk_index }, macho_file);
}
}
fn isReachable(atom: *const Atom, rel: Relocation, macho_file: *MachO) bool {
const target = rel.getTargetSymbol(atom.*, macho_file);
if (target.getSectionFlags().stubs or target.getSectionFlags().objc_stubs) return false;
if (atom.out_n_sect != target.getOutputSectionIndex(macho_file)) return false;
const target_atom = target.getAtom(macho_file).?;
if (target_atom.value == @as(u64, @bitCast(@as(i64, -1)))) return false;
const saddr = @as(i64, @intCast(atom.getAddress(macho_file))) + @as(i64, @intCast(rel.offset - atom.off));
const taddr: i64 = @intCast(rel.getTargetAddress(atom.*, macho_file));
_ = math.cast(i28, taddr + rel.addend - saddr) orelse return false;
return true;
}
pub fn pwriteAll(macho_file: *MachO, bytes: []const u8, offset: u64) error{LinkFailure}!void {
const comp = macho_file.base.comp;
const diags = &comp.link_diags;
macho_file.base.file.?.pwriteAll(bytes, offset) catch |err| {
return diags.fail("failed to write: {s}", .{@errorName(err)});
};
}
pub fn setEndPos(macho_file: *MachO, length: u64) error{LinkFailure}!void {
const comp = macho_file.base.comp;
const diags = &comp.link_diags;
macho_file.base.file.?.setEndPos(length) catch |err| {
return diags.fail("failed to set file end pos: {s}", .{@errorName(err)});
};
}
pub fn cast(macho_file: *MachO, comptime T: type, x: anytype) error{LinkFailure}!T {
return std.math.cast(T, x) orelse {
const comp = macho_file.base.comp;
const diags = &comp.link_diags;
return diags.fail("encountered {d}, overflowing {d}-bit value", .{ x, @bitSizeOf(T) });
};
}
pub fn alignPow(macho_file: *MachO, x: u32) error{LinkFailure}!u32 {
const result, const ov = @shlWithOverflow(@as(u32, 1), try cast(macho_file, u5, x));
if (ov != 0) {
const comp = macho_file.base.comp;
const diags = &comp.link_diags;
return diags.fail("alignment overflow", .{});
}
return result;
}
/// Branch instruction has 26 bits immediate but is 4 byte aligned.
const jump_bits = @bitSizeOf(i28);
const max_distance = (1 << (jump_bits - 1));
/// A branch will need an extender if its target is larger than
/// `2^(jump_bits - 1) - margin` where margin is some arbitrary number.
/// mold uses 5MiB margin, while ld64 uses 4MiB margin. We will follow mold
/// and assume margin to be 5MiB.
const max_allowed_distance = max_distance - 0x500_000;
const MachO = @This();
const std = @import("std");
const build_options = @import("build_options");
const builtin = @import("builtin");
const assert = std.debug.assert;
const fs = std.fs;
const log = std.log.scoped(.link);
const state_log = std.log.scoped(.link_state);
const macho = std.macho;
const math = std.math;
const mem = std.mem;
const meta = std.meta;
const Writer = std.io.Writer;
const aarch64 = @import("../arch/aarch64/bits.zig");
const bind = @import("MachO/dyld_info/bind.zig");
const calcUuid = @import("MachO/uuid.zig").calcUuid;
const codegen = @import("../codegen.zig");
const dead_strip = @import("MachO/dead_strip.zig");
const eh_frame = @import("MachO/eh_frame.zig");
const fat = @import("MachO/fat.zig");
const link = @import("../link.zig");
const load_commands = @import("MachO/load_commands.zig");
const relocatable = @import("MachO/relocatable.zig");
const tapi = @import("tapi.zig");
const target_util = @import("../target.zig");
const trace = @import("../tracy.zig").trace;
const synthetic = @import("MachO/synthetic.zig");
const Alignment = Atom.Alignment;
const Allocator = mem.Allocator;
const Archive = @import("MachO/Archive.zig");
const AtomicBool = std.atomic.Value(bool);
const Bind = bind.Bind;
const Cache = std.Build.Cache;
const CodeSignature = @import("MachO/CodeSignature.zig");
const Compilation = @import("../Compilation.zig");
const DataInCode = synthetic.DataInCode;
const Directory = Cache.Directory;
const Dylib = @import("MachO/Dylib.zig");
const ExportTrie = @import("MachO/dyld_info/Trie.zig");
const Path = Cache.Path;
const File = @import("MachO/file.zig").File;
const GotSection = synthetic.GotSection;
const Hash = std.hash.Wyhash;
const Indsymtab = synthetic.Indsymtab;
const InternalObject = @import("MachO/InternalObject.zig");
const ObjcStubsSection = synthetic.ObjcStubsSection;
const Object = @import("MachO/Object.zig");
const LazyBind = bind.LazyBind;
const LaSymbolPtrSection = synthetic.LaSymbolPtrSection;
const Md5 = std.crypto.hash.Md5;
const Zcu = @import("../Zcu.zig");
const InternPool = @import("../InternPool.zig");
const Rebase = @import("MachO/dyld_info/Rebase.zig");
const StringTable = @import("StringTable.zig");
const StubsSection = synthetic.StubsSection;
const StubsHelperSection = synthetic.StubsHelperSection;
const Symbol = @import("MachO/Symbol.zig");
const Thunk = @import("MachO/Thunk.zig");
const TlvPtrSection = synthetic.TlvPtrSection;
const Value = @import("../Value.zig");
const UnwindInfo = @import("MachO/UnwindInfo.zig");
const WeakBind = bind.WeakBind;
const ZigObject = @import("MachO/ZigObject.zig");
const dev = @import("../dev.zig");
|