aboutsummaryrefslogtreecommitdiffstats
path: root/output/outmacho.c
blob: 3eeb057c62a7cac06661f720d277db5f3a56779f (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
/* ----------------------------------------------------------------------- *
 *
 *   Copyright 1996-2017 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.
 *
 * ----------------------------------------------------------------------- */

/*
 * outmacho.c	output routines for the Netwide Assembler to produce
 *		NeXTstep/OpenStep/Rhapsody/Darwin/MacOS X object files
 */

#include "compiler.h"

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

#include "nasm.h"
#include "nasmlib.h"
#include "ilog2.h"
#include "labels.h"
#include "error.h"
#include "saa.h"
#include "raa.h"
#include "rbtree.h"
#include "outform.h"
#include "outlib.h"
#include "ver.h"
#include "dwarf.h"

#if defined(OF_MACHO) || defined(OF_MACHO64)

/* Mach-O in-file header structure sizes */
#define MACHO_HEADER_SIZE		28
#define MACHO_SEGCMD_SIZE		56
#define MACHO_SECTCMD_SIZE		68
#define MACHO_SYMCMD_SIZE		24
#define MACHO_NLIST_SIZE		12
#define MACHO_RELINFO_SIZE		8

#define MACHO_HEADER64_SIZE		32
#define MACHO_SEGCMD64_SIZE		72
#define MACHO_SECTCMD64_SIZE		80
#define MACHO_NLIST64_SIZE		16

/* Mach-O file header values */
#define	MH_MAGIC		0xfeedface
#define	MH_MAGIC_64		0xfeedfacf
#define CPU_TYPE_I386		7		/* x86 platform */
#define CPU_TYPE_X86_64		0x01000007	/* x86-64 platform */
#define	CPU_SUBTYPE_I386_ALL	3		/* all-x86 compatible */
#define	MH_OBJECT		0x1		/* object file */

/* Mach-O header flags */
#define MH_SUBSECTIONS_VIA_SYMBOLS 0x2000

/* Mach-O load commands */
#define LC_SEGMENT		0x1		/* 32-bit segment load cmd */
#define LC_SEGMENT_64		0x19		/* 64-bit segment load cmd */
#define LC_SYMTAB		0x2		/* symbol table load command */

/* Mach-O relocations numbers */

/* Generic relocs, used by i386 Mach-O */
#define GENERIC_RELOC_VANILLA   0               /* Generic relocation */
#define GENERIC_RELOC_TLV	5		/* Thread local */

#define X86_64_RELOC_UNSIGNED   0               /* Absolute address */
#define X86_64_RELOC_SIGNED     1               /* Signed 32-bit disp */
#define X86_64_RELOC_BRANCH     2		/* CALL/JMP with 32-bit disp */
#define X86_64_RELOC_GOT_LOAD   3		/* MOVQ of GOT entry */
#define X86_64_RELOC_GOT        4		/* Different GOT entry */
#define X86_64_RELOC_SUBTRACTOR 5		/* Subtracting two symbols */
#define X86_64_RELOC_SIGNED_1   6		/* SIGNED with -1 addend */
#define X86_64_RELOC_SIGNED_2   7		/* SIGNED with -2 addend */
#define X86_64_RELOC_SIGNED_4   8		/* SIGNED with -4 addend */
#define X86_64_RELOC_TLV        9		/* Thread local */

/* Mach-O VM permission constants */
#define	VM_PROT_NONE	(0x00)
#define VM_PROT_READ	(0x01)
#define VM_PROT_WRITE	(0x02)
#define VM_PROT_EXECUTE	(0x04)

#define VM_PROT_DEFAULT	(VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE)
#define VM_PROT_ALL	(VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE)

/* Our internal relocation types */
enum reltype {
    RL_ABS,			/* Absolute relocation */
    RL_REL,			/* Relative relocation */
    RL_TLV,			/* Thread local */
    RL_BRANCH,			/* Relative direct branch */
    RL_SUB,			/* X86_64_RELOC_SUBTRACT */
    RL_GOT,			/* X86_64_RELOC_GOT */
    RL_GOTLOAD			/* X86_64_RELOC_GOT_LOAD */
};
#define RL_MAX_32	RL_TLV
#define RL_MAX_64	RL_GOTLOAD

struct macho_fmt {
    uint32_t ptrsize;		/* Pointer size in bytes */
    uint32_t mh_magic;		/* Which magic number to use */
    uint32_t cpu_type;		/* Which CPU type */
    uint32_t lc_segment;	/* Which segment load command */
    uint32_t header_size;	/* Header size */
    uint32_t segcmd_size;	/* Segment command size */
    uint32_t sectcmd_size;	/* Section command size */
    uint32_t nlist_size;	/* Nlist (symbol) size */
    enum reltype maxreltype;	/* Maximum entry in enum reltype permitted */
    uint32_t reloc_abs;		/* Absolute relocation type */
    uint32_t reloc_rel;		/* Relative relocation type */
    uint32_t reloc_tlv;		/* Thread local relocation type */
    bool forcesym;		/* Always use "external" (symbol-relative) relocations */
};

static struct macho_fmt fmt;

static void fwriteptr(uint64_t data, FILE * fp)
{
    fwriteaddr(data, fmt.ptrsize, fp);
}

struct section {
    /* nasm internal data */
    struct section *next;
    struct SAA *data;
    int32_t index;
    int32_t fileindex;
    struct reloc *relocs;
    struct rbtree *syms[2]; /* All/global symbols symbols in section */
    int align;
    bool by_name;		/* This section was specified by full MachO name */

    /* data that goes into the file */
    char sectname[16];          /* what this section is called */
    char segname[16];           /* segment this section will be in */
    uint64_t addr;         /* in-memory address (subject to alignment) */
    uint64_t size;         /* in-memory and -file size  */
    uint64_t offset;	   /* in-file offset */
    uint32_t pad;          /* padding bytes before section */
    uint32_t nreloc;       /* relocation entry count */
    uint32_t flags;        /* type and attributes (masked) */
    uint32_t extreloc;     /* external relocations */
};

#define SECTION_TYPE	0x000000ff      /* section type mask */

#define	S_REGULAR		(0x0)   /* standard section */
#define	S_ZEROFILL		(0x1)   /* zerofill, in-memory only */

#define SECTION_ATTRIBUTES_SYS   0x00ffff00     /* system setable attributes */
#define S_ATTR_SOME_INSTRUCTIONS 0x00000400     /* section contains some
						   machine instructions */
#define S_ATTR_EXT_RELOC         0x00000200     /* section has external relocation entries */
#define S_ATTR_LOC_RELOC         0x00000100     /* section has local relocation entries */
#define S_ATTR_DEBUG		 0x02000000
#define S_ATTR_SELF_MODIFYING_CODE 0x04000000
#define S_ATTR_LIVE_SUPPORT	 0x08000000
#define S_ATTR_NO_DEAD_STRIP	 0x10000000     /* no dead stripping */
#define S_ATTR_STRIP_STATIC_SYMS 0x20000000
#define S_ATTR_NO_TOC            0x40000000
#define S_ATTR_PURE_INSTRUCTIONS 0x80000000	/* section uses pure machine instructions */
#define S_ATTR_DEBUG 0x02000000 /* debug section */

#define S_NASM_TYPE_MASK	 0x800004ff	/* we consider these bits "section type" */

/* fake section for absolute symbols, *not* part of the section linked list */
static struct section absolute_sect;

struct reloc {
    /* nasm internal data */
    struct reloc *next;

    /* data that goes into the file */
    int32_t addr;		/* op's offset in section */
    uint32_t snum:24,		/* contains symbol index if
				 ** ext otherwise in-file
				 ** section number */
	pcrel:1,                /* relative relocation */
	length:2,               /* 0=byte, 1=word, 2=int32_t, 3=int64_t */
	ext:1,                  /* external symbol referenced */
	type:4;                 /* reloc type */
};

#define	R_ABS		0       /* absolute relocation */
#define R_SCATTERED	0x80000000      /* reloc entry is scattered if
					** highest bit == 1 */

struct symbol {
    /* nasm internal data */
    struct rbtree symv[2];	/* All/global symbol rbtrees; "key" contains the
				   symbol offset. */
    struct symbol *next;	/* next symbol in the list */
    char *name;			/* name of this symbol */
    int32_t initial_snum;	/* symbol number used above in reloc */
    int32_t snum;		/* true snum for reloc */

    /* data that goes into the file */
    uint32_t strx;              /* string table index */
    uint8_t type;		/* symbol type */
    uint8_t sect;		/* NO_SECT or section number */
    uint16_t desc;		/* for stab debugging, 0 for us */
};

/* symbol type bits */
#define	N_EXT	0x01            /* global or external symbol */
#define	N_PEXT	0x10            /* private external symbol */

#define	N_UNDF	0x0             /* undefined symbol | n_sect == */
#define	N_ABS	0x2             /* absolute symbol  |  NO_SECT */
#define	N_SECT	0xe             /* defined symbol, n_sect holds
				** section number */

#define	N_TYPE	0x0e            /* type bit mask */

#define DEFAULT_SECTION_ALIGNMENT 0 /* byte (i.e. no) alignment */

/* special section number values */
#define	NO_SECT		0       /* no section, invalid */
#define MAX_SECT	255     /* maximum number of sections */

static struct section *sects, **sectstail, **sectstab;
static struct symbol *syms, **symstail;
static uint32_t nsyms;

/* These variables are set by macho_layout_symbols() to organize
   the symbol table and string table in order the dynamic linker
   expects.  They are then used in macho_write() to put out the
   symbols and strings in that order.

   The order of the symbol table is:
     local symbols
     defined external symbols (sorted by name)
     undefined external symbols (sorted by name)

   The order of the string table is:
     strings for external symbols
     strings for local symbols
 */
static uint32_t ilocalsym = 0;
static uint32_t iextdefsym = 0;
static uint32_t iundefsym = 0;
static uint32_t nlocalsym;
static uint32_t nextdefsym;
static uint32_t nundefsym;
static struct symbol **extdefsyms = NULL;
static struct symbol **undefsyms = NULL;

static struct RAA *extsyms;
static struct SAA *strs;
static uint32_t strslen;

/* Global file information. This should be cleaned up into either
   a structure or as function arguments.  */
static uint32_t head_ncmds = 0;
static uint32_t head_sizeofcmds = 0;
static uint32_t head_flags = 0;
static uint64_t seg_filesize = 0;
static uint64_t seg_vmsize = 0;
static uint32_t seg_nsects = 0;
static uint64_t rel_padcnt = 0;

/*
 * Functions for handling fixed-length zero-padded string
 * fields, that may or may not be null-terminated.
 */

/* Copy a string into a zero-padded fixed-length field */
#define xstrncpy(xdst, xsrc) strncpy(xdst, xsrc, sizeof(xdst))

/* Compare a fixed-length field with a string */
#define xstrncmp(xdst, xsrc) strncmp(xdst, xsrc, sizeof(xdst))

#define alignint32_t(x)							\
    ALIGN(x, sizeof(int32_t))	/* align x to int32_t boundary */

#define alignint64_t(x)							\
    ALIGN(x, sizeof(int64_t))	/* align x to int64_t boundary */

#define alignptr(x) \
    ALIGN(x, fmt.ptrsize)	/* align x to output format width */

static struct section *get_section_by_name(const char *segname,
                                           const char *sectname)
{
    struct section *s;

    for (s = sects; s != NULL; s = s->next)
        if (!xstrncmp(s->segname, segname) && !xstrncmp(s->sectname, sectname))
            break;

    return s;
}

static struct section *get_section_by_index(const int32_t index)
{
    struct section *s;

    for (s = sects; s != NULL; s = s->next)
        if (index == s->index)
            break;

    return s;
}

struct dir_list {
    struct dir_list *next;
    struct dir_list *last;
    const char *dir_name;
    uint32_t dir;
};

struct file_list {
    struct file_list *next;
    struct file_list *last;
    const char *file_name;
    uint32_t file;
    struct dir_list *dir;
};

struct dw_sect_list {
    struct SAA *psaa;
    int32_t section;
    uint32_t line;
    uint64_t offset;
    uint32_t file;
    struct dw_sect_list *next;
    struct dw_sect_list *last;
};

struct section_info {
    uint64_t size;
    int32_t secto;
};

#define DW_LN_BASE (-5)
#define DW_LN_RANGE 14
#define DW_OPCODE_BASE 13
#define DW_MAX_LN (DW_LN_BASE + DW_LN_RANGE)
#define DW_MAX_SP_OPCODE 256

static struct file_list *dw_head_file = 0, *dw_cur_file = 0, **dw_last_file_next = NULL;
static struct dir_list *dw_head_dir = 0, **dw_last_dir_next = NULL;
static struct dw_sect_list  *dw_head_sect = 0, *dw_cur_sect = 0, *dw_last_sect = 0;
static uint32_t  cur_line = 0, dw_num_files = 0, dw_num_dirs = 0, dw_num_sects = 0;
static bool  dbg_immcall = false;
static const char *module_name = NULL;

/*
 * Special section numbers which are used to define Mach-O special
 * symbols, which can be used with WRT to provide PIC relocation
 * types.
 */
static int32_t macho_tlvp_sect;
static int32_t macho_gotpcrel_sect;

static void macho_init(void)
{
    module_name = inname;
    sects = NULL;
    sectstail = &sects;

    /* Fake section for absolute symbols */
    absolute_sect.index = NO_SEG;

    syms = NULL;
    symstail = &syms;
    nsyms = 0;
    nlocalsym = 0;
    nextdefsym = 0;
    nundefsym = 0;

    extsyms = raa_init();
    strs = saa_init(1L);

    /* string table starts with a zero byte so index 0 is an empty string */
    saa_wbytes(strs, zero_buffer, 1);
    strslen = 1;

    /* add special symbol for TLVP */
    macho_tlvp_sect = seg_alloc() + 1;
    define_label("..tlvp", macho_tlvp_sect, 0L, NULL, false, false);

}

static void sect_write(struct section *sect,
                       const uint8_t *data, uint32_t len)
{
    saa_wbytes(sect->data, data, len);
    sect->size += len;
}

/*
 * Find a suitable global symbol for a ..gotpcrel or ..tlvp reference
 */
static struct symbol *macho_find_sym(struct section *s, uint64_t offset,
				     bool global, bool exact)
{
    struct rbtree *srb;

    srb = rb_search(s->syms[global], offset);

    if (!srb || (exact && srb->key != offset)) {
        nasm_error(ERR_NONFATAL, "unable to find a suitable%s%s symbol"
		   " for this reference",
		   global ? " global" : "",
		   s == &absolute_sect ? " absolute " : "");
        return NULL;
    }

    return container_of(srb - global, struct symbol, symv);
}

static int64_t add_reloc(struct section *sect, int32_t section,
			 int64_t offset,
			 enum reltype reltype, int bytes)
{
    struct reloc *r;
    struct section *s;
    int32_t fi;
    int64_t adjust;

    /* Double check this is a valid relocation type for this platform */
    nasm_assert(reltype <= fmt.maxreltype);

    /* the current end of the section will be the symbol's address for
     ** now, might have to be fixed by macho_fixup_relocs() later on. make
     ** sure we don't make the symbol scattered by setting the highest
     ** bit by accident */
    r = nasm_malloc(sizeof(struct reloc));
    r->addr = sect->size & ~R_SCATTERED;
    r->ext = 1;
    adjust = bytes;

    /* match byte count 1, 2, 4, 8 to length codes 0, 1, 2, 3 respectively */
    r->length = ilog2_32(bytes);

    /* set default relocation values */
    r->type = fmt.reloc_abs;
    r->pcrel = 0;
    r->snum = R_ABS;

    s = NULL;
    if (section != NO_SEG)
	s = get_section_by_index(section);
    fi = s ? s->fileindex : NO_SECT;

    /* absolute relocation */
    switch (reltype) {
    case RL_ABS:
	if (section == NO_SEG) {
	    /* absolute (can this even happen?) */
	    r->ext = 0;
	    r->snum = NO_SECT;
	} else if (fi == NO_SECT) {
	    /* external */
	    r->snum = raa_read(extsyms, section);
	} else {
	    /* local */
	    r->ext = 0;
	    r->snum = fi;
	    adjust = -sect->size;
	}
	break;

    case RL_REL:
    case RL_BRANCH:
	r->type = fmt.reloc_rel;
	r->pcrel = 1;
	if (section == NO_SEG) {
	    /* absolute - seems to produce garbage no matter what */
	    nasm_error(ERR_NONFATAL, "Mach-O does not support relative "
		       "references to absolute addresses");
	    goto bail;
#if 0
	    /* This "seems" to be how it ought to work... */

	    struct symbol *sym = macho_find_sym(&absolute_sect, offset,
						false, false);
	    if (!sym)
		goto bail;

	    sect->extreloc = 1;
	    r->snum = NO_SECT;
	    adjust = -sect->size;
#endif
	} else if (fi == NO_SECT) {
	    /* external */
	    sect->extreloc = 1;
	    r->snum = raa_read(extsyms, section);
	    if (reltype == RL_BRANCH)
		r->type = X86_64_RELOC_BRANCH;
	    else if (r->type == GENERIC_RELOC_VANILLA)
		adjust = -sect->size;
	} else {
	    /* local */
	    r->ext = 0;
	    r->snum = fi;
	    adjust = -sect->size;
	}
	break;

    case RL_SUB:
	r->pcrel = 0;
	r->type = X86_64_RELOC_SUBTRACTOR;
	break;

    case RL_GOT:
	r->type = X86_64_RELOC_GOT;
	goto needsym;

    case RL_GOTLOAD:
	r->type = X86_64_RELOC_GOT_LOAD;
	goto needsym;

    case RL_TLV:
	r->type = fmt.reloc_tlv;
	goto needsym;

    needsym:
	r->pcrel = 1;
	if (section == NO_SEG) {
	    nasm_error(ERR_NONFATAL, "Unsupported use of use of WRT");
	} else if (fi == NO_SECT) {
	    /* external */
	    r->snum = raa_read(extsyms, section);
	} else {
	    /* internal - does it really need to be global? */
	    struct symbol *sym = macho_find_sym(s, offset, true,
						reltype != RL_TLV);
	    if (!sym)
		goto bail;

	    r->snum = sym->initial_snum;
	}
	break;
    }

    /* For 64-bit Mach-O, force a symbol reference if at all possible */
    if (!r->ext && r->snum != NO_SECT && fmt.forcesym) {
	struct symbol *sym = macho_find_sym(s, offset, false, false);
	if (sym) {
	    adjust = bytes - sym->symv[0].key;
	    r->snum = sym->initial_snum;
	    r->ext = 1;
	}
    }

    /* NeXT as puts relocs in reversed order (address-wise) into the
     ** files, so we do the same, doesn't seem to make much of a
     ** difference either way */
    r->next = sect->relocs;
    sect->relocs = r;
    if (r->ext)
	sect->extreloc = 1;
    ++sect->nreloc;

    return adjust;

 bail:
    nasm_free(r);
    return 0;
}

static void macho_output(int32_t secto, const void *data,
			 enum out_type type, uint64_t size,
                         int32_t section, int32_t wrt)
{
    struct section *s;
    int64_t addr, offset;
    uint8_t mydata[16], *p;
    bool is_bss;
    enum reltype reltype;

    if (secto == NO_SEG) {
        if (type != OUT_RESERVE)
            nasm_error(ERR_NONFATAL, "attempt to assemble code in "
                  "[ABSOLUTE] space");
        return;
    }

    s = get_section_by_index(secto);

    if (s == NULL) {
        nasm_error(ERR_WARNING, "attempt to assemble code in"
              " section %d: defaulting to `.text'", secto);
        s = get_section_by_name("__TEXT", "__text");

        /* should never happen */
        if (s == NULL)
            nasm_panic(0, "text section not found");
    }

    /* debug code generation only for sections tagged with
     * instruction attribute */
    if (s->flags & S_ATTR_SOME_INSTRUCTIONS)
    {
        struct section_info sinfo;
        sinfo.size = s->size;
        sinfo.secto = secto;
        dfmt->debug_output(0, &sinfo);
    }

    is_bss = (s->flags & SECTION_TYPE) == S_ZEROFILL;

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

    memset(mydata, 0, sizeof(mydata));

    switch (type) {
    case OUT_RESERVE:
        if (!is_bss) {
            nasm_error(ERR_WARNING, "uninitialized space declared in"
		       " %s,%s section: zeroing", s->segname, s->sectname);

            sect_write(s, NULL, size);
        } else
            s->size += size;

        break;

    case OUT_RAWDATA:
        if (section != NO_SEG)
            nasm_panic(0, "OUT_RAWDATA with other than NO_SEG");

        sect_write(s, data, size);
        break;

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

        addr = *(int64_t *)data;
        if (section != NO_SEG) {
            if (section % 2) {
                nasm_error(ERR_NONFATAL, "Mach-O format does not support"
			   " section base references");
            } else if (wrt == NO_SEG) {
	        if (fmt.ptrsize == 8 &&
	            (asize != 8 || addr <= UINT32_MAX)) {
		    nasm_error(ERR_NONFATAL,
			       "Mach-O 64-bit format does not support"
			       " 32-bit absolute addresses");
		} else {
		    add_reloc(s, section, addr, RL_ABS, asize);
		}
	    } else {
		nasm_error(ERR_NONFATAL, "Mach-O format does not support"
			   " this use of WRT");
	    }
	}

        p = mydata;
	WRITEADDR(p, addr, asize);
        sect_write(s, mydata, asize);
        break;
    }

    case OUT_REL1ADR:
    case OUT_REL2ADR:

        p = mydata;
	offset = *(int64_t *)data;
        addr = offset - size;

        if (section != NO_SEG && section % 2) {
            nasm_error(ERR_NONFATAL, "Mach-O format does not support"
		       " section base references");
	} else if (fmt.ptrsize == 8) {
	    nasm_error(ERR_NONFATAL, "Unsupported non-32-bit"
		       " Macho-O relocation [2]");
	} else if (wrt != NO_SEG) {
	    nasm_error(ERR_NONFATAL, "Mach-O format does not support"
		       " this use of WRT");
	    wrt = NO_SEG;	/* we can at least _try_ to continue */
	} else {
	    addr += add_reloc(s, section, addr+size, RL_REL,
                              type == OUT_REL1ADR ? 1 : 2);
	}

        WRITESHORT(p, addr);
        sect_write(s, mydata, type == OUT_REL1ADR ? 1 : 2);
        break;

    case OUT_REL4ADR:
    case OUT_REL8ADR:

        p = mydata;
	offset = *(int64_t *)data;
        addr = offset - size;
	reltype = RL_REL;

        if (section != NO_SEG && section % 2) {
            nasm_error(ERR_NONFATAL, "Mach-O format does not support"
		       " section base references");
        } else if (wrt == NO_SEG) {
	    if (fmt.ptrsize == 8 &&
		(s->flags & S_ATTR_SOME_INSTRUCTIONS)) {
		uint8_t opcode[2];

		opcode[0] = opcode[1] = 0;

		/* HACK: Retrieve instruction opcode */
		if (likely(s->data->datalen >= 2)) {
		    saa_fread(s->data, s->data->datalen-2, opcode, 2);
		} else if (s->data->datalen == 1) {
		    saa_fread(s->data, 0, opcode+1, 1);
		}

		if ((opcode[0] != 0x0f && (opcode[1] & 0xfe) == 0xe8) ||
		    (opcode[0] == 0x0f && (opcode[1] & 0xf0) == 0x80)) {
		    /* Direct call, jmp, or jcc */
		    reltype = RL_BRANCH;
		}
	    }
	} else if (wrt == macho_gotpcrel_sect) {
	    reltype = RL_GOT;

	    if ((s->flags & S_ATTR_SOME_INSTRUCTIONS) &&
		s->data->datalen >= 3) {
		uint8_t gotload[3];

		/* HACK: Retrieve instruction opcode */
		saa_fread(s->data, s->data->datalen-3, gotload, 3);
		if ((gotload[0] & 0xf8) == 0x48 &&
		    gotload[1] == 0x8b &&
		    (gotload[2] & 0307) == 0005) {
		    /* movq <reg>,[rel sym wrt ..gotpcrel] */
		    reltype = RL_GOTLOAD;
		}
	    }
	} else if (wrt == macho_tlvp_sect) {
	    reltype = RL_TLV;
	} else {
	    nasm_error(ERR_NONFATAL, "Mach-O format does not support"
		       " this use of WRT");
	    /* continue with RL_REL */
	}

	addr += add_reloc(s, section, offset, reltype,
                          type == OUT_REL4ADR ? 4 : 8);
        WRITELONG(p, addr);
        sect_write(s, mydata, type == OUT_REL4ADR ? 4 : 8);
        break;

    default:
        nasm_error(ERR_NONFATAL, "Unrepresentable relocation in Mach-O");
        break;
    }
}

