aboutsummaryrefslogtreecommitdiffstats
path: root/output/outelf.c
blob: c0d19e8bb33d66352a3b505a229df077c2e44128 (plain)
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
/* ----------------------------------------------------------------------- *
 *
 *   Copyright 1996-2018 The NASM Authors - All Rights Reserved
 *   See the file AUTHORS included with the NASM distribution for
 *   the specific copyright holders.
 *
 *   Redistribution and use in source and binary forms, with or without
 *   modification, are permitted provided that the following
 *   conditions are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *
 *     THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
 *     CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 *     INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 *     MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 *     DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 *     CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *     SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 *     NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *     LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 *     HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 *     CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 *     OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 *     EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ----------------------------------------------------------------------- */

/*
 * Common code for outelf32 and outelf64
 */

#include "compiler.h"

#include <stdio.h>
#include <stdlib.h>

#include "nasm.h"
#include "nasmlib.h"
#include "error.h"
#include "saa.h"
#include "raa.h"
#include "stdscan.h"
#include "eval.h"
#include "outform.h"
#include "outlib.h"
#include "rbtree.h"
#include "ver.h"

#include "dwarf.h"
#include "stabs.h"
#include "outelf.h"
#include "elf.h"

#if defined(OF_ELF32) || defined(OF_ELF64) || defined(OF_ELFX32)

#define SECT_DELTA 32
static struct elf_section **sects;
static int nsects, sectlen;

#define SHSTR_DELTA 256
static char *shstrtab;
static int shstrtablen, shstrtabsize;

static struct SAA *syms;
static uint32_t nlocals, nglobs, ndebugs; /* Symbol counts */

static int32_t def_seg;

static struct RAA *bsym;

static struct SAA *strs;
static uint32_t strslen;

static struct elf_symbol *fwds;

static char elf_module[FILENAME_MAX];

extern const struct ofmt of_elf32;
extern const struct ofmt of_elf64;
extern const struct ofmt of_elfx32;

static struct ELF_SECTDATA {
    void                *data;
    int64_t             len;
    bool                is_saa;
} *elf_sects;

static int elf_nsect, nsections;
static int64_t elf_foffs;

static void elf_write(void);
static void elf_sect_write(struct elf_section *, const void *, size_t);
static void elf_sect_writeaddr(struct elf_section *, int64_t, size_t);
static void elf_section_header(int name, int type, uint64_t flags,
                               void *data, bool is_saa, uint64_t datalen,
                               int link, int info,
                               uint64_t align, uint64_t entsize);
static void elf_write_sections(void);
static struct SAA *elf_build_symtab(int32_t *, int32_t *);
static struct SAA *elf_build_reltab(uint64_t *, struct elf_reloc *);
static void add_sectname(const char *, const char *);

struct erel {
    int                 offset;
    int                 info;
};

struct symlininfo {
    int                 offset;
    int                 section;        /* index into sects[] */
    int                 segto;          /* internal section number */
    char                *name;          /* shallow-copied pointer of section name */
};

struct linelist {
    struct linelist     *next;
    struct linelist     *last;
    struct symlininfo   info;
    char                *filename;
    int                 line;
};

struct sectlist {
    struct SAA          *psaa;
    int                 section;
    int                 line;
    int                 offset;
    int                 file;
    struct sectlist     *next;
    struct sectlist     *last;
};

/* common debug variables */
static int currentline = 1;
static int debug_immcall = 0;

/* stabs debug variables */
static struct linelist *stabslines = 0;
static int numlinestabs = 0;
static char *stabs_filename = 0;
static uint8_t *stabbuf = 0, *stabstrbuf = 0, *stabrelbuf = 0;
static int stablen, stabstrlen, stabrellen;

/* dwarf debug variables */
static struct linelist *dwarf_flist = 0, *dwarf_clist = 0, *dwarf_elist = 0;
static struct sectlist *dwarf_fsect = 0, *dwarf_csect = 0, *dwarf_esect = 0;
static int dwarf_numfiles = 0, dwarf_nsections;
static uint8_t *arangesbuf = 0, *arangesrelbuf = 0, *pubnamesbuf = 0, *infobuf = 0,  *inforelbuf = 0,
               *abbrevbuf = 0, *linebuf = 0, *linerelbuf = 0, *framebuf = 0, *locbuf = 0;
static int8_t line_base = -5, line_range = 14, opcode_base = 13;
static int arangeslen, arangesrellen, pubnameslen, infolen, inforellen,
           abbrevlen, linelen, linerellen, framelen, loclen;
static int64_t dwarf_infosym, dwarf_abbrevsym, dwarf_linesym;

static struct elf_symbol *lastsym;

/* common debugging routines */
static void debug_typevalue(int32_t);

/* stabs debugging routines */
static void stabs_linenum(const char *filename, int32_t linenumber, int32_t);
static void stabs_output(int, void *);
static void stabs_generate(void);
static void stabs_cleanup(void);

/* dwarf debugging routines */
static void dwarf_init(void);
static void dwarf_linenum(const char *filename, int32_t linenumber, int32_t);
static void dwarf_output(int, void *);
static void dwarf_generate(void);
static void dwarf_cleanup(void);
static void dwarf_findfile(const char *);
static void dwarf_findsect(const int);

static bool is_elf64(void);
static bool is_elf32(void);
static bool is_elfx32(void);

static bool dfmt_is_stabs(void);
static bool dfmt_is_dwarf(void);

/*
 * Special NASM section numbers which are used to define ELF special
 * symbols.
 */
static int32_t elf_gotpc_sect, elf_gotoff_sect;
static int32_t elf_got_sect, elf_plt_sect;
static int32_t elf_sym_sect, elf_gottpoff_sect, elf_tlsie_sect;

uint8_t elf_osabi = 0;      /* Default OSABI = 0 (System V or Linux) */
uint8_t elf_abiver = 0;     /* Current ABI version */

const struct elf_known_section elf_known_sections[] = {
    { ".text",    SHT_PROGBITS, SHF_ALLOC|SHF_EXECINSTR,     16 },
    { ".rodata",  SHT_PROGBITS, SHF_ALLOC,                    4 },
    { ".lrodata", SHT_PROGBITS, SHF_ALLOC,                    4 },
    { ".data",    SHT_PROGBITS, SHF_ALLOC|SHF_WRITE,          4 },
    { ".ldata",   SHT_PROGBITS, SHF_ALLOC|SHF_WRITE,          4 },
    { ".bss",     SHT_NOBITS,   SHF_ALLOC|SHF_WRITE,          4 },
    { ".lbss",    SHT_NOBITS,   SHF_ALLOC|SHF_WRITE,          4 },
    { ".tdata",   SHT_PROGBITS, SHF_ALLOC|SHF_WRITE|SHF_TLS,  4 },
    { ".tbss",    SHT_NOBITS,   SHF_ALLOC|SHF_WRITE|SHF_TLS,  4 },
    { ".comment", SHT_PROGBITS, 0,                            1 },
    { NULL,       SHT_PROGBITS, SHF_ALLOC,                    1 } /* default */
};

/* parse section attributes */
static void elf_section_attrib(char *name, char *attr, int pass,
                               uint32_t *flags_and, uint32_t *flags_or,
                               uint64_t *alignp, uint64_t *entsize, int *type)
{
    char *opt, *val, *next;
    uint64_t align = 0;
    uint64_t xalign = 0;

    opt = nasm_skip_spaces(attr);
    if (!opt || !*opt)
        return;

    while ((opt = nasm_opt_val(opt, &val, &next))) {
        if (!nasm_stricmp(opt, "align")) {
            if (!val) {
                nasm_error(ERR_NONFATAL,
                           "section align without value specified");
            } else {
                bool err;
                uint64_t a = readnum(val, &err);
                if (a && !is_power2(a)) {
                    nasm_error(ERR_NONFATAL,
                               "section alignment %"PRId64" is not a power of two",
                               a);
                } else if (a > align) {
                    align = a;
                }
            }
        } else if (!nasm_stricmp(opt, "alloc")) {
            *flags_and  |= SHF_ALLOC;
            *flags_or   |= SHF_ALLOC;
        } else if (!nasm_stricmp(opt, "noalloc")) {
            *flags_and  |= SHF_ALLOC;
            *flags_or   &= ~SHF_ALLOC;
        } else if (!nasm_stricmp(opt, "exec")) {
            *flags_and  |= SHF_EXECINSTR;
            *flags_or   |= SHF_EXECINSTR;
        } else if (!nasm_stricmp(opt, "noexec")) {
            *flags_and  |= SHF_EXECINSTR;
            *flags_or   &= ~SHF_EXECINSTR;
        } else if (!nasm_stricmp(opt, "write")) {
            *flags_and  |= SHF_WRITE;
            *flags_or   |= SHF_WRITE;
        } else if (!nasm_stricmp(opt, "nowrite")) {
            *flags_and  |= SHF_WRITE;
            *flags_or   &= ~SHF_WRITE;
        } else if (!nasm_stricmp(opt, "tls")) {
            *flags_and  |= SHF_TLS;
            *flags_or   |= SHF_TLS;
        } else if (!nasm_stricmp(opt, "notls")) {
            *flags_and  |= SHF_TLS;
            *flags_or   &= ~SHF_TLS;
        } else if (!nasm_stricmp(opt, "merge")) {
            *flags_and  |= SHF_MERGE;
            *flags_or   |= SHF_MERGE;
        } else if (!nasm_stricmp(opt, "nomerge")) {
            *flags_and  |= SHF_MERGE;
            *flags_or   &= ~SHF_MERGE;
        } else if (!nasm_stricmp(opt, "strings")) {
            *flags_and  |= SHF_STRINGS;
            *flags_or   |= SHF_STRINGS;
        } else if (!nasm_stricmp(opt, "nostrings")) {
            *flags_and  |= SHF_STRINGS;
            *flags_or   &= ~SHF_STRINGS;
        } else if (!nasm_stricmp(opt, "progbits")) {
            *type = SHT_PROGBITS;
        } else if (!nasm_stricmp(opt, "nobits")) {
            *type = SHT_NOBITS;
        } else if (!nasm_stricmp(opt, "ent") || !nasm_stricmp(opt,"entsize")) {
            bool err;
            uint64_t es;
            if (!val) {
                nasm_error(ERR_NONFATAL,
                           "section attribute %s without value specified", opt);
            } else {
                es = readnum(val, &err);
                if (err) {
                    nasm_error(ERR_NONFATAL,
                               "invalid value %s for section attribute %s",
                               val, opt);
                } else {
                    *entsize = es;
                }
            }
        } else if (!nasm_stricmp(opt, "byte")) {
            xalign = *entsize = 1;
        } else if (!nasm_stricmp(opt, "word")) {
            xalign = *entsize = 2;
        } else if (!nasm_stricmp(opt, "dword")) {
            xalign = *entsize = 4;
        } else if (!nasm_stricmp(opt, "qword")) {
            xalign = *entsize = 8;
        } else if (!nasm_stricmp(opt, "tword")) {
            *entsize = 10;
            xalign = 2;
        } else if (!nasm_stricmp(opt, "oword")) {
            xalign = *entsize = 16;
        } else if (!nasm_stricmp(opt, "yword")) {
            xalign = *entsize = 32;
        } else if (!nasm_stricmp(opt, "zword")) {
            xalign = *entsize = 64;
        } else if (pass == 1) {
            nasm_error(ERR_WARNING,
                       "Unknown section attribute '%s' ignored on"
                       " declaration of section `%s'", opt, name);
        }
        opt = next;
    }

    if (!align)
        align = xalign;

    if (!align)
        align = SHA_ANY;

    *alignp = align;
}

static enum directive_result
elf_directive(enum directive directive, char *value, int pass)
{
    int64_t n;
    bool err;
    char *p;

    switch (directive) {
    case D_OSABI:
        if (pass == 2)
            return DIRR_OK; /* ignore in pass 2 */

        n = readnum(value, &err);
        if (err) {
            nasm_error(ERR_NONFATAL, "`osabi' directive requires a parameter");
            return DIRR_ERROR;
        }

        if (n < 0 || n > 255) {
            nasm_error(ERR_NONFATAL, "valid osabi numbers are 0 to 255");
            return DIRR_ERROR;
        }

        elf_osabi  = n;
        elf_abiver = 0;

        p = strchr(value,',');
        if (!p)
            return DIRR_OK;

        n = readnum(p + 1, &err);
        if (err || n < 0 || n > 255) {
            nasm_error(ERR_NONFATAL, "invalid ABI version number (valid: 0 to 255)");
            return DIRR_ERROR;
        }

        elf_abiver = n;
        return DIRR_OK;

    default:
        return DIRR_UNKNOWN;
    }
}

static void elf_init(void)
{
    strlcpy(elf_module, inname, sizeof(elf_module));
    sects = NULL;
    nsects = sectlen = 0;
    syms = saa_init((int32_t)sizeof(struct elf_symbol));
    nlocals = nglobs = ndebugs = 0;
    bsym = raa_init();
    strs = saa_init(1L);
    saa_wbytes(strs, "\0", 1L);
    saa_wbytes(strs, elf_module, strlen(elf_module)+1);
    strslen = 2 + strlen(elf_module);
    shstrtab = NULL;
    shstrtablen = shstrtabsize = 0;;
    add_sectname("", "");

    fwds = NULL;

    /*
     * FIXME: tlsie is Elf32 only and
     * gottpoff is Elfx32|64 only.
     */

    elf_gotpc_sect = seg_alloc();
    backend_label("..gotpc", elf_gotpc_sect + 1, 0L);
    elf_gotoff_sect = seg_alloc();
    backend_label("..gotoff", elf_gotoff_sect + 1, 0L);
    elf_got_sect = seg_alloc();
    backend_label("..got", elf_got_sect + 1, 0L);
    elf_plt_sect = seg_alloc();
    backend_label("..plt", elf_plt_sect + 1, 0L);
    elf_sym_sect = seg_alloc();
    backend_label("..sym", elf_sym_sect + 1, 0L);
    elf_gottpoff_sect = seg_alloc();
    backend_label("..gottpoff", elf_gottpoff_sect + 1, 0L);
    elf_tlsie_sect = seg_alloc();
    backend_label("..tlsie", elf_tlsie_sect + 1, 0L);

    def_seg = seg_alloc();
}

static void elf_cleanup(void)
{
    struct elf_reloc *r;
    int i;

    elf_write();
    for (i = 0; i < nsects; i++) {
        if (sects[i]->type != SHT_NOBITS)
            saa_free(sects[i]->data);
        if (sects[i]->head)
            saa_free(sects[i]->rel);
        while (sects[i]->head) {
            r = sects[i]->head;
            sects[i]->head = sects[i]->head->next;
            nasm_free(r);
        }
    }
    nasm_free(sects);
    saa_free(syms);
    raa_free(bsym);
    saa_free(strs);
    dfmt->cleanup();
}

/* add entry to the elf .shstrtab section */
static void add_sectname(const char *firsthalf, const char *secondhalf)
{
    int len = strlen(firsthalf) + strlen(secondhalf);
    while (shstrtablen + len + 1 > shstrtabsize)
        shstrtab = nasm_realloc(shstrtab, (shstrtabsize += SHSTR_DELTA));
    strcpy(shstrtab + shstrtablen, firsthalf);
    strcat(shstrtab + shstrtablen, secondhalf);
    shstrtablen += len + 1;
}

