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
|
const Wasm = @This();
const std = @import("std");
const builtin = @import("builtin");
const mem = std.mem;
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
const fs = std.fs;
const leb = std.leb;
const log = std.log.scoped(.link);
pub const Atom = @import("Wasm/Atom.zig");
const Dwarf = @import("Dwarf.zig");
const Module = @import("../Module.zig");
const InternPool = @import("../InternPool.zig");
const Compilation = @import("../Compilation.zig");
const CodeGen = @import("../arch/wasm/CodeGen.zig");
const codegen = @import("../codegen.zig");
const link = @import("../link.zig");
const lldMain = @import("../main.zig").lldMain;
const trace = @import("../tracy.zig").trace;
const build_options = @import("build_options");
const wasi_libc = @import("../wasi_libc.zig");
const Cache = std.Build.Cache;
const Type = @import("../type.zig").Type;
const Value = @import("../Value.zig");
const TypedValue = @import("../TypedValue.zig");
const LlvmObject = @import("../codegen/llvm.zig").Object;
const Air = @import("../Air.zig");
const Liveness = @import("../Liveness.zig");
const Symbol = @import("Wasm/Symbol.zig");
const Object = @import("Wasm/Object.zig");
const Archive = @import("Wasm/Archive.zig");
const types = @import("Wasm/types.zig");
pub const Relocation = types.Relocation;
pub const base_tag: link.File.Tag = .wasm;
base: link.File,
entry_name: ?[]const u8,
import_symbols: bool,
export_symbol_names: []const []const u8,
global_base: ?u64,
initial_memory: ?u64,
max_memory: ?u64,
/// Output name of the file
name: []const u8,
/// If this is not null, an object file is created by LLVM and linked with LLD afterwards.
llvm_object: ?*LlvmObject = null,
/// When importing objects from the host environment, a name must be supplied.
/// LLVM uses "env" by default when none is given. This would be a good default for Zig
/// to support existing code.
/// TODO: Allow setting this through a flag?
host_name: []const u8 = "env",
/// List of all `Decl` that are currently alive.
/// Each index maps to the corresponding `Atom.Index`.
decls: std.AutoHashMapUnmanaged(InternPool.DeclIndex, Atom.Index) = .{},
/// Mapping between an `Atom` and its type index representing the Wasm
/// type of the function signature.
atom_types: std.AutoHashMapUnmanaged(Atom.Index, u32) = .{},
/// List of all symbols generated by Zig code.
symbols: std.ArrayListUnmanaged(Symbol) = .{},
/// List of symbol indexes which are free to be used.
symbols_free_list: std.ArrayListUnmanaged(u32) = .{},
/// Maps atoms to their segment index
atoms: std.AutoHashMapUnmanaged(u32, Atom.Index) = .{},
/// List of all atoms.
managed_atoms: std.ArrayListUnmanaged(Atom) = .{},
/// Represents the index into `segments` where the 'code' section
/// lives.
code_section_index: ?u32 = null,
/// The index of the segment representing the custom '.debug_info' section.
debug_info_index: ?u32 = null,
/// The index of the segment representing the custom '.debug_line' section.
debug_line_index: ?u32 = null,
/// The index of the segment representing the custom '.debug_loc' section.
debug_loc_index: ?u32 = null,
/// The index of the segment representing the custom '.debug_ranges' section.
debug_ranges_index: ?u32 = null,
/// The index of the segment representing the custom '.debug_pubnames' section.
debug_pubnames_index: ?u32 = null,
/// The index of the segment representing the custom '.debug_pubtypes' section.
debug_pubtypes_index: ?u32 = null,
/// The index of the segment representing the custom '.debug_pubtypes' section.
debug_str_index: ?u32 = null,
/// The index of the segment representing the custom '.debug_pubtypes' section.
debug_abbrev_index: ?u32 = null,
/// The count of imported functions. This number will be appended
/// to the function indexes as their index starts at the lowest non-extern function.
imported_functions_count: u32 = 0,
/// The count of imported wasm globals. This number will be appended
/// to the global indexes when sections are merged.
imported_globals_count: u32 = 0,
/// The count of imported tables. This number will be appended
/// to the table indexes when sections are merged.
imported_tables_count: u32 = 0,
/// Map of symbol locations, represented by its `types.Import`
imports: std.AutoHashMapUnmanaged(SymbolLoc, types.Import) = .{},
/// Represents non-synthetic section entries.
/// Used for code, data and custom sections.
segments: std.ArrayListUnmanaged(Segment) = .{},
/// Maps a data segment key (such as .rodata) to the index into `segments`.
data_segments: std.StringArrayHashMapUnmanaged(u32) = .{},
/// A table of `types.Segment` which provide meta data
/// about a data symbol such as its name where the key is
/// the segment index, which can be found from `data_segments`
segment_info: std.AutoArrayHashMapUnmanaged(u32, types.Segment) = .{},
/// Deduplicated string table for strings used by symbols, imports and exports.
string_table: StringTable = .{},
/// Debug information for wasm
dwarf: ?Dwarf = null,
// Output sections
/// Output type section
func_types: std.ArrayListUnmanaged(std.wasm.Type) = .{},
/// Output function section where the key is the original
/// function index and the value is function.
/// This allows us to map multiple symbols to the same function.
functions: std.AutoArrayHashMapUnmanaged(struct { file: ?u16, index: u32 }, struct { func: std.wasm.Func, sym_index: u32 }) = .{},
/// Output global section
wasm_globals: std.ArrayListUnmanaged(std.wasm.Global) = .{},
/// Memory section
memories: std.wasm.Memory = .{ .limits = .{
.min = 0,
.max = undefined,
.flags = 0,
} },
/// Output table section
tables: std.ArrayListUnmanaged(std.wasm.Table) = .{},
/// Output export section
exports: std.ArrayListUnmanaged(types.Export) = .{},
/// List of initialization functions. These must be called in order of priority
/// by the (synthetic) __wasm_call_ctors function.
init_funcs: std.ArrayListUnmanaged(InitFuncLoc) = .{},
/// Index to a function defining the entry of the wasm file
entry: ?u32 = null,
/// Indirect function table, used to call function pointers
/// When this is non-zero, we must emit a table entry,
/// as well as an 'elements' section.
///
/// Note: Key is symbol location, value represents the index into the table
function_table: std.AutoHashMapUnmanaged(SymbolLoc, u32) = .{},
/// All object files and their data which are linked into the final binary
objects: std.ArrayListUnmanaged(Object) = .{},
/// All archive files that are lazy loaded.
/// e.g. when an undefined symbol references a symbol from the archive.
archives: std.ArrayListUnmanaged(Archive) = .{},
/// A map of global names (read: offset into string table) to their symbol location
globals: std.AutoHashMapUnmanaged(u32, SymbolLoc) = .{},
/// The list of GOT symbols and their location
got_symbols: std.ArrayListUnmanaged(SymbolLoc) = .{},
/// Maps discarded symbols and their positions to the location of the symbol
/// it was resolved to
discarded: std.AutoHashMapUnmanaged(SymbolLoc, SymbolLoc) = .{},
/// List of all symbol locations which have been resolved by the linker and will be emit
/// into the final binary.
resolved_symbols: std.AutoArrayHashMapUnmanaged(SymbolLoc, void) = .{},
/// Symbols that remain undefined after symbol resolution.
/// Note: The key represents an offset into the string table, rather than the actual string.
undefs: std.AutoArrayHashMapUnmanaged(u32, SymbolLoc) = .{},
/// Maps a symbol's location to an atom. This can be used to find meta
/// data of a symbol, such as its size, or its offset to perform a relocation.
/// Undefined (and synthetic) symbols do not have an Atom and therefore cannot be mapped.
symbol_atom: std.AutoHashMapUnmanaged(SymbolLoc, Atom.Index) = .{},
/// Maps a symbol's location to its export name, which may differ from the decl's name
/// which does the exporting.
/// Note: The value represents the offset into the string table, rather than the actual string.
export_names: std.AutoHashMapUnmanaged(SymbolLoc, u32) = .{},
/// Represents the symbol index of the error name table
/// When this is `null`, no code references an error using runtime `@errorName`.
/// During initializion, a symbol with corresponding atom will be created that is
/// used to perform relocations to the pointer of this table.
/// The actual table is populated during `flush`.
error_table_symbol: ?u32 = null,
// Debug section atoms. These are only set when the current compilation
// unit contains Zig code. The lifetime of these atoms are extended
// until the end of the compiler's lifetime. Meaning they're not freed
// during `flush()` in incremental-mode.
debug_info_atom: ?Atom.Index = null,
debug_line_atom: ?Atom.Index = null,
debug_loc_atom: ?Atom.Index = null,
debug_ranges_atom: ?Atom.Index = null,
debug_abbrev_atom: ?Atom.Index = null,
debug_str_atom: ?Atom.Index = null,
debug_pubnames_atom: ?Atom.Index = null,
debug_pubtypes_atom: ?Atom.Index = null,
/// List of atom indexes of functions that are generated by the backend,
/// rather than by the linker.
synthetic_functions: std.ArrayListUnmanaged(Atom.Index) = .{},
/// Map for storing anonymous declarations. Each anonymous decl maps to its Atom's index.
anon_decls: std.AutoArrayHashMapUnmanaged(InternPool.Index, Atom.Index) = .{},
import_table: bool,
export_table: bool,
pub const Alignment = types.Alignment;
pub const Segment = struct {
alignment: Alignment,
size: u32,
offset: u32,
flags: u32,
pub const Flag = enum(u32) {
WASM_DATA_SEGMENT_IS_PASSIVE = 0x01,
WASM_DATA_SEGMENT_HAS_MEMINDEX = 0x02,
};
pub fn isPassive(segment: Segment) bool {
return segment.flags & @intFromEnum(Flag.WASM_DATA_SEGMENT_IS_PASSIVE) != 0;
}
/// For a given segment, determines if it needs passive initialization
fn needsPassiveInitialization(segment: Segment, import_mem: bool, name: []const u8) bool {
if (import_mem and !std.mem.eql(u8, name, ".bss")) {
return true;
}
return segment.isPassive();
}
};
pub const Export = struct {
sym_index: ?u32 = null,
};
pub const SymbolLoc = struct {
/// The index of the symbol within the specified file
index: u32,
/// The index of the object file where the symbol resides.
/// When this is `null` the symbol comes from a non-object file.
file: ?u16,
/// From a given location, returns the corresponding symbol in the wasm binary
pub fn getSymbol(loc: SymbolLoc, wasm_bin: *const Wasm) *Symbol {
if (wasm_bin.discarded.get(loc)) |new_loc| {
return new_loc.getSymbol(wasm_bin);
}
if (loc.file) |object_index| {
const object = wasm_bin.objects.items[object_index];
return &object.symtable[loc.index];
}
return &wasm_bin.symbols.items[loc.index];
}
/// From a given location, returns the name of the symbol.
pub fn getName(loc: SymbolLoc, wasm_bin: *const Wasm) []const u8 {
if (wasm_bin.discarded.get(loc)) |new_loc| {
return new_loc.getName(wasm_bin);
}
if (loc.file) |object_index| {
const object = wasm_bin.objects.items[object_index];
return object.string_table.get(object.symtable[loc.index].name);
}
return wasm_bin.string_table.get(wasm_bin.symbols.items[loc.index].name);
}
/// From a given symbol location, returns the final location.
/// e.g. when a symbol was resolved and replaced by the symbol
/// in a different file, this will return said location.
/// If the symbol wasn't replaced by another, this will return
/// the given location itwasm.
pub fn finalLoc(loc: SymbolLoc, wasm_bin: *const Wasm) SymbolLoc {
if (wasm_bin.discarded.get(loc)) |new_loc| {
return new_loc.finalLoc(wasm_bin);
}
return loc;
}
};
// Contains the location of the function symbol, as well as
/// the priority itself of the initialization function.
pub const InitFuncLoc = struct {
/// object file index in the list of objects.
/// Unlike `SymbolLoc` this cannot be `null` as we never define
/// our own ctors.
file: u16,
/// Symbol index within the corresponding object file.
index: u32,
/// The priority in which the constructor must be called.
priority: u32,
/// From a given `InitFuncLoc` returns the corresponding function symbol
fn getSymbol(loc: InitFuncLoc, wasm: *const Wasm) *Symbol {
return getSymbolLoc(loc).getSymbol(wasm);
}
/// Turns the given `InitFuncLoc` into a `SymbolLoc`
fn getSymbolLoc(loc: InitFuncLoc) SymbolLoc {
return .{ .file = loc.file, .index = loc.index };
}
/// Returns true when `lhs` has a higher priority (e.i. value closer to 0) than `rhs`.
fn lessThan(ctx: void, lhs: InitFuncLoc, rhs: InitFuncLoc) bool {
_ = ctx;
return lhs.priority < rhs.priority;
}
};
/// Generic string table that duplicates strings
/// and converts them into offsets instead.
pub const StringTable = struct {
/// Table that maps string offsets, which is used to de-duplicate strings.
/// Rather than having the offset map to the data, the `StringContext` holds all bytes of the string.
/// The strings are stored as a contigious array where each string is zero-terminated.
string_table: std.HashMapUnmanaged(
u32,
void,
std.hash_map.StringIndexContext,
std.hash_map.default_max_load_percentage,
) = .{},
/// Holds the actual data of the string table.
string_data: std.ArrayListUnmanaged(u8) = .{},
/// Accepts a string and searches for a corresponding string.
/// When found, de-duplicates the string and returns the existing offset instead.
/// When the string is not found in the `string_table`, a new entry will be inserted
/// and the new offset to its data will be returned.
pub fn put(table: *StringTable, allocator: Allocator, string: []const u8) !u32 {
const gop = try table.string_table.getOrPutContextAdapted(
allocator,
string,
std.hash_map.StringIndexAdapter{ .bytes = &table.string_data },
.{ .bytes = &table.string_data },
);
if (gop.found_existing) {
const off = gop.key_ptr.*;
log.debug("reusing string '{s}' at offset 0x{x}", .{ string, off });
return off;
}
try table.string_data.ensureUnusedCapacity(allocator, string.len + 1);
const offset = @as(u32, @intCast(table.string_data.items.len));
log.debug("writing new string '{s}' at offset 0x{x}", .{ string, offset });
table.string_data.appendSliceAssumeCapacity(string);
table.string_data.appendAssumeCapacity(0);
gop.key_ptr.* = offset;
return offset;
}
/// From a given offset, returns its corresponding string value.
/// Asserts offset does not exceed bounds.
pub fn get(table: StringTable, off: u32) []const u8 {
assert(off < table.string_data.items.len);
return mem.sliceTo(@as([*:0]const u8, @ptrCast(table.string_data.items.ptr + off)), 0);
}
/// Returns the offset of a given string when it exists.
/// Will return null if the given string does not yet exist within the string table.
pub fn getOffset(table: *StringTable, string: []const u8) ?u32 {
return table.string_table.getKeyAdapted(
string,
std.hash_map.StringIndexAdapter{ .bytes = &table.string_data },
);
}
/// Frees all resources of the string table. Any references pointing
/// to the strings will be invalid.
pub fn deinit(table: *StringTable, allocator: Allocator) void {
table.string_data.deinit(allocator);
table.string_table.deinit(allocator);
table.* = undefined;
}
};
pub fn open(
arena: Allocator,
comp: *Compilation,
emit: Compilation.Emit,
options: link.File.OpenOptions,
) !*Wasm {
// TODO: restore saved linker state, don't truncate the file, and
// participate in incremental compilation.
return createEmpty(arena, comp, emit, options);
}
pub fn createEmpty(
arena: Allocator,
comp: *Compilation,
emit: Compilation.Emit,
options: link.File.OpenOptions,
) !*Wasm {
const gpa = comp.gpa;
const target = comp.root_mod.resolved_target.result;
assert(target.ofmt == .wasm);
const use_lld = build_options.have_llvm and comp.config.use_lld;
const use_llvm = comp.config.use_llvm;
const output_mode = comp.config.output_mode;
const shared_memory = comp.config.shared_memory;
const wasi_exec_model = comp.config.wasi_exec_model;
// If using LLD to link, this code should produce an object file so that it
// can be passed to LLD.
// If using LLVM to generate the object file for the zig compilation unit,
// we need a place to put the object file so that it can be subsequently
// handled.
const zcu_object_sub_path = if (!use_lld and !use_llvm)
null
else
try std.fmt.allocPrint(arena, "{s}.o", .{emit.sub_path});
const wasm = try arena.create(Wasm);
wasm.* = .{
.base = .{
.tag = .wasm,
.comp = comp,
.emit = emit,
.zcu_object_sub_path = zcu_object_sub_path,
.gc_sections = options.gc_sections orelse (output_mode != .Obj),
.print_gc_sections = options.print_gc_sections,
.stack_size = options.stack_size orelse switch (target.os.tag) {
.freestanding => 1 * 1024 * 1024, // 1 MiB
else => 16 * 1024 * 1024, // 16 MiB
},
.allow_shlib_undefined = options.allow_shlib_undefined orelse false,
.file = null,
.disable_lld_caching = options.disable_lld_caching,
.build_id = options.build_id,
.rpath_list = options.rpath_list,
},
.name = undefined,
.import_table = options.import_table,
.export_table = options.export_table,
.import_symbols = options.import_symbols,
.export_symbol_names = options.export_symbol_names,
.global_base = options.global_base,
.initial_memory = options.initial_memory,
.max_memory = options.max_memory,
.entry_name = switch (options.entry) {
.disabled => null,
.default => if (output_mode != .Exe) null else defaultEntrySymbolName(wasi_exec_model),
.enabled => defaultEntrySymbolName(wasi_exec_model),
.named => |name| name,
},
};
if (use_llvm and comp.config.have_zcu) {
wasm.llvm_object = try LlvmObject.create(arena, comp);
}
errdefer wasm.base.destroy();
if (use_lld and (use_llvm or !comp.config.have_zcu)) {
// LLVM emits the object file (if any); LLD links it into the final product.
return wasm;
}
// What path should this Wasm linker code output to?
// If using LLD to link, this code should produce an object file so that it
// can be passed to LLD.
const sub_path = if (use_lld) zcu_object_sub_path.? else emit.sub_path;
const file = try emit.directory.handle.createFile(sub_path, .{
.truncate = true,
.read = true,
.mode = if (fs.has_executable_bit)
if (target.os.tag == .wasi and output_mode == .Exe)
fs.File.default_mode | 0b001_000_000
else
fs.File.default_mode
else
0,
});
wasm.base.file = file;
wasm.name = sub_path;
// create stack pointer symbol
{
const loc = try wasm.createSyntheticSymbol("__stack_pointer", .global);
const symbol = loc.getSymbol(wasm);
// For object files we will import the stack pointer symbol
if (output_mode == .Obj) {
symbol.setUndefined(true);
symbol.index = @intCast(wasm.imported_globals_count);
wasm.imported_globals_count += 1;
try wasm.imports.putNoClobber(
gpa,
loc,
.{
.module_name = try wasm.string_table.put(gpa, wasm.host_name),
.name = symbol.name,
.kind = .{ .global = .{ .valtype = .i32, .mutable = true } },
},
);
} else {
symbol.index = @intCast(wasm.imported_globals_count + wasm.wasm_globals.items.len);
symbol.setFlag(.WASM_SYM_VISIBILITY_HIDDEN);
const global = try wasm.wasm_globals.addOne(gpa);
global.* = .{
.global_type = .{
.valtype = .i32,
.mutable = true,
},
.init = .{ .i32_const = 0 },
};
}
}
// create indirect function pointer symbol
{
const loc = try wasm.createSyntheticSymbol("__indirect_function_table", .table);
const symbol = loc.getSymbol(wasm);
const table: std.wasm.Table = .{
.limits = .{ .flags = 0, .min = 0, .max = undefined }, // will be overwritten during `mapFunctionTable`
.reftype = .funcref,
};
if (output_mode == .Obj or options.import_table) {
symbol.setUndefined(true);
symbol.index = @intCast(wasm.imported_tables_count);
wasm.imported_tables_count += 1;
try wasm.imports.put(gpa, loc, .{
.module_name = try wasm.string_table.put(gpa, wasm.host_name),
.name = symbol.name,
.kind = .{ .table = table },
});
} else {
symbol.index = @as(u32, @intCast(wasm.imported_tables_count + wasm.tables.items.len));
try wasm.tables.append(gpa, table);
if (wasm.export_table) {
symbol.setFlag(.WASM_SYM_EXPORTED);
} else {
symbol.setFlag(.WASM_SYM_VISIBILITY_HIDDEN);
}
}
}
// create __wasm_call_ctors
{
const loc = try wasm.createSyntheticSymbol("__wasm_call_ctors", .function);
const symbol = loc.getSymbol(wasm);
symbol.setFlag(.WASM_SYM_VISIBILITY_HIDDEN);
// we do not know the function index until after we merged all sections.
// Therefore we set `symbol.index` and create its corresponding references
// at the end during `initializeCallCtorsFunction`.
}
// shared-memory symbols for TLS support
if (shared_memory) {
{
const loc = try wasm.createSyntheticSymbol("__tls_base", .global);
const symbol = loc.getSymbol(wasm);
symbol.setFlag(.WASM_SYM_VISIBILITY_HIDDEN);
symbol.index = @intCast(wasm.imported_globals_count + wasm.wasm_globals.items.len);
try wasm.wasm_globals.append(gpa, .{
.global_type = .{ .valtype = .i32, .mutable = true },
.init = .{ .i32_const = undefined },
});
}
{
const loc = try wasm.createSyntheticSymbol("__tls_size", .global);
const symbol = loc.getSymbol(wasm);
symbol.setFlag(.WASM_SYM_VISIBILITY_HIDDEN);
symbol.index = @intCast(wasm.imported_globals_count + wasm.wasm_globals.items.len);
try wasm.wasm_globals.append(gpa, .{
.global_type = .{ .valtype = .i32, .mutable = false },
.init = .{ .i32_const = undefined },
});
}
{
const loc = try wasm.createSyntheticSymbol("__tls_align", .global);
const symbol = loc.getSymbol(wasm);
symbol.setFlag(.WASM_SYM_VISIBILITY_HIDDEN);
symbol.index = @intCast(wasm.imported_globals_count + wasm.wasm_globals.items.len);
try wasm.wasm_globals.append(gpa, .{
.global_type = .{ .valtype = .i32, .mutable = false },
.init = .{ .i32_const = undefined },
});
}
{
const loc = try wasm.createSyntheticSymbol("__wasm_init_tls", .function);
const symbol = loc.getSymbol(wasm);
symbol.setFlag(.WASM_SYM_VISIBILITY_HIDDEN);
}
}
return wasm;
}
/// For a given name, creates a new global synthetic symbol.
/// Leaves index undefined and the default flags (0).
fn createSyntheticSymbol(wasm: *Wasm, name: []const u8, tag: Symbol.Tag) !SymbolLoc {
const gpa = wasm.base.comp.gpa;
const name_offset = try wasm.string_table.put(gpa, name);
return wasm.createSyntheticSymbolOffset(name_offset, tag);
}
fn createSyntheticSymbolOffset(wasm: *Wasm, name_offset: u32, tag: Symbol.Tag) !SymbolLoc {
const sym_index = @as(u32, @intCast(wasm.symbols.items.len));
const loc: SymbolLoc = .{ .index = sym_index, .file = null };
const gpa = wasm.base.comp.gpa;
try wasm.symbols.append(gpa, .{
.name = name_offset,
.flags = 0,
.tag = tag,
.index = undefined,
.virtual_address = undefined,
});
try wasm.resolved_symbols.putNoClobber(gpa, loc, {});
try wasm.globals.put(gpa, name_offset, loc);
return loc;
}
/// Initializes symbols and atoms for the debug sections
/// Initialization is only done when compiling Zig code.
/// When Zig is invoked as a linker instead, the atoms
/// and symbols come from the object files instead.
pub fn initDebugSections(wasm: *Wasm) !void {
if (wasm.dwarf == null) return; // not compiling Zig code, so no need to pre-initialize debug sections
assert(wasm.debug_info_index == null);
// this will create an Atom and set the index for us.
wasm.debug_info_atom = try wasm.createDebugSectionForIndex(&wasm.debug_info_index, ".debug_info");
wasm.debug_line_atom = try wasm.createDebugSectionForIndex(&wasm.debug_line_index, ".debug_line");
wasm.debug_loc_atom = try wasm.createDebugSectionForIndex(&wasm.debug_loc_index, ".debug_loc");
wasm.debug_abbrev_atom = try wasm.createDebugSectionForIndex(&wasm.debug_abbrev_index, ".debug_abbrev");
wasm.debug_ranges_atom = try wasm.createDebugSectionForIndex(&wasm.debug_ranges_index, ".debug_ranges");
wasm.debug_str_atom = try wasm.createDebugSectionForIndex(&wasm.debug_str_index, ".debug_str");
wasm.debug_pubnames_atom = try wasm.createDebugSectionForIndex(&wasm.debug_pubnames_index, ".debug_pubnames");
wasm.debug_pubtypes_atom = try wasm.createDebugSectionForIndex(&wasm.debug_pubtypes_index, ".debug_pubtypes");
}
fn parseInputFiles(wasm: *Wasm, files: []const []const u8) !void {
for (files) |path| {
if (try wasm.parseObjectFile(path)) continue;
if (try wasm.parseArchive(path, false)) continue; // load archives lazily
log.warn("Unexpected file format at path: '{s}'", .{path});
}
}
/// Parses the object file from given path. Returns true when the given file was an object
/// file and parsed successfully. Returns false when file is not an object file.
/// May return an error instead when parsing failed.
fn parseObjectFile(wasm: *Wasm, path: []const u8) !bool {
const file = try fs.cwd().openFile(path, .{});
errdefer file.close();
const gpa = wasm.base.comp.gpa;
var object = Object.create(gpa, file, path, null) catch |err| switch (err) {
error.InvalidMagicByte, error.NotObjectFile => return false,
else => |e| return e,
};
errdefer object.deinit(gpa);
try wasm.objects.append(gpa, object);
return true;
}
/// For a given `InternPool.DeclIndex` returns its corresponding `Atom.Index`.
/// When the index was not found, a new `Atom` will be created, and its index will be returned.
/// The newly created Atom is empty with default fields as specified by `Atom.empty`.
pub fn getOrCreateAtomForDecl(wasm: *Wasm, decl_index: InternPool.DeclIndex) !Atom.Index {
const gpa = wasm.base.comp.gpa;
const gop = try wasm.decls.getOrPut(gpa, decl_index);
if (!gop.found_existing) {
const atom_index = try wasm.createAtom();
gop.value_ptr.* = atom_index;
const atom = wasm.getAtom(atom_index);
const symbol = atom.symbolLoc().getSymbol(wasm);
const mod = wasm.base.comp.module.?;
const decl = mod.declPtr(decl_index);
const full_name = mod.intern_pool.stringToSlice(try decl.fullyQualifiedName(mod));
symbol.name = try wasm.string_table.put(gpa, full_name);
}
return gop.value_ptr.*;
}
/// Creates a new empty `Atom` and returns its `Atom.Index`
fn createAtom(wasm: *Wasm) !Atom.Index {
const gpa = wasm.base.comp.gpa;
const index: Atom.Index = @intCast(wasm.managed_atoms.items.len);
const atom = try wasm.managed_atoms.addOne(gpa);
atom.* = Atom.empty;
atom.sym_index = try wasm.allocateSymbol();
try wasm.symbol_atom.putNoClobber(gpa, .{ .file = null, .index = atom.sym_index }, index);
return index;
}
pub inline fn getAtom(wasm: *const Wasm, index: Atom.Index) Atom {
return wasm.managed_atoms.items[index];
}
pub inline fn getAtomPtr(wasm: *Wasm, index: Atom.Index) *Atom {
return &wasm.managed_atoms.items[index];
}
/// Parses an archive file and will then parse each object file
/// that was found in the archive file.
/// Returns false when the file is not an archive file.
/// May return an error instead when parsing failed.
///
/// When `force_load` is `true`, it will for link all object files in the archive.
/// When false, it will only link with object files that contain symbols that
/// are referenced by other object files or Zig code.
fn parseArchive(wasm: *Wasm, path: []const u8, force_load: bool) !bool {
const gpa = wasm.base.comp.gpa;
const file = try fs.cwd().openFile(path, .{});
errdefer file.close();
var archive: Archive = .{
.file = file,
.name = path,
};
archive.parse(gpa) catch |err| switch (err) {
error.EndOfStream, error.NotArchive => {
archive.deinit(gpa);
return false;
},
else => |e| return e,
};
if (!force_load) {
errdefer archive.deinit(gpa);
try wasm.archives.append(gpa, archive);
return true;
}
defer archive.deinit(gpa);
// In this case we must force link all embedded object files within the archive
// We loop over all symbols, and then group them by offset as the offset
// notates where the object file starts.
var offsets = std.AutoArrayHashMap(u32, void).init(gpa);
defer offsets.deinit();
for (archive.toc.values()) |symbol_offsets| {
for (symbol_offsets.items) |sym_offset| {
try offsets.put(sym_offset, {});
}
}
for (offsets.keys()) |file_offset| {
const object = try wasm.objects.addOne(gpa);
object.* = try archive.parseObject(gpa, file_offset);
}
return true;
}
fn requiresTLSReloc(wasm: *const Wasm) bool {
for (wasm.got_symbols.items) |loc| {
if (loc.getSymbol(wasm).isTLS()) {
return true;
}
}
return false;
}
fn resolveSymbolsInObject(wasm: *Wasm, object_index: u16) !void {
const gpa = wasm.base.comp.gpa;
const object: Object = wasm.objects.items[object_index];
log.debug("Resolving symbols in object: '{s}'", .{object.name});
for (object.symtable, 0..) |symbol, i| {
const sym_index = @as(u32, @intCast(i));
const location: SymbolLoc = .{
.file = object_index,
.index = sym_index,
};
const sym_name = object.string_table.get(symbol.name);
if (mem.eql(u8, sym_name, "__indirect_function_table")) {
continue;
}
const sym_name_index = try wasm.string_table.put(gpa, sym_name);
if (symbol.isLocal()) {
if (symbol.isUndefined()) {
log.err("Local symbols are not allowed to reference imports", .{});
log.err(" symbol '{s}' defined in '{s}'", .{ sym_name, object.name });
return error.UndefinedLocal;
}
try wasm.resolved_symbols.putNoClobber(gpa, location, {});
continue;
}
const maybe_existing = try wasm.globals.getOrPut(gpa, sym_name_index);
if (!maybe_existing.found_existing) {
maybe_existing.value_ptr.* = location;
try wasm.resolved_symbols.putNoClobber(gpa, location, {});
if (symbol.isUndefined()) {
try wasm.undefs.putNoClobber(gpa, sym_name_index, location);
}
continue;
}
const existing_loc = maybe_existing.value_ptr.*;
const existing_sym: *Symbol = existing_loc.getSymbol(wasm);
const existing_file_path = if (existing_loc.file) |file| blk: {
break :blk wasm.objects.items[file].name;
} else wasm.name;
if (!existing_sym.isUndefined()) outer: {
if (!symbol.isUndefined()) inner: {
if (symbol.isWeak()) {
break :inner; // ignore the new symbol (discard it)
}
if (existing_sym.isWeak()) {
break :outer; // existing is weak, while new one isn't. Replace it.
}
// both are defined and weak, we have a symbol collision.
log.err("symbol '{s}' defined multiple times", .{sym_name});
log.err(" first definition in '{s}'", .{existing_file_path});
log.err(" next definition in '{s}'", .{object.name});
return error.SymbolCollision;
}
try wasm.discarded.put(gpa, location, existing_loc);
continue; // Do not overwrite defined symbols with undefined symbols
}
if (symbol.tag != existing_sym.tag) {
log.err("symbol '{s}' mismatching type '{s}", .{ sym_name, @tagName(symbol.tag) });
log.err(" first definition in '{s}'", .{existing_file_path});
log.err(" next definition in '{s}'", .{object.name});
return error.SymbolMismatchingType;
}
if (existing_sym.isUndefined() and symbol.isUndefined()) {
// only verify module/import name for function symbols
if (symbol.tag == .function) {
const existing_name = if (existing_loc.file) |file_index| blk: {
const obj = wasm.objects.items[file_index];
const name_index = obj.findImport(symbol.tag.externalType(), existing_sym.index).module_name;
break :blk obj.string_table.get(name_index);
} else blk: {
const name_index = wasm.imports.get(existing_loc).?.module_name;
break :blk wasm.string_table.get(name_index);
};
const module_index = object.findImport(symbol.tag.externalType(), symbol.index).module_name;
const module_name = object.string_table.get(module_index);
if (!mem.eql(u8, existing_name, module_name)) {
log.err("symbol '{s}' module name mismatch. Expected '{s}', but found '{s}'", .{
sym_name,
existing_name,
module_name,
});
log.err(" first definition in '{s}'", .{existing_file_path});
log.err(" next definition in '{s}'", .{object.name});
return error.ModuleNameMismatch;
}
}
// both undefined so skip overwriting existing symbol and discard the new symbol
try wasm.discarded.put(gpa, location, existing_loc);
continue;
}
if (existing_sym.tag == .global) {
const existing_ty = wasm.getGlobalType(existing_loc);
const new_ty = wasm.getGlobalType(location);
if (existing_ty.mutable != new_ty.mutable or existing_ty.valtype != new_ty.valtype) {
log.err("symbol '{s}' mismatching global types", .{sym_name});
log.err(" first definition in '{s}'", .{existing_file_path});
log.err(" next definition in '{s}'", .{object.name});
return error.GlobalTypeMismatch;
}
}
if (existing_sym.tag == .function) {
const existing_ty = wasm.getFunctionSignature(existing_loc);
const new_ty = wasm.getFunctionSignature(location);
if (!existing_ty.eql(new_ty)) {
log.err("symbol '{s}' mismatching function signatures.", .{sym_name});
log.err(" expected signature {}, but found signature {}", .{ existing_ty, new_ty });
log.err(" first definition in '{s}'", .{existing_file_path});
log.err(" next definition in '{s}'", .{object.name});
return error.FunctionSignatureMismatch;
}
}
// when both symbols are weak, we skip overwriting unless the existing
// symbol is weak and the new one isn't, in which case we *do* overwrite it.
if (existing_sym.isWeak() and symbol.isWeak()) blk: {
if (existing_sym.isUndefined() and !symbol.isUndefined()) break :blk;
try wasm.discarded.put(gpa, location, existing_loc);
continue;
}
// simply overwrite with the new symbol
log.debug("Overwriting symbol '{s}'", .{sym_name});
log.debug(" old definition in '{s}'", .{existing_file_path});
log.debug(" new definition in '{s}'", .{object.name});
try wasm.discarded.putNoClobber(gpa, existing_loc, location);
maybe_existing.value_ptr.* = location;
try wasm.globals.put(gpa, sym_name_index, location);
try wasm.resolved_symbols.put(gpa, location, {});
assert(wasm.resolved_symbols.swapRemove(existing_loc));
if (existing_sym.isUndefined()) {
_ = wasm.undefs.swapRemove(sym_name_index);
}
}
}
fn resolveSymbolsInArchives(wasm: *Wasm) !void {
const gpa = wasm.base.comp.gpa;
if (wasm.archives.items.len == 0) return;
log.debug("Resolving symbols in archives", .{});
var index: u32 = 0;
undef_loop: while (index < wasm.undefs.count()) {
const sym_name_index = wasm.undefs.keys()[index];
for (wasm.archives.items) |archive| {
const sym_name = wasm.string_table.get(sym_name_index);
log.debug("Detected symbol '{s}' in archive '{s}', parsing objects..", .{ sym_name, archive.name });
const offset = archive.toc.get(sym_name) orelse {
// symbol does not exist in this archive
continue;
};
// Symbol is found in unparsed object file within current archive.
// Parse object and and resolve symbols again before we check remaining
// undefined symbols.
const object_file_index: u16 = @intCast(wasm.objects.items.len);
const object = try archive.parseObject(gpa, offset.items[0]);
try wasm.objects.append(gpa, object);
try wasm.resolveSymbolsInObject(object_file_index);
// continue loop for any remaining undefined symbols that still exist
// after resolving last object file
continue :undef_loop;
}
index += 1;
}
}
/// Writes an unsigned 32-bit integer as a LEB128-encoded 'i32.const' value.
fn writeI32Const(writer: anytype, val: u32) !void {
try writer.writeByte(std.wasm.opcode(.i32_const));
try leb.writeILEB128(writer, @as(i32, @bitCast(val)));
}
fn setupInitMemoryFunction(wasm: *Wasm) !void {
const comp = wasm.base.comp;
const gpa = comp.gpa;
const shared_memory = comp.config.shared_memory;
const import_memory = comp.config.import_memory;
// Passive segments are used to avoid memory being reinitialized on each
// thread's instantiation. These passive segments are initialized and
// dropped in __wasm_init_memory, which is registered as the start function
// We also initialize bss segments (using memory.fill) as part of this
// function.
if (!wasm.hasPassiveInitializationSegments()) {
return;
}
const flag_address: u32 = if (shared_memory) address: {
// when we have passive initialization segments and shared memory
// `setupMemory` will create this symbol and set its virtual address.
const loc = wasm.findGlobalSymbol("__wasm_init_memory_flag").?;
break :address loc.getSymbol(wasm).virtual_address;
} else 0;
var function_body = std.ArrayList(u8).init(gpa);
defer function_body.deinit();
const writer = function_body.writer();
// we have 0 locals
try leb.writeULEB128(writer, @as(u32, 0));
if (shared_memory) {
// destination blocks
// based on values we jump to corresponding label
try writer.writeByte(std.wasm.opcode(.block)); // $drop
try writer.writeByte(std.wasm.block_empty); // block type
try writer.writeByte(std.wasm.opcode(.block)); // $wait
try writer.writeByte(std.wasm.block_empty); // block type
try writer.writeByte(std.wasm.opcode(.block)); // $init
try writer.writeByte(std.wasm.block_empty); // block type
// atomically check
try writeI32Const(writer, flag_address);
try writeI32Const(writer, 0);
try writeI32Const(writer, 1);
try writer.writeByte(std.wasm.opcode(.atomics_prefix));
try leb.writeULEB128(writer, std.wasm.atomicsOpcode(.i32_atomic_rmw_cmpxchg));
try leb.writeULEB128(writer, @as(u32, 2)); // alignment
try leb.writeULEB128(writer, @as(u32, 0)); // offset
// based on the value from the atomic check, jump to the label.
try writer.writeByte(std.wasm.opcode(.br_table));
try leb.writeULEB128(writer, @as(u32, 2)); // length of the table (we have 3 blocks but because of the mandatory default the length is 2).
try leb.writeULEB128(writer, @as(u32, 0)); // $init
try leb.writeULEB128(writer, @as(u32, 1)); // $wait
try leb.writeULEB128(writer, @as(u32, 2)); // $drop
try writer.writeByte(std.wasm.opcode(.end));
}
var it = wasm.data_segments.iterator();
var segment_index: u32 = 0;
while (it.next()) |entry| : (segment_index += 1) {
const segment: Segment = wasm.segments.items[entry.value_ptr.*];
if (segment.needsPassiveInitialization(import_memory, entry.key_ptr.*)) {
// For passive BSS segments we can simple issue a memory.fill(0).
// For non-BSS segments we do a memory.init. Both these
// instructions take as their first argument the destination
// address.
try writeI32Const(writer, segment.offset);
if (shared_memory and std.mem.eql(u8, entry.key_ptr.*, ".tdata")) {
// When we initialize the TLS segment we also set the `__tls_base`
// global. This allows the runtime to use this static copy of the
// TLS data for the first/main thread.
try writeI32Const(writer, segment.offset);
try writer.writeByte(std.wasm.opcode(.global_set));
const loc = wasm.findGlobalSymbol("__tls_base").?;
try leb.writeULEB128(writer, loc.getSymbol(wasm).index);
}
try writeI32Const(writer, 0);
try writeI32Const(writer, segment.size);
try writer.writeByte(std.wasm.opcode(.misc_prefix));
if (std.mem.eql(u8, entry.key_ptr.*, ".bss")) {
// fill bss segment with zeroes
try leb.writeULEB128(writer, std.wasm.miscOpcode(.memory_fill));
} else {
// initialize the segment
try leb.writeULEB128(writer, std.wasm.miscOpcode(.memory_init));
try leb.writeULEB128(writer, segment_index);
}
try writer.writeByte(0); // memory index immediate
}
}
if (shared_memory) {
// we set the init memory flag to value '2'
try writeI32Const(writer, flag_address);
try writeI32Const(writer, 2);
try writer.writeByte(std.wasm.opcode(.atomics_prefix));
try leb.writeULEB128(writer, std.wasm.atomicsOpcode(.i32_atomic_store));
try leb.writeULEB128(writer, @as(u32, 2)); // alignment
try leb.writeULEB128(writer, @as(u32, 0)); // offset
// notify any waiters for segment initialization completion
try writeI32Const(writer, flag_address);
try writer.writeByte(std.wasm.opcode(.i32_const));
try leb.writeILEB128(writer, @as(i32, -1)); // number of waiters
try writer.writeByte(std.wasm.opcode(.atomics_prefix));
try leb.writeULEB128(writer, std.wasm.atomicsOpcode(.memory_atomic_notify));
try leb.writeULEB128(writer, @as(u32, 2)); // alignment
try leb.writeULEB128(writer, @as(u32, 0)); // offset
try writer.writeByte(std.wasm.opcode(.drop));
// branch and drop segments
try writer.writeByte(std.wasm.opcode(.br));
try leb.writeULEB128(writer, @as(u32, 1));
// wait for thread to initialize memory segments
try writer.writeByte(std.wasm.opcode(.end)); // end $wait
try writeI32Const(writer, flag_address);
try writeI32Const(writer, 1); // expected flag value
try writer.writeByte(std.wasm.opcode(.i64_const));
try leb.writeILEB128(writer, @as(i64, -1)); // timeout
try writer.writeByte(std.wasm.opcode(.atomics_prefix));
try leb.writeULEB128(writer, std.wasm.atomicsOpcode(.memory_atomic_wait32));
try leb.writeULEB128(writer, @as(u32, 2)); // alignment
try leb.writeULEB128(writer, @as(u32, 0)); // offset
try writer.writeByte(std.wasm.opcode(.drop));
try writer.writeByte(std.wasm.opcode(.end)); // end $drop
}
it.reset();
segment_index = 0;
while (it.next()) |entry| : (segment_index += 1) {
const name = entry.key_ptr.*;
const segment: Segment = wasm.segments.items[entry.value_ptr.*];
if (segment.needsPassiveInitialization(import_memory, name) and
!std.mem.eql(u8, name, ".bss"))
{
// The TLS region should not be dropped since its is needed
// during the initialization of each thread (__wasm_init_tls).
if (shared_memory and std.mem.eql(u8, name, ".tdata")) {
continue;
}
try writer.writeByte(std.wasm.opcode(.misc_prefix));
try leb.writeULEB128(writer, std.wasm.miscOpcode(.data_drop));
try leb.writeULEB128(writer, segment_index);
}
}
// End of the function body
try writer.writeByte(std.wasm.opcode(.end));
try wasm.createSyntheticFunction(
"__wasm_init_memory",
std.wasm.Type{ .params = &.{}, .returns = &.{} },
&function_body,
);
}
/// Constructs a synthetic function that performs runtime relocations for
/// TLS symbols. This function is called by `__wasm_init_tls`.
fn setupTLSRelocationsFunction(wasm: *Wasm) !void {
const comp = wasm.base.comp;
const gpa = comp.gpa;
const shared_memory = comp.config.shared_memory;
// When we have TLS GOT entries and shared memory is enabled,
// we must perform runtime relocations or else we don't create the function.
if (!shared_memory or !wasm.requiresTLSReloc()) {
return;
}
// const loc = try wasm.createSyntheticSymbol("__wasm_apply_global_tls_relocs");
var function_body = std.ArrayList(u8).init(gpa);
defer function_body.deinit();
const writer = function_body.writer();
// locals (we have none)
try writer.writeByte(0);
for (wasm.got_symbols.items, 0..) |got_loc, got_index| {
const sym: *Symbol = got_loc.getSymbol(wasm);
if (!sym.isTLS()) continue; // only relocate TLS symbols
if (sym.tag == .data and sym.isDefined()) {
// get __tls_base
try writer.writeByte(std.wasm.opcode(.global_get));
try leb.writeULEB128(writer, wasm.findGlobalSymbol("__tls_base").?.getSymbol(wasm).index);
// add the virtual address of the symbol
try writer.writeByte(std.wasm.opcode(.i32_const));
try leb.writeULEB128(writer, sym.virtual_address);
} else if (sym.tag == .function) {
@panic("TODO: relocate GOT entry of function");
} else continue;
try writer.writeByte(std.wasm.opcode(.i32_add));
try writer.writeByte(std.wasm.opcode(.global_set));
try leb.writeULEB128(writer, wasm.imported_globals_count + @as(u32, @intCast(wasm.wasm_globals.items.len + got_index)));
}
try writer.writeByte(std.wasm.opcode(.end));
try wasm.createSyntheticFunction(
"__wasm_apply_global_tls_relocs",
std.wasm.Type{ .params = &.{}, .returns = &.{} },
&function_body,
);
}
fn validateFeatures(
wasm: *const Wasm,
to_emit: *[@typeInfo(types.Feature.Tag).Enum.fields.len]bool,
emit_features_count: *u32,
) !void {
const comp = wasm.base.comp;
const target = comp.root_mod.resolved_target.result;
const shared_memory = comp.config.shared_memory;
const cpu_features = target.cpu.features;
const infer = cpu_features.isEmpty(); // when the user did not define any features, we infer them from linked objects.
const known_features_count = @typeInfo(types.Feature.Tag).Enum.fields.len;
var allowed = [_]bool{false} ** known_features_count;
var used = [_]u17{0} ** known_features_count;
var disallowed = [_]u17{0} ** known_features_count;
var required = [_]u17{0} ** known_features_count;
// when false, we fail linking. We only verify this after a loop to catch all invalid features.
var valid_feature_set = true;
// will be set to true when there's any TLS segment found in any of the object files
var has_tls = false;
// When the user has given an explicit list of features to enable,
// we extract them and insert each into the 'allowed' list.
if (!infer) {
inline for (@typeInfo(std.Target.wasm.Feature).Enum.fields) |feature_field| {
if (cpu_features.isEnabled(feature_field.value)) {
allowed[feature_field.value] = true;
emit_features_count.* += 1;
}
}
}
// extract all the used, disallowed and required features from each
// linked object file so we can test them.
for (wasm.objects.items, 0..) |object, object_index| {
for (object.features) |feature| {
const value = @as(u16, @intCast(object_index)) << 1 | @as(u1, 1);
switch (feature.prefix) {
.used => {
used[@intFromEnum(feature.tag)] = value;
},
.disallowed => {
disallowed[@intFromEnum(feature.tag)] = value;
},
.required => {
required[@intFromEnum(feature.tag)] = value;
used[@intFromEnum(feature.tag)] = value;
},
}
}
for (object.segment_info) |segment| {
if (segment.isTLS()) {
has_tls = true;
}
}
}
// when we infer the features, we allow each feature found in the 'used' set
// and insert it into the 'allowed' set. When features are not inferred,
// we validate that a used feature is allowed.
for (used, 0..) |used_set, used_index| {
const is_enabled = @as(u1, @truncate(used_set)) != 0;
if (infer) {
allowed[used_index] = is_enabled;
emit_features_count.* += @intFromBool(is_enabled);
} else if (is_enabled and !allowed[used_index]) {
log.err("feature '{}' not allowed, but used by linked object", .{@as(types.Feature.Tag, @enumFromInt(used_index))});
log.err(" defined in '{s}'", .{wasm.objects.items[used_set >> 1].name});
valid_feature_set = false;
}
}
if (!valid_feature_set) {
return error.InvalidFeatureSet;
}
if (shared_memory) {
const disallowed_feature = disallowed[@intFromEnum(types.Feature.Tag.shared_mem)];
if (@as(u1, @truncate(disallowed_feature)) != 0) {
log.err(
"shared-memory is disallowed by '{s}' because it wasn't compiled with 'atomics' and 'bulk-memory' features enabled",
.{wasm.objects.items[disallowed_feature >> 1].name},
);
valid_feature_set = false;
}
for ([_]types.Feature.Tag{ .atomics, .bulk_memory }) |feature| {
if (!allowed[@intFromEnum(feature)]) {
log.err("feature '{}' is not used but is required for shared-memory", .{feature});
}
}
}
if (has_tls) {
for ([_]types.Feature.Tag{ .atomics, .bulk_memory }) |feature| {
if (!allowed[@intFromEnum(feature)]) {
log.err("feature '{}' is not used but is required for thread-local storage", .{feature});
}
}
}
// For each linked object, validate the required and disallowed features
for (wasm.objects.items) |object| {
var object_used_features = [_]bool{false} ** known_features_count;
for (object.features) |feature| {
if (feature.prefix == .disallowed) continue; // already defined in 'disallowed' set.
// from here a feature is always used
const disallowed_feature = disallowed[@intFromEnum(feature.tag)];
if (@as(u1, @truncate(disallowed_feature)) != 0) {
log.err("feature '{}' is disallowed, but used by linked object", .{feature.tag});
log.err(" disallowed by '{s}'", .{wasm.objects.items[disallowed_feature >> 1].name});
log.err(" used in '{s}'", .{object.name});
valid_feature_set = false;
}
object_used_features[@intFromEnum(feature.tag)] = true;
}
// validate the linked object file has each required feature
for (required, 0..) |required_feature, feature_index| {
const is_required = @as(u1, @truncate(required_feature)) != 0;
if (is_required and !object_used_features[feature_index]) {
log.err("feature '{}' is required but not used in linked object", .{@as(types.Feature.Tag, @enumFromInt(feature_index))});
log.err(" required by '{s}'", .{wasm.objects.items[required_feature >> 1].name});
log.err(" missing in '{s}'", .{object.name});
valid_feature_set = false;
}
}
}
if (!valid_feature_set) {
return error.InvalidFeatureSet;
}
to_emit.* = allowed;
}
/// Creates synthetic linker-symbols, but only if they are being referenced from
/// any object file. For instance, the `__heap_base` symbol will only be created,
/// if one or multiple undefined references exist. When none exist, the symbol will
/// not be created, ensuring we don't unneccesarily emit unreferenced symbols.
fn resolveLazySymbols(wasm: *Wasm) !void {
const comp = wasm.base.comp;
const gpa = comp.gpa;
const shared_memory = comp.config.shared_memory;
if (wasm.string_table.getOffset("__heap_base")) |name_offset| {
if (wasm.undefs.fetchSwapRemove(name_offset)) |kv| {
const loc = try wasm.createSyntheticSymbolOffset(name_offset, .data);
try wasm.discarded.putNoClobber(gpa, kv.value, loc);
_ = wasm.resolved_symbols.swapRemove(loc); // we don't want to emit this symbol, only use it for relocations.
}
}
if (wasm.string_table.getOffset("__heap_end")) |name_offset| {
if (wasm.undefs.fetchSwapRemove(name_offset)) |kv| {
const loc = try wasm.createSyntheticSymbolOffset(name_offset, .data);
try wasm.discarded.putNoClobber(gpa, kv.value, loc);
_ = wasm.resolved_symbols.swapRemove(loc);
}
}
if (!shared_memory) {
if (wasm.string_table.getOffset("__tls_base")) |name_offset| {
if (wasm.undefs.fetchSwapRemove(name_offset)) |kv| {
const loc = try wasm.createSyntheticSymbolOffset(name_offset, .global);
try wasm.discarded.putNoClobber(gpa, kv.value, loc);
_ = wasm.resolved_symbols.swapRemove(kv.value);
const symbol = loc.getSymbol(wasm);
symbol.setFlag(.WASM_SYM_VISIBILITY_HIDDEN);
symbol.index = @intCast(wasm.imported_globals_count + wasm.wasm_globals.items.len);
try wasm.wasm_globals.append(gpa, .{
.global_type = .{ .valtype = .i32, .mutable = true },
.init = .{ .i32_const = undefined },
});
}
}
}
if (wasm.string_table.getOffset("__zig_errors_len")) |name_offset| {
if (wasm.undefs.fetchSwapRemove(name_offset)) |kv| {
const loc = try wasm.createSyntheticSymbolOffset(name_offset, .data);
try wasm.discarded.putNoClobber(gpa, kv.value, loc);
_ = wasm.resolved_symbols.swapRemove(kv.value);
}
}
}
// Tries to find a global symbol by its name. Returns null when not found,
/// and its location when it is found.
pub fn findGlobalSymbol(wasm: *Wasm, name: []const u8) ?SymbolLoc {
const offset = wasm.string_table.getOffset(name) orelse return null;
return wasm.globals.get(offset);
}
fn checkUndefinedSymbols(wasm: *const Wasm) !void {
const comp = wasm.base.comp;
if (comp.config.output_mode == .Obj) return;
if (wasm.import_symbols) return;
var found_undefined_symbols = false;
for (wasm.undefs.values()) |undef| {
const symbol = undef.getSymbol(wasm);
if (symbol.tag == .data) {
found_undefined_symbols = true;
const file_name = if (undef.file) |file_index| name: {
break :name wasm.objects.items[file_index].name;
} else wasm.name;
const symbol_name = undef.getName(wasm);
log.err("could not resolve undefined symbol '{s}'", .{symbol_name});
log.err(" defined in '{s}'", .{file_name});
}
}
if (found_undefined_symbols) {
return error.UndefinedSymbol;
}
}
pub fn deinit(wasm: *Wasm) void {
const gpa = wasm.base.comp.gpa;
if (wasm.llvm_object) |llvm_object| llvm_object.deinit();
for (wasm.func_types.items) |*func_type| {
func_type.deinit(gpa);
}
for (wasm.segment_info.values()) |segment_info| {
gpa.free(segment_info.name);
}
for (wasm.objects.items) |*object| {
object.deinit(gpa);
}
for (wasm.archives.items) |*archive| {
archive.deinit(gpa);
}
// For decls and anon decls we free the memory of its atoms.
// The memory of atoms parsed from object files is managed by
// the object file itself, and therefore we can skip those.
{
var it = wasm.decls.valueIterator();
while (it.next()) |atom_index_ptr| {
const atom = wasm.getAtomPtr(atom_index_ptr.*);
for (atom.locals.items) |local_index| {
const local_atom = wasm.getAtomPtr(local_index);
local_atom.deinit(gpa);
}
atom.deinit(gpa);
}
}
{
for (wasm.anon_decls.values()) |atom_index| {
const atom = wasm.getAtomPtr(atom_index);
for (atom.locals.items) |local_index| {
const local_atom = wasm.getAtomPtr(local_index);
local_atom.deinit(gpa);
}
atom.deinit(gpa);
}
}
for (wasm.synthetic_functions.items) |atom_index| {
const atom = wasm.getAtomPtr(atom_index);
atom.deinit(gpa);
}
wasm.decls.deinit(gpa);
wasm.anon_decls.deinit(gpa);
wasm.atom_types.deinit(gpa);
wasm.symbols.deinit(gpa);
wasm.symbols_free_list.deinit(gpa);
wasm.globals.deinit(gpa);
wasm.resolved_symbols.deinit(gpa);
wasm.undefs.deinit(gpa);
wasm.discarded.deinit(gpa);
wasm.symbol_atom.deinit(gpa);
wasm.export_names.deinit(gpa);
wasm.atoms.deinit(gpa);
wasm.managed_atoms.deinit(gpa);
wasm.segments.deinit(gpa);
wasm.data_segments.deinit(gpa);
wasm.segment_info.deinit(gpa);
wasm.objects.deinit(gpa);
wasm.archives.deinit(gpa);
// free output sections
wasm.imports.deinit(gpa);
wasm.func_types.deinit(gpa);
wasm.functions.deinit(gpa);
wasm.wasm_globals.deinit(gpa);
wasm.function_table.deinit(gpa);
wasm.tables.deinit(gpa);
wasm.init_funcs.deinit(gpa);
wasm.exports.deinit(gpa);
wasm.string_table.deinit(gpa);
wasm.synthetic_functions.deinit(gpa);
if (wasm.dwarf) |*dwarf| {
dwarf.deinit();
}
}
/// Allocates a new symbol and returns its index.
/// Will re-use slots when a symbol was freed at an earlier stage.
pub fn allocateSymbol(wasm: *Wasm) !u32 {
const gpa = wasm.base.comp.gpa;
try wasm.symbols.ensureUnusedCapacity(gpa, 1);
const symbol: Symbol = .{
.name = std.math.maxInt(u32), // will be set after updateDecl as well as during atom creation for decls
.flags = @intFromEnum(Symbol.Flag.WASM_SYM_BINDING_LOCAL),
.tag = .undefined, // will be set after updateDecl
.index = std.math.maxInt(u32), // will be set during atom parsing
.virtual_address = std.math.maxInt(u32), // will be set during atom allocation
};
if (wasm.symbols_free_list.popOrNull()) |index| {
wasm.symbols.items[index] = symbol;
return index;
}
const index = @as(u32, @intCast(wasm.symbols.items.len));
wasm.symbols.appendAssumeCapacity(symbol);
return index;
}
pub fn updateFunc(wasm: *Wasm, mod: *Module, func_index: InternPool.Index, air: Air, liveness: Liveness) !void {
if (build_options.skip_non_native and builtin.object_format != .wasm) {
@panic("Attempted to compile for object format that was disabled by build configuration");
}
if (wasm.llvm_object) |llvm_object| return llvm_object.updateFunc(mod, func_index, air, liveness);
const tracy = trace(@src());
defer tracy.end();
const gpa = wasm.base.comp.gpa;
const func = mod.funcInfo(func_index);
const decl_index = func.owner_decl;
const decl = mod.declPtr(decl_index);
const atom_index = try wasm.getOrCreateAtomForDecl(decl_index);
const atom = wasm.getAtomPtr(atom_index);
atom.clear();
// var decl_state: ?Dwarf.DeclState = if (wasm.dwarf) |*dwarf| try dwarf.initDeclState(mod, decl_index) else null;
// defer if (decl_state) |*ds| ds.deinit();
var code_writer = std.ArrayList(u8).init(gpa);
defer code_writer.deinit();
// const result = try codegen.generateFunction(
// &wasm.base,
// decl.srcLoc(mod),
// func,
// air,
// liveness,
// &code_writer,
// if (decl_state) |*ds| .{ .dwarf = ds } else .none,
// );
const result = try codegen.generateFunction(
&wasm.base,
decl.srcLoc(mod),
func_index,
air,
liveness,
&code_writer,
.none,
);
const code = switch (result) {
.ok => code_writer.items,
.fail => |em| {
func.analysis(&mod.intern_pool).state = .codegen_failure;
try mod.failed_decls.put(mod.gpa, decl_index, em);
return;
},
};
// if (wasm.dwarf) |*dwarf| {
// try dwarf.commitDeclState(
// mod,
// decl_index,
// // Actual value will be written after relocation.
// // For Wasm, this is the offset relative to the code section
// // which isn't known until flush().
// 0,
// code.len,
// &decl_state.?,
// );
// }
return wasm.finishUpdateDecl(decl_index, code, .function);
}
// Generate code for the Decl, storing it in memory to be later written to
// the file on flush().
pub fn updateDecl(wasm: *Wasm, mod: *Module, decl_index: InternPool.DeclIndex) !void {
if (build_options.skip_non_native and builtin.object_format != .wasm) {
@panic("Attempted to compile for object format that was disabled by build configuration");
}
if (wasm.llvm_object) |llvm_object| return llvm_object.updateDecl(mod, decl_index);
const tracy = trace(@src());
defer tracy.end();
const decl = mod.declPtr(decl_index);
if (decl.val.getFunction(mod)) |_| {
return;
} else if (decl.val.getExternFunc(mod)) |_| {
return;
}
const gpa = wasm.base.comp.gpa;
const atom_index = try wasm.getOrCreateAtomForDecl(decl_index);
const atom = wasm.getAtomPtr(atom_index);
atom.clear();
if (decl.isExtern(mod)) {
const variable = decl.getOwnedVariable(mod).?;
const name = mod.intern_pool.stringToSlice(decl.name);
const lib_name = mod.intern_pool.stringToSliceUnwrap(variable.lib_name);
return wasm.addOrUpdateImport(name, atom.sym_index, lib_name, null);
}
const val = if (decl.val.getVariable(mod)) |variable| Value.fromInterned(variable.init) else decl.val;
var code_writer = std.ArrayList(u8).init(gpa);
defer code_writer.deinit();
const res = try codegen.generateSymbol(
&wasm.base,
decl.srcLoc(mod),
.{ .ty = decl.ty, .val = val },
&code_writer,
.none,
.{ .parent_atom_index = atom.sym_index },
);
const code = switch (res) {
.ok => code_writer.items,
.fail => |em| {
decl.analysis = .codegen_failure;
try mod.failed_decls.put(mod.gpa, decl_index, em);
return;
},
};
return wasm.finishUpdateDecl(decl_index, code, .data);
}
pub fn updateDeclLineNumber(wasm: *Wasm, mod: *Module, decl_index: InternPool.DeclIndex) !void {
if (wasm.llvm_object) |_| return;
if (wasm.dwarf) |*dw| {
const tracy = trace(@src());
defer tracy.end();
const decl = mod.declPtr(decl_index);
const decl_name = mod.intern_pool.stringToSlice(try decl.fullyQualifiedName(mod));
log.debug("updateDeclLineNumber {s}{*}", .{ decl_name, decl });
try dw.updateDeclLineNumber(mod, decl_index);
}
}
fn finishUpdateDecl(wasm: *Wasm, decl_index: InternPool.DeclIndex, code: []const u8, symbol_tag: Symbol.Tag) !void {
const gpa = wasm.base.comp.gpa;
const mod = wasm.base.comp.module.?;
const decl = mod.declPtr(decl_index);
const atom_index = wasm.decls.get(decl_index).?;
const atom = wasm.getAtomPtr(atom_index);
const symbol = &wasm.symbols.items[atom.sym_index];
const full_name = mod.intern_pool.stringToSlice(try decl.fullyQualifiedName(mod));
symbol.name = try wasm.string_table.put(gpa, full_name);
symbol.tag = symbol_tag;
try atom.code.appendSlice(gpa, code);
try wasm.resolved_symbols.put(gpa, atom.symbolLoc(), {});
atom.size = @intCast(code.len);
if (code.len == 0) return;
atom.alignment = decl.getAlignment(mod);
}
/// From a given symbol location, returns its `wasm.GlobalType`.
/// Asserts the Symbol represents a global.
fn getGlobalType(wasm: *const Wasm, loc: SymbolLoc) std.wasm.GlobalType {
const symbol = loc.getSymbol(wasm);
assert(symbol.tag == .global);
const is_undefined = symbol.isUndefined();
if (loc.file) |file_index| {
const obj: Object = wasm.objects.items[file_index];
if (is_undefined) {
return obj.findImport(.global, symbol.index).kind.global;
}
const import_global_count = obj.importedCountByKind(.global);
return obj.globals[symbol.index - import_global_count].global_type;
}
if (is_undefined) {
return wasm.imports.get(loc).?.kind.global;
}
return wasm.wasm_globals.items[symbol.index].global_type;
}
/// From a given symbol location, returns its `wasm.Type`.
/// Asserts the Symbol represents a function.
fn getFunctionSignature(wasm: *const Wasm, loc: SymbolLoc) std.wasm.Type {
const symbol = loc.getSymbol(wasm);
assert(symbol.tag == .function);
const is_undefined = symbol.isUndefined();
if (loc.file) |file_index| {
const obj: Object = wasm.objects.items[file_index];
if (is_undefined) {
const ty_index = obj.findImport(.function, symbol.index).kind.function;
return obj.func_types[ty_index];
}
const import_function_count = obj.importedCountByKind(.function);
const type_index = obj.functions[symbol.index - import_function_count].type_index;
return obj.func_types[type_index];
}
if (is_undefined) {
const ty_index = wasm.imports.get(loc).?.kind.function;
return wasm.func_types.items[ty_index];
}
return wasm.func_types.items[wasm.functions.get(.{ .file = loc.file, .index = symbol.index }).?.func.type_index];
}
/// Lowers a constant typed value to a local symbol and atom.
/// Returns the symbol index of the local
/// The given `decl` is the parent decl whom owns the constant.
pub fn lowerUnnamedConst(wasm: *Wasm, tv: TypedValue, decl_index: InternPool.DeclIndex) !u32 {
const gpa = wasm.base.comp.gpa;
const mod = wasm.base.comp.module.?;
assert(tv.ty.zigTypeTag(mod) != .Fn); // cannot create local symbols for functions
const decl = mod.declPtr(decl_index);
const parent_atom_index = try wasm.getOrCreateAtomForDecl(decl_index);
const parent_atom = wasm.getAtom(parent_atom_index);
const local_index = parent_atom.locals.items.len;
const fqn = mod.intern_pool.stringToSlice(try decl.fullyQualifiedName(mod));
const name = try std.fmt.allocPrintZ(gpa, "__unnamed_{s}_{d}", .{
fqn, local_index,
});
defer gpa.free(name);
switch (try wasm.lowerConst(name, tv, decl.srcLoc(mod))) {
.ok => |atom_index| {
try wasm.getAtomPtr(parent_atom_index).locals.append(gpa, atom_index);
return wasm.getAtom(atom_index).getSymbolIndex().?;
},
.fail => |em| {
decl.analysis = .codegen_failure;
try mod.failed_decls.put(mod.gpa, decl_index, em);
return error.CodegenFail;
},
}
}
const LowerConstResult = union(enum) {
ok: Atom.Index,
fail: *Module.ErrorMsg,
};
fn lowerConst(wasm: *Wasm, name: []const u8, tv: TypedValue, src_loc: Module.SrcLoc) !LowerConstResult {
const gpa = wasm.base.comp.gpa;
const mod = wasm.base.comp.module.?;
// Create and initialize a new local symbol and atom
const atom_index = try wasm.createAtom();
var value_bytes = std.ArrayList(u8).init(gpa);
defer value_bytes.deinit();
const code = code: {
const atom = wasm.getAtomPtr(atom_index);
atom.alignment = tv.ty.abiAlignment(mod);
wasm.symbols.items[atom.sym_index] = .{
.name = try wasm.string_table.put(gpa, name),
.flags = @intFromEnum(Symbol.Flag.WASM_SYM_BINDING_LOCAL),
.tag = .data,
.index = undefined,
.virtual_address = undefined,
};
try wasm.resolved_symbols.putNoClobber(gpa, atom.symbolLoc(), {});
const result = try codegen.generateSymbol(
&wasm.base,
src_loc,
tv,
&value_bytes,
.none,
.{
.parent_atom_index = atom.sym_index,
.addend = null,
},
);
break :code switch (result) {
.ok => value_bytes.items,
.fail => |em| {
return .{ .fail = em };
},
};
};
const atom = wasm.getAtomPtr(atom_index);
atom.size = @intCast(code.len);
try atom.code.appendSlice(gpa, code);
return .{ .ok = atom_index };
}
/// Returns the symbol index from a symbol of which its flag is set global,
/// such as an exported or imported symbol.
/// If the symbol does not yet exist, creates a new one symbol instead
/// and then returns the index to it.
pub fn getGlobalSymbol(wasm: *Wasm, name: []const u8, lib_name: ?[]const u8) !u32 {
_ = lib_name;
const gpa = wasm.base.comp.gpa;
const name_index = try wasm.string_table.put(gpa, name);
const gop = try wasm.globals.getOrPut(gpa, name_index);
if (gop.found_existing) {
return gop.value_ptr.*.index;
}
var symbol: Symbol = .{
.name = name_index,
.flags = 0,
.index = undefined, // index to type will be set after merging function symbols
.tag = .function,
.virtual_address = undefined,
};
symbol.setGlobal(true);
symbol.setUndefined(true);
const sym_index = if (wasm.symbols_free_list.popOrNull()) |index| index else blk: {
const index: u32 = @intCast(wasm.symbols.items.len);
try wasm.symbols.ensureUnusedCapacity(gpa, 1);
wasm.symbols.items.len += 1;
break :blk index;
};
wasm.symbols.items[sym_index] = symbol;
gop.value_ptr.* = .{ .index = sym_index, .file = null };
try wasm.resolved_symbols.put(gpa, gop.value_ptr.*, {});
try wasm.undefs.putNoClobber(gpa, name_index, gop.value_ptr.*);
return sym_index;
}
/// For a given decl, find the given symbol index's atom, and create a relocation for the type.
/// Returns the given pointer address
pub fn getDeclVAddr(
wasm: *Wasm,
decl_index: InternPool.DeclIndex,
reloc_info: link.File.RelocInfo,
) !u64 {
const target = wasm.base.comp.root_mod.resolved_target.result;
const gpa = wasm.base.comp.gpa;
const mod = wasm.base.comp.module.?;
const decl = mod.declPtr(decl_index);
const target_atom_index = try wasm.getOrCreateAtomForDecl(decl_index);
const target_symbol_index = wasm.getAtom(target_atom_index).sym_index;
assert(reloc_info.parent_atom_index != 0);
const atom_index = wasm.symbol_atom.get(.{ .file = null, .index = reloc_info.parent_atom_index }).?;
const atom = wasm.getAtomPtr(atom_index);
const is_wasm32 = target.cpu.arch == .wasm32;
if (decl.ty.zigTypeTag(mod) == .Fn) {
assert(reloc_info.addend == 0); // addend not allowed for function relocations
// We found a function pointer, so add it to our table,
// as function pointers are not allowed to be stored inside the data section.
// They are instead stored in a function table which are called by index.
try wasm.addTableFunction(target_symbol_index);
try atom.relocs.append(gpa, .{
.index = target_symbol_index,
.offset = @intCast(reloc_info.offset),
.relocation_type = if (is_wasm32) .R_WASM_TABLE_INDEX_I32 else .R_WASM_TABLE_INDEX_I64,
});
} else {
try atom.relocs.append(gpa, .{
.index = target_symbol_index,
.offset = @intCast(reloc_info.offset),
.relocation_type = if (is_wasm32) .R_WASM_MEMORY_ADDR_I32 else .R_WASM_MEMORY_ADDR_I64,
.addend = @intCast(reloc_info.addend),
});
}
// we do not know the final address at this point,
// as atom allocation will determine the address and relocations
// will calculate and rewrite this. Therefore, we simply return the symbol index
// that was targeted.
return target_symbol_index;
}
pub fn lowerAnonDecl(
wasm: *Wasm,
decl_val: InternPool.Index,
explicit_alignment: Alignment,
src_loc: Module.SrcLoc,
) !codegen.Result {
const gpa = wasm.base.comp.gpa;
const gop = try wasm.anon_decls.getOrPut(gpa, decl_val);
if (!gop.found_existing) {
const mod = wasm.base.comp.module.?;
const ty = Type.fromInterned(mod.intern_pool.typeOf(decl_val));
const tv: TypedValue = .{ .ty = ty, .val = Value.fromInterned(decl_val) };
var name_buf: [32]u8 = undefined;
const name = std.fmt.bufPrint(&name_buf, "__anon_{d}", .{
@intFromEnum(decl_val),
}) catch unreachable;
switch (try wasm.lowerConst(name, tv, src_loc)) {
.ok => |atom_index| wasm.anon_decls.values()[gop.index] = atom_index,
.fail => |em| return .{ .fail = em },
}
}
const atom = wasm.getAtomPtr(wasm.anon_decls.values()[gop.index]);
atom.alignment = switch (atom.alignment) {
.none => explicit_alignment,
else => switch (explicit_alignment) {
.none => atom.alignment,
else => atom.alignment.maxStrict(explicit_alignment),
},
};
return .ok;
}
pub fn getAnonDeclVAddr(wasm: *Wasm, decl_val: InternPool.Index, reloc_info: link.File.RelocInfo) !u64 {
const gpa = wasm.base.comp.gpa;
const target = wasm.base.comp.root_mod.resolved_target.result;
const atom_index = wasm.anon_decls.get(decl_val).?;
const target_symbol_index = wasm.getAtom(atom_index).getSymbolIndex().?;
const parent_atom_index = wasm.symbol_atom.get(.{ .file = null, .index = reloc_info.parent_atom_index }).?;
const parent_atom = wasm.getAtomPtr(parent_atom_index);
const is_wasm32 = target.cpu.arch == .wasm32;
const mod = wasm.base.comp.module.?;
const ty = Type.fromInterned(mod.intern_pool.typeOf(decl_val));
if (ty.zigTypeTag(mod) == .Fn) {
assert(reloc_info.addend == 0); // addend not allowed for function relocations
// We found a function pointer, so add it to our table,
// as function pointers are not allowed to be stored inside the data section.
// They are instead stored in a function table which are called by index.
try wasm.addTableFunction(target_symbol_index);
try parent_atom.relocs.append(gpa, .{
.index = target_symbol_index,
.offset = @intCast(reloc_info.offset),
.relocation_type = if (is_wasm32) .R_WASM_TABLE_INDEX_I32 else .R_WASM_TABLE_INDEX_I64,
});
} else {
try parent_atom.relocs.append(gpa, .{
.index = target_symbol_index,
.offset = @intCast(reloc_info.offset),
.relocation_type = if (is_wasm32) .R_WASM_MEMORY_ADDR_I32 else .R_WASM_MEMORY_ADDR_I64,
.addend = @intCast(reloc_info.addend),
});
}
// we do not know the final address at this point,
// as atom allocation will determine the address and relocations
// will calculate and rewrite this. Therefore, we simply return the symbol index
// that was targeted.
return target_symbol_index;
}
pub fn deleteDeclExport(
wasm: *Wasm,
decl_index: InternPool.DeclIndex,
name: InternPool.NullTerminatedString,
) void {
_ = name;
if (wasm.llvm_object) |_| return;
const atom_index = wasm.decls.get(decl_index) orelse return;
const sym_index = wasm.getAtom(atom_index).sym_index;
const loc: SymbolLoc = .{ .file = null, .index = sym_index };
const symbol = loc.getSymbol(wasm);
const symbol_name = wasm.string_table.get(symbol.name);
log.debug("Deleting export for decl '{s}'", .{symbol_name});
if (wasm.export_names.fetchRemove(loc)) |kv| {
assert(wasm.globals.remove(kv.value));
} else {
assert(wasm.globals.remove(symbol.name));
}
}
pub fn updateExports(
wasm: *Wasm,
mod: *Module,
exported: Module.Exported,
exports: []const *Module.Export,
) !void {
if (build_options.skip_non_native and builtin.object_format != .wasm) {
@panic("Attempted to compile for object format that was disabled by build configuration");
}
if (wasm.llvm_object) |llvm_object| return llvm_object.updateExports(mod, exported, exports);
const decl_index = switch (exported) {
.decl_index => |i| i,
.value => |val| {
_ = val;
@panic("TODO: implement Wasm linker code for exporting a constant value");
},
};
const decl = mod.declPtr(decl_index);
const atom_index = try wasm.getOrCreateAtomForDecl(decl_index);
const atom = wasm.getAtom(atom_index);
const atom_sym = atom.symbolLoc().getSymbol(wasm).*;
const gpa = mod.gpa;
for (exports) |exp| {
if (mod.intern_pool.stringToSliceUnwrap(exp.opts.section)) |section| {
try mod.failed_exports.putNoClobber(gpa, exp, try Module.ErrorMsg.create(
gpa,
decl.srcLoc(mod),
"Unimplemented: ExportOptions.section '{s}'",
.{section},
));
continue;
}
const exported_decl_index = switch (exp.exported) {
.value => {
try mod.failed_exports.putNoClobber(gpa, exp, try Module.ErrorMsg.create(
gpa,
decl.srcLoc(mod),
"Unimplemented: exporting a named constant value",
.{},
));
continue;
},
.decl_index => |i| i,
};
const exported_atom_index = try wasm.getOrCreateAtomForDecl(exported_decl_index);
const exported_atom = wasm.getAtom(exported_atom_index);
const export_name = try wasm.string_table.put(gpa, mod.intern_pool.stringToSlice(exp.opts.name));
const sym_loc = exported_atom.symbolLoc();
const symbol = sym_loc.getSymbol(wasm);
symbol.setGlobal(true);
symbol.setUndefined(false);
symbol.index = atom_sym.index;
symbol.tag = atom_sym.tag;
symbol.name = atom_sym.name;
switch (exp.opts.linkage) {
.Internal => {
symbol.setFlag(.WASM_SYM_VISIBILITY_HIDDEN);
symbol.setFlag(.WASM_SYM_BINDING_WEAK);
},
.Weak => {
symbol.setFlag(.WASM_SYM_BINDING_WEAK);
},
.Strong => {}, // symbols are strong by default
.LinkOnce => {
try mod.failed_exports.putNoClobber(gpa, exp, try Module.ErrorMsg.create(
gpa,
decl.srcLoc(mod),
"Unimplemented: LinkOnce",
.{},
));
continue;
},
}
if (wasm.globals.get(export_name)) |existing_loc| {
if (existing_loc.index == atom.sym_index) continue;
const existing_sym: Symbol = existing_loc.getSymbol(wasm).*;
if (!existing_sym.isUndefined()) blk: {
if (symbol.isWeak()) {
try wasm.discarded.put(gpa, existing_loc, sym_loc);
continue; // to-be-exported symbol is weak, so we keep the existing symbol
}
// new symbol is not weak while existing is, replace existing symbol
if (existing_sym.isWeak()) {
break :blk;
}
// When both the to-be-exported symbol and the already existing symbol
// are strong symbols, we have a linker error.
// In the other case we replace one with the other.
try mod.failed_exports.put(gpa, exp, try Module.ErrorMsg.create(
gpa,
decl.srcLoc(mod),
\\LinkError: symbol '{}' defined multiple times
\\ first definition in '{s}'
\\ next definition in '{s}'
,
.{ exp.opts.name.fmt(&mod.intern_pool), wasm.name, wasm.name },
));
continue;
}
// in this case the existing symbol must be replaced either because it's weak or undefined.
try wasm.discarded.put(gpa, existing_loc, sym_loc);
_ = wasm.imports.remove(existing_loc);
_ = wasm.undefs.swapRemove(existing_sym.name);
}
// Ensure the symbol will be exported using the given name
if (!mod.intern_pool.stringEqlSlice(exp.opts.name, sym_loc.getName(wasm))) {
try wasm.export_names.put(gpa, sym_loc, export_name);
}
try wasm.globals.put(
gpa,
export_name,
sym_loc,
);
}
}
pub fn freeDecl(wasm: *Wasm, decl_index: InternPool.DeclIndex) void {
if (wasm.llvm_object) |llvm_object| return llvm_object.freeDecl(decl_index);
const gpa = wasm.base.comp.gpa;
const mod = wasm.base.comp.module.?;
const decl = mod.declPtr(decl_index);
const atom_index = wasm.decls.get(decl_index).?;
const atom = wasm.getAtomPtr(atom_index);
atom.prev = null;
wasm.symbols_free_list.append(gpa, atom.sym_index) catch {};
_ = wasm.decls.remove(decl_index);
wasm.symbols.items[atom.sym_index].tag = .dead;
for (atom.locals.items) |local_atom_index| {
const local_atom = wasm.getAtom(local_atom_index);
const local_symbol = &wasm.symbols.items[local_atom.sym_index];
local_symbol.tag = .dead; // also for any local symbol
wasm.symbols_free_list.append(gpa, local_atom.sym_index) catch {};
assert(wasm.resolved_symbols.swapRemove(local_atom.symbolLoc()));
assert(wasm.symbol_atom.remove(local_atom.symbolLoc()));
}
if (decl.isExtern(mod)) {
_ = wasm.imports.remove(atom.symbolLoc());
}
_ = wasm.resolved_symbols.swapRemove(atom.symbolLoc());
_ = wasm.symbol_atom.remove(atom.symbolLoc());
// if (wasm.dwarf) |*dwarf| {
// dwarf.freeDecl(decl_index);
// }
}
/// Appends a new entry to the indirect function table
pub fn addTableFunction(wasm: *Wasm, symbol_index: u32) !void {
const gpa = wasm.base.comp.gpa;
const index: u32 = @intCast(wasm.function_table.count());
try wasm.function_table.put(gpa, .{ .file = null, .index = symbol_index }, index);
}
/// Assigns indexes to all indirect functions.
/// Starts at offset 1, where the value `0` represents an unresolved function pointer
/// or null-pointer
fn mapFunctionTable(wasm: *Wasm) void {
var it = wasm.function_table.iterator();
var index: u32 = 1;
while (it.next()) |entry| {
const symbol = entry.key_ptr.*.getSymbol(wasm);
if (symbol.isAlive()) {
entry.value_ptr.* = index;
index += 1;
} else {
wasm.function_table.removeByPtr(entry.key_ptr);
}
}
if (wasm.import_table or wasm.base.comp.config.output_mode == .Obj) {
const sym_loc = wasm.findGlobalSymbol("__indirect_function_table").?;
const import = wasm.imports.getPtr(sym_loc).?;
import.kind.table.limits.min = index - 1; // we start at index 1.
} else if (index > 1) {
log.debug("Appending indirect function table", .{});
const sym_loc = wasm.findGlobalSymbol("__indirect_function_table").?;
const symbol = sym_loc.getSymbol(wasm);
const table = &wasm.tables.items[symbol.index - wasm.imported_tables_count];
table.limits = .{ .min = index, .max = index, .flags = 0x1 };
}
}
/// Either creates a new import, or updates one if existing.
/// When `type_index` is non-null, we assume an external function.
/// In all other cases, a data-symbol will be created instead.
pub fn addOrUpdateImport(
wasm: *Wasm,
/// Name of the import
name: []const u8,
/// Symbol index that is external
symbol_index: u32,
/// Optional library name (i.e. `extern "c" fn foo() void`
lib_name: ?[:0]const u8,
/// The index of the type that represents the function signature
/// when the extern is a function. When this is null, a data-symbol
/// is asserted instead.
type_index: ?u32,
) !void {
const gpa = wasm.base.comp.gpa;
assert(symbol_index != 0);
// For the import name, we use the decl's name, rather than the fully qualified name
// Also mangle the name when the lib name is set and not equal to "C" so imports with the same
// name but different module can be resolved correctly.
const mangle_name = lib_name != null and
!std.mem.eql(u8, lib_name.?, "c");
const full_name = if (mangle_name) full_name: {
break :full_name try std.fmt.allocPrint(gpa, "{s}|{s}", .{ name, lib_name.? });
} else name;
defer if (mangle_name) gpa.free(full_name);
const decl_name_index = try wasm.string_table.put(gpa, full_name);
const symbol: *Symbol = &wasm.symbols.items[symbol_index];
symbol.setUndefined(true);
symbol.setGlobal(true);
symbol.name = decl_name_index;
if (mangle_name) {
// we specified a specific name for the symbol that does not match the import name
symbol.setFlag(.WASM_SYM_EXPLICIT_NAME);
}
const global_gop = try wasm.globals.getOrPut(gpa, decl_name_index);
if (!global_gop.found_existing) {
const loc: SymbolLoc = .{ .file = null, .index = symbol_index };
global_gop.value_ptr.* = loc;
try wasm.resolved_symbols.put(gpa, loc, {});
try wasm.undefs.putNoClobber(gpa, decl_name_index, loc);
} else if (global_gop.value_ptr.*.index != symbol_index) {
// We are not updating a symbol, but found an existing global
// symbol with the same name. This means we always favor the
// existing symbol, regardless whether it's defined or not.
// We can also skip storing the import as we will not output
// this symbol.
return wasm.discarded.put(
gpa,
.{ .file = null, .index = symbol_index },
global_gop.value_ptr.*,
);
}
if (type_index) |ty_index| {
const gop = try wasm.imports.getOrPut(gpa, .{ .index = symbol_index, .file = null });
const module_name = if (lib_name) |l_name| blk: {
break :blk l_name;
} else wasm.host_name;
if (!gop.found_existing) {
gop.value_ptr.* = .{
.module_name = try wasm.string_table.put(gpa, module_name),
.name = try wasm.string_table.put(gpa, name),
.kind = .{ .function = ty_index },
};
}
} else {
// non-functions will not be imported from the runtime, but only resolved during link-time
symbol.tag = .data;
}
}
/// Kind represents the type of an Atom, which is only
/// used to parse a decl into an Atom to define in which section
/// or segment it should be placed.
const Kind = union(enum) {
/// Represents the segment the data symbol should
/// be inserted into.
/// TODO: Add TLS segments
data: enum {
read_only,
uninitialized,
initialized,
},
function: void,
/// Returns the segment name the data kind represents.
/// Asserts `kind` has its active tag set to `data`.
fn segmentName(kind: Kind) []const u8 {
switch (kind.data) {
.read_only => return ".rodata.",
.uninitialized => return ".bss.",
.initialized => return ".data.",
}
}
};
/// Parses an Atom and inserts its metadata into the corresponding sections.
fn parseAtom(wasm: *Wasm, atom_index: Atom.Index, kind: Kind) !void {
const comp = wasm.base.comp;
const gpa = comp.gpa;
const shared_memory = comp.config.shared_memory;
const import_memory = comp.config.import_memory;
const atom = wasm.getAtomPtr(atom_index);
const symbol = (SymbolLoc{ .file = null, .index = atom.sym_index }).getSymbol(wasm);
const do_garbage_collect = wasm.base.gc_sections;
if (symbol.isDead() and do_garbage_collect) {
// Prevent unreferenced symbols from being parsed.
return;
}
const final_index: u32 = switch (kind) {
.function => result: {
const index: u32 = @intCast(wasm.functions.count() + wasm.imported_functions_count);
const type_index = wasm.atom_types.get(atom_index).?;
try wasm.functions.putNoClobber(
gpa,
.{ .file = null, .index = index },
.{ .func = .{ .type_index = type_index }, .sym_index = atom.sym_index },
);
symbol.tag = .function;
symbol.index = index;
if (wasm.code_section_index == null) {
wasm.code_section_index = @intCast(wasm.segments.items.len);
try wasm.segments.append(gpa, .{
.alignment = atom.alignment,
.size = atom.size,
.offset = 0,
.flags = 0,
});
}
break :result wasm.code_section_index.?;
},
.data => result: {
const segment_name = try std.mem.concat(gpa, u8, &.{
kind.segmentName(),
wasm.string_table.get(symbol.name),
});
errdefer gpa.free(segment_name);
const segment_info: types.Segment = .{
.name = segment_name,
.alignment = atom.alignment,
.flags = 0,
};
symbol.tag = .data;
// when creating an object file, or importing memory and the data belongs in the .bss segment
// we set the entire region of it to zeroes.
// We do not have to do this when exporting the memory (the default) because the runtime
// will do it for us, and we do not emit the bss segment at all.
if ((wasm.base.comp.config.output_mode == .Obj or import_memory) and kind.data == .uninitialized) {
@memset(atom.code.items, 0);
}
const should_merge = wasm.base.comp.config.output_mode != .Obj;
const gop = try wasm.data_segments.getOrPut(gpa, segment_info.outputName(should_merge));
if (gop.found_existing) {
const index = gop.value_ptr.*;
wasm.segments.items[index].size += atom.size;
symbol.index = @intCast(wasm.segment_info.getIndex(index).?);
// segment info already exists, so free its memory
gpa.free(segment_name);
break :result index;
} else {
const index: u32 = @intCast(wasm.segments.items.len);
var flags: u32 = 0;
if (shared_memory) {
flags |= @intFromEnum(Segment.Flag.WASM_DATA_SEGMENT_IS_PASSIVE);
}
try wasm.segments.append(gpa, .{
.alignment = atom.alignment,
.size = 0,
.offset = 0,
.flags = flags,
});
gop.value_ptr.* = index;
const info_index: u32 = @intCast(wasm.segment_info.count());
try wasm.segment_info.put(gpa, index, segment_info);
symbol.index = info_index;
break :result index;
}
},
};
const segment: *Segment = &wasm.segments.items[final_index];
segment.alignment = segment.alignment.max(atom.alignment);
try wasm.appendAtomAtIndex(final_index, atom_index);
}
/// From a given index, append the given `Atom` at the back of the linked list.
/// Simply inserts it into the map of atoms when it doesn't exist yet.
pub fn appendAtomAtIndex(wasm: *Wasm, index: u32, atom_index: Atom.Index) !void {
const gpa = wasm.base.comp.gpa;
const atom = wasm.getAtomPtr(atom_index);
if (wasm.atoms.getPtr(index)) |last_index_ptr| {
atom.prev = last_index_ptr.*;
last_index_ptr.* = atom_index;
} else {
try wasm.atoms.putNoClobber(gpa, index, atom_index);
}
}
/// Allocates debug atoms into their respective debug sections
/// to merge them with maybe-existing debug atoms from object files.
fn allocateDebugAtoms(wasm: *Wasm) !void {
if (wasm.dwarf == null) return;
const allocAtom = struct {
fn f(bin: *Wasm, maybe_index: *?u32, atom_index: Atom.Index) !void {
const index = maybe_index.* orelse idx: {
const index = @as(u32, @intCast(bin.segments.items.len));
try bin.appendDummySegment();
maybe_index.* = index;
break :idx index;
};
const atom = bin.getAtomPtr(atom_index);
atom.size = @as(u32, @intCast(atom.code.items.len));
bin.symbols.items[atom.sym_index].index = index;
try bin.appendAtomAtIndex(index, atom_index);
}
}.f;
try allocAtom(wasm, &wasm.debug_info_index, wasm.debug_info_atom.?);
try allocAtom(wasm, &wasm.debug_line_index, wasm.debug_line_atom.?);
try allocAtom(wasm, &wasm.debug_loc_index, wasm.debug_loc_atom.?);
try allocAtom(wasm, &wasm.debug_str_index, wasm.debug_str_atom.?);
try allocAtom(wasm, &wasm.debug_ranges_index, wasm.debug_ranges_atom.?);
try allocAtom(wasm, &wasm.debug_abbrev_index, wasm.debug_abbrev_atom.?);
try allocAtom(wasm, &wasm.debug_pubnames_index, wasm.debug_pubnames_atom.?);
try allocAtom(wasm, &wasm.debug_pubtypes_index, wasm.debug_pubtypes_atom.?);
}
fn allocateAtoms(wasm: *Wasm) !void {
// first sort the data segments
try sortDataSegments(wasm);
try allocateDebugAtoms(wasm);
var it = wasm.atoms.iterator();
while (it.next()) |entry| {
const segment = &wasm.segments.items[entry.key_ptr.*];
var atom_index = entry.value_ptr.*;
if (entry.key_ptr.* == wasm.code_section_index) {
// Code section is allocated upon writing as they are required to be ordered
// to synchronise with the function section.
continue;
}
var offset: u32 = 0;
while (true) {
const atom = wasm.getAtomPtr(atom_index);
const symbol_loc = atom.symbolLoc();
// Ensure we get the original symbol, so we verify the correct symbol on whether
// it is dead or not and ensure an atom is removed when dead.
// This is required as we may have parsed aliases into atoms.
const sym = if (symbol_loc.file) |object_index| sym: {
const object = wasm.objects.items[object_index];
break :sym object.symtable[symbol_loc.index];
} else wasm.symbols.items[symbol_loc.index];
// Dead symbols must be unlinked from the linked-list to prevent them
// from being emit into the binary.
if (sym.isDead()) {
if (entry.value_ptr.* == atom_index and atom.prev != null) {
// When the atom is dead and is also the first atom retrieved from wasm.atoms(index) we update
// the entry to point it to the previous atom to ensure we do not start with a dead symbol that
// was removed and therefore do not emit any code at all.
entry.value_ptr.* = atom.prev.?;
}
atom_index = atom.prev orelse break;
atom.prev = null;
continue;
}
offset = @intCast(atom.alignment.forward(offset));
atom.offset = offset;
log.debug("Atom '{s}' allocated from 0x{x:0>8} to 0x{x:0>8} size={d}", .{
symbol_loc.getName(wasm),
offset,
offset + atom.size,
atom.size,
});
offset += atom.size;
atom_index = atom.prev orelse break;
}
segment.size = @intCast(segment.alignment.forward(offset));
}
}
/// For each data symbol, sets the virtual address.
fn allocateVirtualAddresses(wasm: *Wasm) void {
for (wasm.resolved_symbols.keys()) |loc| {
const symbol = loc.getSymbol(wasm);
if (symbol.tag != .data or symbol.isDead()) {
// Only data symbols have virtual addresses.
// Dead symbols do not get allocated, so we don't need to set their virtual address either.
continue;
}
const atom_index = wasm.symbol_atom.get(loc) orelse {
// synthetic symbol that does not contain an atom
continue;
};
const atom = wasm.getAtom(atom_index);
const merge_segment = wasm.base.comp.config.output_mode != .Obj;
const segment_info = if (atom.file) |object_index| blk: {
break :blk wasm.objects.items[object_index].segment_info;
} else wasm.segment_info.values();
const segment_name = segment_info[symbol.index].outputName(merge_segment);
const segment_index = wasm.data_segments.get(segment_name).?;
const segment = wasm.segments.items[segment_index];
// TLS symbols have their virtual address set relative to their own TLS segment,
// rather than the entire Data section.
if (symbol.hasFlag(.WASM_SYM_TLS)) {
symbol.virtual_address = atom.offset;
} else {
symbol.virtual_address = atom.offset + segment.offset;
}
}
}
fn sortDataSegments(wasm: *Wasm) !void {
const gpa = wasm.base.comp.gpa;
var new_mapping: std.StringArrayHashMapUnmanaged(u32) = .{};
try new_mapping.ensureUnusedCapacity(gpa, wasm.data_segments.count());
errdefer new_mapping.deinit(gpa);
const keys = try gpa.dupe([]const u8, wasm.data_segments.keys());
defer gpa.free(keys);
const SortContext = struct {
fn sort(_: void, lhs: []const u8, rhs: []const u8) bool {
return order(lhs) < order(rhs);
}
fn order(name: []const u8) u8 {
if (mem.startsWith(u8, name, ".rodata")) return 0;
if (mem.startsWith(u8, name, ".data")) return 1;
if (mem.startsWith(u8, name, ".text")) return 2;
return 3;
}
};
mem.sort([]const u8, keys, {}, SortContext.sort);
for (keys) |key| {
const segment_index = wasm.data_segments.get(key).?;
new_mapping.putAssumeCapacity(key, segment_index);
}
wasm.data_segments.deinit(gpa);
wasm.data_segments = new_mapping;
}
/// Obtains all initfuncs from each object file, verifies its function signature,
/// and then appends it to our final `init_funcs` list.
/// After all functions have been inserted, the functions will be ordered based
/// on their priority.
/// NOTE: This function must be called before we merged any other section.
/// This is because all init funcs in the object files contain references to the
/// original functions and their types. We need to know the type to verify it doesn't
/// contain any parameters.
fn setupInitFunctions(wasm: *Wasm) !void {
const gpa = wasm.base.comp.gpa;
for (wasm.objects.items, 0..) |object, file_index| {
try wasm.init_funcs.ensureUnusedCapacity(gpa, object.init_funcs.len);
for (object.init_funcs) |init_func| {
const symbol = object.symtable[init_func.symbol_index];
const ty: std.wasm.Type = if (symbol.isUndefined()) ty: {
const imp: types.Import = object.findImport(.function, symbol.index);
break :ty object.func_types[imp.kind.function];
} else ty: {
const func_index = symbol.index - object.importedCountByKind(.function);
const func = object.functions[func_index];
break :ty object.func_types[func.type_index];
};
if (ty.params.len != 0) {
log.err("constructor functions cannot take arguments: '{s}'", .{object.string_table.get(symbol.name)});
return error.InvalidInitFunc;
}
log.debug("appended init func '{s}'\n", .{object.string_table.get(symbol.name)});
wasm.init_funcs.appendAssumeCapacity(.{
.index = init_func.symbol_index,
.file = @as(u16, @intCast(file_index)),
.priority = init_func.priority,
});
try wasm.mark(.{ .index = init_func.symbol_index, .file = @intCast(file_index) });
}
}
// sort the initfunctions based on their priority
mem.sort(InitFuncLoc, wasm.init_funcs.items, {}, InitFuncLoc.lessThan);
if (wasm.init_funcs.items.len > 0) {
const loc = wasm.findGlobalSymbol("__wasm_call_ctors").?;
try wasm.mark(loc);
}
}
/// Generates an atom containing the global error set' size.
/// This will only be generated if the symbol exists.
fn setupErrorsLen(wasm: *Wasm) !void {
const gpa = wasm.base.comp.gpa;
const loc = wasm.findGlobalSymbol("__zig_errors_len") orelse return;
const errors_len = wasm.base.comp.module.?.global_error_set.count();
// overwrite existing atom if it already exists (maybe the error set has increased)
// if not, allcoate a new atom.
const atom_index = if (wasm.symbol_atom.get(loc)) |index| blk: {
const atom = wasm.getAtomPtr(index);
atom.deinit(gpa);
break :blk index;
} else new_atom: {
const atom_index: Atom.Index = @intCast(wasm.managed_atoms.items.len);
try wasm.symbol_atom.put(gpa, loc, atom_index);
try wasm.managed_atoms.append(gpa, undefined);
break :new_atom atom_index;
};
const atom = wasm.getAtomPtr(atom_index);
atom.* = Atom.empty;
atom.sym_index = loc.index;
atom.size = 2;
try atom.code.writer(gpa).writeInt(u16, @intCast(errors_len), .little);
try wasm.parseAtom(atom_index, .{ .data = .read_only });
}
/// Creates a function body for the `__wasm_call_ctors` symbol.
/// Loops over all constructors found in `init_funcs` and calls them
/// respectively based on their priority which was sorted by `setupInitFunctions`.
/// NOTE: This function must be called after we merged all sections to ensure the
/// references to the function stored in the symbol have been finalized so we end
/// up calling the resolved function.
fn initializeCallCtorsFunction(wasm: *Wasm) !void {
const gpa = wasm.base.comp.gpa;
// No code to emit, so also no ctors to call
if (wasm.code_section_index == null) {
// Make sure to remove it from the resolved symbols so we do not emit
// it within any section. TODO: Remove this once we implement garbage collection.
const loc = wasm.findGlobalSymbol("__wasm_call_ctors").?;
assert(wasm.resolved_symbols.swapRemove(loc));
return;
}
var function_body = std.ArrayList(u8).init(gpa);
defer function_body.deinit();
const writer = function_body.writer();
// Create the function body
{
// Write locals count (we have none)
try leb.writeULEB128(writer, @as(u32, 0));
// call constructors
for (wasm.init_funcs.items) |init_func_loc| {
const symbol = init_func_loc.getSymbol(wasm);
const func = wasm.functions.values()[symbol.index - wasm.imported_functions_count].func;
const ty = wasm.func_types.items[func.type_index];
// Call function by its function index
try writer.writeByte(std.wasm.opcode(.call));
try leb.writeULEB128(writer, symbol.index);
// drop all returned values from the stack as __wasm_call_ctors has no return value
for (ty.returns) |_| {
try writer.writeByte(std.wasm.opcode(.drop));
}
}
// End function body
try writer.writeByte(std.wasm.opcode(.end));
}
try wasm.createSyntheticFunction(
"__wasm_call_ctors",
std.wasm.Type{ .params = &.{}, .returns = &.{} },
&function_body,
);
}
fn createSyntheticFunction(
wasm: *Wasm,
symbol_name: []const u8,
func_ty: std.wasm.Type,
function_body: *std.ArrayList(u8),
) !void {
const gpa = wasm.base.comp.gpa;
const loc = wasm.findGlobalSymbol(symbol_name) orelse
try wasm.createSyntheticSymbol(symbol_name, .function);
const symbol = loc.getSymbol(wasm);
if (symbol.isDead()) {
return;
}
const ty_index = try wasm.putOrGetFuncType(func_ty);
// create function with above type
const func_index = wasm.imported_functions_count + @as(u32, @intCast(wasm.functions.count()));
try wasm.functions.putNoClobber(
gpa,
.{ .file = null, .index = func_index },
.{ .func = .{ .type_index = ty_index }, .sym_index = loc.index },
);
symbol.index = func_index;
// create the atom that will be output into the final binary
const atom_index = @as(Atom.Index, @intCast(wasm.managed_atoms.items.len));
const atom = try wasm.managed_atoms.addOne(gpa);
atom.* = .{
.size = @as(u32, @intCast(function_body.items.len)),
.offset = 0,
.sym_index = loc.index,
.file = null,
.alignment = .@"1",
.prev = null,
.code = function_body.moveToUnmanaged(),
.original_offset = 0,
};
try wasm.appendAtomAtIndex(wasm.code_section_index.?, atom_index);
try wasm.symbol_atom.putNoClobber(gpa, loc, atom_index);
}
/// Unlike `createSyntheticFunction` this function is to be called by
/// the codegeneration backend. This will not allocate the created Atom yet,
/// but will instead be appended to `synthetic_functions` list and will be
/// parsed at the end of code generation.
/// Returns the index of the symbol.
pub fn createFunction(
wasm: *Wasm,
symbol_name: []const u8,
func_ty: std.wasm.Type,
function_body: *std.ArrayList(u8),
relocations: *std.ArrayList(Relocation),
) !u32 {
const gpa = wasm.base.comp.gpa;
const loc = try wasm.createSyntheticSymbol(symbol_name, .function);
const atom_index: Atom.Index = @intCast(wasm.managed_atoms.items.len);
const atom = try wasm.managed_atoms.addOne(gpa);
atom.* = .{
.size = @intCast(function_body.items.len),
.offset = 0,
.sym_index = loc.index,
.file = null,
.alignment = .@"1",
.prev = null,
.code = function_body.moveToUnmanaged(),
.relocs = relocations.moveToUnmanaged(),
.original_offset = 0,
};
const symbol = loc.getSymbol(wasm);
symbol.setFlag(.WASM_SYM_VISIBILITY_HIDDEN); // ensure function does not get exported
const section_index = wasm.code_section_index orelse idx: {
const index = @as(u32, @intCast(wasm.segments.items.len));
try wasm.appendDummySegment();
break :idx index;
};
try wasm.appendAtomAtIndex(section_index, atom_index);
try wasm.symbol_atom.putNoClobber(gpa, loc, atom_index);
try wasm.atom_types.put(gpa, atom_index, try wasm.putOrGetFuncType(func_ty));
try wasm.synthetic_functions.append(gpa, atom_index);
return loc.index;
}
/// If required, sets the function index in the `start` section.
fn setupStartSection(wasm: *Wasm) !void {
if (wasm.findGlobalSymbol("__wasm_init_memory")) |loc| {
wasm.entry = loc.getSymbol(wasm).index;
}
}
fn initializeTLSFunction(wasm: *Wasm) !void {
const comp = wasm.base.comp;
const gpa = comp.gpa;
const shared_memory = comp.config.shared_memory;
if (!shared_memory) return;
var function_body = std.ArrayList(u8).init(gpa);
defer function_body.deinit();
const writer = function_body.writer();
// locals
try writer.writeByte(0);
// If there's a TLS segment, initialize it during runtime using the bulk-memory feature
if (wasm.data_segments.getIndex(".tdata")) |data_index| {
const segment_index = wasm.data_segments.entries.items(.value)[data_index];
const segment = wasm.segments.items[segment_index];
const param_local: u32 = 0;
try writer.writeByte(std.wasm.opcode(.local_get));
try leb.writeULEB128(writer, param_local);
const tls_base_loc = wasm.findGlobalSymbol("__tls_base").?;
try writer.writeByte(std.wasm.opcode(.global_set));
try leb.writeULEB128(writer, tls_base_loc.getSymbol(wasm).index);
// load stack values for the bulk-memory operation
{
try writer.writeByte(std.wasm.opcode(.local_get));
try leb.writeULEB128(writer, param_local);
try writer.writeByte(std.wasm.opcode(.i32_const));
try leb.writeULEB128(writer, @as(u32, 0)); //segment offset
try writer.writeByte(std.wasm.opcode(.i32_const));
try leb.writeULEB128(writer, @as(u32, segment.size)); //segment offset
}
// perform the bulk-memory operation to initialize the data segment
try writer.writeByte(std.wasm.opcode(.misc_prefix));
try leb.writeULEB128(writer, std.wasm.miscOpcode(.memory_init));
// segment immediate
try leb.writeULEB128(writer, @as(u32, @intCast(data_index)));
// memory index immediate (always 0)
try leb.writeULEB128(writer, @as(u32, 0));
}
// If we have to perform any TLS relocations, call the corresponding function
// which performs all runtime TLS relocations. This is a synthetic function,
// generated by the linker.
if (wasm.findGlobalSymbol("__wasm_apply_global_tls_relocs")) |loc| {
try writer.writeByte(std.wasm.opcode(.call));
try leb.writeULEB128(writer, loc.getSymbol(wasm).index);
}
try writer.writeByte(std.wasm.opcode(.end));
try wasm.createSyntheticFunction(
"__wasm_init_tls",
std.wasm.Type{ .params = &.{.i32}, .returns = &.{} },
&function_body,
);
}
fn setupImports(wasm: *Wasm) !void {
const gpa = wasm.base.comp.gpa;
log.debug("Merging imports", .{});
var discarded_it = wasm.discarded.keyIterator();
while (discarded_it.next()) |discarded| {
if (discarded.file == null) {
// remove an import if it was resolved
if (wasm.imports.remove(discarded.*)) {
log.debug("Removed symbol '{s}' as an import", .{
discarded.getName(wasm),
});
}
}
}
for (wasm.resolved_symbols.keys()) |symbol_loc| {
const file_index = symbol_loc.file orelse {
// imports generated by Zig code are already in the `import` section
continue;
};
const symbol = symbol_loc.getSymbol(wasm);
if (symbol.isDead() or
!symbol.requiresImport() or
std.mem.eql(u8, symbol_loc.getName(wasm), "__indirect_function_table"))
{
continue;
}
log.debug("Symbol '{s}' will be imported from the host", .{symbol_loc.getName(wasm)});
const object = wasm.objects.items[file_index];
const import = object.findImport(symbol.tag.externalType(), symbol.index);
// We copy the import to a new import to ensure the names contain references
// to the internal string table, rather than of the object file.
const new_imp: types.Import = .{
.module_name = try wasm.string_table.put(gpa, object.string_table.get(import.module_name)),
.name = try wasm.string_table.put(gpa, object.string_table.get(import.name)),
.kind = import.kind,
};
// TODO: De-duplicate imports when they contain the same names and type
try wasm.imports.putNoClobber(gpa, symbol_loc, new_imp);
}
// Assign all indexes of the imports to their representing symbols
var function_index: u32 = 0;
var global_index: u32 = 0;
var table_index: u32 = 0;
var it = wasm.imports.iterator();
while (it.next()) |entry| {
const symbol = entry.key_ptr.*.getSymbol(wasm);
const import: types.Import = entry.value_ptr.*;
switch (import.kind) {
.function => {
symbol.index = function_index;
function_index += 1;
},
.global => {
symbol.index = global_index;
global_index += 1;
},
.table => {
symbol.index = table_index;
table_index += 1;
},
else => unreachable,
}
}
wasm.imported_functions_count = function_index;
wasm.imported_globals_count = global_index;
wasm.imported_tables_count = table_index;
log.debug("Merged ({d}) functions, ({d}) globals, and ({d}) tables into import section", .{
function_index,
global_index,
table_index,
});
}
/// Takes the global, function and table section from each linked object file
/// and merges it into a single section for each.
fn mergeSections(wasm: *Wasm) !void {
const gpa = wasm.base.comp.gpa;
var removed_duplicates = std.ArrayList(SymbolLoc).init(gpa);
defer removed_duplicates.deinit();
for (wasm.resolved_symbols.keys()) |sym_loc| {
if (sym_loc.file == null) {
// Zig code-generated symbols are already within the sections and do not
// require to be merged
continue;
}
const object = &wasm.objects.items[sym_loc.file.?];
const symbol = &object.symtable[sym_loc.index];
if (symbol.isDead() or
symbol.isUndefined() or
(symbol.tag != .function and symbol.tag != .global and symbol.tag != .table))
{
// Skip undefined symbols as they go in the `import` section
// Also skip symbols that do not need to have a section merged.
continue;
}
const offset = object.importedCountByKind(symbol.tag.externalType());
const index = symbol.index - offset;
switch (symbol.tag) {
.function => {
const gop = try wasm.functions.getOrPut(
gpa,
.{ .file = sym_loc.file, .index = symbol.index },
);
if (gop.found_existing) {
// We found an alias to the same function, discard this symbol in favor of
// the original symbol and point the discard function to it. This ensures
// we only emit a single function, instead of duplicates.
symbol.unmark();
try wasm.discarded.putNoClobber(
gpa,
sym_loc,
.{ .file = gop.key_ptr.*.file, .index = gop.value_ptr.*.sym_index },
);
try removed_duplicates.append(sym_loc);
continue;
}
gop.value_ptr.* = .{ .func = object.functions[index], .sym_index = sym_loc.index };
symbol.index = @as(u32, @intCast(gop.index)) + wasm.imported_functions_count;
},
.global => {
const original_global = object.globals[index];
symbol.index = @as(u32, @intCast(wasm.wasm_globals.items.len)) + wasm.imported_globals_count;
try wasm.wasm_globals.append(gpa, original_global);
},
.table => {
const original_table = object.tables[index];
symbol.index = @as(u32, @intCast(wasm.tables.items.len)) + wasm.imported_tables_count;
try wasm.tables.append(gpa, original_table);
},
else => unreachable,
}
}
// For any removed duplicates, remove them from the resolved symbols list
for (removed_duplicates.items) |sym_loc| {
assert(wasm.resolved_symbols.swapRemove(sym_loc));
}
log.debug("Merged ({d}) functions", .{wasm.functions.count()});
log.debug("Merged ({d}) globals", .{wasm.wasm_globals.items.len});
log.debug("Merged ({d}) tables", .{wasm.tables.items.len});
}
/// Merges function types of all object files into the final
/// 'types' section, while assigning the type index to the representing
/// section (import, export, function).
fn mergeTypes(wasm: *Wasm) !void {
const gpa = wasm.base.comp.gpa;
// A map to track which functions have already had their
// type inserted. If we do this for the same function multiple times,
// it will be overwritten with the incorrect type.
var dirty = std.AutoHashMap(u32, void).init(gpa);
try dirty.ensureUnusedCapacity(@as(u32, @intCast(wasm.functions.count())));
defer dirty.deinit();
for (wasm.resolved_symbols.keys()) |sym_loc| {
if (sym_loc.file == null) {
// zig code-generated symbols are already present in final type section
continue;
}
const object = wasm.objects.items[sym_loc.file.?];
const symbol = object.symtable[sym_loc.index];
if (symbol.tag != .function or symbol.isDead()) {
// Only functions have types. Only retrieve the type of referenced functions.
continue;
}
if (symbol.isUndefined()) {
log.debug("Adding type from extern function '{s}'", .{sym_loc.getName(wasm)});
const import: *types.Import = wasm.imports.getPtr(sym_loc) orelse continue;
const original_type = object.func_types[import.kind.function];
import.kind.function = try wasm.putOrGetFuncType(original_type);
} else if (!dirty.contains(symbol.index)) {
log.debug("Adding type from function '{s}'", .{sym_loc.getName(wasm)});
const func = &wasm.functions.values()[symbol.index - wasm.imported_functions_count].func;
func.type_index = try wasm.putOrGetFuncType(object.func_types[func.type_index]);
dirty.putAssumeCapacityNoClobber(symbol.index, {});
}
}
log.debug("Completed merging and deduplicating types. Total count: ({d})", .{wasm.func_types.items.len});
}
fn setupExports(wasm: *Wasm) !void {
const comp = wasm.base.comp;
const gpa = comp.gpa;
if (comp.config.output_mode == .Obj) return;
log.debug("Building exports from symbols", .{});
const force_exp_names = wasm.export_symbol_names;
if (force_exp_names.len > 0) {
var failed_exports = false;
for (force_exp_names) |exp_name| {
const loc = wasm.findGlobalSymbol(exp_name) orelse {
log.err("could not export '{s}', symbol not found", .{exp_name});
failed_exports = true;
continue;
};
const symbol = loc.getSymbol(wasm);
symbol.setFlag(.WASM_SYM_EXPORTED);
}
if (failed_exports) {
return error.MissingSymbol;
}
}
for (wasm.resolved_symbols.keys()) |sym_loc| {
const symbol = sym_loc.getSymbol(wasm);
if (!symbol.isExported(comp.config.rdynamic)) continue;
const sym_name = sym_loc.getName(wasm);
const export_name = if (wasm.export_names.get(sym_loc)) |name| name else blk: {
if (sym_loc.file == null) break :blk symbol.name;
break :blk try wasm.string_table.put(gpa, sym_name);
};
const exp: types.Export = if (symbol.tag == .data) exp: {
const global_index = @as(u32, @intCast(wasm.imported_globals_count + wasm.wasm_globals.items.len));
try wasm.wasm_globals.append(gpa, .{
.global_type = .{ .valtype = .i32, .mutable = false },
.init = .{ .i32_const = @as(i32, @intCast(symbol.virtual_address)) },
});
break :exp .{
.name = export_name,
.kind = .global,
.index = global_index,
};
} else .{
.name = export_name,
.kind = symbol.tag.externalType(),
.index = symbol.index,
};
log.debug("Exporting symbol '{s}' as '{s}' at index: ({d})", .{
sym_name,
wasm.string_table.get(exp.name),
exp.index,
});
try wasm.exports.append(gpa, exp);
}
log.debug("Completed building exports. Total count: ({d})", .{wasm.exports.items.len});
}
fn setupStart(wasm: *Wasm) !void {
const comp = wasm.base.comp;
// do not export entry point if user set none or no default was set.
const entry_name = wasm.entry_name orelse return;
const symbol_loc = wasm.findGlobalSymbol(entry_name) orelse {
log.err("Entry symbol '{s}' missing, use '-fno-entry' to suppress", .{entry_name});
return error.MissingSymbol;
};
const symbol = symbol_loc.getSymbol(wasm);
if (symbol.tag != .function) {
log.err("Entry symbol '{s}' is not a function", .{entry_name});
return error.InvalidEntryKind;
}
// Ensure the symbol is exported so host environment can access it
if (comp.config.output_mode != .Obj) {
symbol.setFlag(.WASM_SYM_EXPORTED);
}
}
/// Sets up the memory section of the wasm module, as well as the stack.
fn setupMemory(wasm: *Wasm) !void {
const comp = wasm.base.comp;
const shared_memory = comp.config.shared_memory;
log.debug("Setting up memory layout", .{});
const page_size = std.wasm.page_size; // 64kb
const stack_alignment: Alignment = .@"16"; // wasm's stack alignment as specified by tool-convention
const heap_alignment: Alignment = .@"16"; // wasm's heap alignment as specified by tool-convention
// Always place the stack at the start by default
// unless the user specified the global-base flag
var place_stack_first = true;
var memory_ptr: u64 = if (wasm.global_base) |base| blk: {
place_stack_first = false;
break :blk base;
} else 0;
const is_obj = comp.config.output_mode == .Obj;
if (place_stack_first and !is_obj) {
memory_ptr = stack_alignment.forward(memory_ptr);
memory_ptr += wasm.base.stack_size;
// We always put the stack pointer global at index 0
wasm.wasm_globals.items[0].init.i32_const = @as(i32, @bitCast(@as(u32, @intCast(memory_ptr))));
}
var offset: u32 = @as(u32, @intCast(memory_ptr));
var data_seg_it = wasm.data_segments.iterator();
while (data_seg_it.next()) |entry| {
const segment = &wasm.segments.items[entry.value_ptr.*];
memory_ptr = segment.alignment.forward(memory_ptr);
// set TLS-related symbols
if (mem.eql(u8, entry.key_ptr.*, ".tdata")) {
if (wasm.findGlobalSymbol("__tls_size")) |loc| {
const sym = loc.getSymbol(wasm);
wasm.wasm_globals.items[sym.index - wasm.imported_globals_count].init.i32_const = @intCast(segment.size);
}
if (wasm.findGlobalSymbol("__tls_align")) |loc| {
const sym = loc.getSymbol(wasm);
wasm.wasm_globals.items[sym.index - wasm.imported_globals_count].init.i32_const = @intCast(segment.alignment.toByteUnitsOptional().?);
}
if (wasm.findGlobalSymbol("__tls_base")) |loc| {
const sym = loc.getSymbol(wasm);
wasm.wasm_globals.items[sym.index - wasm.imported_globals_count].init.i32_const = if (shared_memory)
@as(i32, 0)
else
@as(i32, @intCast(memory_ptr));
}
}
memory_ptr += segment.size;
segment.offset = offset;
offset += segment.size;
}
// create the memory init flag which is used by the init memory function
if (shared_memory and wasm.hasPassiveInitializationSegments()) {
// align to pointer size
memory_ptr = mem.alignForward(u64, memory_ptr, 4);
const loc = try wasm.createSyntheticSymbol("__wasm_init_memory_flag", .data);
const sym = loc.getSymbol(wasm);
sym.virtual_address = @as(u32, @intCast(memory_ptr));
memory_ptr += 4;
}
if (!place_stack_first and !is_obj) {
memory_ptr = stack_alignment.forward(memory_ptr);
memory_ptr += wasm.base.stack_size;
wasm.wasm_globals.items[0].init.i32_const = @as(i32, @bitCast(@as(u32, @intCast(memory_ptr))));
}
// One of the linked object files has a reference to the __heap_base symbol.
// We must set its virtual address so it can be used in relocations.
if (wasm.findGlobalSymbol("__heap_base")) |loc| {
const symbol = loc.getSymbol(wasm);
symbol.virtual_address = @intCast(heap_alignment.forward(memory_ptr));
}
// Setup the max amount of pages
// For now we only support wasm32 by setting the maximum allowed memory size 2^32-1
const max_memory_allowed: u64 = (1 << 32) - 1;
if (wasm.initial_memory) |initial_memory| {
if (!std.mem.isAlignedGeneric(u64, initial_memory, page_size)) {
log.err("Initial memory must be {d}-byte aligned", .{page_size});
return error.MissAlignment;
}
if (memory_ptr > initial_memory) {
log.err("Initial memory too small, must be at least {d} bytes", .{memory_ptr});
return error.MemoryTooSmall;
}
if (initial_memory > max_memory_allowed) {
log.err("Initial memory exceeds maximum memory {d}", .{max_memory_allowed});
return error.MemoryTooBig;
}
memory_ptr = initial_memory;
}
memory_ptr = mem.alignForward(u64, memory_ptr, std.wasm.page_size);
// In case we do not import memory, but define it ourselves,
// set the minimum amount of pages on the memory section.
wasm.memories.limits.min = @as(u32, @intCast(memory_ptr / page_size));
log.debug("Total memory pages: {d}", .{wasm.memories.limits.min});
if (wasm.findGlobalSymbol("__heap_end")) |loc| {
const symbol = loc.getSymbol(wasm);
symbol.virtual_address = @as(u32, @intCast(memory_ptr));
}
if (wasm.max_memory) |max_memory| {
if (!std.mem.isAlignedGeneric(u64, max_memory, page_size)) {
log.err("Maximum memory must be {d}-byte aligned", .{page_size});
return error.MissAlignment;
}
if (memory_ptr > max_memory) {
log.err("Maxmimum memory too small, must be at least {d} bytes", .{memory_ptr});
return error.MemoryTooSmall;
}
if (max_memory > max_memory_allowed) {
log.err("Maximum memory exceeds maxmium amount {d}", .{max_memory_allowed});
return error.MemoryTooBig;
}
wasm.memories.limits.max = @as(u32, @intCast(max_memory / page_size));
wasm.memories.limits.setFlag(.WASM_LIMITS_FLAG_HAS_MAX);
if (shared_memory) {
wasm.memories.limits.setFlag(.WASM_LIMITS_FLAG_IS_SHARED);
}
log.debug("Maximum memory pages: {?d}", .{wasm.memories.limits.max});
}
}
/// From a given object's index and the index of the segment, returns the corresponding
/// index of the segment within the final data section. When the segment does not yet
/// exist, a new one will be initialized and appended. The new index will be returned in that case.
pub fn getMatchingSegment(wasm: *Wasm, object_index: u16, symbol_index: u32) !u32 {
const comp = wasm.base.comp;
const gpa = comp.gpa;
const object: Object = wasm.objects.items[object_index];
const symbol = object.symtable[symbol_index];
const index: u32 = @intCast(wasm.segments.items.len);
const shared_memory = comp.config.shared_memory;
switch (symbol.tag) {
.data => {
const segment_info = object.segment_info[symbol.index];
const merge_segment = comp.config.output_mode != .Obj;
const result = try wasm.data_segments.getOrPut(gpa, segment_info.outputName(merge_segment));
if (!result.found_existing) {
result.value_ptr.* = index;
var flags: u32 = 0;
if (shared_memory) {
flags |= @intFromEnum(Segment.Flag.WASM_DATA_SEGMENT_IS_PASSIVE);
}
try wasm.segments.append(gpa, .{
.alignment = .@"1",
.size = 0,
.offset = 0,
.flags = flags,
});
try wasm.segment_info.putNoClobber(gpa, index, .{
.name = try gpa.dupe(u8, segment_info.name),
.alignment = segment_info.alignment,
.flags = segment_info.flags,
});
return index;
} else return result.value_ptr.*;
},
.function => return wasm.code_section_index orelse blk: {
wasm.code_section_index = index;
try wasm.appendDummySegment();
break :blk index;
},
.section => {
const section_name = object.string_table.get(symbol.name);
if (mem.eql(u8, section_name, ".debug_info")) {
return wasm.debug_info_index orelse blk: {
wasm.debug_info_index = index;
try wasm.appendDummySegment();
break :blk index;
};
} else if (mem.eql(u8, section_name, ".debug_line")) {
return wasm.debug_line_index orelse blk: {
wasm.debug_line_index = index;
try wasm.appendDummySegment();
break :blk index;
};
} else if (mem.eql(u8, section_name, ".debug_loc")) {
return wasm.debug_loc_index orelse blk: {
wasm.debug_loc_index = index;
try wasm.appendDummySegment();
break :blk index;
};
} else if (mem.eql(u8, section_name, ".debug_ranges")) {
return wasm.debug_ranges_index orelse blk: {
wasm.debug_ranges_index = index;
try wasm.appendDummySegment();
break :blk index;
};
} else if (mem.eql(u8, section_name, ".debug_pubnames")) {
return wasm.debug_pubnames_index orelse blk: {
wasm.debug_pubnames_index = index;
try wasm.appendDummySegment();
break :blk index;
};
} else if (mem.eql(u8, section_name, ".debug_pubtypes")) {
return wasm.debug_pubtypes_index orelse blk: {
wasm.debug_pubtypes_index = index;
try wasm.appendDummySegment();
break :blk index;
};
} else if (mem.eql(u8, section_name, ".debug_abbrev")) {
return wasm.debug_abbrev_index orelse blk: {
wasm.debug_abbrev_index = index;
try wasm.appendDummySegment();
break :blk index;
};
} else if (mem.eql(u8, section_name, ".debug_str")) {
return wasm.debug_str_index orelse blk: {
wasm.debug_str_index = index;
try wasm.appendDummySegment();
break :blk index;
};
} else {
log.warn("found unknown section '{s}'", .{section_name});
return error.UnexpectedValue;
}
},
else => unreachable,
}
}
/// Appends a new segment with default field values
fn appendDummySegment(wasm: *Wasm) !void {
const gpa = wasm.base.comp.gpa;
try wasm.segments.append(gpa, .{
.alignment = .@"1",
.size = 0,
.offset = 0,
.flags = 0,
});
}
/// Returns the symbol index of the error name table.
///
/// When the symbol does not yet exist, it will create a new one instead.
pub fn getErrorTableSymbol(wasm: *Wasm) !u32 {
if (wasm.error_table_symbol) |symbol| {
return symbol;
}
// no error was referenced yet, so create a new symbol and atom for it
// and then return said symbol's index. The final table will be populated
// during `flush` when we know all possible error names.
const gpa = wasm.base.comp.gpa;
const atom_index = try wasm.createAtom();
const atom = wasm.getAtomPtr(atom_index);
const slice_ty = Type.slice_const_u8_sentinel_0;
const mod = wasm.base.comp.module.?;
atom.alignment = slice_ty.abiAlignment(mod);
const sym_index = atom.sym_index;
const sym_name = try wasm.string_table.put(gpa, "__zig_err_name_table");
const symbol = &wasm.symbols.items[sym_index];
symbol.* = .{
.name = sym_name,
.tag = .data,
.flags = 0,
.index = 0,
.virtual_address = undefined,
};
symbol.setFlag(.WASM_SYM_VISIBILITY_HIDDEN);
symbol.mark();
try wasm.resolved_symbols.put(gpa, atom.symbolLoc(), {});
log.debug("Error name table was created with symbol index: ({d})", .{sym_index});
wasm.error_table_symbol = sym_index;
return sym_index;
}
/// Populates the error name table, when `error_table_symbol` is not null.
///
/// This creates a table that consists of pointers and length to each error name.
/// The table is what is being pointed to within the runtime bodies that are generated.
fn populateErrorNameTable(wasm: *Wasm) !void {
const gpa = wasm.base.comp.gpa;
const symbol_index = wasm.error_table_symbol orelse return;
const atom_index = wasm.symbol_atom.get(.{ .file = null, .index = symbol_index }).?;
// Rather than creating a symbol for each individual error name,
// we create a symbol for the entire region of error names. We then calculate
// the pointers into the list using addends which are appended to the relocation.
const names_atom_index = try wasm.createAtom();
const names_atom = wasm.getAtomPtr(names_atom_index);
names_atom.alignment = .@"1";
const sym_name = try wasm.string_table.put(gpa, "__zig_err_names");
const names_symbol = &wasm.symbols.items[names_atom.sym_index];
names_symbol.* = .{
.name = sym_name,
.tag = .data,
.flags = 0,
.index = 0,
.virtual_address = undefined,
};
names_symbol.setFlag(.WASM_SYM_VISIBILITY_HIDDEN);
names_symbol.mark();
log.debug("Populating error names", .{});
// Addend for each relocation to the table
var addend: u32 = 0;
const mod = wasm.base.comp.module.?;
for (mod.global_error_set.keys()) |error_name_nts| {
const atom = wasm.getAtomPtr(atom_index);
const error_name = mod.intern_pool.stringToSlice(error_name_nts);
const len = @as(u32, @intCast(error_name.len + 1)); // names are 0-termianted
const slice_ty = Type.slice_const_u8_sentinel_0;
const offset = @as(u32, @intCast(atom.code.items.len));
// first we create the data for the slice of the name
try atom.code.appendNTimes(gpa, 0, 4); // ptr to name, will be relocated
try atom.code.writer(gpa).writeInt(u32, len - 1, .little);
// create relocation to the error name
try atom.relocs.append(gpa, .{
.index = names_atom.sym_index,
.relocation_type = .R_WASM_MEMORY_ADDR_I32,
.offset = offset,
.addend = @as(i32, @intCast(addend)),
});
atom.size += @as(u32, @intCast(slice_ty.abiSize(mod)));
addend += len;
// as we updated the error name table, we now store the actual name within the names atom
try names_atom.code.ensureUnusedCapacity(gpa, len);
names_atom.code.appendSliceAssumeCapacity(error_name);
names_atom.code.appendAssumeCapacity(0);
log.debug("Populated error name: '{s}'", .{error_name});
}
names_atom.size = addend;
const name_loc = names_atom.symbolLoc();
try wasm.resolved_symbols.put(gpa, name_loc, {});
try wasm.symbol_atom.put(gpa, name_loc, names_atom_index);
// link the atoms with the rest of the binary so they can be allocated
// and relocations will be performed.
try wasm.parseAtom(atom_index, .{ .data = .read_only });
try wasm.parseAtom(names_atom_index, .{ .data = .read_only });
}
/// From a given index variable, creates a new debug section.
/// This initializes the index, appends a new segment,
/// and finally, creates a managed `Atom`.
pub fn createDebugSectionForIndex(wasm: *Wasm, index: *?u32, name: []const u8) !Atom.Index {
const gpa = wasm.base.comp.gpa;
const new_index: u32 = @intCast(wasm.segments.items.len);
index.* = new_index;
try wasm.appendDummySegment();
const atom_index = try wasm.createAtom();
const atom = wasm.getAtomPtr(atom_index);
wasm.symbols.items[atom.sym_index] = .{
.tag = .section,
.name = try wasm.string_table.put(gpa, name),
.index = 0,
.flags = @intFromEnum(Symbol.Flag.WASM_SYM_BINDING_LOCAL),
};
atom.alignment = .@"1"; // debug sections are always 1-byte-aligned
return atom_index;
}
fn resetState(wasm: *Wasm) void {
const gpa = wasm.base.comp.gpa;
for (wasm.segment_info.values()) |segment_info| {
gpa.free(segment_info.name);
}
var atom_it = wasm.decls.valueIterator();
while (atom_it.next()) |atom_index| {
const atom = wasm.getAtomPtr(atom_index.*);
atom.prev = null;
for (atom.locals.items) |local_atom_index| {
const local_atom = wasm.getAtomPtr(local_atom_index);
local_atom.prev = null;
}
}
wasm.functions.clearRetainingCapacity();
wasm.exports.clearRetainingCapacity();
wasm.segments.clearRetainingCapacity();
wasm.segment_info.clearRetainingCapacity();
wasm.data_segments.clearRetainingCapacity();
wasm.atoms.clearRetainingCapacity();
wasm.symbol_atom.clearRetainingCapacity();
wasm.code_section_index = null;
wasm.debug_info_index = null;
wasm.debug_line_index = null;
wasm.debug_loc_index = null;
wasm.debug_str_index = null;
wasm.debug_ranges_index = null;
wasm.debug_abbrev_index = null;
wasm.debug_pubnames_index = null;
wasm.debug_pubtypes_index = null;
}
pub fn flush(wasm: *Wasm, arena: Allocator, prog_node: *std.Progress.Node) link.File.FlushError!void {
const comp = wasm.base.comp;
const use_lld = build_options.have_llvm and comp.config.use_lld;
const use_llvm = comp.config.use_llvm;
if (use_lld) {
return wasm.linkWithLLD(arena, prog_node);
} else if (use_llvm) {
return wasm.linkWithZld(arena, prog_node);
} else {
return wasm.flushModule(arena, prog_node);
}
}
/// Uses the in-house linker to link one or multiple object -and archive files into a WebAssembly binary.
fn linkWithZld(wasm: *Wasm, arena: Allocator, prog_node: *std.Progress.Node) link.File.FlushError!void {
const tracy = trace(@src());
defer tracy.end();
const comp = wasm.base.comp;
const shared_memory = comp.config.shared_memory;
const import_memory = comp.config.import_memory;
const directory = wasm.base.emit.directory; // Just an alias to make it shorter to type.
const full_out_path = try directory.join(arena, &[_][]const u8{wasm.base.emit.sub_path});
const opt_zcu = comp.module;
const use_llvm = comp.config.use_llvm;
// If there is no Zig code to compile, then we should skip flushing the output file because it
// will not be part of the linker line anyway.
const module_obj_path: ?[]const u8 = if (opt_zcu != null) blk: {
assert(use_llvm); // `linkWithZld` should never be called when the Wasm backend is used
try wasm.flushModule(arena, prog_node);
if (fs.path.dirname(full_out_path)) |dirname| {
break :blk try fs.path.join(arena, &.{ dirname, wasm.base.zcu_object_sub_path.? });
} else {
break :blk wasm.base.zcu_object_sub_path.?;
}
} else null;
var sub_prog_node = prog_node.start("Wasm Flush", 0);
sub_prog_node.activate();
defer sub_prog_node.end();
const compiler_rt_path: ?[]const u8 = blk: {
if (comp.compiler_rt_obj) |obj| break :blk obj.full_object_path;
if (comp.compiler_rt_lib) |lib| break :blk lib.full_object_path;
break :blk null;
};
const id_symlink_basename = "zld.id";
var man: Cache.Manifest = undefined;
defer if (!wasm.base.disable_lld_caching) man.deinit();
var digest: [Cache.hex_digest_len]u8 = undefined;
const objects = comp.objects;
// NOTE: The following section must be maintained to be equal
// as the section defined in `linkWithLLD`
if (!wasm.base.disable_lld_caching) {
man = comp.cache_parent.obtain();
// We are about to obtain this lock, so here we give other processes a chance first.
wasm.base.releaseLock();
comptime assert(Compilation.link_hash_implementation_version == 12);
for (objects) |obj| {
_ = try man.addFile(obj.path, null);
man.hash.add(obj.must_link);
}
for (comp.c_object_table.keys()) |key| {
_ = try man.addFile(key.status.success.object_path, null);
}
try man.addOptionalFile(module_obj_path);
try man.addOptionalFile(compiler_rt_path);
man.hash.addOptionalBytes(wasm.entry_name);
man.hash.add(wasm.base.stack_size);
man.hash.add(wasm.base.build_id);
man.hash.add(import_memory);
man.hash.add(shared_memory);
man.hash.add(wasm.import_table);
man.hash.add(wasm.export_table);
man.hash.addOptional(wasm.initial_memory);
man.hash.addOptional(wasm.max_memory);
man.hash.addOptional(wasm.global_base);
man.hash.add(wasm.export_symbol_names.len);
// strip does not need to go into the linker hash because it is part of the hash namespace
for (wasm.export_symbol_names) |symbol_name| {
man.hash.addBytes(symbol_name);
}
// We don't actually care whether it's a cache hit or miss; we just need the digest and the lock.
_ = try man.hit();
digest = man.final();
var prev_digest_buf: [digest.len]u8 = undefined;
const prev_digest: []u8 = Cache.readSmallFile(
directory.handle,
id_symlink_basename,
&prev_digest_buf,
) catch |err| blk: {
log.debug("WASM LLD new_digest={s} error: {s}", .{ std.fmt.fmtSliceHexLower(&digest), @errorName(err) });
// Handle this as a cache miss.
break :blk prev_digest_buf[0..0];
};
if (mem.eql(u8, prev_digest, &digest)) {
log.debug("WASM LLD digest={s} match - skipping invocation", .{std.fmt.fmtSliceHexLower(&digest)});
// Hot diggity dog! The output binary is already there.
wasm.base.lock = man.toOwnedLock();
return;
}
log.debug("WASM LLD prev_digest={s} new_digest={s}", .{ std.fmt.fmtSliceHexLower(prev_digest), std.fmt.fmtSliceHexLower(&digest) });
// We are about to change the output file to be different, so we invalidate the build hash now.
directory.handle.deleteFile(id_symlink_basename) catch |err| switch (err) {
error.FileNotFound => {},
else => |e| return e,
};
}
// Positional arguments to the linker such as object files and static archives.
var positionals = std.ArrayList([]const u8).init(arena);
try positionals.ensureUnusedCapacity(objects.len);
const target = comp.root_mod.resolved_target.result;
const output_mode = comp.config.output_mode;
const link_mode = comp.config.link_mode;
const link_libc = comp.config.link_libc;
const link_libcpp = comp.config.link_libcpp;
const wasi_exec_model = comp.config.wasi_exec_model;
// When the target os is WASI, we allow linking with WASI-LIBC
if (target.os.tag == .wasi) {
const is_exe_or_dyn_lib = output_mode == .Exe or
(output_mode == .Lib and link_mode == .Dynamic);
if (is_exe_or_dyn_lib) {
for (comp.wasi_emulated_libs) |crt_file| {
try positionals.append(try comp.get_libc_crt_file(
arena,
wasi_libc.emulatedLibCRFileLibName(crt_file),
));
}
if (link_libc) {
try positionals.append(try comp.get_libc_crt_file(
arena,
wasi_libc.execModelCrtFileFullName(wasi_exec_model),
));
try positionals.append(try comp.get_libc_crt_file(arena, "libc.a"));
}
if (link_libcpp) {
try positionals.append(comp.libcxx_static_lib.?.full_object_path);
try positionals.append(comp.libcxxabi_static_lib.?.full_object_path);
}
}
}
if (module_obj_path) |path| {
try positionals.append(path);
}
for (objects) |object| {
try positionals.append(object.path);
}
for (comp.c_object_table.keys()) |c_object| {
try positionals.append(c_object.status.success.object_path);
}
if (comp.compiler_rt_lib) |lib| try positionals.append(lib.full_object_path);
if (comp.compiler_rt_obj) |obj| try positionals.append(obj.full_object_path);
try wasm.parseInputFiles(positionals.items);
for (wasm.objects.items, 0..) |_, object_index| {
try wasm.resolveSymbolsInObject(@as(u16, @intCast(object_index)));
}
var emit_features_count: u32 = 0;
var enabled_features: [@typeInfo(types.Feature.Tag).Enum.fields.len]bool = undefined;
try wasm.validateFeatures(&enabled_features, &emit_features_count);
try wasm.resolveSymbolsInArchives();
try wasm.resolveLazySymbols();
try wasm.checkUndefinedSymbols();
try wasm.setupInitFunctions();
try wasm.setupStart();
try wasm.markReferences();
try wasm.setupImports();
try wasm.mergeSections();
try wasm.mergeTypes();
try wasm.allocateAtoms();
try wasm.setupMemory();
wasm.allocateVirtualAddresses();
wasm.mapFunctionTable();
try wasm.initializeCallCtorsFunction();
try wasm.setupInitMemoryFunction();
try wasm.setupTLSRelocationsFunction();
try wasm.initializeTLSFunction();
try wasm.setupStartSection();
try wasm.setupExports();
try wasm.writeToFile(enabled_features, emit_features_count, arena);
if (!wasm.base.disable_lld_caching) {
// Update the file with the digest. If it fails we can continue; it only
// means that the next invocation will have an unnecessary cache miss.
Cache.writeSmallFile(directory.handle, id_symlink_basename, &digest) catch |err| {
log.warn("failed to save linking hash digest symlink: {s}", .{@errorName(err)});
};
// Again failure here only means an unnecessary cache miss.
man.writeManifest() catch |err| {
log.warn("failed to write cache manifest when linking: {s}", .{@errorName(err)});
};
// We hang on to this lock so that the output file path can be used without
// other processes clobbering it.
wasm.base.lock = man.toOwnedLock();
}
}
pub fn flushModule(wasm: *Wasm, arena: Allocator, prog_node: *std.Progress.Node) link.File.FlushError!void {
const tracy = trace(@src());
defer tracy.end();
const comp = wasm.base.comp;
if (wasm.llvm_object) |llvm_object| {
try wasm.base.emitLlvmObject(arena, llvm_object, prog_node);
return;
}
var sub_prog_node = prog_node.start("Wasm Flush", 0);
sub_prog_node.activate();
defer sub_prog_node.end();
// ensure the error names table is populated when an error name is referenced
try wasm.populateErrorNameTable();
const objects = comp.objects;
// Positional arguments to the linker such as object files and static archives.
var positionals = std.ArrayList([]const u8).init(arena);
try positionals.ensureUnusedCapacity(objects.len);
for (objects) |object| {
positionals.appendAssumeCapacity(object.path);
}
for (comp.c_object_table.keys()) |c_object| {
try positionals.append(c_object.status.success.object_path);
}
if (comp.compiler_rt_lib) |lib| try positionals.append(lib.full_object_path);
if (comp.compiler_rt_obj) |obj| try positionals.append(obj.full_object_path);
try wasm.parseInputFiles(positionals.items);
for (wasm.objects.items, 0..) |_, object_index| {
try wasm.resolveSymbolsInObject(@as(u16, @intCast(object_index)));
}
var emit_features_count: u32 = 0;
var enabled_features: [@typeInfo(types.Feature.Tag).Enum.fields.len]bool = undefined;
try wasm.validateFeatures(&enabled_features, &emit_features_count);
try wasm.resolveSymbolsInArchives();
try wasm.resolveLazySymbols();
try wasm.checkUndefinedSymbols();
// When we finish/error we reset the state of the linker
// So we can rebuild the binary file on each incremental update
defer wasm.resetState();
try wasm.setupInitFunctions();
try wasm.setupStart();
try wasm.markReferences();
try wasm.setupErrorsLen();
try wasm.setupImports();
if (comp.module) |mod| {
var decl_it = wasm.decls.iterator();
while (decl_it.next()) |entry| {
const decl = mod.declPtr(entry.key_ptr.*);
if (decl.isExtern(mod)) continue;
const atom_index = entry.value_ptr.*;
const atom = wasm.getAtomPtr(atom_index);
if (decl.ty.zigTypeTag(mod) == .Fn) {
try wasm.parseAtom(atom_index, .function);
} else if (decl.getOwnedVariable(mod)) |variable| {
if (variable.is_const) {
try wasm.parseAtom(atom_index, .{ .data = .read_only });
} else if (Value.fromInterned(variable.init).isUndefDeep(mod)) {
// for safe build modes, we store the atom in the data segment,
// whereas for unsafe build modes we store it in bss.
const decl_namespace = mod.namespacePtr(decl.src_namespace);
const optimize_mode = decl_namespace.file_scope.mod.optimize_mode;
const is_initialized = switch (optimize_mode) {
.Debug, .ReleaseSafe => true,
.ReleaseFast, .ReleaseSmall => false,
};
try wasm.parseAtom(atom_index, .{ .data = if (is_initialized) .initialized else .uninitialized });
} else {
// when the decl is all zeroes, we store the atom in the bss segment,
// in all other cases it will be in the data segment.
const is_zeroes = for (atom.code.items) |byte| {
if (byte != 0) break false;
} else true;
try wasm.parseAtom(atom_index, .{ .data = if (is_zeroes) .uninitialized else .initialized });
}
} else {
try wasm.parseAtom(atom_index, .{ .data = .read_only });
}
// also parse atoms for a decl's locals
for (atom.locals.items) |local_atom_index| {
try wasm.parseAtom(local_atom_index, .{ .data = .read_only });
}
}
// parse anonymous declarations
for (wasm.anon_decls.keys(), wasm.anon_decls.values()) |decl_val, atom_index| {
const ty = Type.fromInterned(mod.intern_pool.typeOf(decl_val));
if (ty.zigTypeTag(mod) == .Fn) {
try wasm.parseAtom(atom_index, .function);
} else {
try wasm.parseAtom(atom_index, .{ .data = .read_only });
}
}
// also parse any backend-generated functions
for (wasm.synthetic_functions.items) |atom_index| {
try wasm.parseAtom(atom_index, .function);
}
if (wasm.dwarf) |*dwarf| {
try dwarf.flushModule(comp.module.?);
}
}
try wasm.mergeSections();
try wasm.mergeTypes();
try wasm.allocateAtoms();
try wasm.setupMemory();
wasm.allocateVirtualAddresses();
wasm.mapFunctionTable();
try wasm.initializeCallCtorsFunction();
try wasm.setupInitMemoryFunction();
try wasm.setupTLSRelocationsFunction();
try wasm.initializeTLSFunction();
try wasm.setupStartSection();
try wasm.setupExports();
try wasm.writeToFile(enabled_features, emit_features_count, arena);
}
/// Writes the WebAssembly in-memory module to the file
fn writeToFile(
wasm: *Wasm,
enabled_features: [@typeInfo(types.Feature.Tag).Enum.fields.len]bool,
feature_count: u32,
arena: Allocator,
) !void {
const comp = wasm.base.comp;
const gpa = comp.gpa;
const use_llvm = comp.config.use_llvm;
const use_lld = build_options.have_llvm and comp.config.use_lld;
const shared_memory = comp.config.shared_memory;
const import_memory = comp.config.import_memory;
const export_memory = comp.config.export_memory;
// Size of each section header
const header_size = 5 + 1;
// The amount of sections that will be written
var section_count: u32 = 0;
// Index of the code section. Used to tell relocation table where the section lives.
var code_section_index: ?u32 = null;
// Index of the data section. Used to tell relocation table where the section lives.
var data_section_index: ?u32 = null;
const is_obj = comp.config.output_mode == .Obj or (!use_llvm and use_lld);
var binary_bytes = std.ArrayList(u8).init(gpa);
defer binary_bytes.deinit();
const binary_writer = binary_bytes.writer();
// We write the magic bytes at the end so they will only be written
// if everything succeeded as expected. So populate with 0's for now.
try binary_writer.writeAll(&[_]u8{0} ** 8);
// (Re)set file pointer to 0
try wasm.base.file.?.setEndPos(0);
try wasm.base.file.?.seekTo(0);
// Type section
if (wasm.func_types.items.len != 0) {
const header_offset = try reserveVecSectionHeader(&binary_bytes);
log.debug("Writing type section. Count: ({d})", .{wasm.func_types.items.len});
for (wasm.func_types.items) |func_type| {
try leb.writeULEB128(binary_writer, std.wasm.function_type);
try leb.writeULEB128(binary_writer, @as(u32, @intCast(func_type.params.len)));
for (func_type.params) |param_ty| {
try leb.writeULEB128(binary_writer, std.wasm.valtype(param_ty));
}
try leb.writeULEB128(binary_writer, @as(u32, @intCast(func_type.returns.len)));
for (func_type.returns) |ret_ty| {
try leb.writeULEB128(binary_writer, std.wasm.valtype(ret_ty));
}
}
try writeVecSectionHeader(
binary_bytes.items,
header_offset,
.type,
@intCast(binary_bytes.items.len - header_offset - header_size),
@intCast(wasm.func_types.items.len),
);
section_count += 1;
}
// Import section
if (wasm.imports.count() != 0 or import_memory) {
const header_offset = try reserveVecSectionHeader(&binary_bytes);
var it = wasm.imports.iterator();
while (it.next()) |entry| {
assert(entry.key_ptr.*.getSymbol(wasm).isUndefined());
const import = entry.value_ptr.*;
try wasm.emitImport(binary_writer, import);
}
if (import_memory) {
const mem_name = if (is_obj) "__linear_memory" else "memory";
const mem_imp: types.Import = .{
.module_name = try wasm.string_table.put(gpa, wasm.host_name),
.name = try wasm.string_table.put(gpa, mem_name),
.kind = .{ .memory = wasm.memories.limits },
};
try wasm.emitImport(binary_writer, mem_imp);
}
try writeVecSectionHeader(
binary_bytes.items,
header_offset,
.import,
@intCast(binary_bytes.items.len - header_offset - header_size),
@intCast(wasm.imports.count() + @intFromBool(import_memory)),
);
section_count += 1;
}
// Function section
if (wasm.functions.count() != 0) {
const header_offset = try reserveVecSectionHeader(&binary_bytes);
for (wasm.functions.values()) |function| {
try leb.writeULEB128(binary_writer, function.func.type_index);
}
try writeVecSectionHeader(
binary_bytes.items,
header_offset,
.function,
@intCast(binary_bytes.items.len - header_offset - header_size),
@intCast(wasm.functions.count()),
);
section_count += 1;
}
// Table section
if (wasm.tables.items.len > 0) {
const header_offset = try reserveVecSectionHeader(&binary_bytes);
for (wasm.tables.items) |table| {
try leb.writeULEB128(binary_writer, std.wasm.reftype(table.reftype));
try emitLimits(binary_writer, table.limits);
}
try writeVecSectionHeader(
binary_bytes.items,
header_offset,
.table,
@intCast(binary_bytes.items.len - header_offset - header_size),
@intCast(wasm.tables.items.len),
);
section_count += 1;
}
// Memory section
if (!import_memory) {
const header_offset = try reserveVecSectionHeader(&binary_bytes);
try emitLimits(binary_writer, wasm.memories.limits);
try writeVecSectionHeader(
binary_bytes.items,
header_offset,
.memory,
@intCast(binary_bytes.items.len - header_offset - header_size),
1, // wasm currently only supports 1 linear memory segment
);
section_count += 1;
}
// Global section (used to emit stack pointer)
if (wasm.wasm_globals.items.len > 0) {
const header_offset = try reserveVecSectionHeader(&binary_bytes);
for (wasm.wasm_globals.items) |global| {
try binary_writer.writeByte(std.wasm.valtype(global.global_type.valtype));
try binary_writer.writeByte(@intFromBool(global.global_type.mutable));
try emitInit(binary_writer, global.init);
}
try writeVecSectionHeader(
binary_bytes.items,
header_offset,
.global,
@intCast(binary_bytes.items.len - header_offset - header_size),
@intCast(wasm.wasm_globals.items.len),
);
section_count += 1;
}
// Export section
if (wasm.exports.items.len != 0 or export_memory) {
const header_offset = try reserveVecSectionHeader(&binary_bytes);
for (wasm.exports.items) |exp| {
const name = wasm.string_table.get(exp.name);
try leb.writeULEB128(binary_writer, @as(u32, @intCast(name.len)));
try binary_writer.writeAll(name);
try leb.writeULEB128(binary_writer, @intFromEnum(exp.kind));
try leb.writeULEB128(binary_writer, exp.index);
}
if (export_memory) {
try leb.writeULEB128(binary_writer, @as(u32, @intCast("memory".len)));
try binary_writer.writeAll("memory");
try binary_writer.writeByte(std.wasm.externalKind(.memory));
try leb.writeULEB128(binary_writer, @as(u32, 0));
}
try writeVecSectionHeader(
binary_bytes.items,
header_offset,
.@"export",
@intCast(binary_bytes.items.len - header_offset - header_size),
@intCast(wasm.exports.items.len + @intFromBool(export_memory)),
);
section_count += 1;
}
if (wasm.entry) |entry_index| {
const header_offset = try reserveVecSectionHeader(&binary_bytes);
try writeVecSectionHeader(
binary_bytes.items,
header_offset,
.start,
@intCast(binary_bytes.items.len - header_offset - header_size),
entry_index,
);
}
// element section (function table)
if (wasm.function_table.count() > 0) {
const header_offset = try reserveVecSectionHeader(&binary_bytes);
const table_loc = wasm.findGlobalSymbol("__indirect_function_table").?;
const table_sym = table_loc.getSymbol(wasm);
const flags: u32 = if (table_sym.index == 0) 0x0 else 0x02; // passive with implicit 0-index table or set table index manually
try leb.writeULEB128(binary_writer, flags);
if (flags == 0x02) {
try leb.writeULEB128(binary_writer, table_sym.index);
}
try emitInit(binary_writer, .{ .i32_const = 1 }); // We start at index 1, so unresolved function pointers are invalid
if (flags == 0x02) {
try leb.writeULEB128(binary_writer, @as(u8, 0)); // represents funcref
}
try leb.writeULEB128(binary_writer, @as(u32, @intCast(wasm.function_table.count())));
var symbol_it = wasm.function_table.keyIterator();
while (symbol_it.next()) |symbol_loc_ptr| {
const sym = symbol_loc_ptr.*.getSymbol(wasm);
try leb.writeULEB128(binary_writer, sym.index);
}
try writeVecSectionHeader(
binary_bytes.items,
header_offset,
.element,
@intCast(binary_bytes.items.len - header_offset - header_size),
1,
);
section_count += 1;
}
// When the shared-memory option is enabled, we *must* emit the 'data count' section.
const data_segments_count = wasm.data_segments.count() - @intFromBool(wasm.data_segments.contains(".bss") and !import_memory);
if (data_segments_count != 0 and shared_memory) {
const header_offset = try reserveVecSectionHeader(&binary_bytes);
try writeVecSectionHeader(
binary_bytes.items,
header_offset,
.data_count,
@intCast(binary_bytes.items.len - header_offset - header_size),
@intCast(data_segments_count),
);
}
// Code section
if (wasm.code_section_index != null) {
const header_offset = try reserveVecSectionHeader(&binary_bytes);
const start_offset = binary_bytes.items.len - 5; // minus 5 so start offset is 5 to include entry count
var func_it = wasm.functions.iterator();
while (func_it.next()) |entry| {
const sym_loc: SymbolLoc = .{ .index = entry.value_ptr.sym_index, .file = entry.key_ptr.file };
const atom_index = wasm.symbol_atom.get(sym_loc).?;
const atom = wasm.getAtomPtr(atom_index);
if (!is_obj) {
atom.resolveRelocs(wasm);
}
atom.offset = @intCast(binary_bytes.items.len - start_offset);
try leb.writeULEB128(binary_writer, atom.size);
try binary_writer.writeAll(atom.code.items);
}
try writeVecSectionHeader(
binary_bytes.items,
header_offset,
.code,
@intCast(binary_bytes.items.len - header_offset - header_size),
@intCast(wasm.functions.count()),
);
code_section_index = section_count;
section_count += 1;
}
// Data section
if (data_segments_count != 0) {
const header_offset = try reserveVecSectionHeader(&binary_bytes);
var it = wasm.data_segments.iterator();
var segment_count: u32 = 0;
while (it.next()) |entry| {
// do not output 'bss' section unless we import memory and therefore
// want to guarantee the data is zero initialized
if (!import_memory and std.mem.eql(u8, entry.key_ptr.*, ".bss")) continue;
const segment_index = entry.value_ptr.*;
const segment = wasm.segments.items[segment_index];
if (segment.size == 0) continue; // do not emit empty segments
segment_count += 1;
var atom_index = wasm.atoms.get(segment_index).?;
try leb.writeULEB128(binary_writer, segment.flags);
if (segment.flags & @intFromEnum(Wasm.Segment.Flag.WASM_DATA_SEGMENT_HAS_MEMINDEX) != 0) {
try leb.writeULEB128(binary_writer, @as(u32, 0)); // memory is always index 0 as we only have 1 memory entry
}
// when a segment is passive, it's initialized during runtime.
if (!segment.isPassive()) {
try emitInit(binary_writer, .{ .i32_const = @as(i32, @bitCast(segment.offset)) });
}
// offset into data section
try leb.writeULEB128(binary_writer, segment.size);
// fill in the offset table and the data segments
var current_offset: u32 = 0;
while (true) {
const atom = wasm.getAtomPtr(atom_index);
if (!is_obj) {
atom.resolveRelocs(wasm);
}
// Pad with zeroes to ensure all segments are aligned
if (current_offset != atom.offset) {
const diff = atom.offset - current_offset;
try binary_writer.writeByteNTimes(0, diff);
current_offset += diff;
}
assert(current_offset == atom.offset);
assert(atom.code.items.len == atom.size);
try binary_writer.writeAll(atom.code.items);
current_offset += atom.size;
if (atom.prev) |prev| {
atom_index = prev;
} else {
// also pad with zeroes when last atom to ensure
// segments are aligned.
if (current_offset != segment.size) {
try binary_writer.writeByteNTimes(0, segment.size - current_offset);
current_offset += segment.size - current_offset;
}
break;
}
}
assert(current_offset == segment.size);
}
try writeVecSectionHeader(
binary_bytes.items,
header_offset,
.data,
@intCast(binary_bytes.items.len - header_offset - header_size),
@intCast(segment_count),
);
data_section_index = section_count;
section_count += 1;
}
if (is_obj) {
// relocations need to point to the index of a symbol in the final symbol table. To save memory,
// we never store all symbols in a single table, but store a location reference instead.
// This means that for a relocatable object file, we need to generate one and provide it to the relocation sections.
var symbol_table = std.AutoArrayHashMap(SymbolLoc, u32).init(arena);
try wasm.emitLinkSection(&binary_bytes, &symbol_table);
if (code_section_index) |code_index| {
try wasm.emitCodeRelocations(&binary_bytes, code_index, symbol_table);
}
if (data_section_index) |data_index| {
try wasm.emitDataRelocations(&binary_bytes, data_index, symbol_table);
}
} else if (comp.config.debug_format != .strip) {
try wasm.emitNameSection(&binary_bytes, arena);
}
if (comp.config.debug_format != .strip) {
// The build id must be computed on the main sections only,
// so we have to do it now, before the debug sections.
switch (wasm.base.build_id) {
.none => {},
.fast => {
var id: [16]u8 = undefined;
std.crypto.hash.sha3.TurboShake128(null).hash(binary_bytes.items, &id, .{});
var uuid: [36]u8 = undefined;
_ = try std.fmt.bufPrint(&uuid, "{s}-{s}-{s}-{s}-{s}", .{
std.fmt.fmtSliceHexLower(id[0..4]),
std.fmt.fmtSliceHexLower(id[4..6]),
std.fmt.fmtSliceHexLower(id[6..8]),
std.fmt.fmtSliceHexLower(id[8..10]),
std.fmt.fmtSliceHexLower(id[10..]),
});
try emitBuildIdSection(&binary_bytes, &uuid);
},
.hexstring => |hs| {
var buffer: [32 * 2]u8 = undefined;
const str = std.fmt.bufPrint(&buffer, "{s}", .{
std.fmt.fmtSliceHexLower(hs.toSlice()),
}) catch unreachable;
try emitBuildIdSection(&binary_bytes, str);
},
else => |mode| log.err("build-id '{s}' is not supported for WASM", .{@tagName(mode)}),
}
// if (wasm.dwarf) |*dwarf| {
// const mod = comp.module.?;
// try dwarf.writeDbgAbbrev();
// // for debug info and ranges, the address is always 0,
// // as locations are always offsets relative to 'code' section.
// try dwarf.writeDbgInfoHeader(mod, 0, code_section_size);
// try dwarf.writeDbgAranges(0, code_section_size);
// try dwarf.writeDbgLineHeader();
// }
var debug_bytes = std.ArrayList(u8).init(gpa);
defer debug_bytes.deinit();
const DebugSection = struct {
name: []const u8,
index: ?u32,
};
const debug_sections: []const DebugSection = &.{
.{ .name = ".debug_info", .index = wasm.debug_info_index },
.{ .name = ".debug_pubtypes", .index = wasm.debug_pubtypes_index },
.{ .name = ".debug_abbrev", .index = wasm.debug_abbrev_index },
.{ .name = ".debug_line", .index = wasm.debug_line_index },
.{ .name = ".debug_str", .index = wasm.debug_str_index },
.{ .name = ".debug_pubnames", .index = wasm.debug_pubnames_index },
.{ .name = ".debug_loc", .index = wasm.debug_loc_index },
.{ .name = ".debug_ranges", .index = wasm.debug_ranges_index },
};
for (debug_sections) |item| {
if (item.index) |index| {
var atom = wasm.getAtomPtr(wasm.atoms.get(index).?);
while (true) {
atom.resolveRelocs(wasm);
try debug_bytes.appendSlice(atom.code.items);
atom = if (atom.prev) |prev| wasm.getAtomPtr(prev) else break;
}
try emitDebugSection(&binary_bytes, debug_bytes.items, item.name);
debug_bytes.clearRetainingCapacity();
}
}
try emitProducerSection(&binary_bytes);
if (feature_count > 0) {
try emitFeaturesSection(&binary_bytes, &enabled_features, feature_count);
}
}
// Only when writing all sections executed properly we write the magic
// bytes. This allows us to easily detect what went wrong while generating
// the final binary.
{
const src = std.wasm.magic ++ std.wasm.version;
binary_bytes.items[0..src.len].* = src;
}
// finally, write the entire binary into the file.
var iovec = [_]std.os.iovec_const{.{
.iov_base = binary_bytes.items.ptr,
.iov_len = binary_bytes.items.len,
}};
try wasm.base.file.?.writevAll(&iovec);
}
fn emitDebugSection(binary_bytes: *std.ArrayList(u8), data: []const u8, name: []const u8) !void {
if (data.len == 0) return;
const header_offset = try reserveCustomSectionHeader(binary_bytes);
const writer = binary_bytes.writer();
try leb.writeULEB128(writer, @as(u32, @intCast(name.len)));
try writer.writeAll(name);
const start = binary_bytes.items.len - header_offset;
log.debug("Emit debug section: '{s}' start=0x{x:0>8} end=0x{x:0>8}", .{ name, start, start + data.len });
try writer.writeAll(data);
try writeCustomSectionHeader(
binary_bytes.items,
header_offset,
@as(u32, @intCast(binary_bytes.items.len - header_offset - 6)),
);
}
fn emitProducerSection(binary_bytes: *std.ArrayList(u8)) !void {
const header_offset = try reserveCustomSectionHeader(binary_bytes);
const writer = binary_bytes.writer();
const producers = "producers";
try leb.writeULEB128(writer, @as(u32, @intCast(producers.len)));
try writer.writeAll(producers);
try leb.writeULEB128(writer, @as(u32, 2)); // 2 fields: Language + processed-by
// used for the Zig version
var version_buf: [100]u8 = undefined;
const version = try std.fmt.bufPrint(&version_buf, "{}", .{build_options.semver});
// language field
{
const language = "language";
try leb.writeULEB128(writer, @as(u32, @intCast(language.len)));
try writer.writeAll(language);
// field_value_count (TODO: Parse object files for producer sections to detect their language)
try leb.writeULEB128(writer, @as(u32, 1));
// versioned name
{
try leb.writeULEB128(writer, @as(u32, 3)); // len of "Zig"
try writer.writeAll("Zig");
try leb.writeULEB128(writer, @as(u32, @intCast(version.len)));
try writer.writeAll(version);
}
}
// processed-by field
{
const processed_by = "processed-by";
try leb.writeULEB128(writer, @as(u32, @intCast(processed_by.len)));
try writer.writeAll(processed_by);
// field_value_count (TODO: Parse object files for producer sections to detect other used tools)
try leb.writeULEB128(writer, @as(u32, 1));
// versioned name
{
try leb.writeULEB128(writer, @as(u32, 3)); // len of "Zig"
try writer.writeAll("Zig");
try leb.writeULEB128(writer, @as(u32, @intCast(version.len)));
try writer.writeAll(version);
}
}
try writeCustomSectionHeader(
binary_bytes.items,
header_offset,
@as(u32, @intCast(binary_bytes.items.len - header_offset - 6)),
);
}
fn emitBuildIdSection(binary_bytes: *std.ArrayList(u8), build_id: []const u8) !void {
const header_offset = try reserveCustomSectionHeader(binary_bytes);
const writer = binary_bytes.writer();
const hdr_build_id = "build_id";
try leb.writeULEB128(writer, @as(u32, @intCast(hdr_build_id.len)));
try writer.writeAll(hdr_build_id);
try leb.writeULEB128(writer, @as(u32, 1));
try leb.writeULEB128(writer, @as(u32, @intCast(build_id.len)));
try writer.writeAll(build_id);
try writeCustomSectionHeader(
binary_bytes.items,
header_offset,
@as(u32, @intCast(binary_bytes.items.len - header_offset - 6)),
);
}
fn emitFeaturesSection(binary_bytes: *std.ArrayList(u8), enabled_features: []const bool, features_count: u32) !void {
const header_offset = try reserveCustomSectionHeader(binary_bytes);
const writer = binary_bytes.writer();
const target_features = "target_features";
try leb.writeULEB128(writer, @as(u32, @intCast(target_features.len)));
try writer.writeAll(target_features);
try leb.writeULEB128(writer, features_count);
for (enabled_features, 0..) |enabled, feature_index| {
if (enabled) {
const feature: types.Feature = .{ .prefix = .used, .tag = @as(types.Feature.Tag, @enumFromInt(feature_index)) };
try leb.writeULEB128(writer, @intFromEnum(feature.prefix));
var buf: [100]u8 = undefined;
const string = try std.fmt.bufPrint(&buf, "{}", .{feature.tag});
try leb.writeULEB128(writer, @as(u32, @intCast(string.len)));
try writer.writeAll(string);
}
}
try writeCustomSectionHeader(
binary_bytes.items,
header_offset,
@as(u32, @intCast(binary_bytes.items.len - header_offset - 6)),
);
}
fn emitNameSection(wasm: *Wasm, binary_bytes: *std.ArrayList(u8), arena: std.mem.Allocator) !void {
const comp = wasm.base.comp;
const import_memory = comp.config.import_memory;
const Name = struct {
index: u32,
name: []const u8,
fn lessThan(context: void, lhs: @This(), rhs: @This()) bool {
_ = context;
return lhs.index < rhs.index;
}
};
// we must de-duplicate symbols that point to the same function
var funcs = std.AutoArrayHashMap(u32, Name).init(arena);
try funcs.ensureUnusedCapacity(wasm.functions.count() + wasm.imported_functions_count);
var globals = try std.ArrayList(Name).initCapacity(arena, wasm.wasm_globals.items.len + wasm.imported_globals_count);
var segments = try std.ArrayList(Name).initCapacity(arena, wasm.data_segments.count());
for (wasm.resolved_symbols.keys()) |sym_loc| {
const symbol = sym_loc.getSymbol(wasm).*;
if (symbol.isDead()) {
continue;
}
const name = sym_loc.getName(wasm);
switch (symbol.tag) {
.function => {
const gop = funcs.getOrPutAssumeCapacity(symbol.index);
if (!gop.found_existing) {
gop.value_ptr.* = .{ .index = symbol.index, .name = name };
}
},
.global => globals.appendAssumeCapacity(.{ .index = symbol.index, .name = name }),
else => {},
}
}
// data segments are already 'ordered'
var data_segment_index: u32 = 0;
for (wasm.data_segments.keys()) |key| {
// bss section is not emitted when this condition holds true, so we also
// do not output a name for it.
if (!import_memory and std.mem.eql(u8, key, ".bss")) continue;
segments.appendAssumeCapacity(.{ .index = data_segment_index, .name = key });
data_segment_index += 1;
}
mem.sort(Name, funcs.values(), {}, Name.lessThan);
mem.sort(Name, globals.items, {}, Name.lessThan);
const header_offset = try reserveCustomSectionHeader(binary_bytes);
const writer = binary_bytes.writer();
try leb.writeULEB128(writer, @as(u32, @intCast("name".len)));
try writer.writeAll("name");
try wasm.emitNameSubsection(.function, funcs.values(), writer);
try wasm.emitNameSubsection(.global, globals.items, writer);
try wasm.emitNameSubsection(.data_segment, segments.items, writer);
try writeCustomSectionHeader(
binary_bytes.items,
header_offset,
@as(u32, @intCast(binary_bytes.items.len - header_offset - 6)),
);
}
fn emitNameSubsection(wasm: *Wasm, section_id: std.wasm.NameSubsection, names: anytype, writer: anytype) !void {
const gpa = wasm.base.comp.gpa;
// We must emit subsection size, so first write to a temporary list
var section_list = std.ArrayList(u8).init(gpa);
defer section_list.deinit();
const sub_writer = section_list.writer();
try leb.writeULEB128(sub_writer, @as(u32, @intCast(names.len)));
for (names) |name| {
log.debug("Emit symbol '{s}' type({s})", .{ name.name, @tagName(section_id) });
try leb.writeULEB128(sub_writer, name.index);
try leb.writeULEB128(sub_writer, @as(u32, @intCast(name.name.len)));
try sub_writer.writeAll(name.name);
}
// From now, write to the actual writer
try leb.writeULEB128(writer, @intFromEnum(section_id));
try leb.writeULEB128(writer, @as(u32, @intCast(section_list.items.len)));
try writer.writeAll(section_list.items);
}
fn emitLimits(writer: anytype, limits: std.wasm.Limits) !void {
try writer.writeByte(limits.flags);
try leb.writeULEB128(writer, limits.min);
if (limits.hasFlag(.WASM_LIMITS_FLAG_HAS_MAX)) {
try leb.writeULEB128(writer, limits.max);
}
}
fn emitInit(writer: anytype, init_expr: std.wasm.InitExpression) !void {
switch (init_expr) {
.i32_const => |val| {
try writer.writeByte(std.wasm.opcode(.i32_const));
try leb.writeILEB128(writer, val);
},
.i64_const => |val| {
try writer.writeByte(std.wasm.opcode(.i64_const));
try leb.writeILEB128(writer, val);
},
.f32_const => |val| {
try writer.writeByte(std.wasm.opcode(.f32_const));
try writer.writeInt(u32, @bitCast(val), .little);
},
.f64_const => |val| {
try writer.writeByte(std.wasm.opcode(.f64_const));
try writer.writeInt(u64, @bitCast(val), .little);
},
.global_get => |val| {
try writer.writeByte(std.wasm.opcode(.global_get));
try leb.writeULEB128(writer, val);
},
}
try writer.writeByte(std.wasm.opcode(.end));
}
fn emitImport(wasm: *Wasm, writer: anytype, import: types.Import) !void {
const module_name = wasm.string_table.get(import.module_name);
try leb.writeULEB128(writer, @as(u32, @intCast(module_name.len)));
try writer.writeAll(module_name);
const name = wasm.string_table.get(import.name);
try leb.writeULEB128(writer, @as(u32, @intCast(name.len)));
try writer.writeAll(name);
try writer.writeByte(@intFromEnum(import.kind));
switch (import.kind) {
.function => |type_index| try leb.writeULEB128(writer, type_index),
.global => |global_type| {
try leb.writeULEB128(writer, std.wasm.valtype(global_type.valtype));
try writer.writeByte(@intFromBool(global_type.mutable));
},
.table => |table| {
try leb.writeULEB128(writer, std.wasm.reftype(table.reftype));
try emitLimits(writer, table.limits);
},
.memory => |limits| {
try emitLimits(writer, limits);
},
}
}
fn linkWithLLD(wasm: *Wasm, arena: Allocator, prog_node: *std.Progress.Node) !void {
const tracy = trace(@src());
defer tracy.end();
const comp = wasm.base.comp;
const shared_memory = comp.config.shared_memory;
const export_memory = comp.config.export_memory;
const import_memory = comp.config.import_memory;
const target = comp.root_mod.resolved_target.result;
const gpa = comp.gpa;
const directory = wasm.base.emit.directory; // Just an alias to make it shorter to type.
const full_out_path = try directory.join(arena, &[_][]const u8{wasm.base.emit.sub_path});
// If there is no Zig code to compile, then we should skip flushing the output file because it
// will not be part of the linker line anyway.
const module_obj_path: ?[]const u8 = if (comp.module != null) blk: {
try wasm.flushModule(arena, prog_node);
if (fs.path.dirname(full_out_path)) |dirname| {
break :blk try fs.path.join(arena, &.{ dirname, wasm.base.zcu_object_sub_path.? });
} else {
break :blk wasm.base.zcu_object_sub_path.?;
}
} else null;
var sub_prog_node = prog_node.start("LLD Link", 0);
sub_prog_node.activate();
sub_prog_node.context.refresh();
defer sub_prog_node.end();
const is_obj = comp.config.output_mode == .Obj;
const compiler_rt_path: ?[]const u8 = blk: {
if (comp.compiler_rt_lib) |lib| break :blk lib.full_object_path;
if (comp.compiler_rt_obj) |obj| break :blk obj.full_object_path;
break :blk null;
};
const id_symlink_basename = "lld.id";
var man: Cache.Manifest = undefined;
defer if (!wasm.base.disable_lld_caching) man.deinit();
var digest: [Cache.hex_digest_len]u8 = undefined;
if (!wasm.base.disable_lld_caching) {
man = comp.cache_parent.obtain();
// We are about to obtain this lock, so here we give other processes a chance first.
wasm.base.releaseLock();
comptime assert(Compilation.link_hash_implementation_version == 12);
for (comp.objects) |obj| {
_ = try man.addFile(obj.path, null);
man.hash.add(obj.must_link);
}
for (comp.c_object_table.keys()) |key| {
_ = try man.addFile(key.status.success.object_path, null);
}
try man.addOptionalFile(module_obj_path);
try man.addOptionalFile(compiler_rt_path);
man.hash.addOptionalBytes(wasm.entry_name);
man.hash.add(wasm.base.stack_size);
man.hash.add(wasm.base.build_id);
man.hash.add(import_memory);
man.hash.add(export_memory);
man.hash.add(wasm.import_table);
man.hash.add(wasm.export_table);
man.hash.addOptional(wasm.initial_memory);
man.hash.addOptional(wasm.max_memory);
man.hash.add(shared_memory);
man.hash.addOptional(wasm.global_base);
man.hash.add(wasm.export_symbol_names.len);
// strip does not need to go into the linker hash because it is part of the hash namespace
for (wasm.export_symbol_names) |symbol_name| {
man.hash.addBytes(symbol_name);
}
// We don't actually care whether it's a cache hit or miss; we just need the digest and the lock.
_ = try man.hit();
digest = man.final();
var prev_digest_buf: [digest.len]u8 = undefined;
const prev_digest: []u8 = Cache.readSmallFile(
directory.handle,
id_symlink_basename,
&prev_digest_buf,
) catch |err| blk: {
log.debug("WASM LLD new_digest={s} error: {s}", .{ std.fmt.fmtSliceHexLower(&digest), @errorName(err) });
// Handle this as a cache miss.
break :blk prev_digest_buf[0..0];
};
if (mem.eql(u8, prev_digest, &digest)) {
log.debug("WASM LLD digest={s} match - skipping invocation", .{std.fmt.fmtSliceHexLower(&digest)});
// Hot diggity dog! The output binary is already there.
wasm.base.lock = man.toOwnedLock();
return;
}
log.debug("WASM LLD prev_digest={s} new_digest={s}", .{ std.fmt.fmtSliceHexLower(prev_digest), std.fmt.fmtSliceHexLower(&digest) });
// We are about to change the output file to be different, so we invalidate the build hash now.
directory.handle.deleteFile(id_symlink_basename) catch |err| switch (err) {
error.FileNotFound => {},
else => |e| return e,
};
}
if (is_obj) {
// LLD's WASM driver does not support the equivalent of `-r` so we do a simple file copy
// here. TODO: think carefully about how we can avoid this redundant operation when doing
// build-obj. See also the corresponding TODO in linkAsArchive.
const the_object_path = blk: {
if (comp.objects.len != 0)
break :blk comp.objects[0].path;
if (comp.c_object_table.count() != 0)
break :blk comp.c_object_table.keys()[0].status.success.object_path;
if (module_obj_path) |p|
break :blk p;
// TODO I think this is unreachable. Audit this situation when solving the above TODO
// regarding eliding redundant object -> object transformations.
return error.NoObjectsToLink;
};
// This can happen when using --enable-cache and using the stage1 backend. In this case
// we can skip the file copy.
if (!mem.eql(u8, the_object_path, full_out_path)) {
try fs.cwd().copyFile(the_object_path, fs.cwd(), full_out_path, .{});
}
} else {
// Create an LLD command line and invoke it.
var argv = std.ArrayList([]const u8).init(gpa);
defer argv.deinit();
// We will invoke ourselves as a child process to gain access to LLD.
// This is necessary because LLD does not behave properly as a library -
// it calls exit() and does not reset all global data between invocations.
const linker_command = "wasm-ld";
try argv.appendSlice(&[_][]const u8{ comp.self_exe_path.?, linker_command });
try argv.append("--error-limit=0");
if (comp.config.lto) {
switch (comp.root_mod.optimize_mode) {
.Debug => {},
.ReleaseSmall => try argv.append("-O2"),
.ReleaseFast, .ReleaseSafe => try argv.append("-O3"),
}
}
if (import_memory) {
try argv.append("--import-memory");
}
if (export_memory) {
try argv.append("--export-memory");
}
if (wasm.import_table) {
assert(!wasm.export_table);
try argv.append("--import-table");
}
if (wasm.export_table) {
assert(!wasm.import_table);
try argv.append("--export-table");
}
// For wasm-ld we only need to specify '--no-gc-sections' when the user explicitly
// specified it as garbage collection is enabled by default.
if (!wasm.base.gc_sections) {
try argv.append("--no-gc-sections");
}
if (comp.config.debug_format == .strip) {
try argv.append("-s");
}
if (wasm.initial_memory) |initial_memory| {
const arg = try std.fmt.allocPrint(arena, "--initial-memory={d}", .{initial_memory});
try argv.append(arg);
}
if (wasm.max_memory) |max_memory| {
const arg = try std.fmt.allocPrint(arena, "--max-memory={d}", .{max_memory});
try argv.append(arg);
}
if (shared_memory) {
try argv.append("--shared-memory");
}
if (wasm.global_base) |global_base| {
const arg = try std.fmt.allocPrint(arena, "--global-base={d}", .{global_base});
try argv.append(arg);
} else {
// We prepend it by default, so when a stack overflow happens the runtime will trap correctly,
// rather than silently overwrite all global declarations. See https://github.com/ziglang/zig/issues/4496
//
// The user can overwrite this behavior by setting the global-base
try argv.append("--stack-first");
}
// Users are allowed to specify which symbols they want to export to the wasm host.
for (wasm.export_symbol_names) |symbol_name| {
const arg = try std.fmt.allocPrint(arena, "--export={s}", .{symbol_name});
try argv.append(arg);
}
if (comp.config.rdynamic) {
try argv.append("--export-dynamic");
}
if (wasm.entry_name) |entry_name| {
try argv.appendSlice(&.{ "--entry", entry_name });
} else {
try argv.append("--no-entry");
}
try argv.appendSlice(&.{
"-z",
try std.fmt.allocPrint(arena, "stack-size={d}", .{wasm.base.stack_size}),
});
if (wasm.import_symbols) {
try argv.append("--allow-undefined");
}
if (comp.config.output_mode == .Lib and comp.config.link_mode == .Dynamic) {
try argv.append("--shared");
}
if (comp.config.pie) {
try argv.append("--pie");
}
// XXX - TODO: add when wasm-ld supports --build-id.
// if (wasm.base.build_id) {
// try argv.append("--build-id=tree");
// }
try argv.appendSlice(&.{ "-o", full_out_path });
if (target.cpu.arch == .wasm64) {
try argv.append("-mwasm64");
}
if (target.os.tag == .wasi) {
const is_exe_or_dyn_lib = comp.config.output_mode == .Exe or
(comp.config.output_mode == .Lib and comp.config.link_mode == .Dynamic);
if (is_exe_or_dyn_lib) {
for (comp.wasi_emulated_libs) |crt_file| {
try argv.append(try comp.get_libc_crt_file(
arena,
wasi_libc.emulatedLibCRFileLibName(crt_file),
));
}
if (comp.config.link_libc) {
try argv.append(try comp.get_libc_crt_file(
arena,
wasi_libc.execModelCrtFileFullName(comp.config.wasi_exec_model),
));
try argv.append(try comp.get_libc_crt_file(arena, "libc.a"));
}
if (comp.config.link_libcpp) {
try argv.append(comp.libcxx_static_lib.?.full_object_path);
try argv.append(comp.libcxxabi_static_lib.?.full_object_path);
}
}
}
// Positional arguments to the linker such as object files.
var whole_archive = false;
for (comp.objects) |obj| {
if (obj.must_link and !whole_archive) {
try argv.append("-whole-archive");
whole_archive = true;
} else if (!obj.must_link and whole_archive) {
try argv.append("-no-whole-archive");
whole_archive = false;
}
try argv.append(obj.path);
}
if (whole_archive) {
try argv.append("-no-whole-archive");
whole_archive = false;
}
for (comp.c_object_table.keys()) |key| {
try argv.append(key.status.success.object_path);
}
if (module_obj_path) |p| {
try argv.append(p);
}
if (comp.config.output_mode != .Obj and
!comp.skip_linker_dependencies and
!comp.config.link_libc)
{
try argv.append(comp.libc_static_lib.?.full_object_path);
}
if (compiler_rt_path) |p| {
try argv.append(p);
}
if (comp.verbose_link) {
// Skip over our own name so that the LLD linker name is the first argv item.
Compilation.dump_argv(argv.items[1..]);
}
if (std.process.can_spawn) {
// If possible, we run LLD as a child process because it does not always
// behave properly as a library, unfortunately.
// https://github.com/ziglang/zig/issues/3825
var child = std.ChildProcess.init(argv.items, arena);
if (comp.clang_passthrough_mode) {
child.stdin_behavior = .Inherit;
child.stdout_behavior = .Inherit;
child.stderr_behavior = .Inherit;
const term = child.spawnAndWait() catch |err| {
log.err("unable to spawn {s}: {s}", .{ argv.items[0], @errorName(err) });
return error.UnableToSpawnWasm;
};
switch (term) {
.Exited => |code| {
if (code != 0) {
std.process.exit(code);
}
},
else => std.process.abort(),
}
} else {
child.stdin_behavior = .Ignore;
child.stdout_behavior = .Ignore;
child.stderr_behavior = .Pipe;
try child.spawn();
const stderr = try child.stderr.?.reader().readAllAlloc(arena, std.math.maxInt(usize));
const term = child.wait() catch |err| {
log.err("unable to spawn {s}: {s}", .{ argv.items[0], @errorName(err) });
return error.UnableToSpawnWasm;
};
switch (term) {
.Exited => |code| {
if (code != 0) {
comp.lockAndParseLldStderr(linker_command, stderr);
return error.LLDReportedFailure;
}
},
else => {
log.err("{s} terminated with stderr:\n{s}", .{ argv.items[0], stderr });
return error.LLDCrashed;
},
}
if (stderr.len != 0) {
log.warn("unexpected LLD stderr:\n{s}", .{stderr});
}
}
} else {
const exit_code = try lldMain(arena, argv.items, false);
if (exit_code != 0) {
if (comp.clang_passthrough_mode) {
std.process.exit(exit_code);
} else {
return error.LLDReportedFailure;
}
}
}
// Give +x to the .wasm file if it is an executable and the OS is WASI.
// Some systems may be configured to execute such binaries directly. Even if that
// is not the case, it means we will get "exec format error" when trying to run
// it, and then can react to that in the same way as trying to run an ELF file
// from a foreign CPU architecture.
if (fs.has_executable_bit and target.os.tag == .wasi and
comp.config.output_mode == .Exe)
{
// TODO: what's our strategy for reporting linker errors from this function?
// report a nice error here with the file path if it fails instead of
// just returning the error code.
// chmod does not interact with umask, so we use a conservative -rwxr--r-- here.
std.os.fchmodat(fs.cwd().fd, full_out_path, 0o744, 0) catch |err| switch (err) {
error.OperationNotSupported => unreachable, // Not a symlink.
else => |e| return e,
};
}
}
if (!wasm.base.disable_lld_caching) {
// Update the file with the digest. If it fails we can continue; it only
// means that the next invocation will have an unnecessary cache miss.
Cache.writeSmallFile(directory.handle, id_symlink_basename, &digest) catch |err| {
log.warn("failed to save linking hash digest symlink: {s}", .{@errorName(err)});
};
// Again failure here only means an unnecessary cache miss.
man.writeManifest() catch |err| {
log.warn("failed to write cache manifest when linking: {s}", .{@errorName(err)});
};
// We hang on to this lock so that the output file path can be used without
// other processes clobbering it.
wasm.base.lock = man.toOwnedLock();
}
}
fn reserveVecSectionHeader(bytes: *std.ArrayList(u8)) !u32 {
// section id + fixed leb contents size + fixed leb vector length
const header_size = 1 + 5 + 5;
const offset = @as(u32, @intCast(bytes.items.len));
try bytes.appendSlice(&[_]u8{0} ** header_size);
return offset;
}
fn reserveCustomSectionHeader(bytes: *std.ArrayList(u8)) !u32 {
// unlike regular section, we don't emit the count
const header_size = 1 + 5;
const offset = @as(u32, @intCast(bytes.items.len));
try bytes.appendSlice(&[_]u8{0} ** header_size);
return offset;
}
fn writeVecSectionHeader(buffer: []u8, offset: u32, section: std.wasm.Section, size: u32, items: u32) !void {
var buf: [1 + 5 + 5]u8 = undefined;
buf[0] = @intFromEnum(section);
leb.writeUnsignedFixed(5, buf[1..6], size);
leb.writeUnsignedFixed(5, buf[6..], items);
buffer[offset..][0..buf.len].* = buf;
}
fn writeCustomSectionHeader(buffer: []u8, offset: u32, size: u32) !void {
var buf: [1 + 5]u8 = undefined;
buf[0] = 0; // 0 = 'custom' section
leb.writeUnsignedFixed(5, buf[1..6], size);
buffer[offset..][0..buf.len].* = buf;
}
fn emitLinkSection(wasm: *Wasm, binary_bytes: *std.ArrayList(u8), symbol_table: *std.AutoArrayHashMap(SymbolLoc, u32)) !void {
const offset = try reserveCustomSectionHeader(binary_bytes);
const writer = binary_bytes.writer();
// emit "linking" custom section name
const section_name = "linking";
try leb.writeULEB128(writer, section_name.len);
try writer.writeAll(section_name);
// meta data version, which is currently '2'
try leb.writeULEB128(writer, @as(u32, 2));
// For each subsection type (found in types.Subsection) we can emit a section.
// Currently, we only support emitting segment info and the symbol table.
try wasm.emitSymbolTable(binary_bytes, symbol_table);
try wasm.emitSegmentInfo(binary_bytes);
const size: u32 = @intCast(binary_bytes.items.len - offset - 6);
try writeCustomSectionHeader(binary_bytes.items, offset, size);
}
fn emitSymbolTable(wasm: *Wasm, binary_bytes: *std.ArrayList(u8), symbol_table: *std.AutoArrayHashMap(SymbolLoc, u32)) !void {
const writer = binary_bytes.writer();
try leb.writeULEB128(writer, @intFromEnum(types.SubsectionType.WASM_SYMBOL_TABLE));
const table_offset = binary_bytes.items.len;
var symbol_count: u32 = 0;
for (wasm.resolved_symbols.keys()) |sym_loc| {
const symbol = sym_loc.getSymbol(wasm).*;
if (symbol.tag == .dead) continue; // Do not emit dead symbols
try symbol_table.putNoClobber(sym_loc, symbol_count);
symbol_count += 1;
log.debug("Emit symbol: {}", .{symbol});
try leb.writeULEB128(writer, @intFromEnum(symbol.tag));
try leb.writeULEB128(writer, symbol.flags);
const sym_name = if (wasm.export_names.get(sym_loc)) |exp_name| wasm.string_table.get(exp_name) else sym_loc.getName(wasm);
switch (symbol.tag) {
.data => {
try leb.writeULEB128(writer, @as(u32, @intCast(sym_name.len)));
try writer.writeAll(sym_name);
if (symbol.isDefined()) {
try leb.writeULEB128(writer, symbol.index);
const atom_index = wasm.symbol_atom.get(sym_loc).?;
const atom = wasm.getAtom(atom_index);
try leb.writeULEB128(writer, @as(u32, atom.offset));
try leb.writeULEB128(writer, @as(u32, atom.size));
}
},
.section => {
try leb.writeULEB128(writer, symbol.index);
},
else => {
try leb.writeULEB128(writer, symbol.index);
if (symbol.isDefined()) {
try leb.writeULEB128(writer, @as(u32, @intCast(sym_name.len)));
try writer.writeAll(sym_name);
}
},
}
}
var buf: [10]u8 = undefined;
leb.writeUnsignedFixed(5, buf[0..5], @intCast(binary_bytes.items.len - table_offset + 5));
leb.writeUnsignedFixed(5, buf[5..], symbol_count);
try binary_bytes.insertSlice(table_offset, &buf);
}
fn emitSegmentInfo(wasm: *Wasm, binary_bytes: *std.ArrayList(u8)) !void {
const writer = binary_bytes.writer();
try leb.writeULEB128(writer, @intFromEnum(types.SubsectionType.WASM_SEGMENT_INFO));
const segment_offset = binary_bytes.items.len;
try leb.writeULEB128(writer, @as(u32, @intCast(wasm.segment_info.count())));
for (wasm.segment_info.values()) |segment_info| {
log.debug("Emit segment: {s} align({d}) flags({b})", .{
segment_info.name,
segment_info.alignment,
segment_info.flags,
});
try leb.writeULEB128(writer, @as(u32, @intCast(segment_info.name.len)));
try writer.writeAll(segment_info.name);
try leb.writeULEB128(writer, segment_info.alignment.toLog2Units());
try leb.writeULEB128(writer, segment_info.flags);
}
var buf: [5]u8 = undefined;
leb.writeUnsignedFixed(5, &buf, @as(u32, @intCast(binary_bytes.items.len - segment_offset)));
try binary_bytes.insertSlice(segment_offset, &buf);
}
pub fn getULEB128Size(uint_value: anytype) u32 {
const T = @TypeOf(uint_value);
const U = if (@typeInfo(T).Int.bits < 8) u8 else T;
var value = @as(U, @intCast(uint_value));
var size: u32 = 0;
while (value != 0) : (size += 1) {
value >>= 7;
}
return size;
}
/// For each relocatable section, emits a custom "relocation.<section_name>" section
fn emitCodeRelocations(
wasm: *Wasm,
binary_bytes: *std.ArrayList(u8),
section_index: u32,
symbol_table: std.AutoArrayHashMap(SymbolLoc, u32),
) !void {
const code_index = wasm.code_section_index orelse return;
const writer = binary_bytes.writer();
const header_offset = try reserveCustomSectionHeader(binary_bytes);
// write custom section information
const name = "reloc.CODE";
try leb.writeULEB128(writer, @as(u32, @intCast(name.len)));
try writer.writeAll(name);
try leb.writeULEB128(writer, section_index);
const reloc_start = binary_bytes.items.len;
var count: u32 = 0;
var atom: *Atom = wasm.getAtomPtr(wasm.atoms.get(code_index).?);
// for each atom, we calculate the uleb size and append that
var size_offset: u32 = 5; // account for code section size leb128
while (true) {
size_offset += getULEB128Size(atom.size);
for (atom.relocs.items) |relocation| {
count += 1;
const sym_loc: SymbolLoc = .{ .file = atom.file, .index = relocation.index };
const symbol_index = symbol_table.get(sym_loc).?;
try leb.writeULEB128(writer, @intFromEnum(relocation.relocation_type));
const offset = atom.offset + relocation.offset + size_offset;
try leb.writeULEB128(writer, offset);
try leb.writeULEB128(writer, symbol_index);
if (relocation.relocation_type.addendIsPresent()) {
try leb.writeILEB128(writer, relocation.addend);
}
log.debug("Emit relocation: {}", .{relocation});
}
atom = if (atom.prev) |prev| wasm.getAtomPtr(prev) else break;
}
if (count == 0) return;
var buf: [5]u8 = undefined;
leb.writeUnsignedFixed(5, &buf, count);
try binary_bytes.insertSlice(reloc_start, &buf);
const size: u32 = @intCast(binary_bytes.items.len - header_offset - 6);
try writeCustomSectionHeader(binary_bytes.items, header_offset, size);
}
fn emitDataRelocations(
wasm: *Wasm,
binary_bytes: *std.ArrayList(u8),
section_index: u32,
symbol_table: std.AutoArrayHashMap(SymbolLoc, u32),
) !void {
if (wasm.data_segments.count() == 0) return;
const writer = binary_bytes.writer();
const header_offset = try reserveCustomSectionHeader(binary_bytes);
// write custom section information
const name = "reloc.DATA";
try leb.writeULEB128(writer, @as(u32, @intCast(name.len)));
try writer.writeAll(name);
try leb.writeULEB128(writer, section_index);
const reloc_start = binary_bytes.items.len;
var count: u32 = 0;
// for each atom, we calculate the uleb size and append that
var size_offset: u32 = 5; // account for code section size leb128
for (wasm.data_segments.values()) |segment_index| {
var atom: *Atom = wasm.getAtomPtr(wasm.atoms.get(segment_index).?);
while (true) {
size_offset += getULEB128Size(atom.size);
for (atom.relocs.items) |relocation| {
count += 1;
const sym_loc: SymbolLoc = .{
.file = atom.file,
.index = relocation.index,
};
const symbol_index = symbol_table.get(sym_loc).?;
try leb.writeULEB128(writer, @intFromEnum(relocation.relocation_type));
const offset = atom.offset + relocation.offset + size_offset;
try leb.writeULEB128(writer, offset);
try leb.writeULEB128(writer, symbol_index);
if (relocation.relocation_type.addendIsPresent()) {
try leb.writeILEB128(writer, relocation.addend);
}
log.debug("Emit relocation: {}", .{relocation});
}
atom = if (atom.prev) |prev| wasm.getAtomPtr(prev) else break;
}
}
if (count == 0) return;
var buf: [5]u8 = undefined;
leb.writeUnsignedFixed(5, &buf, count);
try binary_bytes.insertSlice(reloc_start, &buf);
const size = @as(u32, @intCast(binary_bytes.items.len - header_offset - 6));
try writeCustomSectionHeader(binary_bytes.items, header_offset, size);
}
fn hasPassiveInitializationSegments(wasm: *const Wasm) bool {
const comp = wasm.base.comp;
const import_memory = comp.config.import_memory;
var it = wasm.data_segments.iterator();
while (it.next()) |entry| {
const segment: Segment = wasm.segments.items[entry.value_ptr.*];
if (segment.needsPassiveInitialization(import_memory, entry.key_ptr.*)) {
return true;
}
}
return false;
}
pub fn getTypeIndex(wasm: *const Wasm, func_type: std.wasm.Type) ?u32 {
var index: u32 = 0;
while (index < wasm.func_types.items.len) : (index += 1) {
if (wasm.func_types.items[index].eql(func_type)) return index;
}
return null;
}
/// Searches for a matching function signature. When no matching signature is found,
/// a new entry will be made. The value returned is the index of the type within `wasm.func_types`.
pub fn putOrGetFuncType(wasm: *Wasm, func_type: std.wasm.Type) !u32 {
if (wasm.getTypeIndex(func_type)) |index| {
return index;
}
const gpa = wasm.base.comp.gpa;
// functype does not exist.
const index: u32 = @intCast(wasm.func_types.items.len);
const params = try gpa.dupe(std.wasm.Valtype, func_type.params);
errdefer gpa.free(params);
const returns = try gpa.dupe(std.wasm.Valtype, func_type.returns);
errdefer gpa.free(returns);
try wasm.func_types.append(gpa, .{
.params = params,
.returns = returns,
});
return index;
}
/// For the given `decl_index`, stores the corresponding type representing the function signature.
/// Asserts declaration has an associated `Atom`.
/// Returns the index into the list of types.
pub fn storeDeclType(wasm: *Wasm, decl_index: InternPool.DeclIndex, func_type: std.wasm.Type) !u32 {
const gpa = wasm.base.comp.gpa;
const atom_index = wasm.decls.get(decl_index).?;
const index = try wasm.putOrGetFuncType(func_type);
try wasm.atom_types.put(gpa, atom_index, index);
return index;
}
/// Verifies all resolved symbols and checks whether itself needs to be marked alive,
/// as well as any of its references.
fn markReferences(wasm: *Wasm) !void {
const tracy = trace(@src());
defer tracy.end();
const do_garbage_collect = wasm.base.gc_sections;
const comp = wasm.base.comp;
for (wasm.resolved_symbols.keys()) |sym_loc| {
const sym = sym_loc.getSymbol(wasm);
if (sym.isExported(comp.config.rdynamic) or sym.isNoStrip() or !do_garbage_collect) {
try wasm.mark(sym_loc);
continue;
}
// Debug sections may require to be parsed and marked when it contains
// relocations to alive symbols.
if (sym.tag == .section and comp.config.debug_format != .strip) {
const file = sym_loc.file orelse continue; // Incremental debug info is done independently
const object = &wasm.objects.items[file];
const atom_index = try Object.parseSymbolIntoAtom(object, file, sym_loc.index, wasm);
const atom = wasm.getAtom(atom_index);
const atom_sym = atom.symbolLoc().getSymbol(wasm);
atom_sym.mark();
}
}
}
/// Marks a symbol as 'alive' recursively so itself and any references it contains to
/// other symbols will not be omit from the binary.
fn mark(wasm: *Wasm, loc: SymbolLoc) !void {
const symbol = loc.getSymbol(wasm);
if (symbol.isAlive()) {
// Symbol is already marked alive, including its references.
// This means we can skip it so we don't end up marking the same symbols
// multiple times.
return;
}
symbol.mark();
if (symbol.isUndefined()) {
// undefined symbols do not have an associated `Atom` and therefore also
// do not contain relocations.
return;
}
const atom_index = if (loc.file) |file_index| idx: {
const object = &wasm.objects.items[file_index];
const atom_index = try object.parseSymbolIntoAtom(file_index, loc.index, wasm);
break :idx atom_index;
} else wasm.symbol_atom.get(loc) orelse return;
const atom = wasm.getAtom(atom_index);
for (atom.relocs.items) |reloc| {
const target_loc: SymbolLoc = .{ .index = reloc.index, .file = loc.file };
try wasm.mark(target_loc.finalLoc(wasm));
}
}
fn defaultEntrySymbolName(wasi_exec_model: std.builtin.WasiExecModel) []const u8 {
return switch (wasi_exec_model) {
.reactor => "_initialize",
.command => "_start",
};
}
|