/* Translation table from traditional Unix section names to Mach-O */
static const struct sectmap {
    const char *nasmsect;
    const char *segname;
    const char *sectname;
    const uint32_t flags;
} sectmap[] = {
    {".text", "__TEXT", "__text",
     S_REGULAR|S_ATTR_SOME_INSTRUCTIONS|S_ATTR_PURE_INSTRUCTIONS},
    {".data", "__DATA", "__data", S_REGULAR},
    {".rodata", "__DATA", "__const", S_REGULAR},
    {".bss", "__DATA", "__bss", S_ZEROFILL},
    {".debug_abbrev", "__DWARF", "__debug_abbrev", S_ATTR_DEBUG},
    {".debug_info", "__DWARF", "__debug_info", S_ATTR_DEBUG},
    {".debug_line", "__DWARF", "__debug_line", S_ATTR_DEBUG},
    {".debug_str", "__DWARF", "__debug_str", S_ATTR_DEBUG},
    {NULL, NULL, NULL, 0}
};

#define NO_TYPE S_NASM_TYPE_MASK

/* Section type or attribute directives */
static const struct sect_attribs {
    const char *name;
    uint32_t flags;
} sect_attribs[] = {
    { "data", S_REGULAR },
    { "code", S_REGULAR|S_ATTR_SOME_INSTRUCTIONS|S_ATTR_PURE_INSTRUCTIONS },
    { "mixed", S_REGULAR|S_ATTR_SOME_INSTRUCTIONS },
    { "bss", S_ZEROFILL },
    { "zerofill", S_ZEROFILL },
    { "no_dead_strip", NO_TYPE|S_ATTR_NO_DEAD_STRIP },
    { "live_support", NO_TYPE|S_ATTR_LIVE_SUPPORT },
    { "strip_static_syms", NO_TYPE|S_ATTR_STRIP_STATIC_SYMS },
    { "debug", NO_TYPE|S_ATTR_DEBUG },
    { NULL, 0 }
};