static int elf_make_section(char *name, int type, int flags, uint64_t align)
{
    struct elf_section *s;

    s = nasm_zalloc(sizeof(*s));

    if (type != SHT_NOBITS)
        s->data = saa_init(1L);
    s->tail = &s->head;
    if (!strcmp(name, ".text"))
        s->index = def_seg;
    else
        s->index = seg_alloc();
    add_sectname("", name);

    s->name     = nasm_strdup(name);
    s->type     = type;
    s->flags    = flags;
    s->align    = align;

    if (nsects >= sectlen)
        sects = nasm_realloc(sects, (sectlen += SECT_DELTA) * sizeof(*sects));
    sects[nsects++] = s;

    return nsects - 1;
}

static int32_t elf_section_names(char *name, int pass, int *bits)
{
    char *p;
    uint32_t flags, flags_and, flags_or;
    uint64_t align, entsize;
    struct elf_section *s;
    int type, i;

    if (!name) {
        *bits = ofmt->maxbits;
        return def_seg;
    }

    p = nasm_skip_word(name);
    if (*p)
        *p++ = '\0';
    flags_and = flags_or = type = align = entsize = 0;

    elf_section_attrib(name, p, pass, &flags_and,
                       &flags_or, &align, &entsize, &type);

    if (!strcmp(name, ".shstrtab") ||
        !strcmp(name, ".symtab") ||
        !strcmp(name, ".strtab")) {
        nasm_error(ERR_NONFATAL, "attempt to redefine reserved section"
              "name `%s'", name);
        return NO_SEG;
    }

    for (i = 0; i < nsects; i++)
        if (!strcmp(name, sects[i]->name))
            break;
    if (i == nsects) {
        const struct elf_known_section *ks = elf_known_sections;

        while (ks->name) {
            if (!strcmp(name, ks->name))
                break;
            ks++;
        }

        type = type ? type : ks->type;
        align = align ? align : ks->align;
        flags = (ks->flags & ~flags_and) | flags_or;

        i = elf_make_section(name, type, flags, align);
    }

    s = sects[i];

    if (pass == 1) {
        if ((type && s->type != type)
            || ((s->flags & flags_and) != flags_or)
            || (entsize && s->entsize && entsize != s->entsize)) {
            nasm_error(ERR_WARNING,
                       "incompatible section attributes ignored on"
                       " redeclaration of section `%s'", name);
        }
    }

    if (align > s->align)
        s->align = align;

    if (entsize && !s->entsize)
        s->entsize = entsize;

    if (pass == 2 && (flags_or & SHF_MERGE) && s->entsize == 0) {
        if (!(s->flags & SHF_STRINGS))
            nasm_error(ERR_NONFATAL,
                       "section attribute merge specified without an entry size");
        s->entsize = 1;
    }

    return s->index;
}

static void elf_deflabel(char *name, int32_t segment, int64_t offset,
                         int is_global, char *special)
{
    int pos = strslen;
    struct elf_symbol *sym;
    bool special_used = false;

#if defined(DEBUG) && DEBUG>2
    nasm_error(ERR_DEBUG,
            " elf_deflabel: %s, seg=%"PRIx32", off=%"PRIx64", is_global=%d, %s\n",
            name, segment, offset, is_global, special);
#endif
    if (name[0] == '.' && name[1] == '.' && name[2] != '@') {
        /*
         * This is a NASM special symbol. We never allow it into
         * the ELF symbol table, even if it's a valid one. If it
         * _isn't_ a valid one, we should barf immediately.
         *
         * FIXME: tlsie is Elf32 only, and gottpoff is Elfx32|64 only.
         */
        if (strcmp(name, "..gotpc") && strcmp(name, "..gotoff") &&
            strcmp(name, "..got") && strcmp(name, "..plt") &&
            strcmp(name, "..sym") && strcmp(name, "..gottpoff") &&
            strcmp(name, "..tlsie"))
            nasm_error(ERR_NONFATAL, "unrecognised special symbol `%s'", name);
        return;
    }

    if (is_global == 3) {
        struct elf_symbol **s;
        /*
         * Fix up a forward-reference symbol size from the first
         * pass.
         */
        for (s = &fwds; *s; s = &(*s)->nextfwd)
            if (!strcmp((*s)->name, name)) {
                struct tokenval tokval;
                expr *e;
                char *p = nasm_skip_spaces(nasm_skip_word(special));

                stdscan_reset();
                stdscan_set(p);
                tokval.t_type = TOKEN_INVALID;
                e = evaluate(stdscan, NULL, &tokval, NULL, 1, NULL);
                if (e) {
                    if (!is_simple(e))
                        nasm_error(ERR_NONFATAL, "cannot use relocatable"
                              " expression as symbol size");
                    else
                        (*s)->size = reloc_value(e);
                }

                /*
                 * Remove it from the list of unresolved sizes.
                 */
                nasm_free((*s)->name);
                *s = (*s)->nextfwd;
                return;
            }
        return;                 /* it wasn't an important one */
    }

    saa_wbytes(strs, name, (int32_t)(1 + strlen(name)));
    strslen += 1 + strlen(name);

    lastsym = sym = saa_wstruct(syms);

    memset(&sym->symv, 0, sizeof(struct rbtree));

    sym->strpos = pos;
    sym->type = is_global ? SYM_GLOBAL : SYM_LOCAL;
    sym->other = STV_DEFAULT;
    sym->size = 0;
    if (segment == NO_SEG)
        sym->section = SHN_ABS;
    else {
        int i;
        sym->section = SHN_UNDEF;
        if (segment == def_seg) {
            /* we have to be sure at least text section is there */
            int tempint;
            if (segment != elf_section_names(".text", 2, &tempint))
                nasm_panic(0, "strange segment conditions in ELF driver");
        }
        for (i = 0; i < nsects; i++) {
            if (segment == sects[i]->index) {
                sym->section = i + 1;
                break;
            }
        }
    }

    if (is_global == 2) {
        sym->size = offset;
        sym->symv.key = 0;
        sym->section = SHN_COMMON;
        /*
         * We have a common variable. Check the special text to see
         * if it's a valid number and power of two; if so, store it
         * as the alignment for the common variable.
         */
        if (special) {
            bool err;
            sym->symv.key = readnum(special, &err);
            if (err)
                nasm_error(ERR_NONFATAL, "alignment constraint `%s' is not a"
                      " valid number", special);
            else if ((sym->symv.key | (sym->symv.key - 1)) != 2 * sym->symv.key - 1)
                nasm_error(ERR_NONFATAL, "alignment constraint `%s' is not a"
                      " power of two", special);
        }
        special_used = true;
    } else
        sym->symv.key = (sym->section == SHN_UNDEF ? 0 : offset);

    if (sym->type == SYM_GLOBAL) {
        /*
         * If sym->section == SHN_ABS, then the first line of the
         * else section would cause a core dump, because its a reference
         * beyond the end of the section array.
         * This behaviour is exhibited by this code:
         *     GLOBAL crash_nasm
         *     crash_nasm equ 0
         * To avoid such a crash, such requests are silently discarded.
         * This may not be the best solution.
         */
        if (sym->section == SHN_UNDEF || sym->section == SHN_COMMON) {
            bsym = raa_write(bsym, segment, nglobs);
        } else if (sym->section != SHN_ABS) {
            /*
             * This is a global symbol; so we must add it to the rbtree
             * of global symbols in its section.
             *
             * In addition, we check the special text for symbol
             * type and size information.
             */
            sects[sym->section-1]->gsyms =
                rb_insert(sects[sym->section-1]->gsyms, &sym->symv);

            if (special) {
                int n = strcspn(special, " \t");

                if (!nasm_strnicmp(special, "function", n))
                    sym->type |= STT_FUNC;
                else if (!nasm_strnicmp(special, "data", n) ||
                         !nasm_strnicmp(special, "object", n))
                    sym->type |= STT_OBJECT;
                else if (!nasm_strnicmp(special, "notype", n))
                    sym->type |= STT_NOTYPE;
                else
                    nasm_error(ERR_NONFATAL, "unrecognised symbol type `%.*s'",
                          n, special);
                special += n;

                special = nasm_skip_spaces(special);
                if (*special) {
                    n = strcspn(special, " \t");
                    if (!nasm_strnicmp(special, "default", n))
                        sym->other = STV_DEFAULT;
                    else if (!nasm_strnicmp(special, "internal", n))
                        sym->other = STV_INTERNAL;
                    else if (!nasm_strnicmp(special, "hidden", n))
                        sym->other = STV_HIDDEN;
                    else if (!nasm_strnicmp(special, "protected", n))
                        sym->other = STV_PROTECTED;
                    else
                        n = 0;
                    special += n;
                }

                if (*special) {
                    struct tokenval tokval;
                    expr *e;
                    int fwd = 0;
                    char *saveme = stdscan_get();

                    while (special[n] && nasm_isspace(special[n]))
                        n++;
                    /*
                     * We have a size expression; attempt to
                     * evaluate it.
                     */
                    stdscan_reset();
                    stdscan_set(special + n);
                    tokval.t_type = TOKEN_INVALID;
                    e = evaluate(stdscan, NULL, &tokval, &fwd, 0, NULL);
                    if (fwd) {
                        sym->nextfwd = fwds;
                        fwds = sym;
                        sym->name = nasm_strdup(name);
                    } else if (e) {
                        if (!is_simple(e))
                            nasm_error(ERR_NONFATAL, "cannot use relocatable"
                                  " expression as symbol size");
                        else
                            sym->size = reloc_value(e);
                    }
                    stdscan_set(saveme);
                }
                special_used = true;
            }
            /*
             * If TLS segment, mark symbol accordingly.
             */
            if (sects[sym->section - 1]->flags & SHF_TLS) {
                sym->type &= 0xf0;
                sym->type |= STT_TLS;
            }
        }
        sym->globnum = nglobs;
        nglobs++;
    } else
        nlocals++;

    if (special && !special_used)
        nasm_error(ERR_NONFATAL, "no special symbol features supported here");
}

static void elf_add_reloc(struct elf_section *sect, int32_t segment,
                          int64_t offset, int type)
{
    struct elf_reloc *r;

    r = *sect->tail = nasm_zalloc(sizeof(struct elf_reloc));
    sect->tail = &r->next;

    r->address = sect->len;
    r->offset = offset;

    if (segment != NO_SEG) {
        int i;
        for (i = 0; i < nsects; i++)
            if (segment == sects[i]->index)
                r->symbol = i + 2;
        if (!r->symbol)
            r->symbol = GLOBAL_TEMP_BASE + raa_read(bsym, segment);
    }
    r->type = type;

    sect->nrelocs++;
}

/*
 * This routine deals with ..got and ..sym relocations: the more
 * complicated kinds. In shared-library writing, some relocations
 * with respect to global symbols must refer to the precise symbol
 * rather than referring to an offset from the base of the section
 * _containing_ the symbol. Such relocations call to this routine,
 * which searches the symbol list for the symbol in question.
 *
 * R_386_GOT32 | R_X86_64_GOT32 references require the _exact_ symbol address to be
 * used; R_386_32 | R_X86_64_32 references can be at an offset from the symbol.
 * The boolean argument `exact' tells us this.
 *
 * Return value is the adjusted value of `addr', having become an
 * offset from the symbol rather than the section. Should always be
 * zero when returning from an exact call.
 *
 * Limitation: if you define two symbols at the same place,
 * confusion will occur.
 *
 * Inefficiency: we search, currently, using a linked list which
 * isn't even necessarily sorted.
 */
static int64_t elf_add_gsym_reloc(struct elf_section *sect,
                                  int32_t segment, uint64_t offset,
                                  int64_t pcrel, int type, bool exact)
{
    struct elf_reloc *r;
    struct elf_section *s;
    struct elf_symbol *sym;
    struct rbtree *srb;
    int i;

    /*
     * First look up the segment/offset pair and find a global
     * symbol corresponding to it. If it's not one of our segments,
     * then it must be an external symbol, in which case we're fine
     * doing a normal elf_add_reloc after first sanity-checking
     * that the offset from the symbol is zero.
     */
    s = NULL;
    for (i = 0; i < nsects; i++)
        if (segment == sects[i]->index) {
            s = sects[i];
            break;
        }

    if (!s) {
        if (exact && offset)
            nasm_error(ERR_NONFATAL, "invalid access to an external symbol");
        else
            elf_add_reloc(sect, segment, offset - pcrel, type);
        return 0;
    }

    srb = rb_search(s->gsyms, offset);
    if (!srb || (exact && srb->key != offset)) {
        nasm_error(ERR_NONFATAL, "unable to find a suitable global symbol"
                    " for this reference");
        return 0;
    }
    sym = container_of(srb, struct elf_symbol, symv);

    r = *sect->tail = nasm_malloc(sizeof(struct elf_reloc));
    sect->tail = &r->next;

    r->next     = NULL;
    r->address  = sect->len;
    r->offset = offset - pcrel - sym->symv.key;
    r->symbol   = GLOBAL_TEMP_BASE + sym->globnum;
    r->type     = type;

    sect->nrelocs++;
    return r->offset;
}

