summaryrefslogtreecommitdiff
path: root/usr/src/lib/libctf/common/ctf_dwarf.c
blob: 4eda658a9349a04fbe0a87495af08fe2a2423825 (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
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */
/*
 * Copyright 2012 Jason King.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * Copyright 2020 Joyent, Inc.
 * Copyright 2020 Robert Mustacchi
 * Copyright 2021 OmniOS Community Edition (OmniOSce) Association.
 */

/*
 * CTF DWARF conversion theory.
 *
 * DWARF data contains a series of compilation units. Each compilation unit
 * generally refers to an object file or what once was, in the case of linked
 * binaries and shared objects. Each compilation unit has a series of what DWARF
 * calls a DIE (Debugging Information Entry). The set of entries that we care
 * about have type information stored in a series of attributes. Each DIE also
 * has a tag that identifies the kind of attributes that it has.
 *
 * A given DIE may itself have children. For example, a DIE that represents a
 * structure has children which represent members. Whenever we encounter a DIE
 * that has children or other values or types associated with it, we recursively
 * process those children first so that way we can then refer to the generated
 * CTF type id while processing its parent. This reduces the amount of unknowns
 * and fixups that we need. It also ensures that we don't accidentally add types
 * that an overzealous compiler might add to the DWARF data but aren't used by
 * anything in the system.
 *
 * Once we do a conversion, we store a mapping in an AVL tree that goes from the
 * DWARF's die offset, which is relative to the given compilation unit, to a
 * ctf_id_t.
 *
 * Unfortunately, some compilers actually will emit duplicate entries for a
 * given type that look similar, but aren't quite. To that end, we go through
 * and do a variant on a merge once we're done processing a single compilation
 * unit which deduplicates all of the types that are in the unit.
 *
 * Finally, if we encounter an object that has multiple compilation units, then
 * we'll convert all of the compilation units separately and then do a merge, so
 * that way we can result in one single ctf_file_t that represents everything
 * for the object.
 *
 * Conversion Steps
 * ----------------
 *
 * Because a given object we've been given to convert may have multiple
 * compilation units, we break the work into two halves. The first half
 * processes each compilation unit (potentially in parallel) and then the second
 * half optionally merges all of the dies in the first half. First, we'll cover
 * what's involved in converting a single ctf_cu_t's dwarf to CTF. This covers
 * the work done in ctf_dwarf_convert_one().
 *
 * An individual ctf_cu_t, which represents a compilation unit, is converted to
 * CTF in a series of multiple passes.
 *
 * Pass 1: During the first pass we walk all of the top-level dies and if we
 * find a function, variable, struct, union, enum or typedef, we recursively
 * transform all of its types. We don't recurse or process everything, because
 * we don't want to add some of the types that compilers may add which are
 * effectively unused.
 *
 * During pass 1, if we encounter any structures or unions we mark them for
 * fixing up later. This is necessary because we may not be able to determine
 * the full size of a structure at the beginning of time. This will happen if
 * the DWARF attribute DW_AT_byte_size is not present for a member. Because of
 * this possibility we defer adding members to structures or even converting
 * them during pass 1 and save that for pass 2. Adding all of the base
 * structures without any of their members helps deal with any circular
 * dependencies that we might encounter.
 *
 * Pass 2: This pass is used to do the first half of fixing up structures and
 * unions. Rather than walk the entire type space again, we actually walk the
 * list of structures and unions that we marked for later fixing up. Here, we
 * iterate over every structure and add members to the underlying ctf_file_t,
 * but not to the structs themselves. One might wonder why we don't, and the
 * main reason is that libctf requires a ctf_update() be done before adding the
 * members to structures or unions.
 *
 * Pass 3: This pass is used to do the second half of fixing up structures and
 * unions. During this part we always go through and add members to structures
 * and unions that we added to the container in the previous pass. In addition,
 * we set the structure and union's actual size, which may have additional
 * padding added by the compiler, it isn't simply the last offset. DWARF always
 * guarantees an attribute exists for this. Importantly no ctf_id_t's change
 * during pass 2.
 *
 * Pass 4: The next phase is to add CTF entries for all of the symbols and
 * variables that are present in this die. During pass 1 we added entries to a
 * map for each variable and function. During this pass, we iterate over the
 * symbol table and when we encounter a symbol that we have in our lists of
 * translated information which matches, we then add it to the ctf_file_t.
 *
 * Pass 5: Here we go and look for any weak symbols and functions and see if
 * they match anything that we recognize. If so, then we add type information
 * for them at this point based on the matching type.
 *
 * Pass 6: This pass is actually a variant on a merge. The traditional merge
 * process expects there to be no duplicate types. As such, at the end of
 * conversion, we do a dedup on all of the types in the system. The
 * deduplication process is described in lib/libctf/common/ctf_merge.c.
 *
 * Once pass 6 is done, we've finished processing the individual compilation
 * unit.
 *
 * The following steps reflect the general process of doing a conversion.
 *
 * 1) Walk the dwarf section and determine the number of compilation units
 * 2) Create a ctf_cu_t for each compilation unit
 * 3) Add all ctf_cu_t's to a workq
 * 4) Have the workq process each die with ctf_dwarf_convert_one. This itself
 *    is comprised of several steps, which were already enumerated.
 * 5) If we have multiple cu's, we do a ctf merge of all the dies. The mechanics
 *    of the merge are discussed in lib/libctf/common/ctf_merge.c.
 * 6) Free everything up and return a ctf_file_t to the user. If we only had a
 *    single compilation unit, then we give that to the user. Otherwise, we
 *    return the merged ctf_file_t.
 *
 * Threading
 * ---------
 *
 * The process has been designed to be amenable to threading. Each compilation
 * unit has its own type stream, therefore the logical place to divide and
 * conquer is at the compilation unit. Each ctf_cu_t has been built to be able
 * to be processed independently of the others. It has its own libdwarf handle,
 * as a given libdwarf handle may only be used by a single thread at a time.
 * This allows the various ctf_cu_t's to be processed in parallel by different
 * threads.
 *
 * All of the ctf_cu_t's are loaded into a workq which allows for a number of
 * threads to be specified and used as a thread pool to process all of the
 * queued work. We set the number of threads to use in the workq equal to the
 * number of threads that the user has specified.
 *
 * After all of the compilation units have been drained, we use the same number
 * of threads when performing a merge of multiple compilation units, if they
 * exist.
 *
 * While all of these different parts do support and allow for multiple threads,
 * it's important that when only a single thread is specified, that it be the
 * calling thread. This allows the conversion routines to be used in a context
 * that doesn't allow additional threads, such as rtld.
 *
 * Common DWARF Mechanics and Notes
 * --------------------------------
 *
 * At this time, we really only support DWARFv2, though support for DWARFv4 is
 * mostly there. There is no intent to support DWARFv3.
 *
 * Generally types for something are stored in the DW_AT_type attribute. For
 * example, a function's return type will be stored in the local DW_AT_type
 * attribute while the arguments will be in child DIEs. There are also various
 * times when we don't have any DW_AT_type. In that case, the lack of a type
 * implies, at least for C, that its C type is void. Because DWARF doesn't emit
 * one, we have a synthetic void type that we create and manipulate instead and
 * pass it off to consumers on an as-needed basis. If nothing has a void type,
 * it will not be emitted.
 *
 * Architecture Specific Parts
 * ---------------------------
 *
 * The CTF tooling encodes various information about the various architectures
 * in the system. Importantly, the tool assumes that every architecture has a
 * data model where long and pointer are the same size. This is currently the
 * case, as the two data models illumos supports are ILP32 and LP64.
 *
 * In addition, we encode the mapping of various floating point sizes to various
 * types for each architecture. If a new architecture is being added, it should
 * be added to the list. The general design of the ctf conversion tools is to be
 * architecture independent. eg. any of the tools here should be able to convert
 * any architecture's DWARF into ctf; however, this has not been rigorously
 * tested and more importantly, the ctf routines don't currently write out the
 * data in an endian-aware form, they only use that of the currently running
 * library.
 */

#include <libctf_impl.h>
#include <sys/avl.h>
#include <sys/debug.h>
#include <sys/list.h>
#include <gelf.h>
#include <libdwarf.h>
#include <dwarf.h>
#include <libgen.h>
#include <workq.h>
#include <thread.h>
#include <macros.h>
#include <errno.h>

#define	DWARF_VERSION_TWO	2
#define	DWARF_VERSION_FOUR	4
#define	DWARF_VARARGS_NAME	"..."

/*
 * Dwarf may refer recursively to other types that we've already processed. To
 * see if we've already converted them, we look them up in an AVL tree that's
 * sorted by the DWARF id.
 */
typedef struct ctf_dwmap {
	avl_node_t	cdm_avl;
	Dwarf_Off	cdm_off;
	Dwarf_Die	cdm_die;
	ctf_id_t	cdm_id;
	boolean_t	cdm_fix;
} ctf_dwmap_t;

typedef struct ctf_dwvar {
	ctf_list_t	cdv_list;
	char		*cdv_name;
	ctf_id_t	cdv_type;
	boolean_t	cdv_global;
} ctf_dwvar_t;

typedef struct ctf_dwfunc {
	ctf_list_t	cdf_list;
	char		*cdf_name;
	ctf_funcinfo_t	cdf_fip;
	ctf_id_t	*cdf_argv;
	boolean_t	cdf_global;
} ctf_dwfunc_t;

typedef struct ctf_dwbitf {
	ctf_list_t	cdb_list;
	ctf_id_t	cdb_base;
	uint_t		cdb_nbits;
	ctf_id_t	cdb_id;
} ctf_dwbitf_t;

/*
 * The ctf_cu_t represents a single top-level DWARF die unit. While generally,
 * the typical object file has only a single die, if we're asked to convert
 * something that's been linked from multiple sources, multiple dies will exist.
 */
typedef struct ctf_die {
	Elf		*cu_elf;	/* shared libelf handle */
	int		cu_fd;		/* shared file descriptor */
	char		*cu_name;	/* basename of the DIE */
	ctf_merge_t	*cu_cmh;	/* merge handle */
	ctf_list_t	cu_vars;	/* List of variables */
	ctf_list_t	cu_funcs;	/* List of functions */
	ctf_list_t	cu_bitfields;	/* Bit field members */
	Dwarf_Debug	cu_dwarf;	/* libdwarf handle */
	mutex_t		*cu_dwlock;	/* libdwarf lock */
	Dwarf_Die	cu_cu;		/* libdwarf compilation unit */
	Dwarf_Off	cu_cuoff;	/* cu's offset */
	Dwarf_Off	cu_maxoff;	/* maximum offset */
	Dwarf_Half	cu_vers;	/* Dwarf Version */
	Dwarf_Half	cu_addrsz;	/* Dwarf Address Size */
	ctf_file_t	*cu_ctfp;	/* output CTF file */
	avl_tree_t	cu_map;		/* map die offsets to CTF types */
	char		*cu_errbuf;	/* error message buffer */
	size_t		cu_errlen;	/* error message buffer length */
	ctf_convert_t	*cu_handle;	/* ctf convert handle */
	size_t		cu_ptrsz;	/* object's pointer size */
	boolean_t	cu_bigend;	/* is it big endian */
	boolean_t	cu_doweaks;	/* should we convert weak symbols? */
	uint_t		cu_mach;	/* machine type */
	ctf_id_t	cu_voidtid;	/* void pointer */
	ctf_id_t	cu_longtid;	/* id for a 'long' */
} ctf_cu_t;

static int ctf_dwarf_init_die(ctf_cu_t *);
static int ctf_dwarf_offset(ctf_cu_t *, Dwarf_Die, Dwarf_Off *);
static int ctf_dwarf_convert_die(ctf_cu_t *, Dwarf_Die);
static int ctf_dwarf_convert_type(ctf_cu_t *, Dwarf_Die, ctf_id_t *, int);

static int ctf_dwarf_function_count(ctf_cu_t *, Dwarf_Die, ctf_funcinfo_t *,
    boolean_t);
static int ctf_dwarf_convert_fargs(ctf_cu_t *, Dwarf_Die, ctf_funcinfo_t *,
    ctf_id_t *);

#define	DWARF_LOCK(cup) \
	if ((cup)->cu_dwlock != NULL) \
		mutex_enter((cup)->cu_dwlock)
#define	DWARF_UNLOCK(cup) \
	if ((cup)->cu_dwlock != NULL) \
		mutex_exit((cup)->cu_dwlock)

/*
 * This is a generic way to set a CTF Conversion backend error depending on what
 * we were doing. Unless it was one of a specific set of errors that don't
 * indicate a programming / translation bug, eg. ENOMEM, then we transform it
 * into a CTF backend error and fill in the error buffer.
 */
static int
ctf_dwarf_error(ctf_cu_t *cup, ctf_file_t *cfp, int err, const char *fmt, ...)
{
	va_list ap;
	int ret;
	size_t off = 0;
	ssize_t rem = cup->cu_errlen;
	if (cfp != NULL)
		err = ctf_errno(cfp);

	if (err == ENOMEM)
		return (err);

	ret = snprintf(cup->cu_errbuf, rem, "die %s: ",
	    cup->cu_name != NULL ? cup->cu_name : "NULL");
	if (ret < 0)
		goto err;
	off += ret;
	rem = MAX(rem - ret, 0);

	va_start(ap, fmt);
	ret = vsnprintf(cup->cu_errbuf + off, rem, fmt, ap);
	va_end(ap);
	if (ret < 0)
		goto err;

	off += ret;
	rem = MAX(rem - ret, 0);
	if (fmt[strlen(fmt) - 1] != '\n') {
		(void) snprintf(cup->cu_errbuf + off, rem,
		    ": %s\n", ctf_errmsg(err));
	}
	va_end(ap);
	return (ECTF_CONVBKERR);

err:
	cup->cu_errbuf[0] = '\0';
	return (ECTF_CONVBKERR);
}

/*
 * DWARF often opts to put no explicit type to describe a void type. eg. if we
 * have a reference type whose DW_AT_type member doesn't exist, then we should
 * instead assume it points to void. Because this isn't represented, we
 * instead cause it to come into existence.
 */
static ctf_id_t
ctf_dwarf_void(ctf_cu_t *cup)
{
	if (cup->cu_voidtid == CTF_ERR) {
		ctf_encoding_t enc = { CTF_INT_SIGNED, 0, 0 };
		cup->cu_voidtid = ctf_add_integer(cup->cu_ctfp, CTF_ADD_ROOT,
		    "void", &enc);
		if (cup->cu_voidtid == CTF_ERR) {
			(void) snprintf(cup->cu_errbuf, cup->cu_errlen,
			    "failed to create void type: %s\n",
			    ctf_errmsg(ctf_errno(cup->cu_ctfp)));
		}
	}

	return (cup->cu_voidtid);
}

/*
 * There are many different forms that an array index may take. However, we just
 * always force it to be of a type long no matter what. Therefore we use this to
 * have a single instance of long across everything.
 */
static ctf_id_t
ctf_dwarf_long(ctf_cu_t *cup)
{
	if (cup->cu_longtid == CTF_ERR) {
		ctf_encoding_t enc;

		enc.cte_format = CTF_INT_SIGNED;
		enc.cte_offset = 0;
		/* All illumos systems are LP */
		enc.cte_bits = cup->cu_ptrsz * 8;
		cup->cu_longtid = ctf_add_integer(cup->cu_ctfp, CTF_ADD_NONROOT,
		    "long", &enc);
		if (cup->cu_longtid == CTF_ERR) {
			(void) snprintf(cup->cu_errbuf, cup->cu_errlen,
			    "failed to create long type: %s\n",
			    ctf_errmsg(ctf_errno(cup->cu_ctfp)));
		}

	}

	return (cup->cu_longtid);
}

static int
ctf_dwmap_comp(const void *a, const void *b)
{
	const ctf_dwmap_t *ca = a;
	const ctf_dwmap_t *cb = b;

	if (ca->cdm_off > cb->cdm_off)
		return (1);
	if (ca->cdm_off < cb->cdm_off)
		return (-1);
	return (0);
}

static int
ctf_dwmap_add(ctf_cu_t *cup, ctf_id_t id, Dwarf_Die die, boolean_t fix)
{
	int ret;
	avl_index_t index;
	ctf_dwmap_t *dwmap;
	Dwarf_Off off;

	VERIFY(id > 0 && id < CTF_MAX_TYPE);

	if ((ret = ctf_dwarf_offset(cup, die, &off)) != 0)
		return (ret);

	if ((dwmap = ctf_alloc(sizeof (ctf_dwmap_t))) == NULL)
		return (ENOMEM);

	dwmap->cdm_die = die;
	dwmap->cdm_off = off;
	dwmap->cdm_id = id;
	dwmap->cdm_fix = fix;

	ctf_dprintf("dwmap: %p %" DW_PR_DUx "->%d\n", dwmap, off, id);
	VERIFY(avl_find(&cup->cu_map, dwmap, &index) == NULL);
	avl_insert(&cup->cu_map, dwmap, index);
	return (0);
}

static int
ctf_dwarf_attribute(ctf_cu_t *cup, Dwarf_Die die, Dwarf_Half name,
    Dwarf_Attribute *attrp)
{
	int ret;
	Dwarf_Error derr;

	DWARF_LOCK(cup);
	ret = dwarf_attr(die, name, attrp, &derr);
	DWARF_UNLOCK(cup);
	if (ret == DW_DLV_OK)
		return (0);
	if (ret == DW_DLV_NO_ENTRY) {
		*attrp = NULL;
		return (ENOENT);
	}
	(void) snprintf(cup->cu_errbuf, cup->cu_errlen,
	    "failed to get attribute for type: %s\n",
	    dwarf_errmsg(derr));
	return (ECTF_CONVBKERR);
}

static void
ctf_dwarf_dealloc(ctf_cu_t *cup, Dwarf_Ptr ptr, Dwarf_Unsigned type)
{
	DWARF_LOCK(cup);
	dwarf_dealloc(cup->cu_dwarf, ptr, type);
	DWARF_UNLOCK(cup);
}

static int
ctf_dwarf_ref(ctf_cu_t *cup, Dwarf_Die die, Dwarf_Half name, Dwarf_Off *refp)
{
	int ret;
	Dwarf_Attribute attr;
	Dwarf_Error derr;

	if ((ret = ctf_dwarf_attribute(cup, die, name, &attr)) != 0)
		return (ret);

	DWARF_LOCK(cup);
	ret = dwarf_formref(attr, refp, &derr);
	DWARF_UNLOCK(cup);
	if (ret == DW_DLV_OK) {
		ctf_dwarf_dealloc(cup, attr, DW_DLA_ATTR);
		return (0);
	}

	(void) snprintf(cup->cu_errbuf, cup->cu_errlen,
	    "failed to get attribute descriptor offset: %s\n",
	    dwarf_errmsg(derr));
	return (ECTF_CONVBKERR);
}

static int
ctf_dwarf_refdie(ctf_cu_t *cup, Dwarf_Die die, Dwarf_Half name,
    Dwarf_Die *diep)
{
	int ret;
	Dwarf_Off off;
	Dwarf_Error derr;

	if ((ret = ctf_dwarf_ref(cup, die, name, &off)) != 0)
		return (ret);

	off += cup->cu_cuoff;
	DWARF_LOCK(cup);
	ret = dwarf_offdie(cup->cu_dwarf, off, diep, &derr);
	DWARF_UNLOCK(cup);
	if (ret != DW_DLV_OK) {
		(void) snprintf(cup->cu_errbuf, cup->cu_errlen,
		    "failed to get die from offset %" DW_PR_DUu ": %s\n",
		    off, dwarf_errmsg(derr));
		return (ECTF_CONVBKERR);
	}

	return (0);
}

static int
ctf_dwarf_signed(ctf_cu_t *cup, Dwarf_Die die, Dwarf_Half name,
    Dwarf_Signed *valp)
{
	int ret;
	Dwarf_Attribute attr;
	Dwarf_Error derr;

	if ((ret = ctf_dwarf_attribute(cup, die, name, &attr)) != 0)
		return (ret);

	DWARF_LOCK(cup);
	ret = dwarf_formsdata(attr, valp, &derr);
	DWARF_UNLOCK(cup);
	if (ret == DW_DLV_OK) {
		ctf_dwarf_dealloc(cup, attr, DW_DLA_ATTR);
		return (0);
	}

	(void) snprintf(cup->cu_errbuf, cup->cu_errlen,
	    "failed to get signed attribute for type: %s\n",
	    dwarf_errmsg(derr));
	return (ECTF_CONVBKERR);
}

static int
ctf_dwarf_unsigned(ctf_cu_t *cup, Dwarf_Die die, Dwarf_Half name,
    Dwarf_Unsigned *valp)
{
	int ret;
	Dwarf_Attribute attr;
	Dwarf_Error derr;

	if ((ret = ctf_dwarf_attribute(cup, die, name, &attr)) != 0)
		return (ret);

	DWARF_LOCK(cup);
	ret = dwarf_formudata(attr, valp, &derr);
	DWARF_UNLOCK(cup);
	if (ret == DW_DLV_OK) {
		ctf_dwarf_dealloc(cup, attr, DW_DLA_ATTR);
		return (0);
	}

	(void) snprintf(cup->cu_errbuf, cup->cu_errlen,
	    "failed to get unsigned attribute for type: %s\n",
	    dwarf_errmsg(derr));
	return (ECTF_CONVBKERR);
}

static int
ctf_dwarf_boolean(ctf_cu_t *cup, Dwarf_Die die, Dwarf_Half name,
    Dwarf_Bool *val)
{
	int ret;
	Dwarf_Attribute attr;
	Dwarf_Error derr;

	if ((ret = ctf_dwarf_attribute(cup, die, name, &attr)) != 0)
		return (ret);

	DWARF_LOCK(cup);
	ret = dwarf_formflag(attr, val, &derr);
	DWARF_UNLOCK(cup);
	if (ret == DW_DLV_OK) {
		ctf_dwarf_dealloc(cup, attr, DW_DLA_ATTR);
		return (0);
	}

	(void) snprintf(cup->cu_errbuf, cup->cu_errlen,
	    "failed to get boolean attribute for type: %s\n",
	    dwarf_errmsg(derr));

	return (ECTF_CONVBKERR);
}

static int
ctf_dwarf_string(ctf_cu_t *cup, Dwarf_Die die, Dwarf_Half name, char **strp)
{
	int ret;
	char *s;
	Dwarf_Attribute attr;
	Dwarf_Error derr;

	*strp = NULL;
	if ((ret = ctf_dwarf_attribute(cup, die, name, &attr)) != 0)
		return (ret);

	DWARF_LOCK(cup);
	ret = dwarf_formstring(attr, &s, &derr);
	DWARF_UNLOCK(cup);
	if (ret == DW_DLV_OK) {
		if ((*strp = ctf_strdup(s)) == NULL)
			ret = ENOMEM;
		else
			ret = 0;
		ctf_dwarf_dealloc(cup, attr, DW_DLA_ATTR);
		return (ret);
	}

	(void) snprintf(cup->cu_errbuf, cup->cu_errlen,
	    "failed to get string attribute for type: %s\n",
	    dwarf_errmsg(derr));
	return (ECTF_CONVBKERR);
}

/*
 * The encoding of a DW_AT_data_member_location has changed between different
 * revisions of the specification. It may be a general udata form or it may be
 * location data information. In DWARF 2, it is only the latter. In later
 * revisions of the spec, it may be either. To determine the form, we ask the
 * class, which will be of type CONSTANT.
 */
static int
ctf_dwarf_member_location(ctf_cu_t *cup, Dwarf_Die die, Dwarf_Unsigned *valp)
{
	int ret;
	Dwarf_Error derr;
	Dwarf_Attribute attr;
	Dwarf_Locdesc *loc;
	Dwarf_Signed locnum;
	Dwarf_Half form;
	enum Dwarf_Form_Class class;

	if ((ret = ctf_dwarf_attribute(cup, die, DW_AT_data_member_location,
	    &attr)) != 0) {
		return (ret);
	}

	DWARF_LOCK(cup);
	ret = dwarf_whatform(attr, &form, &derr);
	DWARF_UNLOCK(cup);
	if (ret != DW_DLV_OK) {
		(void) snprintf(cup->cu_errbuf, cup->cu_errlen,
		    "failed to get dwarf attribute for for member "
		    "location: %s\n",
		    dwarf_errmsg(derr));
		ctf_dwarf_dealloc(cup, attr, DW_DLA_ATTR);
		return (ECTF_CONVBKERR);
	}

	DWARF_LOCK(cup);
	class = dwarf_get_form_class(cup->cu_vers, DW_AT_data_member_location,
	    cup->cu_addrsz, form);
	if (class == DW_FORM_CLASS_CONSTANT) {
		Dwarf_Signed sign;

		/*
		 * We have a constant. We need to try to get both this as signed
		 * and unsigned data, as unfortunately, DWARF doesn't define the
		 * sign. Which is a joy. We try unsigned first. If neither
		 * match, fall through to the normal path.
		 */
		if (dwarf_formudata(attr, valp, &derr) == DW_DLV_OK) {
			DWARF_UNLOCK(cup);
			ctf_dwarf_dealloc(cup, attr, DW_DLA_ATTR);
			return (0);
		}

		if (dwarf_formsdata(attr, &sign, &derr) == DW_DLV_OK) {
			DWARF_UNLOCK(cup);
			ctf_dwarf_dealloc(cup, attr, DW_DLA_ATTR);
			if (sign < 0) {
				(void) snprintf(cup->cu_errbuf, cup->cu_errlen,
				    "encountered negative member data "
				    "location: %lld\n", sign);
			}
			*valp = (Dwarf_Unsigned)sign;
			return (0);
		}
	}

	if (dwarf_loclist(attr, &loc, &locnum, &derr) != DW_DLV_OK) {
		DWARF_UNLOCK(cup);
		(void) snprintf(cup->cu_errbuf, cup->cu_errlen,
		    "failed to obtain location list for member offset: %s\n",
		    dwarf_errmsg(derr));
		ctf_dwarf_dealloc(cup, attr, DW_DLA_ATTR);
		return (ECTF_CONVBKERR);
	}
	DWARF_UNLOCK(cup);
	ctf_dwarf_dealloc(cup, attr, DW_DLA_ATTR);

	if (locnum != 1 || loc->ld_s->lr_atom != DW_OP_plus_uconst) {
		(void) snprintf(cup->cu_errbuf, cup->cu_errlen,
		    "failed to parse location structure for member\n");
		ctf_dwarf_dealloc(cup, loc->ld_s, DW_DLA_LOC_BLOCK);
		ctf_dwarf_dealloc(cup, loc, DW_DLA_LOCDESC);
		return (ECTF_CONVBKERR);
	}

	*valp = loc->ld_s->lr_number;

	ctf_dwarf_dealloc(cup, loc->ld_s, DW_DLA_LOC_BLOCK);
	ctf_dwarf_dealloc(cup, loc, DW_DLA_LOCDESC);
	return (0);
}


static int
ctf_dwarf_offset(ctf_cu_t *cup, Dwarf_Die die, Dwarf_Off *offsetp)
{
	Dwarf_Error derr;
	int ret;

	DWARF_LOCK(cup);
	ret = dwarf_dieoffset(die, offsetp, &derr);
	DWARF_UNLOCK(cup);
	if (ret == DW_DLV_OK)
		return (0);

	(void) snprintf(cup->cu_errbuf, cup->cu_errlen,
	    "failed to get die offset: %s\n",
	    dwarf_errmsg(derr));
	return (ECTF_CONVBKERR);
}

/* simpler variant for debugging output */
static Dwarf_Off
ctf_die_offset(ctf_cu_t *cup, Dwarf_Die die)
{
	Dwarf_Off off = -1;
	Dwarf_Error derr;

	DWARF_LOCK(cup);
	(void) dwarf_dieoffset(die, &off, &derr);
	DWARF_UNLOCK(cup);
	return (off);
}

static int
ctf_dwarf_tag(ctf_cu_t *cup, Dwarf_Die die, Dwarf_Half *tagp)
{
	Dwarf_Error derr;
	int ret;

	DWARF_LOCK(cup);
	ret = dwarf_tag(die, tagp, &derr);
	DWARF_UNLOCK(cup);
	if (ret == DW_DLV_OK)
		return (0);

	(void) snprintf(cup->cu_errbuf, cup->cu_errlen,
	    "failed to get tag type: %s\n",
	    dwarf_errmsg(derr));
	return (ECTF_CONVBKERR);
}

static int
ctf_dwarf_sib(ctf_cu_t *cup, Dwarf_Die base, Dwarf_Die *sibp)
{
	Dwarf_Error derr;
	int ret;

	*sibp = NULL;
	DWARF_LOCK(cup);
	ret = dwarf_siblingof(cup->cu_dwarf, base, sibp, &derr);
	DWARF_UNLOCK(cup);
	if (ret == DW_DLV_OK || ret == DW_DLV_NO_ENTRY)
		return (0);

	(void) snprintf(cup->cu_errbuf, cup->cu_errlen,
	    "failed to sibling from die: %s\n",
	    dwarf_errmsg(derr));
	return (ECTF_CONVBKERR);
}

static int
ctf_dwarf_child(ctf_cu_t *cup, Dwarf_Die base, Dwarf_Die *childp)
{
	Dwarf_Error derr;
	int ret;

	*childp = NULL;
	DWARF_LOCK(cup);
	ret = dwarf_child(base, childp, &derr);
	DWARF_UNLOCK(cup);
	if (ret == DW_DLV_OK || ret == DW_DLV_NO_ENTRY)
		return (0);

	(void) snprintf(cup->cu_errbuf, cup->cu_errlen,
	    "failed to child from die: %s\n",
	    dwarf_errmsg(derr));
	return (ECTF_CONVBKERR);
}

/*
 * Compilers disagree on what to do to determine if something has global
 * visiblity. Traditionally gcc has used DW_AT_external to indicate this while
 * Studio has used DW_AT_visibility. We check DW_AT_visibility first and then
 * fall back to DW_AT_external. Lack of DW_AT_external implies that it is not.
 */
static int
ctf_dwarf_isglobal(ctf_cu_t *cup, Dwarf_Die die, boolean_t *igp)
{
	int ret;
	Dwarf_Signed vis;
	Dwarf_Bool ext;

	if ((ret = ctf_dwarf_signed(cup, die, DW_AT_visibility, &vis)) == 0) {
		*igp = vis == DW_VIS_exported;
		return (0);
	} else if (ret != ENOENT) {
		return (ret);
	}

	if ((ret = ctf_dwarf_boolean(cup, die, DW_AT_external, &ext)) != 0) {
		if (ret == ENOENT) {
			*igp = B_FALSE;
			return (0);
		}
		return (ret);
	}
	*igp = ext != 0 ? B_TRUE : B_FALSE;
	return (0);
}

static int
ctf_dwarf_die_elfenc(Elf *elf, ctf_cu_t *cup, char *errbuf, size_t errlen)
{
	GElf_Ehdr ehdr;

	if (gelf_getehdr(elf, &ehdr) == NULL) {
		(void) snprintf(errbuf, errlen,
		    "failed to get ELF header: %s\n",
		    elf_errmsg(elf_errno()));
		return (ECTF_CONVBKERR);
	}

	cup->cu_mach = ehdr.e_machine;

	if (ehdr.e_ident[EI_CLASS] == ELFCLASS32) {
		cup->cu_ptrsz = 4;
		VERIFY(ctf_setmodel(cup->cu_ctfp, CTF_MODEL_ILP32) == 0);
	} else if (ehdr.e_ident[EI_CLASS] == ELFCLASS64) {
		cup->cu_ptrsz = 8;
		VERIFY(ctf_setmodel(cup->cu_ctfp, CTF_MODEL_LP64) == 0);
	} else {
		(void) snprintf(errbuf, errlen,
		    "unknown ELF class %d\n", ehdr.e_ident[EI_CLASS]);
		return (ECTF_CONVBKERR);
	}

	if (ehdr.e_ident[EI_DATA] == ELFDATA2LSB) {
		cup->cu_bigend = B_FALSE;
	} else if (ehdr.e_ident[EI_DATA] == ELFDATA2MSB) {
		cup->cu_bigend = B_TRUE;
	} else {
		(void) snprintf(errbuf, errlen,
		    "unknown ELF data encoding: %hhu\n", ehdr.e_ident[EI_DATA]);
		return (ECTF_CONVBKERR);
	}

	return (0);
}

typedef struct ctf_dwarf_fpent {
	size_t	cdfe_size;
	uint_t	cdfe_enc[3];
} ctf_dwarf_fpent_t;

typedef struct ctf_dwarf_fpmap {
	uint_t			cdf_mach;
	ctf_dwarf_fpent_t	cdf_ents[5];
} ctf_dwarf_fpmap_t;

static const ctf_dwarf_fpmap_t ctf_dwarf_fpmaps[] = {
	{ EM_SPARC, {
		{ 4, { CTF_FP_SINGLE, CTF_FP_CPLX, CTF_FP_IMAGRY } },
		{ 8, { CTF_FP_DOUBLE, CTF_FP_DCPLX, CTF_FP_DIMAGRY } },
		{ 16, { CTF_FP_LDOUBLE, CTF_FP_LDCPLX, CTF_FP_LDIMAGRY } },
		{ 0, { 0 } }
	} },
	{ EM_SPARC32PLUS, {
		{ 4, { CTF_FP_SINGLE, CTF_FP_CPLX, CTF_FP_IMAGRY } },
		{ 8, { CTF_FP_DOUBLE, CTF_FP_DCPLX, CTF_FP_DIMAGRY } },
		{ 16, { CTF_FP_LDOUBLE, CTF_FP_LDCPLX, CTF_FP_LDIMAGRY } },
		{ 0, { 0 } }
	} },
	{ EM_SPARCV9, {
		{ 4, { CTF_FP_SINGLE, CTF_FP_CPLX, CTF_FP_IMAGRY } },
		{ 8, { CTF_FP_DOUBLE, CTF_FP_DCPLX, CTF_FP_DIMAGRY } },
		{ 16, { CTF_FP_LDOUBLE, CTF_FP_LDCPLX, CTF_FP_LDIMAGRY } },
		{ 0, { 0 } }
	} },
	{ EM_386, {
		{ 4, { CTF_FP_SINGLE, CTF_FP_CPLX, CTF_FP_IMAGRY } },
		{ 8, { CTF_FP_DOUBLE, CTF_FP_DCPLX, CTF_FP_DIMAGRY } },
		{ 12, { CTF_FP_LDOUBLE, CTF_FP_LDCPLX, CTF_FP_LDIMAGRY } },
		/*
		 * ISO/IEC TS-18661-3:2015 defines several types with analogues
		 * to existing C types. However, in the i386 ABI there is no
		 * corresponding type for a _Float128. While, ideally we would
		 * add this as a discrete type, when C2x formally standardizes
		 * this and a number of additional extensions, we'll want to
		 * change that around. In the interim, we'll encode it as a
		 * weirdly sized long-double, even though not all the tools
		 * will expect an off-abi encoding.
		 */
		{ 16, { CTF_FP_LDOUBLE, CTF_FP_LDCPLX, CTF_FP_LDIMAGRY } },
		{ 0, { 0 } }
	} },
	{ EM_X86_64, {
		{ 4, { CTF_FP_SINGLE, CTF_FP_CPLX, CTF_FP_IMAGRY } },
		{ 8, { CTF_FP_DOUBLE, CTF_FP_DCPLX, CTF_FP_DIMAGRY } },
		{ 16, { CTF_FP_LDOUBLE, CTF_FP_LDCPLX, CTF_FP_LDIMAGRY } },
		{ 0, { 0 } }
	} },
	{ EM_NONE }
};

/*
 * We want to normalize the type names that are used between compilers in the
 * case of complex. gcc prefixes things with types like 'long complex' where as
 * clang only calls them 'complex' in the dwarf even if in the C they are long
 * complex or similar.
 */
static int
ctf_dwarf_fixup_complex(ctf_cu_t *cup, ctf_encoding_t *enc, char **namep)
{
	const char *name;
	*namep = NULL;

	switch (enc->cte_format) {
	case CTF_FP_CPLX:
		name = "complex float";
		break;
	case CTF_FP_DCPLX:
		name = "complex double";
		break;
	case CTF_FP_LDCPLX:
		name = "complex long double";
		break;
	default:
		return (0);
	}

	*namep = ctf_strdup(name);
	if (*namep == NULL) {
		return (ENOMEM);
	}

	return (0);
}

static int
ctf_dwarf_float_base(ctf_cu_t *cup, Dwarf_Signed type, ctf_encoding_t *enc)
{
	const ctf_dwarf_fpmap_t *map = &ctf_dwarf_fpmaps[0];
	const ctf_dwarf_fpent_t *ent;
	uint_t col = 0, mult = 1;

	for (map = &ctf_dwarf_fpmaps[0]; map->cdf_mach != EM_NONE; map++) {
		if (map->cdf_mach == cup->cu_mach)
			break;
	}

	if (map->cdf_mach == EM_NONE) {
		(void) snprintf(cup->cu_errbuf, cup->cu_errlen,
		    "Unsupported machine type: %d\n", cup->cu_mach);
		return (ENOTSUP);
	}

	if (type == DW_ATE_complex_float) {
		mult = 2;
		col = 1;
	} else if (type == DW_ATE_imaginary_float ||
	    type == DW_ATE_SUN_imaginary_float) {
		col = 2;
	}

	ent = &map->cdf_ents[0];
	for (ent = &map->cdf_ents[0]; ent->cdfe_size != 0; ent++) {
		if (ent->cdfe_size * mult * 8 == enc->cte_bits) {
			enc->cte_format = ent->cdfe_enc[col];
			return (0);
		}
	}

	(void) snprintf(cup->cu_errbuf, cup->cu_errlen,
	    "failed to find valid fp mapping for encoding %lld, size %d bits\n",
	    type, enc->cte_bits);
	return (EINVAL);
}

static int
ctf_dwarf_dwarf_base(ctf_cu_t *cup, Dwarf_Die die, int *kindp,
    ctf_encoding_t *enc)
{
	int ret;
	Dwarf_Signed type;

	if ((ret = ctf_dwarf_signed(cup, die, DW_AT_encoding, &type)) != 0)
		return (ret);

	switch (type) {
	case DW_ATE_unsigned:
	case DW_ATE_address:
		*kindp = CTF_K_INTEGER;
		enc->cte_format = 0;
		break;
	case DW_ATE_unsigned_char:
		*kindp = CTF_K_INTEGER;
		enc->cte_format = CTF_INT_CHAR;
		break;
	case DW_ATE_signed:
		*kindp = CTF_K_INTEGER;
		enc->cte_format = CTF_INT_SIGNED;
		break;
	case DW_ATE_signed_char:
		*kindp = CTF_K_INTEGER;
		enc->cte_format = CTF_INT_SIGNED | CTF_INT_CHAR;
		break;
	case DW_ATE_boolean:
		*kindp = CTF_K_INTEGER;
		enc->cte_format = CTF_INT_SIGNED | CTF_INT_BOOL;
		break;
	case DW_ATE_float:
	case DW_ATE_complex_float:
	case DW_ATE_imaginary_float:
	case DW_ATE_SUN_imaginary_float:
	case DW_ATE_SUN_interval_float:
		*kindp = CTF_K_FLOAT;
		if ((ret = ctf_dwarf_float_base(cup, type, enc)) != 0)
			return (ret);
		break;
	default:
		(void) snprintf(cup->cu_errbuf, cup->cu_errlen,
		    "encountered unknown DWARF encoding: %lld\n", type);
		return (ECTF_CONVBKERR);
	}

	return (0);
}

/*
 * Different compilers (at least GCC and Studio) use different names for types.
 * This parses the types and attempts to unify them. If this fails, we just fall
 * back to using the DWARF itself.
 */
static int
ctf_dwarf_parse_int(const char *name, int *kindp, ctf_encoding_t *enc,
    char **newnamep)
{
	char buf[256];
	char *base, *c, *last;
	int nlong = 0, nshort = 0, nchar = 0, nint = 0;
	int sign = 1;

	if (strlen(name) + 1 > sizeof (buf))
		return (EINVAL);

	(void) strlcpy(buf, name, sizeof (buf));
	for (c = strtok_r(buf, " ", &last); c != NULL;
	    c = strtok_r(NULL, " ", &last)) {
		if (strcmp(c, "signed") == 0) {
			sign = 1;
		} else if (strcmp(c, "unsigned") == 0) {
			sign = 0;
		} else if (strcmp(c, "long") == 0) {
			nlong++;
		} else if (strcmp(c, "char") == 0) {
			nchar++;
		} else if (strcmp(c, "short") == 0) {
			nshort++;
		} else if (strcmp(c, "int") == 0) {
			nint++;
		} else {
			/*
			 * If we don't recognize any of the tokens, we'll tell
			 * the caller to fall back to the dwarf-provided
			 * encoding information.
			 */
			return (EINVAL);
		}
	}

	if (nchar > 1 || nshort > 1 || nint > 1 || nlong > 2)
		return (EINVAL);

	if (nchar > 0) {
		if (nlong > 0 || nshort > 0 || nint > 0)
			return (EINVAL);
		base = "char";
	} else if (nshort > 0) {
		if (nlong > 0)
			return (EINVAL);
		base = "short";
	} else if (nlong > 0) {
		base = "long";
	} else {
		base = "int";
	}

	if (nchar > 0)
		enc->cte_format = CTF_INT_CHAR;
	else
		enc->cte_format = 0;

	if (sign > 0)
		enc->cte_format |= CTF_INT_SIGNED;

	(void) snprintf(buf, sizeof (buf), "%s%s%s",
	    (sign ? "" : "unsigned "),
	    (nlong > 1 ? "long " : ""),
	    base);

	*newnamep = ctf_strdup(buf);
	if (*newnamep == NULL)
		return (ENOMEM);
	*kindp = CTF_K_INTEGER;
	return (0);
}

static int
ctf_dwarf_create_base(ctf_cu_t *cup, Dwarf_Die die, ctf_id_t *idp, int isroot,
    Dwarf_Off off)
{
	int ret;
	char *name, *nname = NULL;
	Dwarf_Unsigned sz;
	int kind;
	ctf_encoding_t enc;
	ctf_id_t id;

	if ((ret = ctf_dwarf_string(cup, die, DW_AT_name, &name)) != 0)
		return (ret);
	if ((ret = ctf_dwarf_unsigned(cup, die, DW_AT_byte_size, &sz)) != 0) {
		goto out;
	}
	ctf_dprintf("Creating base type %s from off %llu, size: %d\n", name,
	    off, sz);

	bzero(&enc, sizeof (ctf_encoding_t));
	enc.cte_bits = sz * 8;
	if ((ret = ctf_dwarf_parse_int(name, &kind, &enc, &nname)) == 0) {
		ctf_strfree(name);
		name = nname;
	} else {
		if (ret != EINVAL) {
			goto out;
		}
		ctf_dprintf("falling back to dwarf for base type %s\n", name);
		if ((ret = ctf_dwarf_dwarf_base(cup, die, &kind, &enc)) != 0) {
			goto out;
		}

		if (kind == CTF_K_FLOAT && (ret = ctf_dwarf_fixup_complex(cup,
		    &enc, &nname)) != 0) {
			goto out;
		} else if (nname != NULL) {
			ctf_strfree(name);
			name = nname;
		}
	}

	id = ctf_add_encoded(cup->cu_ctfp, isroot, name, &enc, kind);
	if (id == CTF_ERR) {
		ret = ctf_errno(cup->cu_ctfp);
	} else {
		*idp = id;
		ret = ctf_dwmap_add(cup, id, die, B_FALSE);
	}
out:
	ctf_strfree(name);
	return (ret);
}

/*
 * Getting a member's offset is a surprisingly intricate dance. It works as
 * follows:
 *
 * 1) If we're in DWARFv4, then we either have a DW_AT_data_bit_offset or we
 * have a DW_AT_data_member_location. We won't have both. Thus we check first
 * for DW_AT_data_bit_offset, and if it exists, we're set.
 *
 * Next, if we have a bitfield and we don't have a DW_AT_data_bit_offset, then
 * we have to grab the data location and use the following dance:
 *
 * 2) Gather the set of DW_AT_byte_size, DW_AT_bit_offset, and DW_AT_bit_size.
 * Of course, the DW_AT_byte_size may be omitted, even though it isn't always.
 * When it's been omitted, we then have to say that the size is that of the
 * underlying type, which forces that to be after a ctf_update(). Here, we have
 * to do different things based on whether or not we're using big endian or
 * little endian to obtain the proper offset.
 */
static int
ctf_dwarf_member_offset(ctf_cu_t *cup, Dwarf_Die die, ctf_id_t mid,
    ulong_t *offp)
{
	int ret;
	Dwarf_Unsigned loc, bitsz, bytesz;
	Dwarf_Signed bitoff;
	size_t off;
	ssize_t tsz;

	if ((ret = ctf_dwarf_unsigned(cup, die, DW_AT_data_bit_offset,
	    &loc)) == 0) {
		*offp = loc;
		return (0);
	} else if (ret != ENOENT) {
		return (ret);
	}

	if ((ret = ctf_dwarf_member_location(cup, die, &loc)) != 0)
		return (ret);
	off = loc * 8;

	if ((ret = ctf_dwarf_signed(cup, die, DW_AT_bit_offset,
	    &bitoff)) != 0) {
		if (ret != ENOENT)
			return (ret);
		*offp = off;
		return (0);
	}

	/* At this point we have to have DW_AT_bit_size */
	if ((ret = ctf_dwarf_unsigned(cup, die, DW_AT_bit_size, &bitsz)) != 0)
		return (ret);

	if ((ret = ctf_dwarf_unsigned(cup, die, DW_AT_byte_size,
	    &bytesz)) != 0) {
		if (ret != ENOENT)
			return (ret);
		if ((tsz = ctf_type_size(cup->cu_ctfp, mid)) == CTF_ERR) {
			int e = ctf_errno(cup->cu_ctfp);
			(void) snprintf(cup->cu_errbuf, cup->cu_errlen,
			    "failed to get type size: %s\n", ctf_errmsg(e));
			return (ECTF_CONVBKERR);
		}
	} else {
		tsz = bytesz;
	}
	tsz *= 8;
	if (cup->cu_bigend == B_TRUE) {
		*offp = off + bitoff;
	} else {
		*offp = off + tsz - bitoff - bitsz;
	}

	return (0);
}

/*
 * We need to determine if the member in question is a bitfield. If it is, then
 * we need to go through and create a new type that's based on the actual base
 * type, but has a different size. We also rename the type as a result to help
 * deal with future collisions.
 *
 * Here we need to look and see if we have a DW_AT_bit_size value. If we have a
 * bit size member and it does not equal the byte size member, then we need to
 * create a bitfield type based on this.
 *
 * Note: When we support DWARFv4, there may be a chance that we need to also
 * search for the DW_AT_byte_size if we don't have a DW_AT_bit_size member.
 */
static int
ctf_dwarf_member_bitfield(ctf_cu_t *cup, Dwarf_Die die, ctf_id_t *idp)
{
	int ret;
	Dwarf_Unsigned bitsz;
	ctf_encoding_t e;
	ctf_dwbitf_t *cdb;
	ctf_dtdef_t *dtd;
	ctf_id_t base = *idp;
	int kind;

	if ((ret = ctf_dwarf_unsigned(cup, die, DW_AT_bit_size, &bitsz)) != 0) {
		if (ret == ENOENT)
			return (0);
		return (ret);
	}

	ctf_dprintf("Trying to deal with bitfields on %d:%d\n", base, bitsz);
	/*
	 * Given that we now have a bitsize, time to go do something about it.
	 * We're going to create a new type based on the current one, but first
	 * we need to find the base type. This means we need to traverse any
	 * typedef's, consts, and volatiles until we get to what should be
	 * something of type integer or enumeration.
	 */
	VERIFY(bitsz < UINT32_MAX);
	dtd = ctf_dtd_lookup(cup->cu_ctfp, base);
	VERIFY(dtd != NULL);
	kind = CTF_INFO_KIND(dtd->dtd_data.ctt_info);
	while (kind == CTF_K_TYPEDEF || kind == CTF_K_CONST ||
	    kind == CTF_K_VOLATILE) {
		dtd = ctf_dtd_lookup(cup->cu_ctfp, dtd->dtd_data.ctt_type);
		VERIFY(dtd != NULL);
		kind = CTF_INFO_KIND(dtd->dtd_data.ctt_info);
	}
	ctf_dprintf("got kind %d\n", kind);
	VERIFY(kind == CTF_K_INTEGER || kind == CTF_K_ENUM);

	/*
	 * As surprising as it may be, it is strictly possible to create a
	 * bitfield that is based on an enum. Of course, the C standard leaves
	 * enums sizing as an ABI concern more or less. To that effect, today on
	 * all illumos platforms the size of an enum is generally that of an
	 * int as our supported data models and ABIs all agree on that. So what
	 * we'll do is fake up a CTF encoding here to use. In this case, we'll
	 * treat it as an unsigned value of whatever size the underlying enum
	 * currently has (which is in the ctt_size member of its dynamic type
	 * data).
	 */
	if (kind == CTF_K_INTEGER) {
		e = dtd->dtd_u.dtu_enc;
	} else {
		bzero(&e, sizeof (ctf_encoding_t));
		e.cte_bits = dtd->dtd_data.ctt_size * NBBY;
	}

	for (cdb = ctf_list_next(&cup->cu_bitfields); cdb != NULL;
	    cdb = ctf_list_next(cdb)) {
		if (cdb->cdb_base == base && cdb->cdb_nbits == bitsz)
			break;
	}

	/*
	 * Create a new type if none exists. We name all types in a way that is
	 * guaranteed not to conflict with the corresponding C type. We do this
	 * by using the ':' operator.
	 */
	if (cdb == NULL) {
		size_t namesz;
		char *name;

		e.cte_bits = bitsz;
		namesz = snprintf(NULL, 0, "%s:%d", dtd->dtd_name,
		    (uint32_t)bitsz);
		name = ctf_alloc(namesz + 1);
		if (name == NULL)
			return (ENOMEM);
		cdb = ctf_alloc(sizeof (ctf_dwbitf_t));
		if (cdb == NULL) {
			ctf_free(name, namesz + 1);
			return (ENOMEM);
		}
		(void) snprintf(name, namesz + 1, "%s:%d", dtd->dtd_name,
		    (uint32_t)bitsz);

		cdb->cdb_base = base;
		cdb->cdb_nbits = bitsz;
		cdb->cdb_id = ctf_add_integer(cup->cu_ctfp, CTF_ADD_NONROOT,
		    name, &e);
		if (cdb->cdb_id == CTF_ERR) {
			(void) snprintf(cup->cu_errbuf, cup->cu_errlen,
			    "failed to get add bitfield type %s: %s\n", name,
			    ctf_errmsg(ctf_errno(cup->cu_ctfp)));
			ctf_free(name, namesz + 1);
			ctf_free(cdb, sizeof (ctf_dwbitf_t));
			return (ECTF_CONVBKERR);
		}
		ctf_free(name, namesz + 1);
		ctf_list_append(&cup->cu_bitfields, cdb);
	}

	*idp = cdb->cdb_id;

	return (0);
}

static int
ctf_dwarf_fixup_sou(ctf_cu_t *cup, Dwarf_Die die, ctf_id_t base, boolean_t add)
{
	int ret, kind;
	Dwarf_Die child, memb;
	Dwarf_Unsigned size;

	kind = ctf_type_kind(cup->cu_ctfp, base);
	VERIFY(kind != CTF_ERR);
	VERIFY(kind == CTF_K_STRUCT || kind == CTF_K_UNION);

	/*
	 * Members are in children. However, gcc also allows empty ones.
	 */
	if ((ret = ctf_dwarf_child(cup, die, &child)) != 0)
		return (ret);
	if (child == NULL)
		return (0);

	memb = child;
	while (memb != NULL) {
		Dwarf_Die sib, tdie;
		Dwarf_Half tag;
		ctf_id_t mid;
		char *mname;
		ulong_t memboff = 0;

		if ((ret = ctf_dwarf_tag(cup, memb, &tag)) != 0)
			return (ret);

		if (tag != DW_TAG_member)
			goto next;

		if ((ret = ctf_dwarf_refdie(cup, memb, DW_AT_type, &tdie)) != 0)
			return (ret);

		if ((ret = ctf_dwarf_convert_type(cup, tdie, &mid,
		    CTF_ADD_NONROOT)) != 0)
			return (ret);
		ctf_dprintf("Got back type id: %d\n", mid);

		/*
		 * If we're not adding a member, just go ahead and return.
		 */
		if (add == B_FALSE) {
			if ((ret = ctf_dwarf_member_bitfield(cup, memb,
			    &mid)) != 0)
				return (ret);
			goto next;
		}

		if ((ret = ctf_dwarf_string(cup, memb, DW_AT_name,
		    &mname)) != 0 && ret != ENOENT)
			return (ret);
		if (ret == ENOENT)
			mname = NULL;

		if (kind == CTF_K_UNION) {
			memboff = 0;
		} else if ((ret = ctf_dwarf_member_offset(cup, memb, mid,
		    &memboff)) != 0) {
			if (mname != NULL)
				ctf_strfree(mname);
			return (ret);
		}

		if ((ret = ctf_dwarf_member_bitfield(cup, memb, &mid)) != 0)
			return (ret);

		ret = ctf_add_member(cup->cu_ctfp, base, mname, mid, memboff);
		if (ret == CTF_ERR) {
			(void) snprintf(cup->cu_errbuf, cup->cu_errlen,
			    "failed to add member %s: %s\n",
			    mname, ctf_errmsg(ctf_errno(cup->cu_ctfp)));
			if (mname != NULL)
				ctf_strfree(mname);
			return (ECTF_CONVBKERR);
		}

		if (mname != NULL)
			ctf_strfree(mname);

next:
		if ((ret = ctf_dwarf_sib(cup, memb, &sib)) != 0)
			return (ret);
		memb = sib;
	}

	/*
	 * If we're not adding members, then we don't know the final size of the
	 * structure, so end here.
	 */
	if (add == B_FALSE)
		return (0);

	/* Finally set the size of the structure to the actual byte size */
	if ((ret = ctf_dwarf_unsigned(cup, die, DW_AT_byte_size, &size)) != 0)
		return (ret);
	if ((ctf_set_size(cup->cu_ctfp, base, size)) == CTF_ERR) {
		int e = ctf_errno(cup->cu_ctfp);
		(void) snprintf(cup->cu_errbuf, cup->cu_errlen,
		    "failed to set type size for %d to 0x%x: %s\n", base,
		    (uint32_t)size, ctf_errmsg(e));
		return (ECTF_CONVBKERR);
	}

	return (0);
}

static int
ctf_dwarf_create_sou(ctf_cu_t *cup, Dwarf_Die die, ctf_id_t *idp,
    int kind, int isroot)
{
	int ret;
	char *name;
	ctf_id_t base;
	Dwarf_Die child;
	Dwarf_Bool decl;

	/*
	 * Deal with the terribly annoying case of anonymous structs and unions.
	 * If they don't have a name, set the name to the empty string.
	 */
	if ((ret = ctf_dwarf_string(cup, die, DW_AT_name, &name)) != 0 &&
	    ret != ENOENT)
		return (ret);
	if (ret == ENOENT)
		name = NULL;

	/*
	 * We need to check if we just have a declaration here. If we do, then
	 * instead of creating an actual structure or union, we're just going to
	 * go ahead and create a forward. During a dedup or merge, the forward
	 * will be replaced with the real thing.
	 */
	if ((ret = ctf_dwarf_boolean(cup, die, DW_AT_declaration,
	    &decl)) != 0) {
		if (ret != ENOENT)
			return (ret);
		decl = 0;
	}

	if (decl == B_TRUE) {
		base = ctf_add_forward(cup->cu_ctfp, isroot, name, kind);
	} else if (kind == CTF_K_STRUCT) {
		base = ctf_add_struct(cup->cu_ctfp, isroot, name);
	} else {
		base = ctf_add_union(cup->cu_ctfp, isroot, name);
	}
	ctf_dprintf("added sou %s (%d) (%ld) forward=%d\n",
	    name, kind, base, decl == B_TRUE);
	if (name != NULL)
		ctf_strfree(name);
	if (base == CTF_ERR)
		return (ctf_errno(cup->cu_ctfp));
	*idp = base;

	/*
	 * If it's just a declaration, we're not going to mark it for fix up or
	 * do anything else.
	 */
	if (decl == B_TRUE)
		return (ctf_dwmap_add(cup, base, die, B_FALSE));
	if ((ret = ctf_dwmap_add(cup, base, die, B_TRUE)) != 0)
		return (ret);

	/*
	 * The children of a structure or union are generally members. However,
	 * some compilers actually insert structs and unions there and not as a
	 * top-level die. Therefore, to make sure we honor our pass 1 contract
	 * of having all the base types, but not members, we need to walk this
	 * for instances of a DW_TAG_union_type.
	 */
	if ((ret = ctf_dwarf_child(cup, die, &child)) != 0)
		return (ret);

	while (child != NULL) {
		Dwarf_Half tag;
		Dwarf_Die sib;

		if ((ret = ctf_dwarf_tag(cup, child, &tag)) != 0)
			return (ret);

		switch (tag) {
		case DW_TAG_union_type:
		case DW_TAG_structure_type:
			ret = ctf_dwarf_convert_type(cup, child, NULL,
			    CTF_ADD_NONROOT);
			if (ret != 0) {
				return (ret);
			}
			break;
		default:
			break;
		}

		if ((ret = ctf_dwarf_sib(cup, child, &sib)) != 0)
			return (ret);
		child = sib;
	}

	return (0);
}

static int
ctf_dwarf_array_upper_bound(ctf_cu_t *cup, Dwarf_Die range, ctf_arinfo_t *ar)
{
	Dwarf_Attribute attr;
	Dwarf_Unsigned uval;
	Dwarf_Signed sval;
	Dwarf_Half attrnum, form;
	Dwarf_Error derr;
	enum Dwarf_Form_Class class;
	const char *formstr = NULL;
	uint_t adj = 0;
	int ret = 0;

	ctf_dprintf("setting array upper bound\n");

	ar->ctr_nelems = 0;

	/*
	 * Different compilers use different attributes to indicate the size of
	 * an array. GCC has traditionally used DW_AT_upper_bound, while Clang
	 * uses DW_AT_count. They have slightly different semantics. DW_AT_count
	 * indicates the total number of elements that are present, while
	 * DW_AT_upper_bound indicates the last index, hence we need to add one
	 * to that index to get the count.
	 *
	 * We first search for DW_AT_count and then for DW_AT_upper_bound. If we
	 * find neither, then we treat the lack of this as a zero element array.
	 * Our value is initialized assuming we find a DW_AT_count value.
	 */
	attrnum = DW_AT_count;
	ret = ctf_dwarf_attribute(cup, range, DW_AT_count, &attr);
	if (ret != 0 && ret != ENOENT) {
		return (ret);
	} else if (ret == ENOENT) {
		attrnum = DW_AT_upper_bound;
		ret = ctf_dwarf_attribute(cup, range, DW_AT_upper_bound, &attr);
		if (ret != 0 && ret != ENOENT) {
			return (ret);
		} else if (ret == ENOENT) {
			return (0);
		} else {
			adj = 1;
		}
	}

	DWARF_LOCK(cup);
	ret = dwarf_whatform(attr, &form, &derr);
	if (ret != DW_DLV_OK) {
		(void) snprintf(cup->cu_errbuf, cup->cu_errlen,
		    "failed to get DW_AT_upper_bound attribute form: %s\n",
		    dwarf_errmsg(derr));
		ret = ECTF_CONVBKERR;
		goto done;
	}

	/*
	 * Compilers can indicate array bounds using signed or unsigned values.
	 * Additionally, some compilers may also store the array bounds
	 * using as DW_FORM_data{1,2,4,8} (which DWARF treats as raw data and
	 * expects the caller to understand how to interpret the value).
	 *
	 * GCC 4.4.4 appears to always use unsigned values to encode the
	 * array size (using '(unsigned)-1' to represent a zero-length or
	 * unknown length array). Later versions of GCC use a signed value of
	 * -1 for zero/unknown length arrays, and unsigned values to encode
	 * known array sizes.
	 *
	 * Both dwarf_formsdata() and dwarf_formudata() will retrieve values
	 * as their respective signed/unsigned forms, but both will also
	 * retreive DW_FORM_data{1,2,4,8} values and treat them as signed or
	 * unsigned integers (i.e. dwarf_formsdata() treats DW_FORM_dataXX
	 * as signed integers and dwarf_formudata() treats DW_FORM_dataXX as
	 * unsigned integers). Both will return an error if the form is not
	 * their respective signed/unsigned form, or DW_FORM_dataXX.
	 *
	 * To obtain the upper bound, we use the appropriate
	 * dwarf_form[su]data() function based on the form of DW_AT_upper_bound.
	 * Additionally, we let dwarf_formudata() handle the DW_FORM_dataXX
	 * forms (via the default option in the switch). If the value is in an
	 * unexpected form (i.e. not DW_FORM_udata or DW_FORM_dataXX),
	 * dwarf_formudata() will return failure (i.e. not DW_DLV_OK) and set
	 * derr with the specific error value.
	 */
	switch (form) {
	case DW_FORM_sdata:
		if (dwarf_formsdata(attr, &sval, &derr) == DW_DLV_OK) {
			ar->ctr_nelems = sval + adj;
			goto done;
		}
		break;
	case DW_FORM_udata:
	default:
		if (dwarf_formudata(attr, &uval, &derr) == DW_DLV_OK) {
			ar->ctr_nelems = uval + adj;
			goto done;
		}
		break;
	}

	/*
	 * The value of attr is not always a constant value. For things
	 * such as C99 variable length arrays, it can be a reference to another
	 * entity or a DWARF expression. In either of these cases, we treat
	 * this as a zero length array.
	 */
	class = dwarf_get_form_class(cup->cu_vers, attrnum, cup->cu_addrsz,
	    form);

	if (class == DW_FORM_CLASS_REFERENCE || class == DW_FORM_CLASS_BLOCK)
		goto done;

	if (dwarf_get_FORM_name(form, &formstr) != DW_DLV_OK)
		formstr = "unknown DWARF form";

	(void) snprintf(cup->cu_errbuf, cup->cu_errlen,
	    "failed to get %s (%hu) value for DW_AT_upper_bound: %s\n",
	    formstr, form, dwarf_errmsg(derr));
	ret = ECTF_CONVBKERR;

done:
	DWARF_UNLOCK(cup);
	ctf_dwarf_dealloc(cup, attr, DW_DLA_ATTR);
	return (ret);
}

static int
ctf_dwarf_create_array_range(ctf_cu_t *cup, Dwarf_Die range, ctf_id_t *idp,
    ctf_id_t base, int isroot)
{
	int ret;
	Dwarf_Die sib;
	ctf_arinfo_t ar;

	ctf_dprintf("creating array range\n");

	if ((ret = ctf_dwarf_sib(cup, range, &sib)) != 0)
		return (ret);
	if (sib != NULL) {
		ctf_id_t id;
		if ((ret = ctf_dwarf_create_array_range(cup, sib, &id,
		    base, CTF_ADD_NONROOT)) != 0)
			return (ret);
		ar.ctr_contents = id;
	} else {
		ar.ctr_contents = base;
	}

	if ((ar.ctr_index = ctf_dwarf_long(cup)) == CTF_ERR)
		return (ctf_errno(cup->cu_ctfp));

	if ((ret = ctf_dwarf_array_upper_bound(cup, range, &ar)) != 0)
		return (ret);

	if ((*idp = ctf_add_array(cup->cu_ctfp, isroot, &ar)) == CTF_ERR)
		return (ctf_errno(cup->cu_ctfp));

	return (0);
}

/*
 * Try and create an array type. First, the kind of the array is specified in
 * the DW_AT_type entry. Next, the number of entries is stored in a more
 * complicated form, we should have a child that has the DW_TAG_subrange type.
 */
static int
ctf_dwarf_create_array(ctf_cu_t *cup, Dwarf_Die die, ctf_id_t *idp, int isroot)
{
	int ret;
	Dwarf_Die tdie, rdie;
	ctf_id_t tid;
	Dwarf_Half rtag;

	if ((ret = ctf_dwarf_refdie(cup, die, DW_AT_type, &tdie)) != 0)
		return (ret);
	if ((ret = ctf_dwarf_convert_type(cup, tdie, &tid,
	    CTF_ADD_NONROOT)) != 0)
		return (ret);

	if ((ret = ctf_dwarf_child(cup, die, &rdie)) != 0)
		return (ret);
	if ((ret = ctf_dwarf_tag(cup, rdie, &rtag)) != 0)
		return (ret);
	if (rtag != DW_TAG_subrange_type) {
		(void) snprintf(cup->cu_errbuf, cup->cu_errlen,
		    "encountered array without DW_TAG_subrange_type child\n");
		return (ECTF_CONVBKERR);
	}

	/*
	 * The compiler may opt to describe a multi-dimensional array as one
	 * giant array or it may opt to instead encode it as a series of
	 * subranges. If it's the latter, then for each subrange we introduce a
	 * type. We can always use the base type.
	 */
	if ((ret = ctf_dwarf_create_array_range(cup, rdie, idp, tid,
	    isroot)) != 0)
		return (ret);
	ctf_dprintf("Got back id %d\n", *idp);
	return (ctf_dwmap_add(cup, *idp, die, B_FALSE));
}

/*
 * Given "const int const_array3[11]", GCC7 at least will create a DIE tree of
 * DW_TAG_const_type:DW_TAG_array_type:DW_Tag_const_type:<member_type>.
 *
 * Given C's syntax, this renders out as "const const int const_array3[11]".  To
 * get closer to round-tripping (and make the unit tests work), we'll peek for
 * this case, and avoid adding the extraneous qualifier if we see that the
 * underlying array referent already has the same qualifier.
 *
 * This is unfortunately less trivial than it could be: this issue applies to
 * qualifier sets like "const volatile", as well as multi-dimensional arrays, so
 * we need to descend down those.
 *
 * Returns CTF_ERR on error, or a boolean value otherwise.
 */
static int
needed_array_qualifier(ctf_cu_t *cup, int kind, ctf_id_t ref_id)
{
	const ctf_type_t *t;
	ctf_arinfo_t arinfo;
	int akind;

	if (kind != CTF_K_CONST && kind != CTF_K_VOLATILE &&
	    kind != CTF_K_RESTRICT)
		return (1);

	if ((t = ctf_dyn_lookup_by_id(cup->cu_ctfp, ref_id)) == NULL)
		return (CTF_ERR);

	if (LCTF_INFO_KIND(cup->cu_ctfp, t->ctt_info) != CTF_K_ARRAY)
		return (1);

	if (ctf_dyn_array_info(cup->cu_ctfp, ref_id, &arinfo) != 0)
		return (CTF_ERR);

	ctf_id_t id = arinfo.ctr_contents;

	for (;;) {
		if ((t = ctf_dyn_lookup_by_id(cup->cu_ctfp, id)) == NULL)
			return (CTF_ERR);

		akind = LCTF_INFO_KIND(cup->cu_ctfp, t->ctt_info);

		if (akind == kind)
			break;

		if (akind == CTF_K_ARRAY) {
			if (ctf_dyn_array_info(cup->cu_ctfp,
			    id, &arinfo) != 0)
				return (CTF_ERR);
			id = arinfo.ctr_contents;
			continue;
		}

		if (akind != CTF_K_CONST && akind != CTF_K_VOLATILE &&
		    akind != CTF_K_RESTRICT)
			break;

		id = t->ctt_type;
	}

	if (kind == akind) {
		ctf_dprintf("ignoring extraneous %s qualifier for array %d\n",
		    ctf_kind_name(cup->cu_ctfp, kind), ref_id);
	}

	return (kind != akind);
}

static int
ctf_dwarf_create_reference(ctf_cu_t *cup, Dwarf_Die die, ctf_id_t *idp,
    int kind, int isroot)
{
	int ret;
	ctf_id_t id;
	Dwarf_Die tdie;
	char *name;

	if ((ret = ctf_dwarf_string(cup, die, DW_AT_name, &name)) != 0 &&
	    ret != ENOENT)
		return (ret);
	if (ret == ENOENT)
		name = NULL;

	ctf_dprintf("reference kind %d %s\n", kind, name != NULL ? name : "<>");

	if ((ret = ctf_dwarf_refdie(cup, die, DW_AT_type, &tdie)) != 0) {
		if (ret != ENOENT) {
			ctf_strfree(name);
			return (ret);
		}
		if ((id = ctf_dwarf_void(cup)) == CTF_ERR) {
			ctf_strfree(name);
			return (ctf_errno(cup->cu_ctfp));
		}
	} else {
		if ((ret = ctf_dwarf_convert_type(cup, tdie, &id,
		    CTF_ADD_NONROOT)) != 0) {
			ctf_strfree(name);
			return (ret);
		}
	}

	if ((ret = needed_array_qualifier(cup, kind, id)) <= 0) {
		if (ret != 0) {
			ret = (ctf_errno(cup->cu_ctfp));
		} else {
			*idp = id;
		}

		ctf_strfree(name);
		return (ret);
	}

	if ((*idp = ctf_add_reftype(cup->cu_ctfp, isroot, name, id, kind)) ==
	    CTF_ERR) {
		ctf_strfree(name);
		return (ctf_errno(cup->cu_ctfp));
	}

	ctf_strfree(name);
	return (ctf_dwmap_add(cup, *idp, die, B_FALSE));
}

static int
ctf_dwarf_create_enum(ctf_cu_t *cup, Dwarf_Die die, ctf_id_t *idp, int isroot)
{
	size_t size = 0;
	Dwarf_Die child;
	Dwarf_Unsigned dw;
	ctf_id_t id;
	char *enumname;
	int ret;

	ret = ctf_dwarf_string(cup, die, DW_AT_name, &enumname);
	if (ret != 0 && ret != ENOENT)
		return (ret);
	if (ret == ENOENT)
		enumname = NULL;

	/*
	 * Enumerations may have a size associated with them, particularly if
	 * they're packed. Note, a Dwarf_Unsigned is larger than a size_t on an
	 * ILP32 system.
	 */
	if (ctf_dwarf_unsigned(cup, die, DW_AT_byte_size, &dw) == 0 &&
	    dw < SIZE_MAX) {
		size = (size_t)dw;
	}

	id = ctf_add_enum(cup->cu_ctfp, isroot, enumname, size);
	ctf_dprintf("added enum %s (%d)\n",
	    enumname == NULL ? "<anon>" : enumname, id);
	if (id == CTF_ERR) {
		ret = ctf_errno(cup->cu_ctfp);
		goto out;
	}
	*idp = id;
	if ((ret = ctf_dwmap_add(cup, id, die, B_FALSE)) != 0)
		goto out;

	if ((ret = ctf_dwarf_child(cup, die, &child)) != 0) {
		if (ret == ENOENT)
			ret = 0;
		goto out;
	}

	while (child != NULL) {
		Dwarf_Half tag;
		Dwarf_Signed sval;
		Dwarf_Unsigned uval;
		Dwarf_Die arg = child;
		char *name;
		int eval;

		if ((ret = ctf_dwarf_sib(cup, arg, &child)) != 0)
			break;

		if ((ret = ctf_dwarf_tag(cup, arg, &tag)) != 0)
			break;

		if (tag != DW_TAG_enumerator) {
			if ((ret = ctf_dwarf_convert_type(cup, arg, NULL,
			    CTF_ADD_NONROOT)) != 0) {
				break;
			}
			continue;
		}

		/*
		 * DWARF v4 section 5.7 tells us we'll always have names.
		 */
		if ((ret = ctf_dwarf_string(cup, arg, DW_AT_name, &name)) != 0)
			break;

		/*
		 * We have to be careful here: newer GCCs generate DWARF where
		 * an unsigned value will happily pass ctf_dwarf_signed().
		 * Since negative values will fail ctf_dwarf_unsigned(), we try
		 * that first to make sure we get the right value.
		 */
		if ((ret = ctf_dwarf_unsigned(cup, arg, DW_AT_const_value,
		    &uval)) == 0) {
			eval = (int)uval;
		} else {
			/*
			 * ctf_dwarf_unsigned will have left an error in the
			 * buffer
			 */
			*cup->cu_errbuf = '\0';

			if ((ret = ctf_dwarf_signed(cup, arg, DW_AT_const_value,
			    &sval)) == 0) {
				eval = sval;
			}
		}

		if (ret != 0) {
			if (ret == ENOENT) {
				(void) snprintf(cup->cu_errbuf, cup->cu_errlen,
				    "encountered enumeration without constant "
				    "value\n");
				ret = ECTF_CONVBKERR;
			}
			ctf_strfree(name);
			break;
		}

		ret = ctf_add_enumerator(cup->cu_ctfp, id, name, eval);
		if (ret == CTF_ERR) {
			ret = ctf_errno(cup->cu_ctfp);

			if (ret == ECTF_DTFULL && (cup->cu_handle->cch_flags &
			    CTF_ALLOW_TRUNCATION)) {
				if (cup->cu_handle->cch_warncb != NULL) {
					cup->cu_handle->cch_warncb(
					    cup->cu_handle->cch_warncb_arg,
					    "truncating enumeration %s at %s\n",
					    name, enumname == NULL ? "<anon>" :
					    enumname);
				}
				ret = 0;
			} else {
				(void) snprintf(cup->cu_errbuf, cup->cu_errlen,
				    "failed to add enumerator %s (%d) "
				    "to %s (%d)\n", name, eval,
				    enumname == NULL ? "<anon>" : enumname, id);
			}
			ctf_strfree(name);
			break;
		}
		ctf_strfree(name);
	}

out:

	if (enumname != NULL)
		ctf_strfree(enumname);

	return (ret);
}

/*
 * For a function pointer, walk over and process all of its children, unless we
 * encounter one that's just a declaration. In which case, we error on it.
 */
static int
ctf_dwarf_create_fptr(ctf_cu_t *cup, Dwarf_Die die, ctf_id_t *idp, int isroot)
{
	int ret;
	Dwarf_Bool b;
	ctf_funcinfo_t fi;
	Dwarf_Die retdie;
	ctf_id_t *argv = NULL;

	bzero(&fi, sizeof (ctf_funcinfo_t));

	if ((ret = ctf_dwarf_boolean(cup, die, DW_AT_declaration, &b)) != 0) {
		if (ret != ENOENT)
			return (ret);
	} else {
		if (b != 0)
			return (EPROTOTYPE);
	}

	/*
	 * Return type is in DW_AT_type, if none, it returns void.
	 */
	if ((ret = ctf_dwarf_refdie(cup, die, DW_AT_type, &retdie)) != 0) {
		if (ret != ENOENT)
			return (ret);
		if ((fi.ctc_return = ctf_dwarf_void(cup)) == CTF_ERR)
			return (ctf_errno(cup->cu_ctfp));
	} else {
		if ((ret = ctf_dwarf_convert_type(cup, retdie, &fi.ctc_return,
		    CTF_ADD_NONROOT)) != 0)
			return (ret);
	}

	if ((ret = ctf_dwarf_function_count(cup, die, &fi, B_TRUE)) != 0) {
		return (ret);
	}

	if (fi.ctc_argc != 0) {
		argv = ctf_alloc(sizeof (ctf_id_t) * fi.ctc_argc);
		if (argv == NULL)
			return (ENOMEM);

		if ((ret = ctf_dwarf_convert_fargs(cup, die, &fi, argv)) != 0) {
			ctf_free(argv, sizeof (ctf_id_t) * fi.ctc_argc);
			return (ret);
		}
	}

	if ((*idp = ctf_add_funcptr(cup->cu_ctfp, isroot, &fi, argv)) ==
	    CTF_ERR) {
		ctf_free(argv, sizeof (ctf_id_t) * fi.ctc_argc);
		return (ctf_errno(cup->cu_ctfp));
	}

	ctf_free(argv, sizeof (ctf_id_t) * fi.ctc_argc);
	return (ctf_dwmap_add(cup, *idp, die, B_FALSE));
}

static int
ctf_dwarf_convert_type(ctf_cu_t *cup, Dwarf_Die die, ctf_id_t *idp,
    int isroot)
{
	int ret;
	Dwarf_Off offset;
	Dwarf_Half tag;
	ctf_dwmap_t lookup, *map;
	ctf_id_t id;

	if (idp == NULL)
		idp = &id;

	if ((ret = ctf_dwarf_offset(cup, die, &offset)) != 0)
		return (ret);

	if (offset > cup->cu_maxoff) {
		(void) snprintf(cup->cu_errbuf, cup->cu_errlen,
		    "die offset %llu beyond maximum for header %llu\n",
		    offset, cup->cu_maxoff);
		return (ECTF_CONVBKERR);
	}

	/*
	 * If we've already added an entry for this offset, then we're done.
	 */
	lookup.cdm_off = offset;
	if ((map = avl_find(&cup->cu_map, &lookup, NULL)) != NULL) {
		*idp = map->cdm_id;
		return (0);
	}

	if ((ret = ctf_dwarf_tag(cup, die, &tag)) != 0)
		return (ret);

	ret = ENOTSUP;
	switch (tag) {
	case DW_TAG_base_type:
		ctf_dprintf("base\n");
		ret = ctf_dwarf_create_base(cup, die, idp, isroot, offset);
		break;
	case DW_TAG_array_type:
		ctf_dprintf("array\n");
		ret = ctf_dwarf_create_array(cup, die, idp, isroot);
		break;
	case DW_TAG_enumeration_type:
		ctf_dprintf("enum\n");
		ret = ctf_dwarf_create_enum(cup, die, idp, isroot);
		break;
	case DW_TAG_pointer_type:
		ctf_dprintf("pointer\n");
		ret = ctf_dwarf_create_reference(cup, die, idp, CTF_K_POINTER,
		    isroot);
		break;
	case DW_TAG_structure_type:
		ctf_dprintf("struct\n");
		ret = ctf_dwarf_create_sou(cup, die, idp, CTF_K_STRUCT,
		    isroot);
		break;
	case DW_TAG_subroutine_type:
		ctf_dprintf("fptr\n");
		ret = ctf_dwarf_create_fptr(cup, die, idp, isroot);
		break;
	case DW_TAG_typedef:
		ctf_dprintf("typedef\n");
		ret = ctf_dwarf_create_reference(cup, die, idp, CTF_K_TYPEDEF,
		    isroot);
		break;
	case DW_TAG_union_type:
		ctf_dprintf("union\n");
		ret = ctf_dwarf_create_sou(cup, die, idp, CTF_K_UNION,
		    isroot);
		break;
	case DW_TAG_const_type:
		ctf_dprintf("const\n");
		ret = ctf_dwarf_create_reference(cup, die, idp, CTF_K_CONST,
		    isroot);
		break;
	case DW_TAG_volatile_type:
		ctf_dprintf("volatile\n");
		ret = ctf_dwarf_create_reference(cup, die, idp, CTF_K_VOLATILE,
		    isroot);
		break;
	case DW_TAG_restrict_type:
		ctf_dprintf("restrict\n");
		ret = ctf_dwarf_create_reference(cup, die, idp, CTF_K_RESTRICT,
		    isroot);
		break;
	default:
		ctf_dprintf("ignoring tag type %x\n", tag);
		*idp = CTF_ERR;
		ret = 0;
		break;
	}
	ctf_dprintf("ctf_dwarf_convert_type tag specific handler returned %d\n",
	    ret);

	return (ret);
}

static int
ctf_dwarf_walk_lexical(ctf_cu_t *cup, Dwarf_Die die)
{
	int ret;
	Dwarf_Die child;

	if ((ret = ctf_dwarf_child(cup, die, &child)) != 0)
		return (ret);

	if (child == NULL)
		return (0);

	return (ctf_dwarf_convert_die(cup, die));
}

static int
ctf_dwarf_function_count(ctf_cu_t *cup, Dwarf_Die die, ctf_funcinfo_t *fip,
    boolean_t fptr)
{
	int ret;
	Dwarf_Die child, sib, arg;

	if ((ret = ctf_dwarf_child(cup, die, &child)) != 0)
		return (ret);

	arg = child;
	while (arg != NULL) {
		Dwarf_Half tag;

		if ((ret = ctf_dwarf_tag(cup, arg, &tag)) != 0)
			return (ret);

		/*
		 * We have to check for a varargs type declaration. This will
		 * happen in one of two ways. If we have a function pointer
		 * type, then it'll be done with a tag of type
		 * DW_TAG_unspecified_parameters. However, it only means we have
		 * a variable number of arguments, if we have more than one
		 * argument found so far. Otherwise, when we have a function
		 * type, it instead uses a formal parameter whose name is '...'
		 * to indicate a variable arguments member.
		 *
		 * Also, if we have a function pointer, then we have to expect
		 * that we might not get a name at all.
		 */
		if (tag == DW_TAG_formal_parameter && fptr == B_FALSE) {
			char *name;
			if ((ret = ctf_dwarf_string(cup, die, DW_AT_name,
			    &name)) != 0)
				return (ret);
			if (strcmp(name, DWARF_VARARGS_NAME) == 0)
				fip->ctc_flags |= CTF_FUNC_VARARG;
			else
				fip->ctc_argc++;
			ctf_strfree(name);
		} else if (tag == DW_TAG_formal_parameter) {
			fip->ctc_argc++;
		} else if (tag == DW_TAG_unspecified_parameters &&
		    fip->ctc_argc > 0) {
			fip->ctc_flags |= CTF_FUNC_VARARG;
		}
		if ((ret = ctf_dwarf_sib(cup, arg, &sib)) != 0)
			return (ret);
		arg = sib;
	}

	return (0);
}

static int
ctf_dwarf_convert_fargs(ctf_cu_t *cup, Dwarf_Die die, ctf_funcinfo_t *fip,
    ctf_id_t *argv)
{
	int ret;
	int i = 0;
	Dwarf_Die child, sib, arg;

	if ((ret = ctf_dwarf_child(cup, die, &child)) != 0)
		return (ret);

	arg = child;
	while (arg != NULL) {
		Dwarf_Half tag;

		if ((ret = ctf_dwarf_tag(cup, arg, &tag)) != 0)
			return (ret);
		if (tag == DW_TAG_formal_parameter) {
			Dwarf_Die tdie;

			if ((ret = ctf_dwarf_refdie(cup, arg, DW_AT_type,
			    &tdie)) != 0)
				return (ret);

			if ((ret = ctf_dwarf_convert_type(cup, tdie, &argv[i],
			    CTF_ADD_ROOT)) != 0)
				return (ret);
			i++;

			/*
			 * Once we hit argc entries, we're done. This ensures we
			 * don't accidentally hit a varargs which should be the
			 * last entry.
			 */
			if (i == fip->ctc_argc)
				break;
		}

		if ((ret = ctf_dwarf_sib(cup, arg, &sib)) != 0)
			return (ret);
		arg = sib;
	}

	return (0);
}

static int
ctf_dwarf_convert_function(ctf_cu_t *cup, Dwarf_Die die)
{
	ctf_dwfunc_t *cdf;
	Dwarf_Die tdie;
	Dwarf_Bool b;
	char *name;
	int ret;

	/*
	 * Functions that don't have a name are generally functions that have
	 * been inlined and thus most information about them has been lost. If
	 * we can't get a name, then instead of returning ENOENT, we silently
	 * swallow the error.
	 */
	if ((ret = ctf_dwarf_string(cup, die, DW_AT_name, &name)) != 0) {
		if (ret == ENOENT)
			return (0);
		return (ret);
	}

	ctf_dprintf("beginning work on function %s (die %llx)\n",
	    name, ctf_die_offset(cup, die));

	if ((ret = ctf_dwarf_boolean(cup, die, DW_AT_declaration, &b)) != 0) {
		if (ret != ENOENT) {
			ctf_strfree(name);
			return (ret);
		}
	} else if (b != 0) {
		/*
		 * GCC7 at least creates empty DW_AT_declarations for functions
		 * defined in headers.  As they lack details on the function
		 * prototype, we need to ignore them.  If we later actually
		 * see the relevant function's definition, we will see another
		 * DW_TAG_subprogram that is more complete.
		 */
		ctf_dprintf("ignoring declaration of function %s (die %llx)\n",
		    name, ctf_die_offset(cup, die));
		ctf_strfree(name);
		return (0);
	}

	if ((cdf = ctf_alloc(sizeof (ctf_dwfunc_t))) == NULL) {
		ctf_strfree(name);
		return (ENOMEM);
	}
	bzero(cdf, sizeof (ctf_dwfunc_t));
	cdf->cdf_name = name;

	if ((ret = ctf_dwarf_refdie(cup, die, DW_AT_type, &tdie)) == 0) {
		if ((ret = ctf_dwarf_convert_type(cup, tdie,
		    &(cdf->cdf_fip.ctc_return), CTF_ADD_ROOT)) != 0) {
			ctf_strfree(name);
			ctf_free(cdf, sizeof (ctf_dwfunc_t));
			return (ret);
		}
	} else if (ret != ENOENT) {
		ctf_strfree(name);
		ctf_free(cdf, sizeof (ctf_dwfunc_t));
		return (ret);
	} else {
		if ((cdf->cdf_fip.ctc_return = ctf_dwarf_void(cup)) ==
		    CTF_ERR) {
			ctf_strfree(name);
			ctf_free(cdf, sizeof (ctf_dwfunc_t));
			return (ctf_errno(cup->cu_ctfp));
		}
	}

	/*
	 * A function has a number of children, some of which may not be ones we
	 * care about. Children that we care about have a type of
	 * DW_TAG_formal_parameter. We're going to do two passes, the first to
	 * count the arguments, the second to process them. Afterwards, we
	 * should be good to go ahead and add this function.
	 *
	 * Note, we already got the return type by going in and grabbing it out
	 * of the DW_AT_type.
	 */
	if ((ret = ctf_dwarf_function_count(cup, die, &cdf->cdf_fip,
	    B_FALSE)) != 0) {
		ctf_strfree(name);
		ctf_free(cdf, sizeof (ctf_dwfunc_t));
		return (ret);
	}

	ctf_dprintf("beginning to convert function arguments %s\n", name);
	if (cdf->cdf_fip.ctc_argc != 0) {
		uint_t argc = cdf->cdf_fip.ctc_argc;
		cdf->cdf_argv = ctf_alloc(sizeof (ctf_id_t) * argc);
		if (cdf->cdf_argv == NULL) {
			ctf_strfree(name);
			ctf_free(cdf, sizeof (ctf_dwfunc_t));
			return (ENOMEM);
		}
		if ((ret = ctf_dwarf_convert_fargs(cup, die,
		    &cdf->cdf_fip, cdf->cdf_argv)) != 0) {
			ctf_free(cdf->cdf_argv, sizeof (ctf_id_t) * argc);
			ctf_strfree(name);
			ctf_free(cdf, sizeof (ctf_dwfunc_t));
			return (ret);
		}
	} else {
		cdf->cdf_argv = NULL;
	}

	if ((ret = ctf_dwarf_isglobal(cup, die, &cdf->cdf_global)) != 0) {
		ctf_free(cdf->cdf_argv, sizeof (ctf_id_t) *
		    cdf->cdf_fip.ctc_argc);
		ctf_strfree(name);
		ctf_free(cdf, sizeof (ctf_dwfunc_t));
		return (ret);
	}

	ctf_list_append(&cup->cu_funcs, cdf);
	return (ret);
}

/*
 * Convert variables, but only if they're not prototypes and have names.
 */
static int
ctf_dwarf_convert_variable(ctf_cu_t *cup, Dwarf_Die die)
{
	int ret;
	char *name;
	Dwarf_Bool b;
	Dwarf_Die tdie;
	ctf_id_t id;
	ctf_dwvar_t *cdv;

	/* Skip "Non-Defining Declarations" */
	if ((ret = ctf_dwarf_boolean(cup, die, DW_AT_declaration, &b)) == 0) {
		if (b != 0)
			return (0);
	} else if (ret != ENOENT) {
		return (ret);
	}

	/*
	 * If we find a DIE of "Declarations Completing Non-Defining
	 * Declarations", we will use the referenced type's DIE.  This isn't
	 * quite correct, e.g. DW_AT_decl_line will be the forward declaration
	 * not this site.  It's sufficient for what we need, however: in
	 * particular, we should find DW_AT_external as needed there.
	 */
	if ((ret = ctf_dwarf_refdie(cup, die, DW_AT_specification,
	    &tdie)) == 0) {
		Dwarf_Off offset;
		if ((ret = ctf_dwarf_offset(cup, tdie, &offset)) != 0)
			return (ret);
		ctf_dprintf("die 0x%llx DW_AT_specification -> die 0x%llx\n",
		    ctf_die_offset(cup, die), ctf_die_offset(cup, tdie));
		die = tdie;
	} else if (ret != ENOENT) {
		return (ret);
	}

	if ((ret = ctf_dwarf_string(cup, die, DW_AT_name, &name)) != 0 &&
	    ret != ENOENT)
		return (ret);
	if (ret == ENOENT)
		return (0);

	if ((ret = ctf_dwarf_refdie(cup, die, DW_AT_type, &tdie)) != 0) {
		ctf_strfree(name);
		return (ret);
	}

	if ((ret = ctf_dwarf_convert_type(cup, tdie, &id,
	    CTF_ADD_ROOT)) != 0)
		return (ret);

	if ((cdv = ctf_alloc(sizeof (ctf_dwvar_t))) == NULL) {
		ctf_strfree(name);
		return (ENOMEM);
	}

	cdv->cdv_name = name;
	cdv->cdv_type = id;

	if ((ret = ctf_dwarf_isglobal(cup, die, &cdv->cdv_global)) != 0) {
		ctf_free(cdv, sizeof (ctf_dwvar_t));
		ctf_strfree(name);
		return (ret);
	}

	ctf_list_append(&cup->cu_vars, cdv);
	return (0);
}

/*
 * Walk through our set of top-level types and process them.
 */
static int
ctf_dwarf_walk_toplevel(ctf_cu_t *cup, Dwarf_Die die)
{
	int ret;
	Dwarf_Off offset;
	Dwarf_Half tag;

	if ((ret = ctf_dwarf_offset(cup, die, &offset)) != 0)
		return (ret);

	if (offset > cup->cu_maxoff) {
		(void) snprintf(cup->cu_errbuf, cup->cu_errlen,
		    "die offset %llu beyond maximum for header %llu\n",
		    offset, cup->cu_maxoff);
		return (ECTF_CONVBKERR);
	}

	if ((ret = ctf_dwarf_tag(cup, die, &tag)) != 0)
		return (ret);

	ret = 0;
	switch (tag) {
	case DW_TAG_subprogram:
		ctf_dprintf("top level func\n");
		ret = ctf_dwarf_convert_function(cup, die);
		break;
	case DW_TAG_variable:
		ctf_dprintf("top level var\n");
		ret = ctf_dwarf_convert_variable(cup, die);
		break;
	case DW_TAG_lexical_block:
		ctf_dprintf("top level block\n");
		ret = ctf_dwarf_walk_lexical(cup, die);
		break;
	case DW_TAG_enumeration_type:
	case DW_TAG_structure_type:
	case DW_TAG_typedef:
	case DW_TAG_union_type:
		ctf_dprintf("top level type\n");
		ret = ctf_dwarf_convert_type(cup, die, NULL, B_TRUE);
		break;
	default:
		break;
	}

	return (ret);
}


/*
 * We're given a node. At this node we need to convert it and then proceed to
 * convert any siblings that are associaed with this die.
 */
static int
ctf_dwarf_convert_die(ctf_cu_t *cup, Dwarf_Die die)
{
	while (die != NULL) {
		int ret;
		Dwarf_Die sib;

		if ((ret = ctf_dwarf_walk_toplevel(cup, die)) != 0)
			return (ret);

		if ((ret = ctf_dwarf_sib(cup, die, &sib)) != 0)
			return (ret);
		die = sib;
	}
	return (0);
}

static int
ctf_dwarf_fixup_die(ctf_cu_t *cup, boolean_t addpass)
{
	ctf_dwmap_t *map;

	for (map = avl_first(&cup->cu_map); map != NULL;
	    map = AVL_NEXT(&cup->cu_map, map)) {
		int ret;
		if (map->cdm_fix == B_FALSE)
			continue;
		if ((ret = ctf_dwarf_fixup_sou(cup, map->cdm_die, map->cdm_id,
		    addpass)) != 0)
			return (ret);
	}

	return (0);
}

/*
 * The DWARF information about a symbol and the information in the symbol table
 * may not be the same due to symbol reduction that is performed by ld due to a
 * mapfile or other such directive. We process weak symbols at a later time.
 *
 * The following are the rules that we employ:
 *
 * 1. A DWARF function that is considered exported matches STB_GLOBAL entries
 * with the same name.
 *
 * 2. A DWARF function that is considered exported matches STB_LOCAL entries
 * with the same name and the same file. This case may happen due to mapfile
 * reduction.
 *
 * 3. A DWARF function that is not considered exported matches STB_LOCAL entries
 * with the same name and the same file.
 *
 * 4. A DWARF function that has the same name as the symbol table entry, but the
 * files do not match. This is considered a 'fuzzy' match. This may also happen
 * due to a mapfile reduction. Fuzzy matching is only used when we know that the
 * file in question refers to the primary object. This is because when a symbol
 * is reduced in a mapfile, it's always going to be tagged as a local value in
 * the generated output and it is considered as to belong to the primary file
 * which is the first STT_FILE symbol we see.
 */
static boolean_t
ctf_dwarf_symbol_match(const char *symtab_file, const char *symtab_name,
    uint_t symtab_bind, const char *dwarf_file, const char *dwarf_name,
    boolean_t dwarf_global, boolean_t *is_fuzzy)
{
	*is_fuzzy = B_FALSE;

	if (symtab_bind != STB_LOCAL && symtab_bind != STB_GLOBAL) {
		return (B_FALSE);
	}

	if (strcmp(symtab_name, dwarf_name) != 0) {
		return (B_FALSE);
	}

	if (symtab_bind == STB_GLOBAL) {
		return (dwarf_global);
	}

	if (strcmp(symtab_file, dwarf_file) == 0) {
		return (B_TRUE);
	}

	if (dwarf_global) {
		*is_fuzzy = B_TRUE;
		return (B_TRUE);
	}

	return (B_FALSE);
}

static ctf_dwfunc_t *
ctf_dwarf_match_func(ctf_cu_t *cup, const char *file, const char *name,
    uint_t bind, boolean_t primary)
{
	ctf_dwfunc_t *cdf, *fuzzy = NULL;

	if (bind == STB_WEAK)
		return (NULL);

	if (bind == STB_LOCAL && (file == NULL || cup->cu_name == NULL))
		return (NULL);

	for (cdf = ctf_list_next(&cup->cu_funcs); cdf != NULL;
	    cdf = ctf_list_next(cdf)) {
		boolean_t is_fuzzy = B_FALSE;

		if (ctf_dwarf_symbol_match(file, name, bind, cup->cu_name,
		    cdf->cdf_name, cdf->cdf_global, &is_fuzzy)) {
			if (is_fuzzy) {
				if (primary) {
					fuzzy = cdf;
				}
				continue;
			} else {
				return (cdf);
			}
		}
	}

	return (fuzzy);
}

static ctf_dwvar_t *
ctf_dwarf_match_var(ctf_cu_t *cup, const char *file, const char *name,
    uint_t bind, boolean_t primary)
{
	ctf_dwvar_t *cdv, *fuzzy = NULL;

	if (bind == STB_WEAK)
		return (NULL);

	if (bind == STB_LOCAL && (file == NULL || cup->cu_name == NULL))
		return (NULL);

	for (cdv = ctf_list_next(&cup->cu_vars); cdv != NULL;
	    cdv = ctf_list_next(cdv)) {
		boolean_t is_fuzzy = B_FALSE;

		if (ctf_dwarf_symbol_match(file, name, bind, cup->cu_name,
		    cdv->cdv_name, cdv->cdv_global, &is_fuzzy)) {
			if (is_fuzzy) {
				if (primary) {
					fuzzy = cdv;
				}
			} else {
				return (cdv);
			}
		}
	}

	return (fuzzy);
}

static int
ctf_dwarf_conv_funcvars_cb(const Elf64_Sym *symp, ulong_t idx,
    const char *file, const char *name, boolean_t primary, void *arg)
{
	int ret;
	uint_t bind, type;
	ctf_cu_t *cup = arg;

	bind = GELF_ST_BIND(symp->st_info);
	type = GELF_ST_TYPE(symp->st_info);

	/*
	 * Come back to weak symbols in another pass
	 */
	if (bind == STB_WEAK)
		return (0);

	if (type == STT_OBJECT) {
		ctf_dwvar_t *cdv = ctf_dwarf_match_var(cup, file, name,
		    bind, primary);
		if (cdv == NULL)
			return (0);
		ret = ctf_add_object(cup->cu_ctfp, idx, cdv->cdv_type);
		ctf_dprintf("added object %s->%ld\n", name, cdv->cdv_type);
	} else {
		ctf_dwfunc_t *cdf = ctf_dwarf_match_func(cup, file, name,
		    bind, primary);
		if (cdf == NULL)
			return (0);
		ret = ctf_add_function(cup->cu_ctfp, idx, &cdf->cdf_fip,
		    cdf->cdf_argv);
		ctf_dprintf("added function %s\n", name);
	}

	if (ret == CTF_ERR) {
		return (ctf_errno(cup->cu_ctfp));
	}

	return (0);
}

static int
ctf_dwarf_conv_funcvars(ctf_cu_t *cup)
{
	return (ctf_symtab_iter(cup->cu_ctfp, ctf_dwarf_conv_funcvars_cb, cup));
}

/*
 * If we have a weak symbol, attempt to find the strong symbol it will resolve
 * to.  Note: the code where this actually happens is in sym_process() in
 * cmd/sgs/libld/common/syms.c
 *
 * Finding the matching symbol is unfortunately not trivial.  For a symbol to be
 * a candidate, it must:
 *
 * - have the same type (function, object)
 * - have the same value (address)
 * - have the same size
 * - not be another weak symbol
 * - belong to the same section (checked via section index)
 *
 * To perform this check, we first iterate over the symbol table. For each weak
 * symbol that we encounter, we then do a second walk over the symbol table,
 * calling ctf_dwarf_conv_check_weak(). If a symbol matches the above, then it's
 * either a local or global symbol. If we find a global symbol then we go with
 * it and stop searching for additional matches.
 *
 * If instead, we find a local symbol, things are more complicated. The first
 * thing we do is to try and see if we have file information about both symbols
 * (STT_FILE). If they both have file information and it matches, then we treat
 * that as a good match and stop searching for additional matches.
 *
 * Otherwise, this means we have a non-matching file and a local symbol. We
 * treat this as a candidate and if we find a better match (one of the two cases
 * above), use that instead. There are two different ways this can happen.
 * Either this is a completely different symbol, or it's a once-global symbol
 * that was scoped to local via a mapfile.  In the former case, curfile is
 * likely inaccurate since the linker does not preserve the needed curfile in
 * the order of the symbol table (see the comments about locally scoped symbols
 * in libld's update_osym()).  As we can't tell this case from the former one,
 * we use this symbol iff no other matching symbol is found.
 *
 * What we really need here is a SUNW section containing weak<->strong mappings
 * that we can consume.
 */
typedef struct ctf_dwarf_weak_arg {
	const Elf64_Sym *cweak_symp;
	const char *cweak_file;
	boolean_t cweak_candidate;
	ulong_t cweak_idx;
} ctf_dwarf_weak_arg_t;

static int
ctf_dwarf_conv_check_weak(const Elf64_Sym *symp, ulong_t idx, const char *file,
    const char *name, boolean_t primary, void *arg)
{
	ctf_dwarf_weak_arg_t *cweak = arg;

	const Elf64_Sym *wsymp = cweak->cweak_symp;

	ctf_dprintf("comparing weak to %s\n", name);

	if (GELF_ST_BIND(symp->st_info) == STB_WEAK) {
		return (0);
	}

	if (GELF_ST_TYPE(wsymp->st_info) != GELF_ST_TYPE(symp->st_info)) {
		return (0);
	}

	if (wsymp->st_value != symp->st_value) {
		return (0);
	}

	if (wsymp->st_size != symp->st_size) {
		return (0);
	}

	if (wsymp->st_shndx != symp->st_shndx) {
		return (0);
	}

	/*
	 * Check if it's a weak candidate.
	 */
	if (GELF_ST_BIND(symp->st_info) == STB_LOCAL &&
	    (file == NULL || cweak->cweak_file == NULL ||
	    strcmp(file, cweak->cweak_file) != 0)) {
		cweak->cweak_candidate = B_TRUE;
		cweak->cweak_idx = idx;
		return (0);
	}

	/*
	 * Found a match, break.
	 */
	cweak->cweak_idx = idx;
	return (1);
}

static int
ctf_dwarf_duplicate_sym(ctf_cu_t *cup, ulong_t idx, ulong_t matchidx)
{
	ctf_id_t id = ctf_lookup_by_symbol(cup->cu_ctfp, matchidx);

	/*
	 * If we matched something that for some reason didn't have type data,
	 * we don't consider that a fatal error and silently swallow it.
	 */
	if (id == CTF_ERR) {
		if (ctf_errno(cup->cu_ctfp) == ECTF_NOTYPEDAT)
			return (0);
		else
			return (ctf_errno(cup->cu_ctfp));
	}

	if (ctf_add_object(cup->cu_ctfp, idx, id) == CTF_ERR)
		return (ctf_errno(cup->cu_ctfp));

	return (0);
}

static int
ctf_dwarf_duplicate_func(ctf_cu_t *cup, ulong_t idx, ulong_t matchidx)
{
	int ret;
	ctf_funcinfo_t fip;
	ctf_id_t *args = NULL;

	if (ctf_func_info(cup->cu_ctfp, matchidx, &fip) == CTF_ERR) {
		if (ctf_errno(cup->cu_ctfp) == ECTF_NOFUNCDAT)
			return (0);
		else
			return (ctf_errno(cup->cu_ctfp));
	}

	if (fip.ctc_argc != 0) {
		args = ctf_alloc(sizeof (ctf_id_t) * fip.ctc_argc);
		if (args == NULL)
			return (ENOMEM);

		if (ctf_func_args(cup->cu_ctfp, matchidx, fip.ctc_argc, args) ==
		    CTF_ERR) {
			ctf_free(args, sizeof (ctf_id_t) * fip.ctc_argc);
			return (ctf_errno(cup->cu_ctfp));
		}
	}

	ret = ctf_add_function(cup->cu_ctfp, idx, &fip, args);
	if (args != NULL)
		ctf_free(args, sizeof (ctf_id_t) * fip.ctc_argc);
	if (ret == CTF_ERR)
		return (ctf_errno(cup->cu_ctfp));

	return (0);
}

static int
ctf_dwarf_conv_weaks_cb(const Elf64_Sym *symp, ulong_t idx, const char *file,
    const char *name, boolean_t primary, void *arg)
{
	int ret, type;
	ctf_dwarf_weak_arg_t cweak;
	ctf_cu_t *cup = arg;

	/*
	 * We only care about weak symbols.
	 */
	if (GELF_ST_BIND(symp->st_info) != STB_WEAK)
		return (0);

	type = GELF_ST_TYPE(symp->st_info);
	ASSERT(type == STT_OBJECT || type == STT_FUNC);

	/*
	 * For each weak symbol we encounter, we need to do a second iteration
	 * to try and find a match. We should probably think about other
	 * techniques to try and save us time in the future.
	 */
	cweak.cweak_symp = symp;
	cweak.cweak_file = file;
	cweak.cweak_candidate = B_FALSE;
	cweak.cweak_idx = 0;

	ctf_dprintf("Trying to find weak equiv for %s\n", name);

	ret = ctf_symtab_iter(cup->cu_ctfp, ctf_dwarf_conv_check_weak, &cweak);
	VERIFY(ret == 0 || ret == 1);

	/*
	 * Nothing was ever found, we're not going to add anything for this
	 * entry.
	 */
	if (ret == 0 && cweak.cweak_candidate == B_FALSE) {
		ctf_dprintf("found no weak match for %s\n", name);
		return (0);
	}

	/*
	 * Now, finally go and add the type based on the match.
	 */
	ctf_dprintf("matched weak symbol %lu to %lu\n", idx, cweak.cweak_idx);
	if (type == STT_OBJECT) {
		ret = ctf_dwarf_duplicate_sym(cup, idx, cweak.cweak_idx);
	} else {
		ret = ctf_dwarf_duplicate_func(cup, idx, cweak.cweak_idx);
	}

	return (ret);
}

static int
ctf_dwarf_conv_weaks(ctf_cu_t *cup)
{
	return (ctf_symtab_iter(cup->cu_ctfp, ctf_dwarf_conv_weaks_cb, cup));
}

static int
ctf_dwarf_convert_one(void *arg, void *unused)
{
	int ret;
	ctf_file_t *dedup;
	ctf_cu_t *cup = arg;
	const char *name = cup->cu_name != NULL ? cup->cu_name : "NULL";

	VERIFY(cup != NULL);

	if ((ret = ctf_dwarf_init_die(cup)) != 0)
		return (ret);

	ctf_dprintf("converting die: %s - max offset: %x\n", name,
	    cup->cu_maxoff);

	ret = ctf_dwarf_convert_die(cup, cup->cu_cu);
	ctf_dprintf("ctf_dwarf_convert_die (%s) returned %d\n", name,
	    ret);
	if (ret != 0)
		return (ret);

	if (ctf_update(cup->cu_ctfp) != 0) {
		return (ctf_dwarf_error(cup, cup->cu_ctfp, 0,
		    "failed to update output ctf container"));
	}

	ret = ctf_dwarf_fixup_die(cup, B_FALSE);
	ctf_dprintf("ctf_dwarf_fixup_die (%s, FALSE) returned %d\n", name,
	    ret);
	if (ret != 0)
		return (ret);

	if (ctf_update(cup->cu_ctfp) != 0) {
		return (ctf_dwarf_error(cup, cup->cu_ctfp, 0,
		    "failed to update output ctf container"));
	}

	ret = ctf_dwarf_fixup_die(cup, B_TRUE);
	ctf_dprintf("ctf_dwarf_fixup_die (%s, TRUE) returned %d\n", name,
	    ret);
	if (ret != 0)
		return (ret);

	if (ctf_update(cup->cu_ctfp) != 0) {
		return (ctf_dwarf_error(cup, cup->cu_ctfp, 0,
		    "failed to update output ctf container"));
	}

	if ((ret = ctf_dwarf_conv_funcvars(cup)) != 0) {
		ctf_dprintf("ctf_dwarf_conv_funcvars (%s) returned %d\n",
		    name, ret);
		return (ctf_dwarf_error(cup, NULL, ret,
		    "failed to convert strong functions and variables"));
	}

	if (ctf_update(cup->cu_ctfp) != 0) {
		return (ctf_dwarf_error(cup, cup->cu_ctfp, 0,
		    "failed to update output ctf container"));
	}

	if (cup->cu_doweaks == B_TRUE) {
		if ((ret = ctf_dwarf_conv_weaks(cup)) != 0) {
			ctf_dprintf("ctf_dwarf_conv_weaks (%s) returned %d\n",
			    name, ret);
			return (ctf_dwarf_error(cup, NULL, ret,
			    "failed to convert weak functions and variables"));
		}

		if (ctf_update(cup->cu_ctfp) != 0) {
			return (ctf_dwarf_error(cup, cup->cu_ctfp, 0,
			    "failed to update output ctf container"));
		}
	}

	ctf_phase_dump(cup->cu_ctfp, "pre-dwarf-dedup", name);
	ctf_dprintf("adding inputs for dedup\n");
	if ((ret = ctf_merge_add(cup->cu_cmh, cup->cu_ctfp)) != 0) {
		return (ctf_dwarf_error(cup, NULL, ret,
		    "failed to add inputs for merge"));
	}

	ctf_dprintf("starting dedup of %s\n", name);
	if ((ret = ctf_merge_dedup(cup->cu_cmh, &dedup)) != 0) {
		return (ctf_dwarf_error(cup, NULL, ret,
		    "failed to deduplicate die"));
	}

	ctf_close(cup->cu_ctfp);
	cup->cu_ctfp = dedup;
	ctf_phase_dump(cup->cu_ctfp, "post-dwarf-dedup", name);

	return (0);
}

static void
ctf_dwarf_free_die(ctf_cu_t *cup)
{
	ctf_dwfunc_t *cdf, *ndf;
	ctf_dwvar_t *cdv, *ndv;
	ctf_dwbitf_t *cdb, *ndb;
	ctf_dwmap_t *map;
	void *cookie;

	ctf_dprintf("Beginning to free die: %p\n", cup);

	VERIFY3P(cup->cu_elf, !=, NULL);
	cup->cu_elf = NULL;

	ctf_dprintf("Trying to free name: %p\n", cup->cu_name);
	if (cup->cu_name != NULL) {
		ctf_strfree(cup->cu_name);
		cup->cu_name = NULL;
	}

	ctf_dprintf("Trying to free merge handle: %p\n", cup->cu_cmh);
	if (cup->cu_cmh != NULL) {
		ctf_merge_fini(cup->cu_cmh);
		cup->cu_cmh = NULL;
	}

	ctf_dprintf("Trying to free functions\n");
	for (cdf = ctf_list_next(&cup->cu_funcs); cdf != NULL; cdf = ndf) {
		ndf = ctf_list_next(cdf);
		ctf_strfree(cdf->cdf_name);
		if (cdf->cdf_fip.ctc_argc != 0) {
			ctf_free(cdf->cdf_argv,
			    sizeof (ctf_id_t) * cdf->cdf_fip.ctc_argc);
		}
		ctf_free(cdf, sizeof (ctf_dwfunc_t));
	}

	ctf_dprintf("Trying to free variables\n");
	for (cdv = ctf_list_next(&cup->cu_vars); cdv != NULL; cdv = ndv) {
		ndv = ctf_list_next(cdv);
		ctf_strfree(cdv->cdv_name);
		ctf_free(cdv, sizeof (ctf_dwvar_t));
	}

	ctf_dprintf("Trying to free bitfields\n");
	for (cdb = ctf_list_next(&cup->cu_bitfields); cdb != NULL; cdb = ndb) {
		ndb = ctf_list_next(cdb);
		ctf_free(cdb, sizeof (ctf_dwbitf_t));
	}

	if (cup->cu_ctfp != NULL) {
		ctf_close(cup->cu_ctfp);
		cup->cu_ctfp = NULL;
	}

	cookie = NULL;
	while ((map = avl_destroy_nodes(&cup->cu_map, &cookie)) != NULL)
		ctf_free(map, sizeof (ctf_dwmap_t));
	avl_destroy(&cup->cu_map);
	cup->cu_errbuf = NULL;

	if (cup->cu_cu != NULL) {
		ctf_dwarf_dealloc(cup, cup->cu_cu, DW_DLA_DIE);
		cup->cu_cu = NULL;
	}
}

static int
ctf_dwarf_count_dies(Dwarf_Debug dw, Dwarf_Error *derr, uint_t *ndies,
    char *errbuf, size_t errlen)
{
	int ret;
	Dwarf_Half vers;
	Dwarf_Unsigned nexthdr;

	while ((ret = dwarf_next_cu_header(dw, NULL, &vers, NULL, NULL,
	    &nexthdr, derr)) != DW_DLV_NO_ENTRY) {
		if (ret != DW_DLV_OK) {
			(void) snprintf(errbuf, errlen,
			    "file does not contain valid DWARF data: %s\n",
			    dwarf_errmsg(*derr));
			return (ECTF_CONVBKERR);
		}

		switch (vers) {
		case DWARF_VERSION_TWO:
		case DWARF_VERSION_FOUR:
			break;
		default:
			(void) snprintf(errbuf, errlen,
			    "unsupported DWARF version: %d\n", vers);
			return (ECTF_CONVBKERR);
		}
		*ndies = *ndies + 1;
	}

	return (0);
}

/*
 * Fill out just enough of each ctf_cu_t for the conversion process to
 * be able to finish the rest in a (potentially) multithreaded context.
 */
static int
ctf_dwarf_preinit_dies(ctf_convert_t *cch, int fd, Elf *elf, Dwarf_Debug dw,
    mutex_t *dwlock, Dwarf_Error *derr, uint_t ndies, ctf_cu_t *cdies,
    char *errbuf, size_t errlen)
{
	Dwarf_Unsigned hdrlen, abboff, nexthdr;
	Dwarf_Half addrsz, vers;
	Dwarf_Unsigned offset = 0;
	uint_t added = 0;
	int ret, i = 0;

	while ((ret = dwarf_next_cu_header(dw, &hdrlen, &vers, &abboff,
	    &addrsz, &nexthdr, derr)) != DW_DLV_NO_ENTRY) {
		Dwarf_Die cu;
		ctf_cu_t *cup;
		char *name;

		VERIFY3U(i, <, ndies);

		cup = &cdies[i++];

		cup->cu_handle = cch;
		cup->cu_fd = fd;
		cup->cu_elf = elf;
		cup->cu_dwarf = dw;
		cup->cu_errbuf = errbuf;
		cup->cu_errlen = errlen;
		cup->cu_dwarf = dw;
		if (ndies > 1) {
			/*
			 * Only need to lock calls into libdwarf if there are
			 * multiple CUs.
			 */
			cup->cu_dwlock = dwlock;
			cup->cu_doweaks = B_FALSE;
		} else {
			cup->cu_doweaks = B_TRUE;
		}

		cup->cu_voidtid = CTF_ERR;
		cup->cu_longtid = CTF_ERR;
		cup->cu_cuoff = offset;
		cup->cu_maxoff = nexthdr - 1;
		cup->cu_vers = vers;
		cup->cu_addrsz = addrsz;

		if ((ret = ctf_dwarf_sib(cup, NULL, &cu)) != 0) {
			ctf_dprintf("cu %d - no cu %d\n", i, ret);
			return (ret);
		}

		if (cu == NULL) {
			ctf_dprintf("cu %d - no cu data\n", i);
			(void) snprintf(cup->cu_errbuf, cup->cu_errlen,
			    "file does not contain DWARF data\n");
			return (ECTF_CONVNODEBUG);
		}

		if (ctf_dwarf_string(cup, cu, DW_AT_name, &name) == 0) {
			char *b = basename(name);

			cup->cu_name = strdup(b);
			ctf_strfree(name);
			if (cup->cu_name == NULL)
				return (ENOMEM);
		}

		ret = ctf_dwarf_child(cup, cu, &cup->cu_cu);
		dwarf_dealloc(cup->cu_dwarf, cu, DW_DLA_DIE);
		if (ret != 0) {
			ctf_dprintf("cu %d - no child '%s' %d\n",
			    i, cup->cu_name != NULL ? cup->cu_name : "NULL",
			    ret);
			return (ret);
		}

		if (cup->cu_cu == NULL) {
			size_t len;

			ctf_dprintf("cu %d - no child data '%s' %d\n",
			    i, cup->cu_name != NULL ? cup->cu_name : "NULL",
			    ret);
			if (cup->cu_name != NULL &&
			    (len = strlen(cup->cu_name)) > 2 &&
			    strncmp(".c", &cup->cu_name[len - 2], 2) == 0) {
				/*
				 * Missing DEBUG data for a .c file, return an
				 * error unless this is permitted.
				 */
				if (!(cch->cch_flags &
				    CTF_ALLOW_MISSING_DEBUG)) {
					(void) snprintf(
					    cup->cu_errbuf, cup->cu_errlen,
					    "missing debug information "
					    "(first seen in %s)\n",
					    cup->cu_name);
					return (ECTF_CONVNODEBUG);
				}
				if (cch->cch_warncb != NULL) {
					cch->cch_warncb(cch->cch_warncb_arg,
					    "file %s is missing debug "
					    "information\n", cup->cu_name);
				}
			}
		} else {
			added++;
		}

		ctf_dprintf("Pre-initialised cu %d - '%s'\n", i,
		    cup->cu_name != NULL ? cup->cu_name : "NULL");

		offset = nexthdr;
	}

	/*
	 * If none of the CUs had debug data, return an error.
	 */
	if (added == 0)
		return (ECTF_CONVNODEBUG);

	return (0);
}

static int
ctf_dwarf_init_die(ctf_cu_t *cup)
{
	int ret;

	cup->cu_ctfp = ctf_fdcreate(cup->cu_fd, &ret);
	if (cup->cu_ctfp == NULL)
		return (ret);

	avl_create(&cup->cu_map, ctf_dwmap_comp, sizeof (ctf_dwmap_t),
	    offsetof(ctf_dwmap_t, cdm_avl));

	if ((ret = ctf_dwarf_die_elfenc(cup->cu_elf, cup,
	    cup->cu_errbuf, cup->cu_errlen)) != 0) {
		return (ret);
	}

	if ((cup->cu_cmh = ctf_merge_init(cup->cu_fd, &ret)) == NULL)
		return (ret);

	return (0);
}

/*
 * This is our only recourse to identify a C source file that is missing debug
 * info: it will be mentioned as an STT_FILE, but not have a compile unit entry.
 * (A traditional ctfmerge works on individual files, so can identify missing
 * DWARF more directly, via ctf_has_c_source() on the .o file.)
 *
 * As we operate on basenames, this can of course miss some cases, but it's
 * better than not checking at all.
 *
 * We explicitly whitelist some CRT components.  Failing that, there's always
 * the -m option.
 */
static boolean_t
c_source_has_debug(ctf_convert_t *cch, const char *file,
    ctf_cu_t *cus, size_t nr_cus)
{
	const char *basename = strrchr(file, '/');
	ctf_convert_filelist_t *ccf;

	if (basename == NULL)
		basename = file;
	else
		basename++;

	if (strcmp(basename, "common-crt.c") == 0 ||
	    strcmp(basename, "gmon.c") == 0 ||
	    strcmp(basename, "dlink_init.c") == 0 ||
	    strcmp(basename, "dlink_common.c") == 0 ||
	    strcmp(basename, "ssp_ns.c") == 0 ||
	    strncmp(basename, "crt", strlen("crt")) == 0 ||
	    strncmp(basename, "values-", strlen("values-")) == 0)
		return (B_TRUE);

	for (ccf = list_head(&cch->cch_nodebug); ccf != NULL;
	    ccf = list_next(&cch->cch_nodebug, ccf)) {
		if (ccf->ccf_basename != NULL &&
		    strcmp(basename, ccf->ccf_basename) == 0) {
			return (B_TRUE);
		}
	}

	for (size_t i = 0; i < nr_cus; i++) {
		if (cus[i].cu_name != NULL &&
		    strcmp(basename, cus[i].cu_name) == 0) {
			return (B_TRUE);
		}
	}

	return (B_FALSE);
}

static int
ctf_dwarf_check_missing(ctf_convert_t *cch, ctf_cu_t *cus, size_t nr_cus,
    Elf *elf, char *errmsg, size_t errlen)
{
	Elf_Scn *scn, *strscn;
	Elf_Data *data, *strdata;
	GElf_Shdr shdr;
	ulong_t i;
	int ret = 0;

	scn = NULL;
	while ((scn = elf_nextscn(elf, scn)) != NULL) {
		if (gelf_getshdr(scn, &shdr) == NULL) {
			(void) snprintf(errmsg, errlen,
			    "failed to get section header: %s\n",
			    elf_errmsg(elf_errno()));
			return (EINVAL);
		}

		if (shdr.sh_type == SHT_SYMTAB)
			break;
	}

	if (scn == NULL)
		return (0);

	if ((strscn = elf_getscn(elf, shdr.sh_link)) == NULL) {
		(void) snprintf(errmsg, errlen,
		    "failed to get str section: %s\n",
		    elf_errmsg(elf_errno()));
		return (EINVAL);
	}

	if ((data = elf_getdata(scn, NULL)) == NULL) {
		(void) snprintf(errmsg, errlen, "failed to read section: %s\n",
		    elf_errmsg(elf_errno()));
		return (EINVAL);
	}

	if ((strdata = elf_getdata(strscn, NULL)) == NULL) {
		(void) snprintf(errmsg, errlen,
		    "failed to read string table: %s\n",
		    elf_errmsg(elf_errno()));
		return (EINVAL);
	}

	for (i = 0; i < shdr.sh_size / shdr.sh_entsize; i++) {
		GElf_Sym sym;
		const char *file;
		size_t len;

		if (gelf_getsym(data, i, &sym) == NULL) {
			(void) snprintf(errmsg, errlen,
			    "failed to read sym %lu: %s\n",
			    i, elf_errmsg(elf_errno()));
			return (EINVAL);
		}

		if (GELF_ST_TYPE(sym.st_info) != STT_FILE)
			continue;

		file = (const char *)((uintptr_t)strdata->d_buf + sym.st_name);
		len = strlen(file);
		if (len < 2 || strncmp(".c", &file[len - 2], 2) != 0)
			continue;

		if (!c_source_has_debug(cch, file, cus, nr_cus)) {
			if (cch->cch_warncb != NULL) {
				cch->cch_warncb(
				    cch->cch_warncb_arg,
				    "file %s is missing debug information\n",
				    file);
			}
			if (ret != ECTF_CONVNODEBUG) {
				(void) snprintf(errmsg, errlen,
				    "missing debug information "
				    "(first seen in %s)\n", file);
				ret = ECTF_CONVNODEBUG;
			}
		}
	}

	return (ret);
}

static int
ctf_dwarf_convert_batch(uint_t start, uint_t end, int fd, uint_t nthrs,
    workq_t *wqp, ctf_cu_t *cdies, ctf_file_t **fpp)
{
	ctf_file_t *fpprev = NULL;
	uint_t i, added;
	ctf_cu_t *cup;
	int ret, err;

	ctf_dprintf("Processing CU batch %u - %u\n", start, end - 1);

	added = 0;
	for (i = start; i < end; i++) {
		cup = &cdies[i];
		if (cup->cu_cu == NULL)
			continue;
		ctf_dprintf("adding cu %s: %p, %x %x\n",
		    cup->cu_name != NULL ? cup->cu_name : "NULL",
		    cup->cu_cu, cup->cu_cuoff, cup->cu_maxoff);
		if (workq_add(wqp, cup) == -1) {
			err = errno;
			goto out;
		}
		added++;
	}

	/*
	 * No debug data found in this batch, move on to the next.
	 * NB:	ctf_dwarf_preinit_dies() has already checked that there is at
	 *	least one CU with debug data present.
	 */
	if (added == 0) {
		err = 0;
		goto out;
	}

	ctf_dprintf("Running conversion phase\n");

	/* Run the conversions */
	ret = workq_work(wqp, ctf_dwarf_convert_one, NULL, &err);
	if (ret == WORKQ_ERROR) {
		err = errno;
		goto out;
	} else if (ret == WORKQ_UERROR) {
		ctf_dprintf("internal convert failed: %s\n",
		    ctf_errmsg(err));
		goto out;
	}

	ctf_dprintf("starting merge phase\n");

	ctf_merge_t *cmp = ctf_merge_init(fd, &err);
	if (cmp == NULL)
		goto out;

	if ((err = ctf_merge_set_nthreads(cmp, nthrs)) != 0) {
		ctf_merge_fini(cmp);
		goto out;
	}

	/*
	 * If we have the result of a previous merge then add it as an input to
	 * the next one.
	 */
	if (*fpp != NULL) {
		ctf_dprintf("adding previous merge CU\n");
		fpprev = *fpp;
		*fpp = NULL;
		if ((err = ctf_merge_add(cmp, fpprev)) != 0) {
			ctf_merge_fini(cmp);
			goto out;
		}
	}

	ctf_dprintf("adding CUs to merge\n");
	for (i = start; i < end; i++) {
		cup = &cdies[i];
		if (cup->cu_cu == NULL)
			continue;
		if ((err = ctf_merge_add(cmp, cup->cu_ctfp)) != 0) {
			ctf_merge_fini(cmp);
			*fpp = NULL;
			goto out;
		}
	}

	ctf_dprintf("performing merge\n");
	err = ctf_merge_merge(cmp, fpp);
	if (err != 0) {
		ctf_dprintf("failed merge!\n");
		*fpp = NULL;
		ctf_merge_fini(cmp);
		goto out;
	}

	ctf_merge_fini(cmp);

	ctf_dprintf("freeing CUs\n");
	for (i = start; i < end; i++) {
		cup = &cdies[i];
		ctf_dprintf("freeing cu %d\n", i);
		ctf_dwarf_free_die(cup);
	}

out:
	ctf_close(fpprev);
	return (err);
}

int
ctf_dwarf_convert(ctf_convert_t *cch, int fd, Elf *elf, ctf_file_t **fpp,
    char *errbuf, size_t errlen)
{
	int err, ret;
	uint_t ndies, i, bsize, nthrs;
	Dwarf_Debug dw;
	Dwarf_Error derr;
	ctf_cu_t *cdies = NULL, *cup;
	workq_t *wqp = NULL;
	mutex_t dwlock = ERRORCHECKMUTEX;

	*fpp = NULL;

	ret = dwarf_elf_init(elf, DW_DLC_READ, NULL, NULL, &dw, &derr);
	if (ret != DW_DLV_OK) {
		if (ret == DW_DLV_NO_ENTRY ||
		    dwarf_errno(derr) == DW_DLE_DEBUG_INFO_NULL) {
			(void) snprintf(errbuf, errlen,
			    "file does not contain DWARF data\n");
			return (ECTF_CONVNODEBUG);
		}

		(void) snprintf(errbuf, errlen,
		    "dwarf_elf_init() failed: %s\n", dwarf_errmsg(derr));
		return (ECTF_CONVBKERR);
	}

	/*
	 * Iterate over all of the compilation units and create a ctf_cu_t for
	 * each of them.  This is used to determine if we have zero, one, or
	 * multiple dies to convert. If we have zero, that's an error. If
	 * there's only one die, that's the simple case.  No merge needed and
	 * only a single Dwarf_Debug as well.
	 */
	ndies = 0;
	err = ctf_dwarf_count_dies(dw, &derr, &ndies, errbuf, errlen);

	ctf_dprintf("found %d DWARF CUs\n", ndies);

	if (ndies == 0) {
		(void) snprintf(errbuf, errlen,
		    "file does not contain DWARF data\n");
		(void) dwarf_finish(dw, &derr);
		return (ECTF_CONVNODEBUG);
	}

	cdies = ctf_alloc(sizeof (ctf_cu_t) * ndies);
	if (cdies == NULL) {
		(void) dwarf_finish(dw, &derr);
		return (ENOMEM);
	}

	bzero(cdies, sizeof (ctf_cu_t) * ndies);

	if ((err = ctf_dwarf_preinit_dies(cch, fd, elf, dw, &dwlock, &derr,
	    ndies, cdies, errbuf, errlen)) != 0) {
		goto out;
	}

	if ((err = ctf_dwarf_check_missing(cch, cdies, ndies, elf,
	    errbuf, errlen)) != 0) {
		if (!(cch->cch_flags & CTF_ALLOW_MISSING_DEBUG)) {
			goto out;
		}
		if (err != ECTF_CONVNODEBUG && *errbuf != '\0' &&
		    cch->cch_warncb != NULL) {
			cch->cch_warncb(cch->cch_warncb_arg, "%s", errbuf);
			*errbuf = '\0';
		}
	}

	/* Only one cu, no merge required */
	if (ndies == 1) {
		cup = cdies;

		if ((err = ctf_dwarf_convert_one(cup, NULL)) != 0)
			goto out;

		*fpp = cup->cu_ctfp;
		cup->cu_ctfp = NULL;
		ctf_dwarf_free_die(cup);
		goto success;
	}

	/*
	 * There's no need to have either more threads or a batch size larger
	 * than the total number of dies, even if the user requested them.
	 */
	nthrs = min(ndies, cch->cch_nthreads);
	bsize = min(ndies, cch->cch_batchsize);

	if (workq_init(&wqp, nthrs) == -1) {
		err = errno;
		goto out;
	}

	/*
	 * In order to avoid exhausting memory limits when converting files
	 * with a large number of dies, we process them in batches.
	 */
	for (i = 0; i < ndies; i += bsize) {
		err = ctf_dwarf_convert_batch(i, min(i + bsize, ndies),
		    fd, nthrs, wqp, cdies, fpp);
		if (err != 0) {
			*fpp = NULL;
			goto out;
		}
	}

success:
	err = 0;
	ctf_dprintf("successfully converted!\n");

out:
	(void) dwarf_finish(dw, &derr);
	workq_fini(wqp);
	ctf_free(cdies, sizeof (ctf_cu_t) * ndies);
	return (err);
}