static int32_t macho_section(char *name, int pass, int *bits)
{
    char *sectionAttributes;
    const struct sectmap *sm;
    struct section *s;
    const char *section, *segment;
    uint32_t flags;
    const struct sect_attribs *sa;
    char *currentAttribute;
    char *comma;

    bool new_seg;

    (void)pass;

    /* Default to the appropriate number of bits. */
    if (!name) {
        *bits = fmt.ptrsize << 3;
        name = ".text";
        sectionAttributes = NULL;
    } else {
        sectionAttributes = name;
        name = nasm_strsep(&sectionAttributes, " \t");
    }

    section = segment = NULL;
    flags = 0;

    comma = strchr(name, ',');
    if (comma) {
	int len;

	*comma = '\0';
	segment = name;
	section = comma+1;

	len = strlen(segment);
	if (len == 0) {
	    nasm_error(ERR_NONFATAL, "empty segment name\n");
	} else if (len > 16) {
	    nasm_error(ERR_NONFATAL, "segment name %s too long\n", segment);
	}

	len = strlen(section);
	if (len == 0) {
	    nasm_error(ERR_NONFATAL, "empty section name\n");
	} else if (len > 16) {
	    nasm_error(ERR_NONFATAL, "section name %s too long\n", section);
	}

	if (!strcmp(section, "__text")) {
	    flags = S_REGULAR | S_ATTR_SOME_INSTRUCTIONS |
		S_ATTR_PURE_INSTRUCTIONS;
	} else if (!strcmp(section, "__bss")) {
	    flags = S_ZEROFILL;
	} else {
	    flags = S_REGULAR;
	}
    } else {
	for (sm = sectmap; sm->nasmsect != NULL; ++sm) {
	    /* make lookup into section name translation table */
	    if (!strcmp(name, sm->nasmsect)) {
		segment = sm->segname;
		section = sm->sectname;
		flags = sm->flags;
		goto found;
	    }
	}
	nasm_error(ERR_NONFATAL, "unknown section name\n");
	return NO_SEG;
    }

 found:
    /* try to find section with that name */
    s = get_section_by_name(segment, section);

    /* create it if it doesn't exist yet */
    if (!s) {
	new_seg = true;

	s = *sectstail = nasm_zalloc(sizeof(struct section));
	sectstail = &s->next;

	s->data = saa_init(1L);
	s->index = seg_alloc();
	s->fileindex = ++seg_nsects;
	s->align = -1;
	s->pad = -1;
	s->offset = -1;
	s->by_name = false;

	xstrncpy(s->segname, segment);
	xstrncpy(s->sectname, section);
	s->size = 0;
	s->nreloc = 0;
	s->flags = flags;
    } else {
	new_seg = false;
    }

    if (comma)
	*comma = ',';		/* Restore comma */

    s->by_name = s->by_name || comma; /* Was specified by name */

    flags = NO_TYPE;

    while (sectionAttributes &&
	   (currentAttribute = nasm_strsep(&sectionAttributes, " \t"))) {
	if (!*currentAttribute)
	    continue;

	if (!nasm_strnicmp("align=", currentAttribute, 6)) {
	    char *end;
	    int newAlignment, value;

	    value = strtoul(currentAttribute + 6, (char**)&end, 0);
	    newAlignment = alignlog2_32(value);

	    if (0 != *end) {
		nasm_error(ERR_NONFATAL,
			   "unknown or missing alignment value \"%s\" "
			   "specified for section \"%s\"",
			   currentAttribute + 6,
			   name);
	    } else if (0 > newAlignment) {
		nasm_error(ERR_NONFATAL,
			   "alignment of %d (for section \"%s\") is not "
			   "a power of two",
			   value,
			   name);
	    }

	    if (s->align < newAlignment)
		s->align = newAlignment;
	} else {
	    for (sa = sect_attribs; sa->name; sa++) {
		if (!nasm_stricmp(sa->name, currentAttribute)) {
		    if ((sa->flags & S_NASM_TYPE_MASK) != NO_TYPE) {
			flags = (flags & ~S_NASM_TYPE_MASK)
			    | (sa->flags & S_NASM_TYPE_MASK);
		    }
		    flags |= sa->flags & ~S_NASM_TYPE_MASK;
		    break;
		}
	    }

	    if (!sa->name) {
		nasm_error(ERR_NONFATAL,
			   "unknown section attribute %s for section %s",
			   currentAttribute, name);
	    }
	}
    }

    if ((flags & S_NASM_TYPE_MASK) != NO_TYPE) {
	if (!new_seg && ((s->flags ^ flags) & S_NASM_TYPE_MASK)) {
	    nasm_error(ERR_NONFATAL,
		       "inconsistent section attributes for section %s\n",
		       name);
	} else {
	    s->flags = (s->flags & ~S_NASM_TYPE_MASK) | flags;
	}
    } else {
	s->flags |= flags & ~S_NASM_TYPE_MASK;
    }

    return s->index;
}