static void elf32_out(int32_t segto, const void *data,
                      enum out_type type, uint64_t size,
                      int32_t segment, int32_t wrt)
{
    struct elf_section *s;
    int64_t addr;
    int reltype, bytes;
    int i;
    static struct symlininfo sinfo;

    /*
     * handle absolute-assembly (structure definitions)
     */
    if (segto == NO_SEG) {
        if (type != OUT_RESERVE)
            nasm_error(ERR_NONFATAL, "attempt to assemble code in [ABSOLUTE]"
                  " space");
        return;
    }

    s = NULL;
    for (i = 0; i < nsects; i++)
        if (segto == sects[i]->index) {
            s = sects[i];
            break;
        }
    if (!s) {
        int tempint;            /* ignored */
        if (segto != elf_section_names(".text", 2, &tempint))
            nasm_panic(0, "strange segment conditions in ELF driver");
        else {
            s = sects[nsects - 1];
            i = nsects - 1;
        }
    }

    /* again some stabs debugging stuff */
    sinfo.offset = s->len;
    sinfo.section = i;
    sinfo.segto = segto;
    sinfo.name = s->name;
    dfmt->debug_output(TY_DEBUGSYMLIN, &sinfo);
    /* end of debugging stuff */

    if (s->type == SHT_NOBITS && type != OUT_RESERVE) {
        nasm_error(ERR_WARNING, "attempt to initialize memory in"
              " BSS section `%s': ignored", s->name);
        s->len += realsize(type, size);
        return;
    }

    switch (type) {
    case OUT_RESERVE:
        if (s->type == SHT_PROGBITS) {
            nasm_error(ERR_WARNING, "uninitialized space declared in"
                  " non-BSS section `%s': zeroing", s->name);
            elf_sect_write(s, NULL, size);
        } else
            s->len += size;
        break;

    case OUT_RAWDATA:
        if (segment != NO_SEG)
            nasm_panic(0, "OUT_RAWDATA with other than NO_SEG");
        elf_sect_write(s, data, size);
        break;

    case OUT_ADDRESS:
    {
        bool gnu16 = false;
        int asize = abs((int)size);

        addr = *(int64_t *)data;
        if (segment != NO_SEG) {
            if (segment % 2) {
                nasm_error(ERR_NONFATAL, "ELF format does not support"
                      " segment base references");
            } else {
                if (wrt == NO_SEG) {
                    /*
                     * The if() is a hack to deal with compilers which
                     * don't handle switch() statements with 64-bit
                     * expressions.
                     */
                    switch (asize) {
                    case 1:
                        gnu16 = true;
                        elf_add_reloc(s, segment, 0, R_386_8);
                        break;
                    case 2:
                        gnu16 = true;
                        elf_add_reloc(s, segment, 0, R_386_16);
                        break;
                    case 4:
                        elf_add_reloc(s, segment, 0, R_386_32);
                        break;
                    default: /* Error issued further down */
                        break;
                    }
                } else if (wrt == elf_gotpc_sect + 1) {
                    /*
                     * The user will supply GOT relative to $$. ELF
                     * will let us have GOT relative to $. So we
                     * need to fix up the data item by $-$$.
                     */
                    addr += s->len;
                    elf_add_reloc(s, segment, 0, R_386_GOTPC);
                } else if (wrt == elf_gotoff_sect + 1) {
                    elf_add_reloc(s, segment, 0, R_386_GOTOFF);
                } else if (wrt == elf_tlsie_sect + 1) {
                    addr = elf_add_gsym_reloc(s, segment, addr, 0,
                                              R_386_TLS_IE, true);
                } else if (wrt == elf_got_sect + 1) {
                    addr = elf_add_gsym_reloc(s, segment, addr, 0,
                                              R_386_GOT32, true);
                } else if (wrt == elf_sym_sect + 1) {
                    switch (asize) {
                    case 1:
                        gnu16 = true;
                        addr = elf_add_gsym_reloc(s, segment, addr, 0,
                                                  R_386_8, false);
                        break;
                    case 2:
                        gnu16 = true;
                        addr = elf_add_gsym_reloc(s, segment, addr, 0,
                                                  R_386_16, false);
                        break;
                    case 4:
                        addr = elf_add_gsym_reloc(s, segment, addr, 0,
                                                  R_386_32, false);
                        break;
                    default:
                        break;
                    }
                } else if (wrt == elf_plt_sect + 1) {
                    nasm_error(ERR_NONFATAL, "ELF format cannot produce non-PC-"
                          "relative PLT references");
                } else {
                    nasm_error(ERR_NONFATAL, "ELF format does not support this"
                          " use of WRT");
                    wrt = NO_SEG; /* we can at least _try_ to continue */
                }
            }
        }

        if (gnu16) {
            nasm_error(ERR_WARNING | WARN_GNUELF,
                  "8- or 16-bit relocations in ELF32 is a GNU extension");
        } else if (asize != 4 && segment != NO_SEG) {
            nasm_error(ERR_NONFATAL, "Unsupported non-32-bit ELF relocation");
        }
        elf_sect_writeaddr(s, addr, asize);
        break;
    }

    case OUT_REL1ADR:
        reltype = R_386_PC8;
        bytes = 1;
        goto rel12adr;
    case OUT_REL2ADR:
        reltype = R_386_PC16;
        bytes = 2;
        goto rel12adr;

rel12adr:
        addr = *(int64_t *)data - size;
        nasm_assert(segment != segto);
        if (segment != NO_SEG && segment % 2) {
            nasm_error(ERR_NONFATAL, "ELF format does not support"
                  " segment base references");
        } else {
            if (wrt == NO_SEG) {
                nasm_error(ERR_WARNING | WARN_GNUELF,
                      "8- or 16-bit relocations in ELF is a GNU extension");
                elf_add_reloc(s, segment, 0, reltype);
            } else {
                nasm_error(ERR_NONFATAL,
                      "Unsupported non-32-bit ELF relocation");
            }
        }
        elf_sect_writeaddr(s, addr, bytes);
        break;

    case OUT_REL4ADR:
        addr = *(int64_t *)data - size;
        if (segment == segto)
            nasm_panic(0, "intra-segment OUT_REL4ADR");
        if (segment != NO_SEG && segment % 2) {
            nasm_error(ERR_NONFATAL, "ELF format does not support"
                  " segment base references");
        } else {
            if (wrt == NO_SEG) {
                elf_add_reloc(s, segment, 0, R_386_PC32);
            } else if (wrt == elf_plt_sect + 1) {
                elf_add_reloc(s, segment, 0, R_386_PLT32);
            } else if (wrt == elf_gotpc_sect + 1 ||
                       wrt == elf_gotoff_sect + 1 ||
                       wrt == elf_got_sect + 1) {
                nasm_error(ERR_NONFATAL, "ELF format cannot produce PC-"
                      "relative GOT references");
            } else {
                nasm_error(ERR_NONFATAL, "ELF format does not support this"
                      " use of WRT");
                wrt = NO_SEG;   /* we can at least _try_ to continue */
            }
        }
        elf_sect_writeaddr(s, addr, 4);
        break;

    case OUT_REL8ADR:
        nasm_error(ERR_NONFATAL, "32-bit ELF format does not support 64-bit relocations");
        addr = 0;
        elf_sect_writeaddr(s, addr, 8);
        break;

    default:
        panic();
    }
}
static void elf64_out(int32_t segto, const void *data,
                      enum out_type type, uint64_t size,
                      int32_t segment, int32_t wrt)
{
    struct elf_section *s;
    int64_t addr;
    int reltype, bytes;
    int i;
    static struct symlininfo sinfo;

    /*
     * handle absolute-assembly (structure definitions)
     */
    if (segto == NO_SEG) {
        if (type != OUT_RESERVE)
            nasm_error(ERR_NONFATAL, "attempt to assemble code in [ABSOLUTE]"
                  " space");
        return;
    }

    s = NULL;
    for (i = 0; i < nsects; i++)
        if (segto == sects[i]->index) {
            s = sects[i];
            break;
        }
    if (!s) {
        int tempint;            /* ignored */
        if (segto != elf_section_names(".text", 2, &tempint))
            nasm_panic(0, "strange segment conditions in ELF driver");
        else {
            s = sects[nsects - 1];
            i = nsects - 1;
        }
    }

    /* again some stabs debugging stuff */
    sinfo.offset = s->len;
    sinfo.section = i;
    sinfo.segto = segto;
    sinfo.name = s->name;
    dfmt->debug_output(TY_DEBUGSYMLIN, &sinfo);
    /* end of debugging stuff */

    if (s->type == SHT_NOBITS && type != OUT_RESERVE) {
        nasm_error(ERR_WARNING, "attempt to initialize memory in"
              " BSS section `%s': ignored", s->name);
        s->len += realsize(type, size);
        return;
    }

    switch (type) {
    case OUT_RESERVE:
        if (s->type == SHT_PROGBITS) {
            nasm_error(ERR_WARNING, "uninitialized space declared in"
                  " non-BSS section `%s': zeroing", s->name);
            elf_sect_write(s, NULL, size);
        } else
            s->len += size;
        break;

    case OUT_RAWDATA:
        if (segment != NO_SEG)
            nasm_panic(0, "OUT_RAWDATA with other than NO_SEG");
        elf_sect_write(s, data, size);
        break;

    case OUT_ADDRESS:
    {
        int isize = (int)size;
        int asize = abs((int)size);

        addr = *(int64_t *)data;
        if (segment == NO_SEG) {
            /* Do nothing */
        } else if (segment % 2) {
            nasm_error(ERR_NONFATAL, "ELF format does not support"
                  " segment base references");
        } else {
            if (wrt == NO_SEG) {
                switch (isize) {
                case 1:
                case -1:
                    elf_add_reloc(s, segment, addr, R_X86_64_8);
                    break;
                case 2:
                case -2:
                    elf_add_reloc(s, segment, addr, R_X86_64_16);
                    break;
                case 4:
                    elf_add_reloc(s, segment, addr, R_X86_64_32);
                    break;
                case -4:
                    elf_add_reloc(s, segment, addr, R_X86_64_32S);
                    break;
                case 8:
                case -8:
                    elf_add_reloc(s, segment, addr, R_X86_64_64);
                    break;
                default:
                    nasm_panic(0, "internal error elf64-hpa-871");
                    break;
                }
                addr = 0;
            } else if (wrt == elf_gotpc_sect + 1) {
                /*
                 * The user will supply GOT relative to $$. ELF
                 * will let us have GOT relative to $. So we
                 * need to fix up the data item by $-$$.
                 */
                addr += s->len;
                elf_add_reloc(s, segment, addr, R_X86_64_GOTPC32);
                addr = 0;
            } else if (wrt == elf_gotoff_sect + 1) {
                if (asize != 8) {
                    nasm_error(ERR_NONFATAL, "ELF64 requires ..gotoff "
                          "references to be qword");
                } else {
                    elf_add_reloc(s, segment, addr, R_X86_64_GOTOFF64);
                    addr = 0;
                }
            } else if (wrt == elf_got_sect + 1) {
                switch (asize) {
                case 4:
                    elf_add_gsym_reloc(s, segment, addr, 0,
                                       R_X86_64_GOT32, true);
                    addr = 0;
                    break;
                case 8:
                    elf_add_gsym_reloc(s, segment, addr, 0,
                                       R_X86_64_GOT64, true);
                    addr = 0;
                    break;
                default:
                    nasm_error(ERR_NONFATAL, "invalid ..got reference");
                    break;
                }
            } else if (wrt == elf_sym_sect + 1) {
                switch (isize) {
                case 1:
                case -1:
                    elf_add_gsym_reloc(s, segment, addr, 0,
                                       R_X86_64_8, false);
                    addr = 0;
                    break;
                case 2:
                case -2:
                    elf_add_gsym_reloc(s, segment, addr, 0,
                                       R_X86_64_16, false);
                    addr = 0;
                    break;
                case 4:
                    elf_add_gsym_reloc(s, segment, addr, 0,
                                       R_X86_64_32, false);
                    addr = 0;
                    break;
                case -4:
                    elf_add_gsym_reloc(s, segment, addr, 0,
                                       R_X86_64_32S, false);
                    addr = 0;
                    break;
                case 8:
                case -8:
                    elf_add_gsym_reloc(s, segment, addr, 0,
                                       R_X86_64_64, false);
                    addr = 0;
                    break;
                default:
                    nasm_panic(0, "internal error elf64-hpa-903");
                    break;
                }
            } else if (wrt == elf_plt_sect + 1) {
                nasm_error(ERR_NONFATAL, "ELF format cannot produce non-PC-"
                      "relative PLT references");
            } else {
                nasm_error(ERR_NONFATAL, "ELF format does not support this"
                      " use of WRT");
            }
        }
        elf_sect_writeaddr(s, addr, asize);
        break;
    }

    case OUT_REL1ADR:
        reltype = R_X86_64_PC8;
        bytes = 1;
        goto rel12adr;

    case OUT_REL2ADR:
        reltype = R_X86_64_PC16;
        bytes = 2;
        goto rel12adr;

rel12adr:
        addr = *(int64_t *)data - size;
        if (segment == segto)
            nasm_panic(0, "intra-segment OUT_REL1ADR");
        if (segment == NO_SEG) {
            /* Do nothing */
        } else if (segment % 2) {
            nasm_error(ERR_NONFATAL, "ELF format does not support"
                  " segment base references");
        } else {
            if (wrt == NO_SEG) {
                elf_add_reloc(s, segment, addr, reltype);
                addr = 0;
            } else {
                nasm_error(ERR_NONFATAL,
                      "Unsupported non-32-bit ELF relocation");
            }
        }
        elf_sect_writeaddr(s, addr, bytes);
        break;

    case OUT_REL4ADR:
        addr = *(int64_t *)data - size;
        if (segment == segto)
            nasm_panic(0, "intra-segment OUT_REL4ADR");
        if (segment == NO_SEG) {
            /* Do nothing */
        } else if (segment % 2) {
            nasm_error(ERR_NONFATAL, "ELF64 format does not support"
                  " segment base references");
        } else {
            if (wrt == NO_SEG) {
                elf_add_reloc(s, segment, addr, R_X86_64_PC32);
                addr = 0;
            } else if (wrt == elf_plt_sect + 1) {
                elf_add_gsym_reloc(s, segment, addr+size, size,
                                   R_X86_64_PLT32, true);
                addr = 0;
            } else if (wrt == elf_gotpc_sect + 1 ||
                       wrt == elf_got_sect + 1) {
                elf_add_gsym_reloc(s, segment, addr+size, size,
                                   R_X86_64_GOTPCREL, true);
                addr = 0;
            } else if (wrt == elf_gotoff_sect + 1 ||
                       wrt == elf_got_sect + 1) {
                nasm_error(ERR_NONFATAL, "ELF64 requires ..gotoff references to be "
                      "qword absolute");
            } else if (wrt == elf_gottpoff_sect + 1) {
                elf_add_gsym_reloc(s, segment, addr+size, size,
                                   R_X86_64_GOTTPOFF, true);
                addr = 0;
            } else {
                nasm_error(ERR_NONFATAL, "ELF64 format does not support this"
                      " use of WRT");
            }
        }
        elf_sect_writeaddr(s, addr, 4);
        break;

    case OUT_REL8ADR:
        addr = *(int64_t *)data - size;
        if (segment == segto)
            nasm_panic(0, "intra-segment OUT_REL8ADR");
        if (segment == NO_SEG) {
            /* Do nothing */
        } else if (segment % 2) {
            nasm_error(ERR_NONFATAL, "ELF64 format does not support"
                  " segment base references");
        } else {
            if (wrt == NO_SEG) {
                elf_add_reloc(s, segment, addr, R_X86_64_PC64);
                addr = 0;
            } else if (wrt == elf_gotpc_sect + 1 ||
                       wrt == elf_got_sect + 1) {
                elf_add_gsym_reloc(s, segment, addr+size, size,
                                   R_X86_64_GOTPCREL64, true);
                addr = 0;
            } else if (wrt == elf_gotoff_sect + 1 ||
                       wrt == elf_got_sect + 1) {
                nasm_error(ERR_NONFATAL, "ELF64 requires ..gotoff references to be "
                      "absolute");
            } else if (wrt == elf_gottpoff_sect + 1) {
                nasm_error(ERR_NONFATAL, "ELF64 requires ..gottpoff references to be "
                      "dword");
            } else {
                nasm_error(ERR_NONFATAL, "ELF64 format does not support this"
                      " use of WRT");
            }
        }
        elf_sect_writeaddr(s, addr, 8);
        break;

    default:
        panic();
    }
}

static void elfx32_out(int32_t segto, const void *data,
                       enum out_type type, uint64_t size,
                       int32_t segment, int32_t wrt)
{
    struct elf_section *s;
    int64_t addr;
    int reltype, bytes;
    int i;
    static struct symlininfo sinfo;

    /*
     * handle absolute-assembly (structure definitions)
     */
    if (segto == NO_SEG) {
        if (type != OUT_RESERVE)
            nasm_error(ERR_NONFATAL, "attempt to assemble code in [ABSOLUTE]"
                  " space");
        return;
    }

    s = NULL;
    for (i = 0; i < nsects; i++)
        if (segto == sects[i]->index) {
            s = sects[i];
            break;
        }
    if (!s) {
        int tempint;            /* ignored */
        if (segto != elf_section_names(".text", 2, &tempint))
            nasm_panic(0, "strange segment conditions in ELF driver");
        else {
            s = sects[nsects - 1];
            i = nsects - 1;
        }
    }

    /* again some stabs debugging stuff */
    sinfo.offset = s->len;
    sinfo.section = i;
    sinfo.segto = segto;
    sinfo.name = s->name;
    dfmt->debug_output(TY_DEBUGSYMLIN, &sinfo);
    /* end of debugging stuff */

    if (s->type == SHT_NOBITS && type != OUT_RESERVE) {
        nasm_error(ERR_WARNING, "attempt to initialize memory in"
              " BSS section `%s': ignored", s->name);
        s->len += realsize(type, size);
        return;
    }

    switch (type) {
    case OUT_RESERVE:
        if (s->type == SHT_PROGBITS) {
            nasm_error(ERR_WARNING, "uninitialized space declared in"
                  " non-BSS section `%s': zeroing", s->name);
            elf_sect_write(s, NULL, size);
        } else
            s->len += size;
        break;

    case OUT_RAWDATA:
        if (segment != NO_SEG)
            nasm_panic(0, "OUT_RAWDATA with other than NO_SEG");
        elf_sect_write(s, data, size);
        break;

    case OUT_ADDRESS:
    {
        int isize = (int)size;
        int asize = abs((int)size);

        addr = *(int64_t *)data;
        if (segment == NO_SEG) {
            /* Do nothing */
        } else if (segment % 2) {
            nasm_error(ERR_NONFATAL, "ELF format does not support"
                  " segment base references");
        } else {
            if (wrt == NO_SEG) {
                switch (isize) {
                case 1:
                case -1:
                    elf_add_reloc(s, segment, addr, R_X86_64_8);
                    break;
                case 2:
                case -2:
                    elf_add_reloc(s, segment, addr, R_X86_64_16);
                    break;
                case 4:
                    elf_add_reloc(s, segment, addr, R_X86_64_32);
                    break;
                case -4:
                    elf_add_reloc(s, segment, addr, R_X86_64_32S);
                    break;
                case 8:
                case -8:
                    elf_add_reloc(s, segment, addr, R_X86_64_64);
                    break;
                default:
                    nasm_panic(0, "internal error elfx32-hpa-871");
                    break;
                }
                addr = 0;
            } else if (wrt == elf_gotpc_sect + 1) {
                /*
                 * The user will supply GOT relative to $$. ELF
                 * will let us have GOT relative to $. So we
                 * need to fix up the data item by $-$$.
                 */
                addr += s->len;
                elf_add_reloc(s, segment, addr, R_X86_64_GOTPC32);
                addr = 0;
            } else if (wrt == elf_gotoff_sect + 1) {
                nasm_error(ERR_NONFATAL, "ELFX32 doesn't support "
                      "R_X86_64_GOTOFF64");
            } else if (wrt == elf_got_sect + 1) {
                switch (asize) {
                case 4:
                    elf_add_gsym_reloc(s, segment, addr, 0,
                                       R_X86_64_GOT32, true);
                    addr = 0;
                    break;
                default:
                    nasm_error(ERR_NONFATAL, "invalid ..got reference");
                    break;
                }
            } else if (wrt == elf_sym_sect + 1) {
                switch (isize) {
                case 1:
                case -1:
                    elf_add_gsym_reloc(s, segment, addr, 0,
                                       R_X86_64_8, false);
                    addr = 0;
                    break;
                case 2:
                case -2:
                    elf_add_gsym_reloc(s, segment, addr, 0,
                                       R_X86_64_16, false);
                    addr = 0;
                    break;
                case 4:
                    elf_add_gsym_reloc(s, segment, addr, 0,
                                       R_X86_64_32, false);
                    addr = 0;
                    break;
                case -4:
                    elf_add_gsym_reloc(s, segment, addr, 0,
                                       R_X86_64_32S, false);
                    addr = 0;
                    break;
                case 8:
                case -8:
                    elf_add_gsym_reloc(s, segment, addr, 0,
                                       R_X86_64_64, false);
                    addr = 0;
                    break;
                default:
                    nasm_panic(0, "internal error elfx32-hpa-903");
                    break;
                }
            } else if (wrt == elf_plt_sect + 1) {
                nasm_error(ERR_NONFATAL, "ELF format cannot produce non-PC-"
                      "relative PLT references");
            } else {
                nasm_error(ERR_NONFATAL, "ELF format does not support this"
                      " use of WRT");
            }
        }
        elf_sect_writeaddr(s, addr, asize);
        break;
    }

    case OUT_REL1ADR:
        reltype = R_X86_64_PC8;
        bytes = 1;
        goto rel12adr;

    case OUT_REL2ADR:
        reltype = R_X86_64_PC16;
        bytes = 2;
        goto rel12adr;

rel12adr:
        addr = *(int64_t *)data - size;
        if (segment == segto)
            nasm_panic(0, "intra-segment OUT_REL1ADR");
        if (segment == NO_SEG) {
            /* Do nothing */
        } else if (segment % 2) {
            nasm_error(ERR_NONFATAL, "ELF format does not support"
                  " segment base references");
        } else {
            if (wrt == NO_SEG) {
                elf_add_reloc(s, segment, addr, reltype);
                addr = 0;
            } else {
                nasm_error(ERR_NONFATAL,
                      "Unsupported non-32-bit ELF relocation");
            }
        }
        elf_sect_writeaddr(s, addr, bytes);
        break;

    case OUT_REL4ADR:
        addr = *(int64_t *)data - size;
        if (segment == segto)
            nasm_panic(0, "intra-segment OUT_REL4ADR");
        if (segment == NO_SEG) {
            /* Do nothing */
        } else if (segment % 2) {
            nasm_error(ERR_NONFATAL, "ELFX32 format does not support"
                  " segment base references");
        } else {
            if (wrt == NO_SEG) {
                elf_add_reloc(s, segment, addr, R_X86_64_PC32);
                addr = 0;
            } else if (wrt == elf_plt_sect + 1) {
                elf_add_gsym_reloc(s, segment, addr+size, size,
                                   R_X86_64_PLT32, true);
                addr = 0;
            } else if (wrt == elf_gotpc_sect + 1 ||
                       wrt == elf_got_sect + 1) {
                elf_add_gsym_reloc(s, segment, addr+size, size,
                                   R_X86_64_GOTPCREL, true);
                addr = 0;
            } else if (wrt == elf_gotoff_sect + 1 ||
                       wrt == elf_got_sect + 1) {
                nasm_error(ERR_NONFATAL, "invalid ..gotoff reference");
            } else if (wrt == elf_gottpoff_sect + 1) {
                elf_add_gsym_reloc(s, segment, addr+size, size,
                                   R_X86_64_GOTTPOFF, true);
                addr = 0;
            } else {
                nasm_error(ERR_NONFATAL, "ELFX32 format does not support this"
                      " use of WRT");
            }
        }
        elf_sect_writeaddr(s, addr, 4);
        break;

    case OUT_REL8ADR:
        nasm_error(ERR_NONFATAL, "32-bit ELF format does not support 64-bit relocations");
        addr = 0;
        elf_sect_writeaddr(s, addr, 8);
        break;

    default:
        panic();
    }
}

static void elf_write(void)
{
    int align;
    char *p;
    int i;

    struct SAA *symtab;
    int32_t symtablen, symtablocal;

    /*
     * Work out how many sections we will have. We have SHN_UNDEF,
     * then the flexible user sections, then the fixed sections
     * `.shstrtab', `.symtab' and `.strtab', then optionally
     * relocation sections for the user sections.
     */
    nsections = sec_numspecial + 1;
	if (dfmt_is_stabs())
        nsections += 3;
    else if (dfmt_is_dwarf())
        nsections += 10;

    add_sectname("", ".shstrtab");
    add_sectname("", ".symtab");
    add_sectname("", ".strtab");
    for (i = 0; i < nsects; i++) {
        nsections++;            /* for the section itself */
        if (sects[i]->head) {
            nsections++;        /* for its relocations */
            add_sectname(is_elf32() ? ".rel" : ".rela", sects[i]->name);
        }
    }

    if (dfmt_is_stabs()) {
        /* in case the debug information is wanted, just add these three sections... */
        add_sectname("", ".stab");
        add_sectname("", ".stabstr");
        add_sectname(is_elf32() ? ".rel" : ".rela", ".stab");
    } else if (dfmt_is_dwarf()) {
        /* the dwarf debug standard specifies the following ten sections,
           not all of which are currently implemented,
           although all of them are defined. */
#define debug_aranges (int64_t) (nsections-10)
#define debug_info (int64_t) (nsections-7)
#define debug_abbrev (int64_t) (nsections-5)
#define debug_line (int64_t) (nsections-4)
        add_sectname("", ".debug_aranges");
        add_sectname(".rela", ".debug_aranges");
        add_sectname("", ".debug_pubnames");
        add_sectname("", ".debug_info");
        add_sectname(".rela", ".debug_info");
        add_sectname("", ".debug_abbrev");
        add_sectname("", ".debug_line");
        add_sectname(".rela", ".debug_line");
        add_sectname("", ".debug_frame");
        add_sectname("", ".debug_loc");
    }

    /*
     * Output the ELF header.
     */
    if (is_elf32() || is_elfx32()) {
        Elf32_Ehdr ehdr;

        nasm_zero(ehdr.e_ident);
        memcpy(ehdr.e_ident, ELFMAG, SELFMAG);
        ehdr.e_ident[EI_CLASS]      = ELFCLASS32;
        ehdr.e_ident[EI_DATA]       = ELFDATA2LSB;
        ehdr.e_ident[EI_VERSION]    = EV_CURRENT;
        ehdr.e_ident[EI_OSABI]      = elf_osabi;
        ehdr.e_ident[EI_ABIVERSION] = elf_abiver;

        ehdr.e_type                 = cpu_to_le16(ET_REL);
        ehdr.e_machine              = cpu_to_le16(is_elf32() ? EM_386 : EM_X86_64);
        ehdr.e_version              = cpu_to_le16(EV_CURRENT);
        ehdr.e_entry                = 0;
        ehdr.e_phoff                = 0;
        ehdr.e_shoff                = sizeof(Elf64_Ehdr);
        ehdr.e_flags                = 0;
        ehdr.e_ehsize               = cpu_to_le16(sizeof(Elf32_Ehdr));
        ehdr.e_phentsize            = 0;
        ehdr.e_phnum                = 0;
        ehdr.e_shentsize            = cpu_to_le16(sizeof(Elf32_Shdr));
        ehdr.e_shnum                = cpu_to_le16(nsections);
        ehdr.e_shstrndx             = cpu_to_le16(sec_shstrtab);

        nasm_write(&ehdr, sizeof(ehdr), ofile);
        fwritezero(sizeof(Elf64_Ehdr) - sizeof(Elf32_Ehdr), ofile);
    } else {
        Elf64_Ehdr ehdr;

        nasm_assert(is_elf64());

        nasm_zero(ehdr.e_ident);
        memcpy(ehdr.e_ident, ELFMAG, SELFMAG);
        ehdr.e_ident[EI_CLASS]      = ELFCLASS64;
        ehdr.e_ident[EI_DATA]       = ELFDATA2LSB;
        ehdr.e_ident[EI_VERSION]    = EV_CURRENT;
        ehdr.e_ident[EI_OSABI]      = elf_osabi;
        ehdr.e_ident[EI_ABIVERSION] = elf_abiver;

        ehdr.e_type                 = cpu_to_le16(ET_REL);
        ehdr.e_machine              = cpu_to_le16(EM_X86_64);
        ehdr.e_version              = cpu_to_le16(EV_CURRENT);
        ehdr.e_entry                = 0;
        ehdr.e_phoff                = 0;
        ehdr.e_shoff                = sizeof(Elf64_Ehdr);
        ehdr.e_flags                = 0;
        ehdr.e_ehsize               = cpu_to_le16(sizeof(Elf64_Ehdr));
        ehdr.e_phentsize            = 0;
        ehdr.e_phnum                = 0;
        ehdr.e_shentsize            = cpu_to_le16(sizeof(Elf64_Shdr));
        ehdr.e_shnum                = cpu_to_le16(nsections);
        ehdr.e_shstrndx             = cpu_to_le16(sec_shstrtab);

        nasm_write(&ehdr, sizeof(ehdr), ofile);
    }

    /*
     * Build the symbol table and relocation tables.
     */
    symtab = elf_build_symtab(&symtablen, &symtablocal);
    for (i = 0; i < nsects; i++)
        if (sects[i]->head)
            sects[i]->rel = elf_build_reltab(&sects[i]->rellen,
                                             sects[i]->head);

    /*
     * Now output the section header table.
     */

    elf_foffs = sizeof(Elf64_Ehdr) + (is_elf64() ? sizeof(Elf64_Shdr): sizeof(Elf32_Shdr)) * nsections;
    align = ALIGN(elf_foffs, SEC_FILEALIGN) - elf_foffs;
    elf_foffs += align;
    elf_nsect = 0;
    elf_sects = nasm_malloc(sizeof(*elf_sects) * nsections);

    /* SHN_UNDEF */
    elf_section_header(0, SHT_NULL, 0, NULL, false, 0, SHN_UNDEF, 0, 0, 0);
    p = shstrtab + 1;

    /* The normal sections */
    for (i = 0; i < nsects; i++) {
        elf_section_header(p - shstrtab, sects[i]->type, sects[i]->flags,
                           sects[i]->data, true,
                           sects[i]->len, 0, 0,
                           sects[i]->align, sects[i]->entsize);
        p += strlen(p) + 1;
    }

    /* .shstrtab */
    elf_section_header(p - shstrtab, SHT_STRTAB, 0, shstrtab, false,
                       shstrtablen, 0, 0, 1, 0);
    p += strlen(p) + 1;

    /* .symtab */
    if (is_elf64())
        elf_section_header(p - shstrtab, SHT_SYMTAB, 0, symtab, true,
                           symtablen, sec_strtab, symtablocal, 8, 24);
    else
        elf_section_header(p - shstrtab, SHT_SYMTAB, 0, symtab, true,
                           symtablen, sec_strtab, symtablocal, 4, 16);
    p += strlen(p) + 1;

    /* .strtab */
    elf_section_header(p - shstrtab, SHT_STRTAB, 0, strs, true,
                       strslen, 0, 0, 1, 0);
    p += strlen(p) + 1;

    /* The relocation sections */
    if (is_elf32()) {
        for (i = 0; i < nsects; i++) {
            if (sects[i]->head) {
                elf_section_header(p - shstrtab, SHT_REL, 0, sects[i]->rel, true,
                                   sects[i]->rellen, sec_symtab, i + 1, 4, 8);
                p += strlen(p) + 1;
            }
        }
    } else if (is_elfx32()) {
        for (i = 0; i < nsects; i++) {
            if (sects[i]->head) {
                elf_section_header(p - shstrtab, SHT_RELA, 0, sects[i]->rel, true,
                                   sects[i]->rellen, sec_symtab, i + 1, 4, 12);
                p += strlen(p) + 1;
            }
        }
    } else {
        nasm_assert(is_elf64());
        for (i = 0; i < nsects; i++) {
            if (sects[i]->head) {
                elf_section_header(p - shstrtab, SHT_RELA, 0, sects[i]->rel, true,
                                   sects[i]->rellen, sec_symtab, i + 1, 8, 24);
                p += strlen(p) + 1;
            }
        }
    }

    if (dfmt_is_stabs()) {
        /* for debugging information, create the last three sections
           which are the .stab , .stabstr and .rel.stab sections respectively */

        /* this function call creates the stab sections in memory */
        stabs_generate();

        if (stabbuf && stabstrbuf && stabrelbuf) {
            elf_section_header(p - shstrtab, SHT_PROGBITS, 0, stabbuf, false,
                                stablen, sec_stabstr, 0, 4, 12);
            p += strlen(p) + 1;

            elf_section_header(p - shstrtab, SHT_STRTAB, 0, stabstrbuf, false,
                               stabstrlen, 0, 0, 4, 0);
            p += strlen(p) + 1;

            /* link -> symtable  info -> section to refer to */
            if (is_elf32()) {
                elf_section_header(p - shstrtab, SHT_REL, 0, stabrelbuf, false,
                                   stabrellen, sec_symtab, sec_stab, 4, 8);
            } else {
                elf_section_header(p - shstrtab, SHT_RELA, 0, stabrelbuf, false,
                                   stabrellen, sec_symtab, sec_stab, 4, is_elf64() ? 24 : 12);
            }
            p += strlen(p) + 1;
        }
    } else if (dfmt_is_dwarf()) {
            /* for dwarf debugging information, create the ten dwarf sections */

            /* this function call creates the dwarf sections in memory */
            if (dwarf_fsect)
                dwarf_generate();

            elf_section_header(p - shstrtab, SHT_PROGBITS, 0, arangesbuf, false,
                               arangeslen, 0, 0, 1, 0);
            p += strlen(p) + 1;

            elf_section_header(p - shstrtab, SHT_RELA, 0, arangesrelbuf, false,
                               arangesrellen, sec_symtab,
                               is_elf64() ? debug_aranges : sec_debug_aranges,
                               1, is_elf64() ? 24 : 12);
            p += strlen(p) + 1;

            elf_section_header(p - shstrtab, SHT_PROGBITS, 0, pubnamesbuf,
                               false, pubnameslen, 0, 0, 1, 0);
            p += strlen(p) + 1;

            elf_section_header(p - shstrtab, SHT_PROGBITS, 0, infobuf, false,
                               infolen, 0, 0, 1, 0);
            p += strlen(p) + 1;

            elf_section_header(p - shstrtab, SHT_RELA, 0, inforelbuf, false,
                               inforellen, sec_symtab,
                               is_elf64() ? debug_info : sec_debug_info,
                               1, is_elf64() ? 24 : 12);
            p += strlen(p) + 1;

            elf_section_header(p - shstrtab, SHT_PROGBITS, 0, abbrevbuf, false,
                               abbrevlen, 0, 0, 1, 0);
            p += strlen(p) + 1;

            elf_section_header(p - shstrtab, SHT_PROGBITS, 0, linebuf, false,
                               linelen, 0, 0, 1, 0);
            p += strlen(p) + 1;

            elf_section_header(p - shstrtab, SHT_RELA, 0, linerelbuf, false,
                               linerellen, sec_symtab,
                               is_elf64() ? debug_line : sec_debug_line,
                               1, is_elf64() ? 24 : 12);
            p += strlen(p) + 1;

            elf_section_header(p - shstrtab, SHT_PROGBITS, 0, framebuf, false,
                               framelen, 0, 0, 8, 0);
            p += strlen(p) + 1;

            elf_section_header(p - shstrtab, SHT_PROGBITS, 0, locbuf, false,
                               loclen, 0, 0, 1, 0);
            p += strlen(p) + 1;
    }
    fwritezero(align, ofile);

    /*
     * Now output the sections.
     */
    elf_write_sections();

    nasm_free(elf_sects);
    saa_free(symtab);
}