static void macho_symdef(char *name, int32_t section, int64_t offset,
                         int is_global, char *special)
{
    struct symbol *sym;
    struct section *s;
    bool special_used = false;

#if defined(DEBUG) && DEBUG>2
    nasm_error(ERR_DEBUG,
            " macho_symdef: %s, sec=%"PRIx32", off=%"PRIx64", is_global=%d, %s\n",
            name, section, offset, is_global, special);
#endif

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

            if (!nasm_strnicmp(special, "private_extern", n)) {
                for (sym = syms; sym != NULL; sym = sym->next) {
                    if (!strcmp(name, sym->name)) {
                        if (sym->type & N_PEXT)
                            return; /* nothing to be done */
                        else
                            break;
                    }
                }
            }
        }
        nasm_error(ERR_NONFATAL, "The Mach-O format does not "
              "(yet) support forward reference fixups.");
        return;
    }

    if (name[0] == '.' && name[1] == '.' && name[2] != '@') {
	/*
	 * This is a NASM special symbol. We never allow it into
	 * the Macho-O symbol table, even if it's a valid one. If it
	 * _isn't_ a valid one, we should barf immediately.
	 */
	if (strcmp(name, "..gotpcrel") && strcmp(name, "..tlvp"))
            nasm_error(ERR_NONFATAL, "unrecognized special symbol `%s'", name);
	return;
    }

    sym = *symstail = nasm_zalloc(sizeof(struct symbol));
    sym->next = NULL;
    symstail = &sym->next;

    sym->name = name;
    sym->strx = strslen;
    sym->type = 0;
    sym->desc = 0;
    sym->symv[0].key = offset;
    sym->symv[1].key = offset;
    sym->initial_snum = -1;

    /* external and common symbols get N_EXT */
    if (is_global != 0) {
        sym->type |= N_EXT;
    }
    if (is_global == 1) {
        /* check special to see if the global symbol shall be marked as private external: N_PEXT */
        if (special) {
            int n = strcspn(special, " \t");

            if (!nasm_strnicmp(special, "private_extern", n))
                sym->type |= N_PEXT;
            else
                nasm_error(ERR_NONFATAL, "unrecognised symbol type `%.*s'", n, special);
        }
        special_used = true;
    }

    if (section == NO_SEG) {
        /* symbols in no section get absolute */
        sym->type |= N_ABS;
        sym->sect = NO_SECT;

	s = &absolute_sect;
    } else {
	s = get_section_by_index(section);

        sym->type |= N_SECT;

        /* get the in-file index of the section the symbol was defined in */
        sym->sect = s ? s->fileindex : NO_SECT;

	/* track the initially allocated symbol number for use in future fix-ups */
	sym->initial_snum = nsyms;

        if (!s) {
            /* remember symbol number of references to external
             ** symbols, this works because every external symbol gets
             ** its own section number allocated internally by nasm and
             ** can so be used as a key */
	    extsyms = raa_write(extsyms, section, nsyms);

            switch (is_global) {
            case 1:
            case 2:
                /* there isn't actually a difference between global
                 ** and common symbols, both even have their size in
                 ** sym->symv[0].key */
                sym->type = N_EXT;
                break;

            default:
                /* give an error on unfound section if it's not an
                 ** external or common symbol (assemble_file() does a
                 ** seg_alloc() on every call for them) */
                nasm_panic(0, "in-file index for section %d not found, is_global = %d", section, is_global);
		break;
            }
	}
    }

    if (s) {
	s->syms[0] = rb_insert(s->syms[0], &sym->symv[0]);
	if (is_global)
	    s->syms[1] = rb_insert(s->syms[1], &sym->symv[1]);
    }

    ++nsyms;

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