static struct SAA *elf_build_symtab(int32_t *len, int32_t *local)
{
    struct SAA *s = saa_init(1L);
    struct elf_symbol *sym;
    int i;

    size_t usize = is_elf64() ? sizeof(Elf64_Sym) : sizeof(Elf32_Sym);
    union {
        Elf32_Sym   sym32;
        Elf64_Sym   sym64;
    } u;

    *len = *local = 0;

    /*
     * Zero symbol first as required by spec.
     */
    saa_wbytes(s, NULL, usize);
    *len += usize;
    (*local)++;

    /*
     * Next, an entry for the file name.
     */
    if (is_elf64()) {
        u.sym64.st_name     = cpu_to_le32(1);
        u.sym64.st_info     = ELF64_ST_INFO(STB_LOCAL, STT_FILE);
        u.sym64.st_other    = 0;
        u.sym64.st_shndx    = cpu_to_le16(SHN_ABS);
        u.sym64.st_value    = 0;
        u.sym64.st_size     = 0;
    } else {
        u.sym32.st_name     = cpu_to_le32(1);
        u.sym32.st_value    = 0;
        u.sym32.st_size     = 0;
        u.sym32.st_info     = ELF32_ST_INFO(STB_LOCAL, STT_FILE);
        u.sym32.st_other    = 0;
        u.sym32.st_shndx    = cpu_to_le16(SHN_ABS);
    }
    saa_wbytes(s, &u, usize);
    *len += usize;
    (*local)++;


    /*
     * Now some standard symbols defining the segments, for relocation
     * purposes.
     */
    if (is_elf64()) {
        u.sym64.st_name     = 0;
        u.sym64.st_other    = 0;
        u.sym64.st_value    = 0;
        u.sym64.st_size     = 0;
        for (i = 1; i <= nsects; i++) {
            u.sym64.st_info      = ELF64_ST_INFO(STB_LOCAL, STT_SECTION);
            u.sym64.st_shndx     = cpu_to_le16(i);
            saa_wbytes(s, &u, usize);
            *len += usize;
            (*local)++;
        }
    } else {
        u.sym32.st_name     = 0;
        u.sym32.st_value    = 0;
        u.sym32.st_size     = 0;
        u.sym32.st_other    = 0;
        for (i = 1; i <= nsects; i++) {
            u.sym32.st_info      = ELF32_ST_INFO(STB_LOCAL, STT_SECTION);
            u.sym32.st_shndx     = cpu_to_le16(i);
            saa_wbytes(s, &u, usize);
            *len += usize;
            (*local)++;
        }
    }

    /*
     * Now the other local symbols.
     */
    saa_rewind(syms);
    if (is_elf64()) {
        while ((sym = saa_rstruct(syms))) {
            if (sym->type & SYM_GLOBAL)
                continue;
            u.sym64.st_name     = cpu_to_le32(sym->strpos);
            u.sym64.st_info     = sym->type;
            u.sym64.st_other    = sym->other;
            u.sym64.st_shndx    = cpu_to_le16(sym->section);
            u.sym64.st_value    = cpu_to_le64(sym->symv.key);
            u.sym64.st_size     = cpu_to_le64(sym->size);
            saa_wbytes(s, &u, usize);
            *len += usize;
            (*local)++;
        }
        /*
         * dwarf needs symbols for debug sections
         * which are relocation targets.
         */
        if (dfmt_is_dwarf()) {
            dwarf_infosym = *local;
            u.sym64.st_name     = 0;
            u.sym64.st_info     = ELF64_ST_INFO(STB_LOCAL, STT_SECTION);
            u.sym64.st_other    = 0;
            u.sym64.st_shndx    = cpu_to_le16(debug_info);
            u.sym64.st_value    = 0;
            u.sym64.st_size     = 0;
            saa_wbytes(s, &u, usize);
            *len += usize;
            (*local)++;
            dwarf_abbrevsym = *local;
            u.sym64.st_name     = 0;
            u.sym64.st_info     = ELF64_ST_INFO(STB_LOCAL, STT_SECTION);
            u.sym64.st_other    = 0;
            u.sym64.st_shndx    = cpu_to_le16(debug_abbrev);
            u.sym64.st_value    = 0;
            u.sym64.st_size     = 0;
            saa_wbytes(s, &u, usize);
            *len += usize;
            (*local)++;
            dwarf_linesym = *local;
            u.sym64.st_name     = 0;
            u.sym64.st_info     = ELF64_ST_INFO(STB_LOCAL, STT_SECTION);
            u.sym64.st_other    = 0;
            u.sym64.st_shndx    = cpu_to_le16(debug_line);
            u.sym64.st_value    = 0;
            u.sym64.st_size     = 0;
            saa_wbytes(s, &u, usize);
            *len += usize;
            (*local)++;
        }
    } else {
        while ((sym = saa_rstruct(syms))) {
            if (sym->type & SYM_GLOBAL)
                continue;
            u.sym32.st_name     = cpu_to_le32(sym->strpos);
            u.sym32.st_value    = cpu_to_le32(sym->symv.key);
            u.sym32.st_size     = cpu_to_le32(sym->size);
            u.sym32.st_info     = sym->type;
            u.sym32.st_other    = sym->other;
            u.sym32.st_shndx    = cpu_to_le16(sym->section);
            saa_wbytes(s, &u, usize);
            *len += usize;
            (*local)++;
        }
        /*
         * dwarf needs symbols for debug sections
         * which are relocation targets.
         */
        if (dfmt_is_dwarf()) {
            dwarf_infosym = *local;
            u.sym32.st_name     = 0;
            u.sym32.st_value    = 0;
            u.sym32.st_size     = 0;
            u.sym32.st_info     = ELF32_ST_INFO(STB_LOCAL, STT_SECTION);
            u.sym32.st_other    = 0;
            u.sym32.st_shndx    = cpu_to_le16(sec_debug_info);
            saa_wbytes(s, &u, usize);
            *len += usize;
            (*local)++;
            dwarf_abbrevsym = *local;
            u.sym32.st_name     = 0;
            u.sym32.st_value    = 0;
            u.sym32.st_size     = 0;
            u.sym32.st_info     = ELF32_ST_INFO(STB_LOCAL, STT_SECTION);
            u.sym32.st_other    = 0;
            u.sym32.st_shndx    = cpu_to_le16(sec_debug_abbrev);
            saa_wbytes(s, &u, usize);
            *len += usize;
            (*local)++;
            dwarf_linesym = *local;
            u.sym32.st_name     = 0;
            u.sym32.st_value    = 0;
            u.sym32.st_size     = 0;
            u.sym32.st_info     = ELF32_ST_INFO(STB_LOCAL, STT_SECTION);
            u.sym32.st_other    = 0;
            u.sym32.st_shndx    = cpu_to_le16(sec_debug_line);
            saa_wbytes(s, &u, usize);
            *len += usize;
            (*local)++;
        }
    }

    /*
     * Now the global symbols.
     */
    saa_rewind(syms);
    if (is_elf64()) {
        while ((sym = saa_rstruct(syms))) {
            if (!(sym->type & SYM_GLOBAL))
                continue;
            u.sym64.st_name     = cpu_to_le32(sym->strpos);
            u.sym64.st_info     = sym->type;
            u.sym64.st_other    = sym->other;
            u.sym64.st_shndx    = cpu_to_le16(sym->section);
            u.sym64.st_value    = cpu_to_le64(sym->symv.key);
            u.sym64.st_size     = cpu_to_le64(sym->size);
            saa_wbytes(s, &u, usize);
            *len += usize;
        }
    } else {
        while ((sym = saa_rstruct(syms))) {
            if (!(sym->type & SYM_GLOBAL))
                continue;
            u.sym32.st_name     = cpu_to_le32(sym->strpos);
            u.sym32.st_value    = cpu_to_le32(sym->symv.key);
            u.sym32.st_size     = cpu_to_le32(sym->size);
            u.sym32.st_info     = sym->type;
            u.sym32.st_other    = sym->other;
            u.sym32.st_shndx    = cpu_to_le16(sym->section);
            saa_wbytes(s, &u, usize);
            *len += usize;
        }
    }

    return s;
}

static struct SAA *elf_build_reltab(uint64_t *len, struct elf_reloc *r)
{
    struct SAA *s;
    int32_t global_offset;

    size_t usize = is_elf64() ? sizeof(Elf64_Rela) :
        (is_elfx32() ? sizeof(Elf32_Rela) : sizeof(Elf32_Rel));
    union {
        Elf32_Rel   rel32;
        Elf32_Rela  rela32;
        Elf64_Rela  rela64;
    } u;

    if (!r)
        return NULL;

    s = saa_init(1L);
    *len = 0;

    /*
     * How to onvert from a global placeholder to a real symbol index;
     * the +2 refers to the two special entries, the null entry and
     * the filename entry.
     */
    global_offset = -GLOBAL_TEMP_BASE + nsects + nlocals + ndebugs + 2;

    if (is_elf32()) {
        while (r) {
            int32_t sym = r->symbol;

            if (sym >= GLOBAL_TEMP_BASE)
                sym += global_offset;

            u.rel32.r_offset    = cpu_to_le32(r->address);
            u.rel32.r_info      = cpu_to_le32(ELF32_R_INFO(sym, r->type));
            saa_wbytes(s, &u, usize);
            *len += usize;

            r = r->next;
        }
    } else if (is_elfx32()) {
        while (r) {
            int32_t sym = r->symbol;

            if (sym >= GLOBAL_TEMP_BASE)
                sym += global_offset;

            u.rela32.r_offset   = cpu_to_le32(r->address);
            u.rela32.r_info     = cpu_to_le32(ELF32_R_INFO(sym, r->type));
            u.rela32.r_addend   = cpu_to_le32(r->offset);
            saa_wbytes(s, &u, usize);
            *len += usize;

            r = r->next;
        }
    } else {
        nasm_assert(is_elf64());
        while (r) {
            int32_t sym = r->symbol;

            if (sym >= GLOBAL_TEMP_BASE)
                sym += global_offset;

            u.rela64.r_offset   = cpu_to_le64(r->address);
            u.rela64.r_info     = cpu_to_le64(ELF64_R_INFO(sym, r->type));
            u.rela64.r_addend   = cpu_to_le64(r->offset);
            saa_wbytes(s, &u, usize);
            *len += usize;

            r = r->next;
        }
    }

    return s;
}

static void elf_section_header(int name, int type, uint64_t flags,
                               void *data, bool is_saa, uint64_t datalen,
                               int link, int info,
                               uint64_t align, uint64_t entsize)
{
    union {
        Elf32_Shdr  shdr32;
        Elf64_Shdr  shdr64;
    } shdr;

    elf_sects[elf_nsect].data = data;
    elf_sects[elf_nsect].len = datalen;
    elf_sects[elf_nsect].is_saa = is_saa;
    elf_nsect++;

    if (is_elf32() || is_elfx32()) {
        shdr.shdr32.sh_name         = cpu_to_le32(name);
        shdr.shdr32.sh_type         = cpu_to_le32(type);
        shdr.shdr32.sh_flags        = cpu_to_le32(flags);
        shdr.shdr32.sh_addr         = 0;
        shdr.shdr32.sh_offset       = cpu_to_le32(type == SHT_NULL ? 0 : elf_foffs);
        shdr.shdr32.sh_size         = cpu_to_le32(datalen);
        if (data)
            elf_foffs += ALIGN(datalen, SEC_FILEALIGN);
        shdr.shdr32.sh_link         = cpu_to_le32(link);
        shdr.shdr32.sh_info         = cpu_to_le32(info);
        shdr.shdr32.sh_addralign    = cpu_to_le32(align);
        shdr.shdr32.sh_entsize      = cpu_to_le32(entsize);
    } else {
        nasm_assert(is_elf64());

        shdr.shdr64.sh_name         = cpu_to_le32(name);
        shdr.shdr64.sh_type         = cpu_to_le32(type);
        shdr.shdr64.sh_flags        = cpu_to_le64(flags);
        shdr.shdr64.sh_addr         = 0;
        shdr.shdr64.sh_offset       = cpu_to_le64(type == SHT_NULL ? 0 : elf_foffs);
        shdr.shdr64.sh_size         = cpu_to_le32(datalen);
        if (data)
            elf_foffs += ALIGN(datalen, SEC_FILEALIGN);
        shdr.shdr64.sh_link        = cpu_to_le32(link);
        shdr.shdr64.sh_info        = cpu_to_le32(info);
        shdr.shdr64.sh_addralign   = cpu_to_le64(align);
        shdr.shdr64.sh_entsize     = cpu_to_le64(entsize);
    }

    nasm_write(&shdr, is_elf64() ? sizeof(shdr.shdr64) : sizeof(shdr.shdr32), ofile);
}

static void elf_write_sections(void)
{
    int i;
    for (i = 0; i < elf_nsect; i++)
        if (elf_sects[i].data) {
            int32_t len = elf_sects[i].len;
            int32_t reallen = ALIGN(len, SEC_FILEALIGN);
            int32_t align = reallen - len;
            if (elf_sects[i].is_saa)
                saa_fpwrite(elf_sects[i].data, ofile);
            else
                nasm_write(elf_sects[i].data, len, ofile);
            fwritezero(align, ofile);
        }
}

static void elf_sect_write(struct elf_section *sect, const void *data, size_t len)
{
    saa_wbytes(sect->data, data, len);
    sect->len += len;
}

static void elf_sect_writeaddr(struct elf_section *sect, int64_t data, size_t len)
{
    saa_writeaddr(sect->data, data, len);
    sect->len += len;
}

static void elf_sectalign(int32_t seg, unsigned int value)
{
    struct elf_section *s = NULL;
    int i;

    for (i = 0; i < nsects; i++) {
        if (sects[i]->index == seg) {
            s = sects[i];
            break;
        }
    }
    if (!s || !is_power2(value))
        return;

    if (value > s->align)
        s->align = value;
}

static int32_t elf_segbase(int32_t segment)
{
    return segment;
}

extern macros_t elf_stdmac[];

/* Claim "elf" as a pragma namespace, for the future */
static const struct pragma_facility elf_pragma_list[] =
{
    { "elf", NULL },
    { NULL, NULL }          /* Implements the canonical output name */
};


static const struct dfmt elf32_df_dwarf = {
    "ELF32 (i386) dwarf debug format for Linux/Unix",
    "dwarf",
    dwarf_init,
    dwarf_linenum,
    null_debug_deflabel,
    null_debug_directive,
    debug_typevalue,
    dwarf_output,
    dwarf_cleanup,
    NULL                        /* pragma list */
};

static const struct dfmt elf32_df_stabs = {
    "ELF32 (i386) stabs debug format for Linux/Unix",
    "stabs",
    null_debug_init,
    stabs_linenum,
    null_debug_deflabel,
    null_debug_directive,
    debug_typevalue,
    stabs_output,
    stabs_cleanup,
    NULL                        /* pragma list */
};

static const struct dfmt * const elf32_debugs_arr[3] =
  { &elf32_df_dwarf, &elf32_df_stabs, NULL };

const struct ofmt of_elf32 = {
    "ELF32 (i386) object files (e.g. Linux)",
    "elf32",
    ".o",
    0,
    32,
    elf32_debugs_arr,
    &elf32_df_stabs,
    elf_stdmac,
    elf_init,
    null_reset,
    nasm_do_legacy_output,
    elf32_out,
    elf_deflabel,
    elf_section_names,
    NULL,
    elf_sectalign,
    elf_segbase,
    elf_directive,
    elf_cleanup,
    elf_pragma_list,
};

static const struct dfmt elf64_df_dwarf = {
    "ELF64 (x86-64) dwarf debug format for Linux/Unix",
    "dwarf",
    dwarf_init,
    dwarf_linenum,
    null_debug_deflabel,
    null_debug_directive,
    debug_typevalue,
    dwarf_output,
    dwarf_cleanup,
    NULL                        /* pragma list */
};

static const struct dfmt elf64_df_stabs = {
    "ELF64 (x86-64) stabs debug format for Linux/Unix",
    "stabs",
    null_debug_init,
    stabs_linenum,
    null_debug_deflabel,
    null_debug_directive,
    debug_typevalue,
    stabs_output,
    stabs_cleanup,
    NULL                        /* pragma list */
};

static const struct dfmt * const elf64_debugs_arr[3] =
  { &elf64_df_dwarf, &elf64_df_stabs, NULL };

const struct ofmt of_elf64 = {
    "ELF64 (x86_64) object files (e.g. Linux)",
    "elf64",
    ".o",
    0,
    64,
    elf64_debugs_arr,
    &elf64_df_stabs,
    elf_stdmac,
    elf_init,
    null_reset,
    nasm_do_legacy_output,
    elf64_out,
    elf_deflabel,
    elf_section_names,
    NULL,
    elf_sectalign,
    elf_segbase,
    elf_directive,
    elf_cleanup,
    elf_pragma_list,
};

static const struct dfmt elfx32_df_dwarf = {
    "ELFX32 (x86-64) dwarf debug format for Linux/Unix",
    "dwarf",
    dwarf_init,
    dwarf_linenum,
    null_debug_deflabel,
    null_debug_directive,
    debug_typevalue,
    dwarf_output,
    dwarf_cleanup,
    NULL                        /* pragma list */
};

static const struct dfmt elfx32_df_stabs = {
    "ELFX32 (x86-64) stabs debug format for Linux/Unix",
    "stabs",
    null_debug_init,
    stabs_linenum,
    null_debug_deflabel,
    null_debug_directive,
    debug_typevalue,
    stabs_output,
    stabs_cleanup,
    elf_pragma_list,
};

static const struct dfmt * const elfx32_debugs_arr[3] =
  { &elfx32_df_dwarf, &elfx32_df_stabs, NULL };

const struct ofmt of_elfx32 = {
    "ELFX32 (x86_64) object files (e.g. Linux)",
    "elfx32",
    ".o",
    0,
    64,
    elfx32_debugs_arr,
    &elfx32_df_stabs,
    elf_stdmac,
    elf_init,
    null_reset,
    nasm_do_legacy_output,
    elfx32_out,
    elf_deflabel,
    elf_section_names,
    NULL,
    elf_sectalign,
    elf_segbase,
    elf_directive,
    elf_cleanup,
    NULL                        /* pragma list */
};

static bool is_elf64(void)
{
	return ofmt == &of_elf64;
}

static bool is_elf32(void)
{
	return ofmt == &of_elf32;
}

static bool is_elfx32(void)
{
	return ofmt == &of_elfx32;
}

static bool dfmt_is_stabs(void)
{
	return dfmt == &elf32_df_stabs ||
               dfmt == &elfx32_df_stabs ||
               dfmt == &elf64_df_stabs;
}

static bool dfmt_is_dwarf(void)
{
	return dfmt == &elf32_df_dwarf ||
               dfmt == &elfx32_df_dwarf ||
               dfmt == &elf64_df_dwarf;
}

/* common debugging routines */
static void debug_typevalue(int32_t type)
{
    int32_t stype, ssize;
    switch (TYM_TYPE(type)) {
        case TY_LABEL:
            ssize = 0;
            stype = STT_NOTYPE;
            break;
        case TY_BYTE:
            ssize = 1;
            stype = STT_OBJECT;
            break;
        case TY_WORD:
            ssize = 2;
            stype = STT_OBJECT;
            break;
        case TY_DWORD:
            ssize = 4;
            stype = STT_OBJECT;
            break;
        case TY_FLOAT:
            ssize = 4;
            stype = STT_OBJECT;
            break;
        case TY_QWORD:
            ssize = 8;
            stype = STT_OBJECT;
            break;
        case TY_TBYTE:
            ssize = 10;
            stype = STT_OBJECT;
            break;
        case TY_OWORD:
            ssize = 16;
            stype = STT_OBJECT;
            break;
        case TY_YWORD:
            ssize = 32;
            stype = STT_OBJECT;
            break;
        case TY_ZWORD:
            ssize = 64;
            stype = STT_OBJECT;
            break;
        case TY_COMMON:
            ssize = 0;
            stype = STT_COMMON;
            break;
        case TY_SEG:
            ssize = 0;
            stype = STT_SECTION;
            break;
        case TY_EXTERN:
            ssize = 0;
            stype = STT_NOTYPE;
            break;
        case TY_EQU:
            ssize = 0;
            stype = STT_NOTYPE;
            break;
        default:
            ssize = 0;
            stype = STT_NOTYPE;
            break;
    }
    if (stype == STT_OBJECT && lastsym && !lastsym->type) {
        lastsym->size = ssize;
        lastsym->type = stype;
    }
}

/* stabs debugging routines */

static void stabs_linenum(const char *filename, int32_t linenumber, int32_t segto)
{
    (void)segto;
    if (!stabs_filename) {
        stabs_filename = nasm_malloc(strlen(filename) + 1);
        strcpy(stabs_filename, filename);
    } else {
        if (strcmp(stabs_filename, filename)) {
            /* yep, a memory leak...this program is one-shot anyway, so who cares...
               in fact, this leak comes in quite handy to maintain a list of files
               encountered so far in the symbol lines... */

            /* why not nasm_free(stabs_filename); we're done with the old one */

            stabs_filename = nasm_malloc(strlen(filename) + 1);
            strcpy(stabs_filename, filename);
        }
    }
    debug_immcall = 1;
    currentline = linenumber;
}

static void stabs_output(int type, void *param)
{
    struct symlininfo *s;
    struct linelist *el;
    if (type == TY_DEBUGSYMLIN) {
        if (debug_immcall) {
            s = (struct symlininfo *)param;
            if (!(sects[s->section]->flags & SHF_EXECINSTR))
                return; /* line info is only collected for executable sections */
            numlinestabs++;
            el = nasm_malloc(sizeof(struct linelist));
            el->info.offset = s->offset;
            el->info.section = s->section;
            el->info.name = s->name;
            el->line = currentline;
            el->filename = stabs_filename;
            el->next = 0;
            if (stabslines) {
                stabslines->last->next = el;
                stabslines->last = el;
            } else {
                stabslines = el;
                stabslines->last = el;
            }
        }
    }
    debug_immcall = 0;
}

/* for creating the .stab , .stabstr and .rel.stab sections in memory */

static void stabs_generate(void)
{
    int i, numfiles, strsize, numstabs = 0, currfile, mainfileindex;
    uint8_t *sbuf, *ssbuf, *rbuf, *sptr, *rptr;
    char **allfiles;
    int *fileidx;

    struct linelist *ptr;

    ptr = stabslines;

    allfiles = nasm_zalloc(numlinestabs * sizeof(char *));
    numfiles = 0;
    while (ptr) {
        if (numfiles == 0) {
            allfiles[0] = ptr->filename;
            numfiles++;
        } else {
            for (i = 0; i < numfiles; i++) {
                if (!strcmp(allfiles[i], ptr->filename))
                    break;
            }
            if (i >= numfiles) {
                allfiles[i] = ptr->filename;
                numfiles++;
            }
        }
        ptr = ptr->next;
    }
    strsize = 1;
    fileidx = nasm_malloc(numfiles * sizeof(int));
    for (i = 0; i < numfiles; i++) {
        fileidx[i] = strsize;
        strsize += strlen(allfiles[i]) + 1;
    }
    currfile = mainfileindex = 0;
    for (i = 0; i < numfiles; i++) {
        if (!strcmp(allfiles[i], elf_module)) {
            currfile = mainfileindex = i;
            break;
        }
    }

    /*
     * worst case size of the stab buffer would be:
     * the sourcefiles changes each line, which would mean 1 SOL, 1 SYMLIN per line
     * plus one "ending" entry
     */
    sbuf = nasm_malloc((numlinestabs * 2 + 4) *
                                    sizeof(struct stabentry));
    ssbuf = nasm_malloc(strsize);
    rbuf = nasm_malloc(numlinestabs * (is_elf64() ? 16 : 8) * (2 + 3));
    rptr = rbuf;

    for (i = 0; i < numfiles; i++)
        strcpy((char *)ssbuf + fileidx[i], allfiles[i]);
    ssbuf[0] = 0;

    stabstrlen = strsize;       /* set global variable for length of stab strings */

    sptr = sbuf;
    ptr = stabslines;
    numstabs = 0;

    if (ptr) {
        /*
         * this is the first stab, its strx points to the filename of the
         * the source-file, the n_desc field should be set to the number
         * of remaining stabs
         */
        WRITE_STAB(sptr, fileidx[0], 0, 0, 0, stabstrlen);

        /* this is the stab for the main source file */
        WRITE_STAB(sptr, fileidx[mainfileindex], N_SO, 0, 0, 0);

        /* relocation table entry */

        /*
         * Since the symbol table has two entries before
         * the section symbols, the index in the info.section
         * member must be adjusted by adding 2
         */

        if (is_elf32()) {
            WRITELONG(rptr, (sptr - sbuf) - 4);
            WRITELONG(rptr, ((ptr->info.section + 2) << 8) | R_386_32);
        } else if (is_elfx32()) {
            WRITELONG(rptr, (sptr - sbuf) - 4);
            WRITELONG(rptr, ((ptr->info.section + 2) << 8) | R_X86_64_32);
            WRITELONG(rptr, 0);
        } else {
            nasm_assert(is_elf64());
            WRITEDLONG(rptr, (int64_t)(sptr - sbuf) - 4);
            WRITELONG(rptr, R_X86_64_32);
            WRITELONG(rptr, ptr->info.section + 2);
            WRITEDLONG(rptr, 0);
        }
        numstabs++;
    }

    if (is_elf32()) {
        while (ptr) {
            if (strcmp(allfiles[currfile], ptr->filename)) {
                /* oops file has changed... */
                for (i = 0; i < numfiles; i++)
                    if (!strcmp(allfiles[i], ptr->filename))
                        break;
                currfile = i;
                WRITE_STAB(sptr, fileidx[currfile], N_SOL, 0, 0,
                           ptr->info.offset);
                numstabs++;

                /* relocation table entry */
                WRITELONG(rptr, (sptr - sbuf) - 4);
                WRITELONG(rptr, ((ptr->info.section + 2) << 8) | R_386_32);
            }

            WRITE_STAB(sptr, 0, N_SLINE, 0, ptr->line, ptr->info.offset);
            numstabs++;

            /* relocation table entry */
            WRITELONG(rptr, (sptr - sbuf) - 4);
            WRITELONG(rptr, ((ptr->info.section + 2) << 8) | R_386_32);

            ptr = ptr->next;
        }
    } else if (is_elfx32()) {
        while (ptr) {
            if (strcmp(allfiles[currfile], ptr->filename)) {
                /* oops file has changed... */
                for (i = 0; i < numfiles; i++)
                    if (!strcmp(allfiles[i], ptr->filename))
                        break;
                currfile = i;
                WRITE_STAB(sptr, fileidx[currfile], N_SOL, 0, 0,
                           ptr->info.offset);
                numstabs++;

                /* relocation table entry */
                WRITELONG(rptr, (sptr - sbuf) - 4);
                WRITELONG(rptr, ((ptr->info.section + 2) << 8) | R_X86_64_32);
                WRITELONG(rptr, ptr->info.offset);
            }

            WRITE_STAB(sptr, 0, N_SLINE, 0, ptr->line, ptr->info.offset);
            numstabs++;

            /* relocation table entry */
            WRITELONG(rptr, (sptr - sbuf) - 4);
            WRITELONG(rptr, ((ptr->info.section + 2) << 8) | R_X86_64_32);
            WRITELONG(rptr, ptr->info.offset);

            ptr = ptr->next;
        }
    } else {
        nasm_assert(is_elf64());
        while (ptr) {
            if (strcmp(allfiles[currfile], ptr->filename)) {
                /* oops file has changed... */
                for (i = 0; i < numfiles; i++)
                    if (!strcmp(allfiles[i], ptr->filename))
                        break;
                currfile = i;
                WRITE_STAB(sptr, fileidx[currfile], N_SOL, 0, 0,
                           ptr->info.offset);
                numstabs++;

                /* relocation table entry */
                WRITEDLONG(rptr, (int64_t)(sptr - sbuf) - 4);
                WRITELONG(rptr, R_X86_64_32);
                WRITELONG(rptr, ptr->info.section + 2);
                WRITEDLONG(rptr, ptr->info.offset);
            }

            WRITE_STAB(sptr, 0, N_SLINE, 0, ptr->line, ptr->info.offset);
            numstabs++;

            /* relocation table entry */
            WRITEDLONG(rptr, (int64_t)(sptr - sbuf) - 4);
            WRITELONG(rptr, R_X86_64_32);
            WRITELONG(rptr, ptr->info.section + 2);
            WRITEDLONG(rptr, ptr->info.offset);

            ptr = ptr->next;
        }
    }

    /* this is an "ending" token */
    WRITE_STAB(sptr, 0, N_SO, 0, 0, 0);
    numstabs++;

    ((struct stabentry *)sbuf)->n_desc = numstabs;

    nasm_free(allfiles);
    nasm_free(fileidx);

    stablen = (sptr - sbuf);
    stabrellen = (rptr - rbuf);
    stabrelbuf = rbuf;
    stabbuf = sbuf;
    stabstrbuf = ssbuf;
}