static void macho_sectalign(int32_t seg, unsigned int value)
{
    struct section *s;
    int align;

    nasm_assert(!(seg & 1));

    s = get_section_by_index(seg);

    if (!s || !is_power2(value))
        return;

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

static int32_t macho_segbase(int32_t section)
{
    return section;
}

extern macros_t macho_stdmac[];

/* Comparison function for qsort symbol layout.  */
static int layout_compare (const struct symbol **s1,
			   const struct symbol **s2)
{
    return (strcmp ((*s1)->name, (*s2)->name));
}

/* The native assembler does a few things in a similar function

	* Remove temporary labels
	* Sort symbols according to local, external, undefined (by name)
	* Order the string table

   We do not remove temporary labels right now.

   numsyms is the total number of symbols we have. strtabsize is the
   number entries in the string table.  */

static void macho_layout_symbols (uint32_t *numsyms,
				  uint32_t *strtabsize)
{
    struct symbol *sym, **symp;
    uint32_t i,j;

    *numsyms = 0;
    *strtabsize = sizeof (char);

    symp = &syms;

    while ((sym = *symp)) {
	/* Undefined symbols are now external.  */
	if (sym->type == N_UNDF)
	    sym->type |= N_EXT;

	if ((sym->type & N_EXT) == 0) {
	    sym->snum = *numsyms;
	    *numsyms = *numsyms + 1;
	    nlocalsym++;
	}
	else {
	    if ((sym->type & N_TYPE) != N_UNDF) {
		nextdefsym++;
	    } else {
		nundefsym++;
	    }

	    /* If we handle debug info we'll want
	       to check for it here instead of just
	       adding the symbol to the string table.  */
	    sym->strx = *strtabsize;
	    saa_wbytes (strs, sym->name, (int32_t)(strlen(sym->name) + 1));
	    *strtabsize += strlen(sym->name) + 1;
	}
	symp = &(sym->next);
    }

    /* Next, sort the symbols.  Most of this code is a direct translation from
       the Apple cctools symbol layout. We need to keep compatibility with that.  */
    /* Set the indexes for symbol groups into the symbol table */
    ilocalsym = 0;
    iextdefsym = nlocalsym;
    iundefsym = nlocalsym + nextdefsym;

    /* allocate arrays for sorting externals by name */
    extdefsyms = nasm_malloc(nextdefsym * sizeof(struct symbol *));
    undefsyms = nasm_malloc(nundefsym * sizeof(struct symbol *));

    i = 0;
    j = 0;

    symp = &syms;

    while ((sym = *symp)) {

	if((sym->type & N_EXT) == 0) {
	    sym->strx = *strtabsize;
	    saa_wbytes (strs, sym->name, (int32_t)(strlen (sym->name) + 1));
	    *strtabsize += strlen(sym->name) + 1;
	}
	else {
	    if ((sym->type & N_TYPE) != N_UNDF) {
		extdefsyms[i++] = sym;
	    } else {
		undefsyms[j++] = sym;
	    }
	}
	symp = &(sym->next);
    }

    qsort(extdefsyms, nextdefsym, sizeof(struct symbol *),
	  (int (*)(const void *, const void *))layout_compare);
    qsort(undefsyms, nundefsym, sizeof(struct symbol *),
	  (int (*)(const void *, const void *))layout_compare);

    for(i = 0; i < nextdefsym; i++) {
	extdefsyms[i]->snum = *numsyms;
	*numsyms += 1;
    }
    for(j = 0; j < nundefsym; j++) {
	undefsyms[j]->snum = *numsyms;
	*numsyms += 1;
    }
}

/* Calculate some values we'll need for writing later.  */

static void macho_calculate_sizes (void)
{
    struct section *s;
    int fi;

    /* count sections and calculate in-memory and in-file offsets */
    for (s = sects; s != NULL; s = s->next) {
        uint64_t newaddr;

        /* recalculate segment address based on alignment and vm size */
        s->addr = seg_vmsize;

        /* we need section alignment to calculate final section address */
        if (s->align == -1)
            s->align = DEFAULT_SECTION_ALIGNMENT;

        newaddr = ALIGN(s->addr, UINT64_C(1) << s->align);
        s->addr = newaddr;

        seg_vmsize = newaddr + s->size;

        /* zerofill sections aren't actually written to the file */
        if ((s->flags & SECTION_TYPE) != S_ZEROFILL) {
	    /*
	     * LLVM/Xcode as always aligns the section data to 4
	     * bytes; there is a comment in the LLVM source code that
	     * perhaps aligning to pointer size would be better.
	     */
	    s->pad = ALIGN(seg_filesize, 4) - seg_filesize;
	    s->offset = seg_filesize + s->pad;
            seg_filesize += s->size + s->pad;

            /* filesize and vmsize needs to be aligned */
            seg_vmsize += s->pad;
	}
    }

    /* calculate size of all headers, load commands and sections to
    ** get a pointer to the start of all the raw data */
    if (seg_nsects > 0) {
        ++head_ncmds;
        head_sizeofcmds += fmt.segcmd_size  + seg_nsects * fmt.sectcmd_size;
    }

    if (nsyms > 0) {
	++head_ncmds;
	head_sizeofcmds += MACHO_SYMCMD_SIZE;
    }

    if (seg_nsects > MAX_SECT) {
	nasm_fatal(0, "MachO output is limited to %d sections\n",
		   MAX_SECT);
    }

    /* Create a table of sections by file index to avoid linear search */
    sectstab = nasm_malloc((seg_nsects + 1) * sizeof(*sectstab));
    sectstab[NO_SECT] = &absolute_sect;
    for (s = sects, fi = 1; s != NULL; s = s->next, fi++)
	sectstab[fi] = s;
}

/* Write out the header information for the file.  */

static void macho_write_header (void)
{
    fwriteint32_t(fmt.mh_magic, ofile);	/* magic */
    fwriteint32_t(fmt.cpu_type, ofile);	/* CPU type */
    fwriteint32_t(CPU_SUBTYPE_I386_ALL, ofile);	/* CPU subtype */
    fwriteint32_t(MH_OBJECT, ofile);	/* Mach-O file type */
    fwriteint32_t(head_ncmds, ofile);	/* number of load commands */
    fwriteint32_t(head_sizeofcmds, ofile);	/* size of load commands */
    fwriteint32_t(head_flags, ofile);		/* flags, if any */
    fwritezero(fmt.header_size - 7*4, ofile);	/* reserved fields */
}

/* Write out the segment load command at offset.  */

static uint32_t macho_write_segment (uint64_t offset)
{
    uint64_t rel_base = alignptr(offset + seg_filesize);
    uint32_t s_reloff = 0;
    struct section *s;

    fwriteint32_t(fmt.lc_segment, ofile);        /* cmd == LC_SEGMENT_64 */

    /* size of load command including section load commands */
    fwriteint32_t(fmt.segcmd_size + seg_nsects * fmt.sectcmd_size,
		  ofile);

    /* in an MH_OBJECT file all sections are in one unnamed (name
    ** all zeros) segment */
    fwritezero(16, ofile);
    fwriteptr(0, ofile);		     /* in-memory offset */
    fwriteptr(seg_vmsize, ofile);	     /* in-memory size */
    fwriteptr(offset, ofile);	             /* in-file offset to data */
    fwriteptr(seg_filesize, ofile);	     /* in-file size */
    fwriteint32_t(VM_PROT_DEFAULT, ofile);   /* maximum vm protection */
    fwriteint32_t(VM_PROT_DEFAULT, ofile);   /* initial vm protection */
    fwriteint32_t(seg_nsects, ofile);        /* number of sections */
    fwriteint32_t(0, ofile);		     /* no flags */

    /* emit section headers */
    for (s = sects; s != NULL; s = s->next) {
	if (s->nreloc) {
	    nasm_assert((s->flags & SECTION_TYPE) != S_ZEROFILL);
	    s->flags |= S_ATTR_LOC_RELOC;
	    if (s->extreloc)
		s->flags |= S_ATTR_EXT_RELOC;
	} else if (!xstrncmp(s->segname, "__DATA") &&
		   !xstrncmp(s->sectname, "__const") &&
		   !s->by_name &&
		   !get_section_by_name("__TEXT", "__const")) {
	    /*
	     * The MachO equivalent to .rodata can be either
	     * __DATA,__const or __TEXT,__const; the latter only if
	     * there are no relocations.  However, when mixed it is
	     * better to specify the segments explicitly.
	     */
	    xstrncpy(s->segname, "__TEXT");
	}

        nasm_write(s->sectname, sizeof(s->sectname), ofile);
        nasm_write(s->segname, sizeof(s->segname), ofile);
        fwriteptr(s->addr, ofile);
        fwriteptr(s->size, ofile);

        /* dummy data for zerofill sections or proper values */
        if ((s->flags & SECTION_TYPE) != S_ZEROFILL) {
	    nasm_assert(s->pad != (uint32_t)-1);
	    offset += s->pad;
            fwriteint32_t(offset, ofile);
	    offset += s->size;
            /* Write out section alignment, as a power of two.
            e.g. 32-bit word alignment would be 2 (2^2 = 4).  */
            fwriteint32_t(s->align, ofile);
            /* To be compatible with cctools as we emit
            a zero reloff if we have no relocations.  */
            fwriteint32_t(s->nreloc ? rel_base + s_reloff : 0, ofile);
            fwriteint32_t(s->nreloc, ofile);

            s_reloff += s->nreloc * MACHO_RELINFO_SIZE;
        } else {
            fwriteint32_t(0, ofile);
            fwriteint32_t(s->align, ofile);
            fwriteint32_t(0, ofile);
            fwriteint32_t(0, ofile);
        }

        fwriteint32_t(s->flags, ofile);      /* flags */
        fwriteint32_t(0, ofile);	     /* reserved */
        fwriteptr(0, ofile);		     /* reserved */
    }

    rel_padcnt = rel_base - offset;
    offset = rel_base + s_reloff;

    return offset;
}

/* For a given chain of relocs r, write out the entire relocation
   chain to the object file.  */

static void macho_write_relocs (struct reloc *r)
{
    while (r) {
	uint32_t word2;

	fwriteint32_t(r->addr, ofile); /* reloc offset */

	word2 = r->snum;
	word2 |= r->pcrel << 24;
	word2 |= r->length << 25;
	word2 |= r->ext << 27;
	word2 |= r->type << 28;
	fwriteint32_t(word2, ofile); /* reloc data */
	r = r->next;
    }
}

/* Write out the section data.  */
static void macho_write_section (void)
{
    struct section *s;
    struct reloc *r;
    uint8_t *p;
    int32_t len;
    int64_t l;
    union offset {
	uint64_t val;
	uint8_t buf[8];
    } blk;

    for (s = sects; s != NULL; s = s->next) {
	if ((s->flags & SECTION_TYPE) == S_ZEROFILL)
	    continue;

	/* Like a.out Mach-O references things in the data or bss
	 * sections by addresses which are actually relative to the
	 * start of the _text_ section, in the _file_. See outaout.c
	 * for more information. */
	saa_rewind(s->data);
	for (r = s->relocs; r != NULL; r = r->next) {
	    len = (uint32_t)1 << r->length;
	    if (len > 4)	/* Can this ever be an issue?! */
		len = 8;
	    blk.val = 0;
	    saa_fread(s->data, r->addr, blk.buf, len);

	    /* get offset based on relocation type */
#ifdef WORDS_LITTLEENDIAN
	    l = blk.val;
#else
	    l  = blk.buf[0];
	    l += ((int64_t)blk.buf[1]) << 8;
	    l += ((int64_t)blk.buf[2]) << 16;
	    l += ((int64_t)blk.buf[3]) << 24;
	    l += ((int64_t)blk.buf[4]) << 32;
	    l += ((int64_t)blk.buf[5]) << 40;
	    l += ((int64_t)blk.buf[6]) << 48;
	    l += ((int64_t)blk.buf[7]) << 56;
#endif

	    /* If the relocation is internal add to the current section
	       offset. Otherwise the only value we need is the symbol
	       offset which we already have. The linker takes care
	       of the rest of the address.  */
	    if (!r->ext) {
		/* generate final address by section address and offset */
		nasm_assert(r->snum <= seg_nsects);
		l += sectstab[r->snum]->addr;
		if (r->pcrel)
		    l -= s->addr;
	    } else if (r->pcrel && r->type == GENERIC_RELOC_VANILLA) {
		l -= s->addr;
	    }

	    /* write new offset back */
	    p = blk.buf;
	    WRITEDLONG(p, l);
	    saa_fwrite(s->data, r->addr, blk.buf, len);
	}

	/* dump the section data to file */
	fwritezero(s->pad, ofile);
	saa_fpwrite(s->data, ofile);
    }

    /* pad last section up to reloc entries on pointer boundary */
    fwritezero(rel_padcnt, ofile);

    /* emit relocation entries */
    for (s = sects; s != NULL; s = s->next)
	macho_write_relocs (s->relocs);
}

/* Write out the symbol table. We should already have sorted this
   before now.  */
static void macho_write_symtab (void)
{
    struct symbol *sym;
    uint64_t i;

    /* we don't need to pad here since MACHO_RELINFO_SIZE == 8 */

    for (sym = syms; sym != NULL; sym = sym->next) {
	if ((sym->type & N_EXT) == 0) {
	    fwriteint32_t(sym->strx, ofile);		/* string table entry number */
	    nasm_write(&sym->type, 1, ofile);		/* symbol type */
	    nasm_write(&sym->sect, 1, ofile);		/* section */
	    fwriteint16_t(sym->desc, ofile);		/* description */

	    /* Fix up the symbol value now that we know the final section
	       sizes.  */
	    if (((sym->type & N_TYPE) == N_SECT) && (sym->sect != NO_SECT)) {
		nasm_assert(sym->sect <= seg_nsects);
		sym->symv[0].key += sectstab[sym->sect]->addr;
	    }

	    fwriteptr(sym->symv[0].key, ofile);	/* value (i.e. offset) */
	}
    }

    for (i = 0; i < nextdefsym; i++) {
	sym = extdefsyms[i];
	fwriteint32_t(sym->strx, ofile);
	nasm_write(&sym->type, 1, ofile);	/* symbol type */
	nasm_write(&sym->sect, 1, ofile);	/* section */
	fwriteint16_t(sym->desc, ofile);	/* description */

	/* Fix up the symbol value now that we know the final section
	   sizes.  */
	if (((sym->type & N_TYPE) == N_SECT) && (sym->sect != NO_SECT)) {
	    nasm_assert(sym->sect <= seg_nsects);
	    sym->symv[0].key += sectstab[sym->sect]->addr;
	}

	fwriteptr(sym->symv[0].key, ofile); /* value (i.e. offset) */
    }

     for (i = 0; i < nundefsym; i++) {
	 sym = undefsyms[i];
	 fwriteint32_t(sym->strx, ofile);
	 nasm_write(&sym->type, 1, ofile);	/* symbol type */
	 nasm_write(&sym->sect, 1, ofile);	/* section */
	 fwriteint16_t(sym->desc, ofile);	/* description */

	/* Fix up the symbol value now that we know the final section
	   sizes.  */
	 if (((sym->type & N_TYPE) == N_SECT) && (sym->sect != NO_SECT)) {
	    nasm_assert(sym->sect <= seg_nsects);
	    sym->symv[0].key += sectstab[sym->sect]->addr;
	 }

	 fwriteptr(sym->symv[0].key, ofile); /* value (i.e. offset) */
     }

}

/* Fixup the snum in the relocation entries, we should be
   doing this only for externally referenced symbols. */
static void macho_fixup_relocs (struct reloc *r)
{
    struct symbol *sym;

    while (r != NULL) {
	if (r->ext) {
	    for (sym = syms; sym != NULL; sym = sym->next) {
		if (sym->initial_snum == r->snum) {
		    r->snum = sym->snum;
		    break;
		}
	    }
	}
	r = r->next;
    }
}

/* Write out the object file.  */

static void macho_write (void)
{
    uint64_t offset = 0;

    /* mach-o object file structure:
    **
    ** mach header
    **  uint32_t magic
    **  int   cpu type
    **  int   cpu subtype
    **  uint32_t mach file type
    **  uint32_t number of load commands
    **  uint32_t size of all load commands
    **   (includes section struct size of segment command)
    **  uint32_t flags
    **
    ** segment command
    **  uint32_t command type == LC_SEGMENT[_64]
    **  uint32_t size of load command
    **   (including section load commands)
    **  char[16] segment name
    **  pointer  in-memory offset
    **  pointer  in-memory size
    **  pointer  in-file offset to data area
    **  pointer  in-file size
    **   (in-memory size excluding zerofill sections)
    **  int   maximum vm protection
    **  int   initial vm protection
    **  uint32_t number of sections
    **  uint32_t flags
    **
    ** section commands
    **   char[16] section name
    **   char[16] segment name
    **   pointer  in-memory offset
    **   pointer  in-memory size
    **   uint32_t in-file offset
    **   uint32_t alignment
    **    (irrelevant in MH_OBJECT)
    **   uint32_t in-file offset of relocation entires
    **   uint32_t number of relocations
    **   uint32_t flags
    **   uint32_t reserved
    **   uint32_t reserved
    **
    ** symbol table command
    **  uint32_t command type == LC_SYMTAB
    **  uint32_t size of load command
    **  uint32_t symbol table offset
    **  uint32_t number of symbol table entries
    **  uint32_t string table offset
    **  uint32_t string table size
    **
    ** raw section data
    **
    ** padding to pointer boundary
    **
    ** relocation data (struct reloc)
    ** int32_t offset
    **  uint data (symbolnum, pcrel, length, extern, type)
    **
    ** symbol table data (struct nlist)
    **  int32_t  string table entry number
    **  uint8_t type
    **   (extern, absolute, defined in section)
    **  uint8_t section
    **   (0 for global symbols, section number of definition (>= 1, <=
    **   254) for local symbols, size of variable for common symbols
    **   [type == extern])
    **  int16_t description
    **   (for stab debugging format)
    **  pointer value (i.e. file offset) of symbol or stab offset
    **
    ** string table data
    **  list of null-terminated strings
    */

    /* Emit the Mach-O header.  */
    macho_write_header();

    offset = fmt.header_size + head_sizeofcmds;

    /* emit the segment load command */
    if (seg_nsects > 0)
	offset = macho_write_segment (offset);
    else
        nasm_error(ERR_WARNING, "no sections?");

    if (nsyms > 0) {
        /* write out symbol command */
        fwriteint32_t(LC_SYMTAB, ofile); /* cmd == LC_SYMTAB */
        fwriteint32_t(MACHO_SYMCMD_SIZE, ofile); /* size of load command */
        fwriteint32_t(offset, ofile);    /* symbol table offset */
        fwriteint32_t(nsyms, ofile);     /* number of symbol
                                         ** table entries */
        offset += nsyms * fmt.nlist_size;
        fwriteint32_t(offset, ofile);    /* string table offset */
        fwriteint32_t(strslen, ofile);   /* string table size */
    }

    /* emit section data */
    if (seg_nsects > 0)
	macho_write_section ();

    /* emit symbol table if we have symbols */
    if (nsyms > 0)
	macho_write_symtab ();

    /* we don't need to pad here, we are already aligned */

    /* emit string table */
    saa_fpwrite(strs, ofile);
}
/* We do quite a bit here, starting with finalizing all of the data
   for the object file, writing, and then freeing all of the data from
   the file.  */

static void macho_cleanup(void)
{
    struct section *s;
    struct reloc *r;
    struct symbol *sym;

    dfmt->cleanup();

    /* Sort all symbols.  */
    macho_layout_symbols (&nsyms, &strslen);

    /* Fixup relocation entries */
    for (s = sects; s != NULL; s = s->next) {
	macho_fixup_relocs (s->relocs);
    }

    /* First calculate and finalize needed values.  */
    macho_calculate_sizes();
    macho_write();

    /* free up everything */
    while (sects->next) {
        s = sects;
        sects = sects->next;

        saa_free(s->data);
        while (s->relocs != NULL) {
            r = s->relocs;
            s->relocs = s->relocs->next;
            nasm_free(r);
        }

        nasm_free(s);
    }

    saa_free(strs);
    raa_free(extsyms);

    while (syms) {
       sym = syms;
       syms = syms->next;
       nasm_free (sym);
    }

    nasm_free(extdefsyms);
    nasm_free(undefsyms);
    nasm_free(sectstab);
}

static bool macho_set_section_attribute_by_symbol(const char *label, uint32_t flags)
{
    struct section *s;
    int32_t nasm_seg;
    int64_t offset;

    if (!lookup_label(label, &nasm_seg, &offset)) {
	nasm_error(ERR_NONFATAL, "unknown symbol `%s' in no_dead_strip", label);
	return false;
    }

    s = get_section_by_index(nasm_seg);
    if (!s) {
	nasm_error(ERR_NONFATAL, "symbol `%s' is external or absolute", label);
	return false;
    }

    s->flags |= flags;
    return true;
}

/*
 * Mark a symbol for no dead stripping
 */
static enum directive_result macho_no_dead_strip(const char *labels)
{
    char *s, *p, *ep;
    char ec;
    enum directive_result rv = DIRR_ERROR;
    bool real = passn > 1;

    p = s = nasm_strdup(labels);
    while (*p) {
	ep = nasm_skip_identifier(p);
	if (!ep) {
	    nasm_error(ERR_NONFATAL, "invalid symbol in NO_DEAD_STRIP");
	    goto err;
	}
	ec = *ep;
	if (ec && ec != ',' && !nasm_isspace(ec)) {
	    nasm_error(ERR_NONFATAL, "cannot parse contents after symbol");
	    goto err;
	}
	*ep = '\0';
	if (real) {
	    if (!macho_set_section_attribute_by_symbol(p, S_ATTR_NO_DEAD_STRIP))
		rv = DIRR_ERROR;
	}
	*ep = ec;
	p = nasm_skip_spaces(ep);
	if (*p == ',')
	    p = nasm_skip_spaces(++p);
    }

    rv = DIRR_OK;

err:
    nasm_free(s);
    return rv;
}

/*
 * Mach-O pragmas
 */
static enum directive_result
macho_pragma(const struct pragma *pragma)
{
    bool real = passn > 1;

    switch (pragma->opcode) {
    case D_SUBSECTIONS_VIA_SYMBOLS:
	if (*pragma->tail)
	    return DIRR_BADPARAM;

	if (real)
	    head_flags |= MH_SUBSECTIONS_VIA_SYMBOLS;

	return DIRR_OK;

    case D_NO_DEAD_STRIP:
	return macho_no_dead_strip(pragma->tail);

    default:
	return DIRR_UNKNOWN;	/* Not a Mach-O directive */
    }
}

static const struct pragma_facility macho_pragma_list[] = {
    { "macho", macho_pragma },
    { NULL, macho_pragma }	/* Implements macho32/macho64 namespaces */
};

static void macho_dbg_generate(void)
{
    uint8_t *p_buf = NULL, *p_buf_base = NULL;
    size_t saa_len = 0, high_addr = 0, total_len = 0;
    struct section *p_section = NULL;
    /* calculated at debug_str and referenced at debug_info */
    uint32_t producer_str_offset = 0, module_str_offset = 0, dir_str_offset = 0;

    /* debug section defines */
    {
        int bits = 0;
        macho_section(".debug_abbrev", 0, &bits);
        macho_section(".debug_info", 0, &bits);
        macho_section(".debug_line", 0, &bits);
        macho_section(".debug_str", 0, &bits);
    }

    /* dw section walk to find high_addr and total_len */
    {
        struct dw_sect_list *p_sect;

        list_for_each(p_sect, dw_head_sect) {
            uint64_t offset = get_section_by_index(p_sect->section)->size;
            struct SAA *p_linep = p_sect->psaa;

            saa_write8(p_linep, 2); /* std op 2 */
            saa_write8(p_linep, offset - p_sect->offset);
            saa_write8(p_linep, DW_LNS_extended_op);
            saa_write8(p_linep, 1); /* operand length */
            saa_write8(p_linep, DW_LNE_end_sequence);

            total_len += p_linep->datalen;
            high_addr += offset;
        }
    }

    /* debug line */
    {
        struct dw_sect_list *p_sect;
        size_t linep_off, buf_size;
        struct SAA *p_lines = saa_init(1L);
        struct dir_list *p_dir;
        struct file_list *p_file;

        p_section = get_section_by_name("__DWARF", "__debug_line");
        nasm_assert(p_section != NULL);

        saa_write8(p_lines, 1); /* minimum instruction length */
        saa_write8(p_lines, 1); /* initial value of "is_stmt" */
        saa_write8(p_lines, DW_LN_BASE); /* line base */
        saa_write8(p_lines, DW_LN_RANGE); /* line range */
        saa_write8(p_lines, DW_OPCODE_BASE); /* opcode base */
        saa_write8(p_lines, 0); /* std opcode 1 length */
        saa_write8(p_lines, 1); /* std opcode 2 length */
        saa_write8(p_lines, 1); /* std opcode 3 length */
        saa_write8(p_lines, 1); /* std opcode 4 length */
        saa_write8(p_lines, 1); /* std opcode 5 length */
        saa_write8(p_lines, 0); /* std opcode 6 length */
        saa_write8(p_lines, 0); /* std opcode 7 length */
        saa_write8(p_lines, 0); /* std opcode 8 length */
        saa_write8(p_lines, 1); /* std opcode 9 length */
        saa_write8(p_lines, 0); /* std opcode 10 length */
        saa_write8(p_lines, 0); /* std opcode 11 length */
        saa_write8(p_lines, 1); /* std opcode 12 length */
        list_for_each(p_dir, dw_head_dir) {
            saa_wcstring(p_lines, p_dir->dir_name);
        }
        saa_write8(p_lines, 0); /* end of table */

        list_for_each(p_file, dw_head_file) {
            saa_wcstring(p_lines, p_file->file_name);
            saa_write8(p_lines, p_file->dir->dir); /* directory id */
            saa_write8(p_lines, 0); /* time */
            saa_write8(p_lines, 0); /* size */
        }
        saa_write8(p_lines, 0); /* end of table */

        linep_off = p_lines->datalen;
        /* 10 bytes for initial & prolong length, and dwarf version info */
        buf_size = saa_len = linep_off + total_len + 10;
        p_buf_base = p_buf = nasm_malloc(buf_size);

        WRITELONG(p_buf, saa_len - 4); /* initial length; size excluding itself */
        WRITESHORT(p_buf, 2); /* dwarf version */
        WRITELONG(p_buf, linep_off); /* prolong length */

        saa_rnbytes(p_lines, p_buf, linep_off);
        p_buf += linep_off;
        saa_free(p_lines);

        list_for_each(p_sect, dw_head_sect) {
            struct SAA *p_linep = p_sect->psaa;

            saa_len = p_linep->datalen;
            saa_rnbytes(p_linep, p_buf, saa_len);
            p_buf += saa_len;

            saa_free(p_linep);
        }

        macho_output(p_section->index, p_buf_base, OUT_RAWDATA, buf_size, NO_SEG, 0);

        nasm_free(p_buf_base);
    }

    /* string section */
    {
        struct SAA *p_str = saa_init(1L);
        char *cur_path = nasm_realpath(module_name);
        char *cur_file = nasm_basename(cur_path);
        char *cur_dir = nasm_dirname(cur_path);

        p_section = get_section_by_name("__DWARF", "__debug_str");
        nasm_assert(p_section != NULL);

        producer_str_offset = 0;
        module_str_offset = dir_str_offset = saa_wcstring(p_str, nasm_signature);
        dir_str_offset += saa_wcstring(p_str, cur_file);
        saa_wcstring(p_str, cur_dir);

        saa_len = p_str->datalen;
        p_buf = nasm_malloc(saa_len);
        saa_rnbytes(p_str, p_buf, saa_len);
        macho_output(p_section->index, p_buf, OUT_RAWDATA, saa_len, NO_SEG, 0);

        nasm_free(cur_path);
        nasm_free(cur_file);
        nasm_free(cur_dir);
        saa_free(p_str);
        nasm_free(p_buf);
    }

    /* debug info */
    {
        struct SAA *p_info = saa_init(1L);

        p_section = get_section_by_name("__DWARF", "__debug_info");
        nasm_assert(p_section != NULL);

        /* size will be overwritten once determined, so skip in p_info layout */
        saa_write16(p_info, 2); /* dwarf version */
        saa_write32(p_info, 0); /* offset info abbrev */
        saa_write8(p_info, (ofmt == &of_macho64) ? 8 : 4);   /* pointer size  */

        saa_write8(p_info, 1);   /* abbrev entry number  */

        saa_write32(p_info, producer_str_offset); /* offset from string table for DW_AT_producer  */
        saa_write16(p_info, DW_LANG_Mips_Assembler); /* DW_AT_language  */
        saa_write32(p_info, module_str_offset); /* offset from string table for DW_AT_name  */
        saa_write32(p_info, dir_str_offset); /* offset from string table for DW_AT_comp_dir */
        saa_write32(p_info, 0); /* DW_AT_stmt_list  */

        if (ofmt == &of_macho64) {
            saa_write64(p_info, 0); /* DW_AT_low_pc */
            saa_write64(p_info, high_addr); /* DW_AT_high_pc */
        } else  {
            saa_write32(p_info, 0); /* DW_AT_low_pc */
            saa_write32(p_info, high_addr); /* DW_AT_high_pc */
        }

        saa_write8(p_info, 2);   /* abbrev entry number */

        if (ofmt == &of_macho64) {
            saa_write64(p_info, 0); /* DW_AT_low_pc */
            saa_write64(p_info, 0); /* DW_AT_frame_base */
        } else  {
            saa_write32(p_info, 0); /* DW_AT_low_pc */
            saa_write32(p_info, 0); /* DW_AT_frame_base */
        }
        saa_write8(p_info, DW_END_default);

        saa_len = p_info->datalen;
        p_buf_base = p_buf = nasm_malloc(saa_len + 4); /* 4B for size info */

        WRITELONG(p_buf, saa_len);
        saa_rnbytes(p_info, p_buf, saa_len);
        macho_output(p_section->index, p_buf_base, OUT_RAWDATA, saa_len + 4, NO_SEG, 0);

        saa_free(p_info);
        nasm_free(p_buf_base);
    }

    /* abbrev section */
    {
        struct SAA *p_abbrev = saa_init(1L);

        p_section = get_section_by_name("__DWARF", "__debug_abbrev");
        nasm_assert(p_section != NULL);

        saa_write8(p_abbrev, 1); /* entry number */

        saa_write8(p_abbrev, DW_TAG_compile_unit);
        saa_write8(p_abbrev, DW_CHILDREN_yes);

        saa_write8(p_abbrev, DW_AT_producer);
        saa_write8(p_abbrev, DW_FORM_strp);

        saa_write8(p_abbrev, DW_AT_language);
        saa_write8(p_abbrev, DW_FORM_data2);

        saa_write8(p_abbrev, DW_AT_name);
        saa_write8(p_abbrev, DW_FORM_strp);

        saa_write8(p_abbrev, DW_AT_comp_dir);
        saa_write8(p_abbrev, DW_FORM_strp);

        saa_write8(p_abbrev, DW_AT_stmt_list);
        saa_write8(p_abbrev, DW_FORM_data4);

        saa_write8(p_abbrev, DW_AT_low_pc);
        saa_write8(p_abbrev, DW_FORM_addr);

        saa_write8(p_abbrev, DW_AT_high_pc);
        saa_write8(p_abbrev, DW_FORM_addr);

        saa_write16(p_abbrev, DW_END_default);

        saa_write8(p_abbrev, 2); /* entry number */

        saa_write8(p_abbrev, DW_TAG_subprogram);
        saa_write8(p_abbrev, DW_CHILDREN_no);

        saa_write8(p_abbrev, DW_AT_low_pc);
        saa_write8(p_abbrev, DW_FORM_addr);

        saa_write8(p_abbrev, DW_AT_frame_base);
        saa_write8(p_abbrev, DW_FORM_addr);

        saa_write16(p_abbrev, DW_END_default);

	saa_write8(p_abbrev, 0); /* Terminal zero entry */

        saa_len = p_abbrev->datalen;

        p_buf = nasm_malloc(saa_len);

        saa_rnbytes(p_abbrev, p_buf, saa_len);
        macho_output(p_section->index, p_buf, OUT_RAWDATA, saa_len, NO_SEG, 0);

        saa_free(p_abbrev);
        nasm_free(p_buf);
    }
}

static void new_file_list (const char *file_name, const char *dir_name)
{
    struct dir_list *dir_list;
    bool need_new_dir_list = true;

    nasm_new(dw_cur_file);
    dw_cur_file->file = ++dw_num_files;
    dw_cur_file->file_name = file_name;
    if(!dw_head_file) {
        dw_head_file = dw_cur_file;
    } else {
        *dw_last_file_next = dw_cur_file;
    }
    dw_last_file_next = &(dw_cur_file->next);

    if(dw_head_dir) {
        list_for_each(dir_list, dw_head_dir) {
            if(!(strcmp(dir_name, dir_list->dir_name))) {
                dw_cur_file->dir = dir_list;
                need_new_dir_list = false;
                break;
            }
        }
    }

    if(need_new_dir_list)
    {
        nasm_new(dir_list);
        dir_list->dir = dw_num_dirs++;
        dir_list->dir_name = dir_name;
        if(!dw_head_dir) {
            dw_head_dir = dir_list;
        } else {
            *dw_last_dir_next = dir_list;
        }
        dw_last_dir_next = &(dir_list->next);
        dw_cur_file->dir = dir_list;
    }
}

static void macho_dbg_init(void)
{
}

static void macho_dbg_linenum(const char *file_name, int32_t line_num, int32_t segto)
{
    bool need_new_list = true;
    const char *cur_file = nasm_basename(file_name);
    const char *cur_dir  = nasm_dirname(file_name);
    (void)segto;

    if(!dw_cur_file || strcmp(cur_file, dw_cur_file->file_name) ||
        strcmp(cur_dir, dw_cur_file->dir->dir_name)) {
        if(dw_head_file) {
            struct file_list *match;

            list_for_each(match, dw_head_file) {
                if(!(strcmp(cur_file, match->file_name)) &&
                    !(strcmp(cur_dir, match->dir->dir_name))) {
                    dw_cur_file = match;
                    dw_cur_file->dir = match->dir;
                    need_new_list = false;
                    break;
                }
            }
        }

        if(need_new_list) {
            new_file_list(cur_file, cur_dir);
        }
    }

    dbg_immcall = true;
    cur_line = line_num;
}

static void macho_dbg_output(int type, void *param)
{
    struct section_info *sinfo_param = (struct section_info *)param;
    int32_t secto = sinfo_param->secto;
    bool need_new_sect = false;
    struct SAA *p_linep = NULL;
    (void)type;

    if(!(dw_cur_sect && (dw_cur_sect->section == secto))) {
        need_new_sect = true;
        if(dw_head_sect) {
            struct dw_sect_list *match = dw_head_sect;
            uint32_t idx = 0;

            for(; idx < dw_num_sects; idx++) {
                if(match->section == secto) {
                    dw_cur_sect = match;
                    need_new_sect = false;
                    break;
                }
                match = match->next;
            }
        }
    }

    if(need_new_sect) {
        nasm_new(dw_cur_sect);
        dw_num_sects ++;
        p_linep = dw_cur_sect->psaa = saa_init(1L);
        dw_cur_sect->line = dw_cur_sect->file = 1;
        dw_cur_sect->offset = 0;
        dw_cur_sect->next = NULL;
        dw_cur_sect->section = secto;

        saa_write8(p_linep, DW_LNS_extended_op);
        saa_write8(p_linep, (ofmt == &of_macho64) ? 9 : 5);
        saa_write8(p_linep, DW_LNE_set_address);
        if (ofmt == &of_macho64) {
            saa_write64(p_linep, 0);
        } else {
            saa_write32(p_linep, 0);
        }

        if(!dw_head_sect) {
            dw_head_sect = dw_last_sect = dw_cur_sect;
        } else {
            dw_last_sect->next = dw_cur_sect;
            dw_last_sect = dw_cur_sect;
        }
    }

    if(dbg_immcall == true) {
        int32_t line_delta = cur_line - dw_cur_sect->line;
        int32_t offset_delta = sinfo_param->size - dw_cur_sect->offset;
        uint32_t cur_file = dw_cur_file->file;
        p_linep = dw_cur_sect->psaa;

        if(cur_file != dw_cur_sect->file) {
            saa_write8(p_linep, DW_LNS_set_file);
            saa_write8(p_linep, cur_file);
            dw_cur_sect->file = cur_file;
        }

        if(line_delta) {
            int special_opcode = (line_delta - DW_LN_BASE) + (DW_LN_RANGE * offset_delta) +
                                             DW_OPCODE_BASE;

            if((line_delta >= DW_LN_BASE) && (line_delta < DW_MAX_LN) &&
                (special_opcode < DW_MAX_SP_OPCODE)) {
                saa_write8(p_linep, special_opcode);
            } else {
                saa_write8(p_linep, DW_LNS_advance_line);
                saa_wleb128s(p_linep, line_delta);
                if(offset_delta) {
                    saa_write8(p_linep, DW_LNS_advance_pc);
                    saa_wleb128u(p_linep, offset_delta);
                }
                saa_write8(p_linep, DW_LNS_copy);
            }

            dw_cur_sect->line = cur_line;
            dw_cur_sect->offset = sinfo_param->size;
        }

        dbg_immcall = false;
    }
}

static void macho_dbg_cleanup(void)
{
    /* dwarf sectors generation */
    macho_dbg_generate();

    {
        struct dw_sect_list *p_sect = dw_head_sect;
        struct file_list *p_file = dw_head_file;
        uint32_t idx = 0;

        for(; idx < dw_num_sects; idx++) {
            struct dw_sect_list *next = p_sect->next;
            nasm_free(p_sect);
            p_sect = next;
        }

        for(idx = 0; idx < dw_num_files; idx++) {
            struct file_list *next = p_file->next;
            nasm_free(p_file);
            p_file = next;
        }
    }
}

#ifdef OF_MACHO32
static const struct macho_fmt macho32_fmt = {
    4,
    MH_MAGIC,
    CPU_TYPE_I386,
    LC_SEGMENT,
    MACHO_HEADER_SIZE,
    MACHO_SEGCMD_SIZE,
    MACHO_SECTCMD_SIZE,
    MACHO_NLIST_SIZE,
    RL_MAX_32,
    GENERIC_RELOC_VANILLA,
    GENERIC_RELOC_VANILLA,
    GENERIC_RELOC_TLV,
    false			/* Allow segment-relative relocations */
};

static void macho32_init(void)
{
    fmt = macho32_fmt;
    macho_init();

    macho_gotpcrel_sect = NO_SEG;
}

static const struct dfmt macho32_df_dwarf = {
    "MachO32 (i386) dwarf debug format for Darwin/MacOS",
    "dwarf",
    macho_dbg_init,
    macho_dbg_linenum,
    null_debug_deflabel,
    null_debug_directive,
    null_debug_typevalue,
    macho_dbg_output,
    macho_dbg_cleanup,
    NULL /*pragma list*/
};

static const struct dfmt * const macho32_df_arr[2] =
 { &macho32_df_dwarf, NULL };

const struct ofmt of_macho32 = {
    "NeXTstep/OpenStep/Rhapsody/Darwin/MacOS X (i386) object files",
    "macho32",
    ".o",
    OFMT_KEEP_ADDR,
    32,
    macho32_df_arr,
    &macho32_df_dwarf,
    macho_stdmac,
    macho32_init,
    nasm_do_legacy_output,
    macho_output,
    macho_symdef,
    macho_section,
    macho_sectalign,
    macho_segbase,
    null_directive,
    macho_cleanup,
    macho_pragma_list
};
#endif

#ifdef OF_MACHO64
static const struct macho_fmt macho64_fmt = {
    8,
    MH_MAGIC_64,
    CPU_TYPE_X86_64,
    LC_SEGMENT_64,
    MACHO_HEADER64_SIZE,
    MACHO_SEGCMD64_SIZE,
    MACHO_SECTCMD64_SIZE,
    MACHO_NLIST64_SIZE,
    RL_MAX_64,
    X86_64_RELOC_UNSIGNED,
    X86_64_RELOC_SIGNED,
    X86_64_RELOC_TLV,
    true			/* Force symbol-relative relocations */
};

static void macho64_init(void)
{
    fmt = macho64_fmt;
    macho_init();

    /* add special symbol for ..gotpcrel */
    macho_gotpcrel_sect = seg_alloc() + 1;
    define_label("..gotpcrel", macho_gotpcrel_sect, 0L, NULL, false, false);
}

static const struct dfmt macho64_df_dwarf = {
    "MachO64 (x86-64) dwarf debug format for Darwin/MacOS",
    "dwarf",
    macho_dbg_init,
    macho_dbg_linenum,
    null_debug_deflabel,
    null_debug_directive,
    null_debug_typevalue,
    macho_dbg_output,
    macho_dbg_cleanup,
    NULL /*pragma list*/
};

static const struct dfmt * const macho64_df_arr[2] =
 { &macho64_df_dwarf, NULL };

const struct ofmt of_macho64 = {
    "NeXTstep/OpenStep/Rhapsody/Darwin/MacOS X (x86_64) object files",
    "macho64",
    ".o",
    OFMT_KEEP_ADDR,
    64,
    macho64_df_arr,
    &macho64_df_dwarf,
    macho_stdmac,
    macho64_init,
    nasm_do_legacy_output,
    macho_output,
    macho_symdef,
    macho_section,
    macho_sectalign,
    macho_segbase,
    null_directive,
    macho_cleanup,
    macho_pragma_list,
};
#endif

#endif

/*
 * Local Variables:
 * mode:c
 * c-basic-offset:4
 * End:
 *
 * end of file */