static void stabs_cleanup(void)
{
    struct linelist *ptr, *del;
    if (!stabslines)
        return;

    ptr = stabslines;
    while (ptr) {
        del = ptr;
        ptr = ptr->next;
        nasm_free(del);
    }

    nasm_free(stabbuf);
    nasm_free(stabrelbuf);
    nasm_free(stabstrbuf);
}

/* dwarf routines */

static void dwarf_init(void)
{
    ndebugs = 3; /* 3 debug symbols */
}

static void dwarf_linenum(const char *filename, int32_t linenumber,
                            int32_t segto)
{
    (void)segto;
    dwarf_findfile(filename);
    debug_immcall = 1;
    currentline = linenumber;
}

/* called from elf_out with type == TY_DEBUGSYMLIN */
static void dwarf_output(int type, void *param)
{
    int ln, aa, inx, maxln, soc;
    struct symlininfo *s;
    struct SAA *plinep;

    (void)type;

    s = (struct symlininfo *)param;

    /* line number info is only gathered for executable sections */
    if (!(sects[s->section]->flags & SHF_EXECINSTR))
        return;

    /* Check if section index has changed */
    if (!(dwarf_csect && (dwarf_csect->section) == (s->section)))
        dwarf_findsect(s->section);

    /* do nothing unless line or file has changed */
    if (!debug_immcall)
        return;

    ln = currentline - dwarf_csect->line;
    aa = s->offset - dwarf_csect->offset;
    inx = dwarf_clist->line;
    plinep = dwarf_csect->psaa;
    /* check for file change */
    if (!(inx == dwarf_csect->file)) {
        saa_write8(plinep,DW_LNS_set_file);
        saa_write8(plinep,inx);
        dwarf_csect->file = inx;
    }
    /* check for line change */
    if (ln) {
        /* test if in range of special op code */
        maxln = line_base + line_range;
        soc = (ln - line_base) + (line_range * aa) + opcode_base;
        if (ln >= line_base && ln < maxln && soc < 256) {
            saa_write8(plinep,soc);
        } else {
            saa_write8(plinep,DW_LNS_advance_line);
            saa_wleb128s(plinep,ln);
            if (aa) {
                saa_write8(plinep,DW_LNS_advance_pc);
                saa_wleb128u(plinep,aa);
            }
            saa_write8(plinep,DW_LNS_copy);
        }
        dwarf_csect->line = currentline;
        dwarf_csect->offset = s->offset;
    }

    /* show change handled */
    debug_immcall = 0;
}


static void dwarf_generate(void)
{
    uint8_t *pbuf;
    int indx;
    struct linelist *ftentry;
    struct SAA *paranges, *ppubnames, *pinfo, *pabbrev, *plines, *plinep;
    struct SAA *parangesrel, *plinesrel, *pinforel;
    struct sectlist *psect;
    size_t saalen, linepoff, totlen, highaddr;

    if (is_elf32()) {
        /* write epilogues for each line program range */
        /* and build aranges section */
        paranges = saa_init(1L);
        parangesrel = saa_init(1L);
        saa_write16(paranges,2);    /* dwarf version */
        saa_write32(parangesrel, paranges->datalen+4);
        saa_write32(parangesrel, (dwarf_infosym << 8) +  R_386_32); /* reloc to info */
        saa_write32(parangesrel, 0);
        saa_write32(paranges,0);    /* offset into info */
        saa_write8(paranges,4);     /* pointer size */
        saa_write8(paranges,0);     /* not segmented */
        saa_write32(paranges,0);    /* padding */
        /* iterate though sectlist entries */
        psect = dwarf_fsect;
        totlen = 0;
        highaddr = 0;
        for (indx = 0; indx < dwarf_nsections; indx++) {
            plinep = psect->psaa;
            /* Line Number Program Epilogue */
            saa_write8(plinep,2);           /* std op 2 */
            saa_write8(plinep,(sects[psect->section]->len)-psect->offset);
            saa_write8(plinep,DW_LNS_extended_op);
            saa_write8(plinep,1);           /* operand length */
            saa_write8(plinep,DW_LNE_end_sequence);
            totlen += plinep->datalen;
            /* range table relocation entry */
            saa_write32(parangesrel, paranges->datalen + 4);
            saa_write32(parangesrel, ((uint32_t) (psect->section + 2) << 8) +  R_386_32);
            saa_write32(parangesrel, (uint32_t) 0);
            /* range table entry */
            saa_write32(paranges,0x0000);   /* range start */
            saa_write32(paranges,sects[psect->section]->len); /* range length */
            highaddr += sects[psect->section]->len;
            /* done with this entry */
            psect = psect->next;
        }
        saa_write32(paranges,0);    /* null address */
        saa_write32(paranges,0);    /* null length */
        saalen = paranges->datalen;
        arangeslen = saalen + 4;
        arangesbuf = pbuf = nasm_malloc(arangeslen);
        WRITELONG(pbuf,saalen);     /* initial length */
        saa_rnbytes(paranges, pbuf, saalen);
        saa_free(paranges);
    } else if (is_elfx32()) {
        /* write epilogues for each line program range */
        /* and build aranges section */
        paranges = saa_init(1L);
        parangesrel = saa_init(1L);
        saa_write16(paranges,3);            /* dwarf version */
        saa_write32(parangesrel, paranges->datalen+4);
        saa_write32(parangesrel, (dwarf_infosym << 8) +  R_X86_64_32); /* reloc to info */
        saa_write32(parangesrel, 0);
        saa_write32(paranges,0);            /* offset into info */
        saa_write8(paranges,4);             /* pointer size */
        saa_write8(paranges,0);             /* not segmented */
        saa_write32(paranges,0);            /* padding */
        /* iterate though sectlist entries */
        psect = dwarf_fsect;
        totlen = 0;
        highaddr = 0;
        for (indx = 0; indx < dwarf_nsections; indx++)  {
            plinep = psect->psaa;
            /* Line Number Program Epilogue */
            saa_write8(plinep,2);			/* std op 2 */
            saa_write8(plinep,(sects[psect->section]->len)-psect->offset);
            saa_write8(plinep,DW_LNS_extended_op);
            saa_write8(plinep,1);			/* operand length */
            saa_write8(plinep,DW_LNE_end_sequence);
            totlen += plinep->datalen;
            /* range table relocation entry */
            saa_write32(parangesrel, paranges->datalen + 4);
            saa_write32(parangesrel, ((uint32_t) (psect->section + 2) << 8) +  R_X86_64_32);
            saa_write32(parangesrel, (uint32_t) 0);
            /* range table entry */
            saa_write32(paranges,0x0000);		/* range start */
            saa_write32(paranges,sects[psect->section]->len);	/* range length */
            highaddr += sects[psect->section]->len;
            /* done with this entry */
            psect = psect->next;
        }
        saa_write32(paranges,0);		/* null address */
        saa_write32(paranges,0);		/* null length */
        saalen = paranges->datalen;
        arangeslen = saalen + 4;
        arangesbuf = pbuf = nasm_malloc(arangeslen);
        WRITELONG(pbuf,saalen);			/* initial length */
        saa_rnbytes(paranges, pbuf, saalen);
        saa_free(paranges);
    } else {
        nasm_assert(is_elf64());
        /* write epilogues for each line program range */
        /* and build aranges section */
        paranges = saa_init(1L);
        parangesrel = saa_init(1L);
        saa_write16(paranges,3);            /* dwarf version */
        saa_write64(parangesrel, paranges->datalen+4);
        saa_write64(parangesrel, (dwarf_infosym << 32) +  R_X86_64_32); /* reloc to info */
        saa_write64(parangesrel, 0);
        saa_write32(paranges,0);            /* offset into info */
        saa_write8(paranges,8);             /* pointer size */
        saa_write8(paranges,0);             /* not segmented */
        saa_write32(paranges,0);            /* padding */
        /* iterate though sectlist entries */
        psect = dwarf_fsect;
        totlen = 0;
        highaddr = 0;
        for (indx = 0; indx < dwarf_nsections; indx++) {
            plinep = psect->psaa;
            /* Line Number Program Epilogue */
            saa_write8(plinep,2);			/* std op 2 */
            saa_write8(plinep,(sects[psect->section]->len)-psect->offset);
            saa_write8(plinep,DW_LNS_extended_op);
            saa_write8(plinep,1);			/* operand length */
            saa_write8(plinep,DW_LNE_end_sequence);
            totlen += plinep->datalen;
            /* range table relocation entry */
            saa_write64(parangesrel, paranges->datalen + 4);
            saa_write64(parangesrel, ((uint64_t) (psect->section + 2) << 32) +  R_X86_64_64);
            saa_write64(parangesrel, (uint64_t) 0);
            /* range table entry */
            saa_write64(paranges,0x0000);		/* range start */
            saa_write64(paranges,sects[psect->section]->len);	/* range length */
            highaddr += sects[psect->section]->len;
            /* done with this entry */
            psect = psect->next;
        }
        saa_write64(paranges,0);		/* null address */
        saa_write64(paranges,0);		/* null length */
        saalen = paranges->datalen;
        arangeslen = saalen + 4;
        arangesbuf = pbuf = nasm_malloc(arangeslen);
        WRITELONG(pbuf,saalen);			/* initial length */
        saa_rnbytes(paranges, pbuf, saalen);
        saa_free(paranges);
    }

    /* build rela.aranges section */
    arangesrellen = saalen = parangesrel->datalen;
    arangesrelbuf = pbuf = nasm_malloc(arangesrellen);
    saa_rnbytes(parangesrel, pbuf, saalen);
    saa_free(parangesrel);

    /* build pubnames section */
    ppubnames = saa_init(1L);
    saa_write16(ppubnames,3);   /* dwarf version */
    saa_write32(ppubnames,0);   /* offset into info */
    saa_write32(ppubnames,0);   /* space used in info */
    saa_write32(ppubnames,0);   /* end of list */
    saalen = ppubnames->datalen;
    pubnameslen = saalen + 4;
    pubnamesbuf = pbuf = nasm_malloc(pubnameslen);
    WRITELONG(pbuf,saalen);     /* initial length */
    saa_rnbytes(ppubnames, pbuf, saalen);
    saa_free(ppubnames);

    if (is_elf32()) {
        /* build info section */
        pinfo = saa_init(1L);
        pinforel = saa_init(1L);
        saa_write16(pinfo,2);       /* dwarf version */
        saa_write32(pinforel, pinfo->datalen + 4);
        saa_write32(pinforel, (dwarf_abbrevsym << 8) +  R_386_32); /* reloc to abbrev */
        saa_write32(pinforel, 0);
        saa_write32(pinfo,0);       /* offset into abbrev */
        saa_write8(pinfo,4);        /* pointer size */
        saa_write8(pinfo,1);        /* abbrviation number LEB128u */
        saa_write32(pinforel, pinfo->datalen + 4);
        saa_write32(pinforel, ((dwarf_fsect->section + 2) << 8) +  R_386_32);
        saa_write32(pinforel, 0);
        saa_write32(pinfo,0);       /* DW_AT_low_pc */
        saa_write32(pinforel, pinfo->datalen + 4);
        saa_write32(pinforel, ((dwarf_fsect->section + 2) << 8) +  R_386_32);
        saa_write32(pinforel, 0);
        saa_write32(pinfo,highaddr);    /* DW_AT_high_pc */
        saa_write32(pinforel, pinfo->datalen + 4);
        saa_write32(pinforel, (dwarf_linesym << 8) +  R_386_32); /* reloc to line */
        saa_write32(pinforel, 0);
        saa_write32(pinfo,0);       /* DW_AT_stmt_list */
        saa_wbytes(pinfo, elf_module, strlen(elf_module)+1);
        saa_wbytes(pinfo, nasm_signature, strlen(nasm_signature)+1);
        saa_write16(pinfo,DW_LANG_Mips_Assembler);
        saa_write8(pinfo,2);        /* abbrviation number LEB128u */
        saa_write32(pinforel, pinfo->datalen + 4);
        saa_write32(pinforel, ((dwarf_fsect->section + 2) << 8) +  R_386_32);
        saa_write32(pinforel, 0);
        saa_write32(pinfo,0);       /* DW_AT_low_pc */
        saa_write32(pinfo,0);       /* DW_AT_frame_base */
        saa_write8(pinfo,0);        /* end of entries */
        saalen = pinfo->datalen;
        infolen = saalen + 4;
        infobuf = pbuf = nasm_malloc(infolen);
        WRITELONG(pbuf,saalen);     /* initial length */
        saa_rnbytes(pinfo, pbuf, saalen);
        saa_free(pinfo);
    } else if (is_elfx32()) {
        /* build info section */
        pinfo = saa_init(1L);
        pinforel = saa_init(1L);
        saa_write16(pinfo,3);			/* dwarf version */
        saa_write32(pinforel, pinfo->datalen + 4);
        saa_write32(pinforel, (dwarf_abbrevsym << 8) + R_X86_64_32); /* reloc to abbrev */
        saa_write32(pinforel, 0);
        saa_write32(pinfo,0);			/* offset into abbrev */
        saa_write8(pinfo,4);			/* pointer size */
        saa_write8(pinfo,1);			/* abbrviation number LEB128u */
        saa_write32(pinforel, pinfo->datalen + 4);
        saa_write32(pinforel, ((dwarf_fsect->section + 2) << 8) + R_X86_64_32);
        saa_write32(pinforel, 0);
        saa_write32(pinfo,0);			/* DW_AT_low_pc */
        saa_write32(pinforel, pinfo->datalen + 4);
        saa_write32(pinforel, ((dwarf_fsect->section + 2) << 8) + R_X86_64_32);
        saa_write32(pinforel, 0);
        saa_write32(pinfo,highaddr);		/* DW_AT_high_pc */
        saa_write32(pinforel, pinfo->datalen + 4);
        saa_write32(pinforel, (dwarf_linesym << 8) + R_X86_64_32); /* reloc to line */
        saa_write32(pinforel, 0);
        saa_write32(pinfo,0);			/* DW_AT_stmt_list */
        saa_wbytes(pinfo, elf_module, strlen(elf_module)+1);
        saa_wbytes(pinfo, nasm_signature, strlen(nasm_signature)+1);
        saa_write16(pinfo,DW_LANG_Mips_Assembler);
        saa_write8(pinfo,2);			/* abbrviation number LEB128u */
        saa_write32(pinforel, pinfo->datalen + 4);
        saa_write32(pinforel, ((dwarf_fsect->section + 2) << 8) +  R_X86_64_32);
        saa_write32(pinforel, 0);
        saa_write32(pinfo,0);			/* DW_AT_low_pc */
        saa_write32(pinfo,0);			/* DW_AT_frame_base */
        saa_write8(pinfo,0);			/* end of entries */
        saalen = pinfo->datalen;
        infolen = saalen + 4;
        infobuf = pbuf = nasm_malloc(infolen);
        WRITELONG(pbuf,saalen);     /* initial length */
        saa_rnbytes(pinfo, pbuf, saalen);
        saa_free(pinfo);
    } else {
        nasm_assert(is_elf64());
        /* build info section */
        pinfo = saa_init(1L);
        pinforel = saa_init(1L);
        saa_write16(pinfo,3);			/* dwarf version */
        saa_write64(pinforel, pinfo->datalen + 4);
        saa_write64(pinforel, (dwarf_abbrevsym << 32) +  R_X86_64_32); /* reloc to abbrev */
        saa_write64(pinforel, 0);
        saa_write32(pinfo,0);			/* offset into abbrev */
        saa_write8(pinfo,8);			/* pointer size */
        saa_write8(pinfo,1);			/* abbrviation number LEB128u */
        saa_write64(pinforel, pinfo->datalen + 4);
        saa_write64(pinforel, ((uint64_t)(dwarf_fsect->section + 2) << 32) +  R_X86_64_64);
        saa_write64(pinforel, 0);
        saa_write64(pinfo,0);			/* DW_AT_low_pc */
        saa_write64(pinforel, pinfo->datalen + 4);
        saa_write64(pinforel, ((uint64_t)(dwarf_fsect->section + 2) << 32) +  R_X86_64_64);
        saa_write64(pinforel, 0);
        saa_write64(pinfo,highaddr);		/* DW_AT_high_pc */
        saa_write64(pinforel, pinfo->datalen + 4);
        saa_write64(pinforel, (dwarf_linesym << 32) +  R_X86_64_32); /* reloc to line */
        saa_write64(pinforel, 0);
        saa_write32(pinfo,0);			/* DW_AT_stmt_list */
        saa_wbytes(pinfo, elf_module, strlen(elf_module)+1);
        saa_wbytes(pinfo, nasm_signature, strlen(nasm_signature)+1);
        saa_write16(pinfo,DW_LANG_Mips_Assembler);
        saa_write8(pinfo,2);			/* abbrviation number LEB128u */
        saa_write64(pinforel, pinfo->datalen + 4);
        saa_write64(pinforel, ((uint64_t)(dwarf_fsect->section + 2) << 32) +  R_X86_64_64);
        saa_write64(pinforel, 0);
        saa_write64(pinfo,0);			/* DW_AT_low_pc */
        saa_write64(pinfo,0);			/* DW_AT_frame_base */
        saa_write8(pinfo,0);			/* end of entries */
        saalen = pinfo->datalen;
        infolen = saalen + 4;
        infobuf = pbuf = nasm_malloc(infolen);
        WRITELONG(pbuf,saalen);     /* initial length */
        saa_rnbytes(pinfo, pbuf, saalen);
        saa_free(pinfo);
    }

    /* build rela.info section */
    inforellen = saalen = pinforel->datalen;
    inforelbuf = pbuf = nasm_malloc(inforellen);
    saa_rnbytes(pinforel, pbuf, saalen);
    saa_free(pinforel);

    /* build abbrev section */
    pabbrev = saa_init(1L);
    saa_write8(pabbrev,1);      /* entry number LEB128u */
    saa_write8(pabbrev,DW_TAG_compile_unit);    /* tag LEB128u */
    saa_write8(pabbrev,1);      /* has children */
    /* the following attributes and forms are all LEB128u values */
    saa_write8(pabbrev,DW_AT_low_pc);
    saa_write8(pabbrev,DW_FORM_addr);
    saa_write8(pabbrev,DW_AT_high_pc);
    saa_write8(pabbrev,DW_FORM_addr);
    saa_write8(pabbrev,DW_AT_stmt_list);
    saa_write8(pabbrev,DW_FORM_data4);
    saa_write8(pabbrev,DW_AT_name);
    saa_write8(pabbrev,DW_FORM_string);
    saa_write8(pabbrev,DW_AT_producer);
    saa_write8(pabbrev,DW_FORM_string);
    saa_write8(pabbrev,DW_AT_language);
    saa_write8(pabbrev,DW_FORM_data2);
    saa_write16(pabbrev,0);     /* end of entry */
    /* LEB128u usage same as above */
    saa_write8(pabbrev,2);      /* entry number */
    saa_write8(pabbrev,DW_TAG_subprogram);
    saa_write8(pabbrev,0);      /* no children */
    saa_write8(pabbrev,DW_AT_low_pc);
    saa_write8(pabbrev,DW_FORM_addr);
    saa_write8(pabbrev,DW_AT_frame_base);
    saa_write8(pabbrev,DW_FORM_data4);
    saa_write16(pabbrev,0);     /* end of entry */
    /* Terminal zero entry */
    saa_write8(pabbrev,0);
    abbrevlen = saalen = pabbrev->datalen;
    abbrevbuf = pbuf = nasm_malloc(saalen);
    saa_rnbytes(pabbrev, pbuf, saalen);
    saa_free(pabbrev);

    /* build line section */
    /* prolog */
    plines = saa_init(1L);
    saa_write8(plines,1);           /* Minimum Instruction Length */
    saa_write8(plines,1);           /* Initial value of 'is_stmt' */
    saa_write8(plines,line_base);   /* Line Base */
    saa_write8(plines,line_range);  /* Line Range */
    saa_write8(plines,opcode_base); /* Opcode Base */
    /* standard opcode lengths (# of LEB128u operands) */
    saa_write8(plines,0);           /* Std opcode 1 length */
    saa_write8(plines,1);           /* Std opcode 2 length */
    saa_write8(plines,1);           /* Std opcode 3 length */
    saa_write8(plines,1);           /* Std opcode 4 length */
    saa_write8(plines,1);           /* Std opcode 5 length */
    saa_write8(plines,0);           /* Std opcode 6 length */
    saa_write8(plines,0);           /* Std opcode 7 length */
    saa_write8(plines,0);           /* Std opcode 8 length */
    saa_write8(plines,1);           /* Std opcode 9 length */
    saa_write8(plines,0);           /* Std opcode 10 length */
    saa_write8(plines,0);           /* Std opcode 11 length */
    saa_write8(plines,1);           /* Std opcode 12 length */
    /* Directory Table */
    saa_write8(plines,0);           /* End of table */
    /* File Name Table */
    ftentry = dwarf_flist;
    for (indx = 0; indx < dwarf_numfiles; indx++) {
        saa_wbytes(plines, ftentry->filename, (int32_t)(strlen(ftentry->filename) + 1));
        saa_write8(plines,0);       /* directory  LEB128u */
        saa_write8(plines,0);       /* time LEB128u */
        saa_write8(plines,0);       /* size LEB128u */
        ftentry = ftentry->next;
    }
    saa_write8(plines,0);           /* End of table */
    linepoff = plines->datalen;
    linelen = linepoff + totlen + 10;
    linebuf = pbuf = nasm_malloc(linelen);
    WRITELONG(pbuf,linelen-4);      /* initial length */
    WRITESHORT(pbuf,3);             /* dwarf version */
    WRITELONG(pbuf,linepoff);       /* offset to line number program */
    /* write line header */
    saalen = linepoff;
    saa_rnbytes(plines, pbuf, saalen);   /* read a given no. of bytes */
    pbuf += linepoff;
    saa_free(plines);
    /* concatonate line program ranges */
    linepoff += 13;
    plinesrel = saa_init(1L);
    psect = dwarf_fsect;
    if (is_elf32()) {
        for (indx = 0; indx < dwarf_nsections; indx++) {
            saa_write32(plinesrel, linepoff);
            saa_write32(plinesrel, ((uint32_t) (psect->section + 2) << 8) +  R_386_32);
            saa_write32(plinesrel, (uint32_t) 0);
            plinep = psect->psaa;
            saalen = plinep->datalen;
            saa_rnbytes(plinep, pbuf, saalen);
            pbuf += saalen;
            linepoff += saalen;
            saa_free(plinep);
            /* done with this entry */
            psect = psect->next;
        }
    } else if (is_elfx32()) {
        for (indx = 0; indx < dwarf_nsections; indx++) {
            saa_write32(plinesrel, linepoff);
            saa_write32(plinesrel, ((psect->section + 2) << 8) + R_X86_64_32);
            saa_write32(plinesrel, 0);
            plinep = psect->psaa;
            saalen = plinep->datalen;
            saa_rnbytes(plinep, pbuf, saalen);
            pbuf += saalen;
            linepoff += saalen;
            saa_free(plinep);
            /* done with this entry */
            psect = psect->next;
        }
    } else {
        nasm_assert(is_elf64());
        for (indx = 0; indx < dwarf_nsections; indx++) {
            saa_write64(plinesrel, linepoff);
            saa_write64(plinesrel, ((uint64_t) (psect->section + 2) << 32) +  R_X86_64_64);
            saa_write64(plinesrel, (uint64_t) 0);
            plinep = psect->psaa;
            saalen = plinep->datalen;
            saa_rnbytes(plinep, pbuf, saalen);
            pbuf += saalen;
            linepoff += saalen;
            saa_free(plinep);
            /* done with this entry */
            psect = psect->next;
        }
    }

    /* build rela.lines section */
    linerellen =saalen = plinesrel->datalen;
    linerelbuf = pbuf = nasm_malloc(linerellen);
    saa_rnbytes(plinesrel, pbuf, saalen);
    saa_free(plinesrel);

    /* build frame section */
    framelen = 4;
    framebuf = pbuf = nasm_malloc(framelen);
    WRITELONG(pbuf,framelen-4); /* initial length */

    /* build loc section */
    loclen = 16;
    locbuf = pbuf = nasm_malloc(loclen);
    if (is_elf32()) {
        WRITELONG(pbuf,0);  /* null  beginning offset */
        WRITELONG(pbuf,0);  /* null  ending offset */
    } else if (is_elfx32()) {
        WRITELONG(pbuf,0);  /* null  beginning offset */
        WRITELONG(pbuf,0);  /* null  ending offset */
    } else {
        nasm_assert(is_elf64());
        WRITEDLONG(pbuf,0);  /* null  beginning offset */
        WRITEDLONG(pbuf,0);  /* null  ending offset */
    }
}

static void dwarf_cleanup(void)
{
    nasm_free(arangesbuf);
    nasm_free(arangesrelbuf);
    nasm_free(pubnamesbuf);
    nasm_free(infobuf);
    nasm_free(inforelbuf);
    nasm_free(abbrevbuf);
    nasm_free(linebuf);
    nasm_free(linerelbuf);
    nasm_free(framebuf);
    nasm_free(locbuf);
}

static void dwarf_findfile(const char * fname)
{
    int finx;
    struct linelist *match;

    /* return if fname is current file name */
    if (dwarf_clist && !(strcmp(fname, dwarf_clist->filename)))
        return;

    /* search for match */
    match = 0;
    if (dwarf_flist) {
        match = dwarf_flist;
        for (finx = 0; finx < dwarf_numfiles; finx++) {
            if (!(strcmp(fname, match->filename))) {
                dwarf_clist = match;
                return;
            }
            match = match->next;
        }
    }

    /* add file name to end of list */
    dwarf_clist = nasm_malloc(sizeof(struct linelist));
    dwarf_numfiles++;
    dwarf_clist->line = dwarf_numfiles;
    dwarf_clist->filename = nasm_malloc(strlen(fname) + 1);
    strcpy(dwarf_clist->filename,fname);
    dwarf_clist->next = 0;
    if (!dwarf_flist) {     /* if first entry */
        dwarf_flist = dwarf_elist = dwarf_clist;
        dwarf_clist->last = 0;
    } else {                /* chain to previous entry */
        dwarf_elist->next = dwarf_clist;
        dwarf_elist = dwarf_clist;
    }
}

static void dwarf_findsect(const int index)
{
    int sinx;
    struct sectlist *match;
    struct SAA *plinep;

    /* return if index is current section index */
    if (dwarf_csect && (dwarf_csect->section == index))
        return;

    /* search for match */
    match = 0;
    if (dwarf_fsect) {
        match = dwarf_fsect;
        for (sinx = 0; sinx < dwarf_nsections; sinx++) {
            if (match->section == index) {
                dwarf_csect = match;
                return;
            }
            match = match->next;
        }
    }

    /* add entry to end of list */
    dwarf_csect = nasm_malloc(sizeof(struct sectlist));
    dwarf_nsections++;
    dwarf_csect->psaa = plinep = saa_init(1L);
    dwarf_csect->line = 1;
    dwarf_csect->offset = 0;
    dwarf_csect->file = 1;
    dwarf_csect->section = index;
    dwarf_csect->next = 0;
    /* set relocatable address at start of line program */
    saa_write8(plinep,DW_LNS_extended_op);
    saa_write8(plinep,is_elf64() ? 9 : 5);   /* operand length */
    saa_write8(plinep,DW_LNE_set_address);
    if (is_elf64())
        saa_write64(plinep,0);  /* Start Address */
    else
        saa_write32(plinep,0);  /* Start Address */

    if (!dwarf_fsect) { /* if first entry */
        dwarf_fsect = dwarf_esect = dwarf_csect;
        dwarf_csect->last = 0;
    } else {            /* chain to previous entry */
        dwarf_esect->next = dwarf_csect;
        dwarf_esect = dwarf_csect;
    }
}

#endif /* defined(OF_ELF32) || defined(OF_ELF64) || defined(OF_ELFX32) */