summaryrefslogtreecommitdiff
path: root/usr/src/lib/libproc/common/Psymtab.c
blob: 7527c7e10ccf33d3f8db74bc582a512c4de4a4a2 (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
/*
 * 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 (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
 * Copyright 2016 Joyent, Inc.
 * Copyright (c) 2013 by Delphix. All rights reserved.
 * Copyright 2021 Oxide Computer Company
 */

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <unistd.h>
#include <ctype.h>
#include <fcntl.h>
#include <string.h>
#include <strings.h>
#include <memory.h>
#include <errno.h>
#include <dirent.h>
#include <signal.h>
#include <limits.h>
#include <libgen.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/sysmacros.h>
#include <sys/crc32.h>

#include "libproc.h"
#include "Pcontrol.h"
#include "Putil.h"
#include "Psymtab_machelf.h"

static file_info_t *build_map_symtab(struct ps_prochandle *, map_info_t *);
static map_info_t *exec_map(struct ps_prochandle *);
static map_info_t *object_to_map(struct ps_prochandle *, Lmid_t, const char *);
static map_info_t *object_name_to_map(struct ps_prochandle *,
	Lmid_t, const char *);
static GElf_Sym *sym_by_name(sym_tbl_t *, const char *, GElf_Sym *, uint_t *);
static int read_ehdr32(struct ps_prochandle *, Elf32_Ehdr *, uint_t *,
    uintptr_t);
#ifdef _LP64
static int read_ehdr64(struct ps_prochandle *, Elf64_Ehdr *, uint_t *,
    uintptr_t);
#endif
static uint32_t psym_crc32[] = { CRC32_TABLE };

#define	DATA_TYPES	\
	((1 << STT_OBJECT) | (1 << STT_FUNC) | \
	(1 << STT_COMMON) | (1 << STT_TLS))
#define	IS_DATA_TYPE(tp)	(((1 << (tp)) & DATA_TYPES) != 0)

#define	MA_RWX	(MA_READ | MA_WRITE | MA_EXEC)

/*
 * Minimum and maximum length of a build-id that we'll accept. Generally it's a
 * 20 byte SHA1 and it's expected that the first byte (which is two ascii
 * characters) indicates a directory and the remaining bytes become the file
 * name. Therefore, our minimum length is at least 2 bytes (one for the
 * directory and one for the name) and the max is a bit over the minimum -- 64,
 * just in case folks do something odd. The string length is three times the max
 * length. This accounts for the fact that each byte is two characters, a null
 * terminator, and the directory '/' character.
 */
#define	MINBUILDID	2
#define	MAXBUILDID	64
#define	BUILDID_STRLEN	(3*MAXBUILDID)
#define	BUILDID_NAME	".note.gnu.build-id"
#define	DBGLINK_NAME	".gnu_debuglink"

typedef enum {
	PRO_NATURAL,
	PRO_BYADDR,
	PRO_BYNAME
} pr_order_t;

static int
addr_cmp(const void *aa, const void *bb)
{
	uintptr_t a = *((uintptr_t *)aa);
	uintptr_t b = *((uintptr_t *)bb);

	if (a > b)
		return (1);
	if (a < b)
		return (-1);
	return (0);
}

/*
 * This function creates a list of addresses for a load object's sections.
 * The list is in ascending address order and alternates start address
 * then end address for each section we're interested in. The function
 * returns a pointer to the list, which must be freed by the caller.
 */
static uintptr_t *
get_saddrs(struct ps_prochandle *P, uintptr_t ehdr_start, uint_t *n)
{
	uintptr_t a, addr, *addrs, last = 0;
	uint_t i, naddrs = 0, unordered = 0;

	if (P->status.pr_dmodel == PR_MODEL_ILP32) {
		Elf32_Ehdr ehdr;
		Elf32_Phdr phdr;
		uint_t phnum;

		if (read_ehdr32(P, &ehdr, &phnum, ehdr_start) != 0)
			return (NULL);

		addrs = malloc(sizeof (uintptr_t) * phnum * 2);
		a = ehdr_start + ehdr.e_phoff;
		for (i = 0; i < phnum; i++, a += ehdr.e_phentsize) {
			if (Pread(P, &phdr, sizeof (phdr), a) !=
			    sizeof (phdr)) {
				free(addrs);
				return (NULL);
			}
			if (phdr.p_type != PT_LOAD || phdr.p_memsz == 0)
				continue;

			addr = phdr.p_vaddr;
			if (ehdr.e_type == ET_DYN)
				addr += ehdr_start;
			if (last > addr)
				unordered = 1;
			addrs[naddrs++] = addr;
			addrs[naddrs++] = last = addr + phdr.p_memsz - 1;
		}
#ifdef _LP64
	} else {
		Elf64_Ehdr ehdr;
		Elf64_Phdr phdr;
		uint_t phnum;

		if (read_ehdr64(P, &ehdr, &phnum, ehdr_start) != 0)
			return (NULL);

		addrs = malloc(sizeof (uintptr_t) * phnum * 2);
		a = ehdr_start + ehdr.e_phoff;
		for (i = 0; i < phnum; i++, a += ehdr.e_phentsize) {
			if (Pread(P, &phdr, sizeof (phdr), a) !=
			    sizeof (phdr)) {
				free(addrs);
				return (NULL);
			}
			if (phdr.p_type != PT_LOAD || phdr.p_memsz == 0)
				continue;

			addr = phdr.p_vaddr;
			if (ehdr.e_type == ET_DYN)
				addr += ehdr_start;
			if (last > addr)
				unordered = 1;
			addrs[naddrs++] = addr;
			addrs[naddrs++] = last = addr + phdr.p_memsz - 1;
		}
#endif
	}

	if (unordered)
		qsort(addrs, naddrs, sizeof (uintptr_t), addr_cmp);

	*n = naddrs;
	return (addrs);
}

/*
 * Allocation function for a new file_info_t
 */
file_info_t *
file_info_new(struct ps_prochandle *P, map_info_t *mptr)
{
	file_info_t *fptr;
	map_info_t *mp;
	uintptr_t mstart, mend, sstart, send;
	uint_t i;

	if ((fptr = calloc(1, sizeof (file_info_t))) == NULL)
		return (NULL);

	list_insert_tail(&P->file_head, fptr);
	(void) strcpy(fptr->file_pname, mptr->map_pmap.pr_mapname);
	mptr->map_file = fptr;
	fptr->file_ref = 1;
	fptr->file_fd = -1;
	fptr->file_dbgfile = -1;
	P->num_files++;

	/*
	 * To figure out which map_info_t instances correspond to the mappings
	 * for this load object we try to obtain the start and end address
	 * for each section of our in-memory ELF image. If successful, we
	 * walk down the list of addresses and the list of map_info_t
	 * instances in lock step to correctly find the mappings that
	 * correspond to this load object.
	 */
	if ((fptr->file_saddrs = get_saddrs(P, mptr->map_pmap.pr_vaddr,
	    &fptr->file_nsaddrs)) == NULL)
		return (fptr);

	mp = P->mappings;
	i = 0;
	while (mp < P->mappings + P->map_count && i < fptr->file_nsaddrs) {

		/* Calculate the start and end of the mapping and section */
		mstart = mp->map_pmap.pr_vaddr;
		mend = mp->map_pmap.pr_vaddr + mp->map_pmap.pr_size;
		sstart = fptr->file_saddrs[i];
		send = fptr->file_saddrs[i + 1];

		if (mend <= sstart) {
			/* This mapping is below the current section */
			mp++;
		} else if (mstart >= send) {
			/* This mapping is above the current section */
			i += 2;
		} else {
			/* This mapping overlaps the current section */
			if (mp->map_file == NULL) {
				dprintf("file_info_new: associating "
				    "segment at %p\n",
				    (void *)mp->map_pmap.pr_vaddr);
				mp->map_file = fptr;
				fptr->file_ref++;
			} else {
				dprintf("file_info_new: segment at %p "
				    "already associated with %s\n",
				    (void *)mp->map_pmap.pr_vaddr,
				    (mp == mptr ? "this file" :
				    mp->map_file->file_pname));
			}
			mp++;
		}
	}

	return (fptr);
}

/*
 * Deallocation function for a file_info_t
 */
static void
file_info_free(struct ps_prochandle *P, file_info_t *fptr)
{
	if (--fptr->file_ref == 0) {
		list_remove(&P->file_head, fptr);
		if (fptr->file_symtab.sym_elf) {
			(void) elf_end(fptr->file_symtab.sym_elf);
			free(fptr->file_symtab.sym_elfmem);
		}
		if (fptr->file_symtab.sym_byname)
			free(fptr->file_symtab.sym_byname);
		if (fptr->file_symtab.sym_byaddr)
			free(fptr->file_symtab.sym_byaddr);

		if (fptr->file_dynsym.sym_elf) {
			(void) elf_end(fptr->file_dynsym.sym_elf);
			free(fptr->file_dynsym.sym_elfmem);
		}
		if (fptr->file_dynsym.sym_byname)
			free(fptr->file_dynsym.sym_byname);
		if (fptr->file_dynsym.sym_byaddr)
			free(fptr->file_dynsym.sym_byaddr);

		if (fptr->file_lo)
			free(fptr->file_lo);
		if (fptr->file_lname)
			free(fptr->file_lname);
		if (fptr->file_rname)
			free(fptr->file_rname);
		if (fptr->file_elf)
			(void) elf_end(fptr->file_elf);
		if (fptr->file_elfmem != NULL)
			free(fptr->file_elfmem);
		if (fptr->file_fd >= 0)
			(void) close(fptr->file_fd);
		if (fptr->file_dbgelf)
			(void) elf_end(fptr->file_dbgelf);
		if (fptr->file_dbgfile >= 0)
			(void) close(fptr->file_dbgfile);
		ctf_close(fptr->file_ctfp);
		free(fptr->file_ctf_buf);
		if (fptr->file_saddrs)
			free(fptr->file_saddrs);
		free(fptr);
		P->num_files--;
	}
}

/*
 * Deallocation function for a map_info_t
 */
static void
map_info_free(struct ps_prochandle *P, map_info_t *mptr)
{
	file_info_t *fptr;

	if ((fptr = mptr->map_file) != NULL) {
		if (fptr->file_map == mptr)
			fptr->file_map = NULL;
		file_info_free(P, fptr);
	}
	if (P->execname && mptr == P->map_exec) {
		free(P->execname);
		P->execname = NULL;
	}
	if (P->auxv && (mptr == P->map_exec || mptr == P->map_ldso)) {
		free(P->auxv);
		P->auxv = NULL;
		P->nauxv = 0;
	}
	if (mptr == P->map_exec)
		P->map_exec = NULL;
	if (mptr == P->map_ldso)
		P->map_ldso = NULL;
}

/*
 * Call-back function for librtld_db to iterate through all of its shared
 * libraries.  We use this to get the load object names for the mappings.
 */
static int
map_iter(const rd_loadobj_t *lop, void *cd)
{
	char buf[PATH_MAX];
	struct ps_prochandle *P = cd;
	map_info_t *mptr;
	file_info_t *fptr;

	dprintf("encountered rd object at %p\n", (void *)lop->rl_base);

	if ((mptr = Paddr2mptr(P, lop->rl_base)) == NULL) {
		dprintf("map_iter: base address doesn't match any mapping\n");
		return (1); /* Base address does not match any mapping */
	}

	if ((fptr = mptr->map_file) == NULL &&
	    (fptr = file_info_new(P, mptr)) == NULL) {
		dprintf("map_iter: failed to allocate a new file_info_t\n");
		return (1); /* Failed to allocate a new file_info_t */
	}

	if ((fptr->file_lo == NULL) &&
	    (fptr->file_lo = malloc(sizeof (rd_loadobj_t))) == NULL) {
		dprintf("map_iter: failed to allocate rd_loadobj_t\n");
		file_info_free(P, fptr);
		return (1); /* Failed to allocate rd_loadobj_t */
	}

	fptr->file_map = mptr;
	*fptr->file_lo = *lop;

	fptr->file_lo->rl_plt_base = fptr->file_plt_base;
	fptr->file_lo->rl_plt_size = fptr->file_plt_size;

	if (fptr->file_lname) {
		free(fptr->file_lname);
		fptr->file_lname = NULL;
		fptr->file_lbase = NULL;
	}
	if (fptr->file_rname) {
		free(fptr->file_rname);
		fptr->file_rname = NULL;
		fptr->file_rbase = NULL;
	}

	if (Pread_string(P, buf, sizeof (buf), lop->rl_nameaddr) > 0) {
		if ((fptr->file_lname = strdup(buf)) != NULL)
			fptr->file_lbase = basename(fptr->file_lname);
	} else {
		dprintf("map_iter: failed to read string at %p\n",
		    (void *)lop->rl_nameaddr);
	}

	if ((Pfindmap(P, mptr, buf, sizeof (buf)) != NULL) &&
	    ((fptr->file_rname = strdup(buf)) != NULL))
		fptr->file_rbase = basename(fptr->file_rname);

	dprintf("loaded rd object %s lmid %lx\n",
	    fptr->file_lname ? buf : "<NULL>", lop->rl_lmident);
	return (1);
}

static void
map_set(struct ps_prochandle *P, map_info_t *mptr, const char *lname)
{
	file_info_t *fptr;
	char buf[PATH_MAX];

	if ((fptr = mptr->map_file) == NULL &&
	    (fptr = file_info_new(P, mptr)) == NULL)
		return; /* Failed to allocate a new file_info_t */

	fptr->file_map = mptr;

	if ((fptr->file_lo == NULL) &&
	    (fptr->file_lo = malloc(sizeof (rd_loadobj_t))) == NULL) {
		file_info_free(P, fptr);
		return; /* Failed to allocate rd_loadobj_t */
	}

	(void) memset(fptr->file_lo, 0, sizeof (rd_loadobj_t));
	fptr->file_lo->rl_base = mptr->map_pmap.pr_vaddr;
	fptr->file_lo->rl_bend =
	    mptr->map_pmap.pr_vaddr + mptr->map_pmap.pr_size;

	fptr->file_lo->rl_plt_base = fptr->file_plt_base;
	fptr->file_lo->rl_plt_size = fptr->file_plt_size;

	if ((fptr->file_lname == NULL) &&
	    (fptr->file_lname = strdup(lname)) != NULL)
		fptr->file_lbase = basename(fptr->file_lname);

	if ((Pfindmap(P, mptr, buf, sizeof (buf)) != NULL) &&
	    ((fptr->file_rname = strdup(buf)) != NULL))
		fptr->file_rbase = basename(fptr->file_rname);
}

static void
load_static_maps(struct ps_prochandle *P)
{
	map_info_t *mptr;

	/*
	 * Construct the map for the a.out.
	 */
	if ((mptr = object_name_to_map(P, PR_LMID_EVERY, PR_OBJ_EXEC)) != NULL)
		map_set(P, mptr, "a.out");

	/*
	 * If the dynamic linker exists for this process,
	 * construct the map for it.
	 */
	if (Pgetauxval(P, AT_BASE) != -1L &&
	    (mptr = object_name_to_map(P, PR_LMID_EVERY, PR_OBJ_LDSO)) != NULL)
		map_set(P, mptr, "ld.so.1");
}

int
Preadmaps(struct ps_prochandle *P, prmap_t **Pmapp, ssize_t *nmapp)
{
	return (P->ops.pop_read_maps(P, Pmapp, nmapp, P->data));
}

/*
 * Go through all the address space mappings, validating or updating
 * the information already gathered, or gathering new information.
 *
 * This function is only called when we suspect that the mappings have changed
 * because this is the first time we're calling it or because of rtld activity.
 */
void
Pupdate_maps(struct ps_prochandle *P)
{
	prmap_t *Pmap = NULL;
	prmap_t *pmap;
	ssize_t nmap;
	int i;
	uint_t oldmapcount;
	map_info_t *newmap, *newp;
	map_info_t *mptr;

	if (P->info_valid || P->state == PS_UNDEAD)
		return;

	Preadauxvec(P);

	if (Preadmaps(P, &Pmap, &nmap) != 0)
		return;

	if ((newmap = calloc(1, nmap * sizeof (map_info_t))) == NULL)
		return;

	/*
	 * We try to merge any file information we may have for existing
	 * mappings, to avoid having to rebuild the file info.
	 */
	mptr = P->mappings;
	pmap = Pmap;
	newp = newmap;
	oldmapcount = P->map_count;
	for (i = 0; i < nmap; i++, pmap++, newp++) {

		if (oldmapcount == 0) {
			/*
			 * We've exhausted all the old mappings.  Every new
			 * mapping should be added.
			 */
			newp->map_pmap = *pmap;

		} else if (pmap->pr_vaddr == mptr->map_pmap.pr_vaddr &&
		    pmap->pr_size == mptr->map_pmap.pr_size &&
		    pmap->pr_offset == mptr->map_pmap.pr_offset &&
		    (pmap->pr_mflags & ~(MA_BREAK | MA_STACK)) ==
		    (mptr->map_pmap.pr_mflags & ~(MA_BREAK | MA_STACK)) &&
		    pmap->pr_pagesize == mptr->map_pmap.pr_pagesize &&
		    pmap->pr_shmid == mptr->map_pmap.pr_shmid &&
		    strcmp(pmap->pr_mapname, mptr->map_pmap.pr_mapname) == 0) {

			/*
			 * This mapping matches exactly.  Copy over the old
			 * mapping, taking care to get the latest flags.
			 * Make sure the associated file_info_t is updated
			 * appropriately.
			 */
			*newp = *mptr;
			if (P->map_exec == mptr)
				P->map_exec = newp;
			if (P->map_ldso == mptr)
				P->map_ldso = newp;
			newp->map_pmap.pr_mflags = pmap->pr_mflags;
			if (mptr->map_file != NULL &&
			    mptr->map_file->file_map == mptr)
				mptr->map_file->file_map = newp;
			oldmapcount--;
			mptr++;

		} else if (pmap->pr_vaddr + pmap->pr_size >
		    mptr->map_pmap.pr_vaddr) {

			/*
			 * The old mapping doesn't exist any more, remove it
			 * from the list.
			 */
			map_info_free(P, mptr);
			oldmapcount--;
			i--;
			newp--;
			pmap--;
			mptr++;

		} else {

			/*
			 * This is a new mapping, add it directly.
			 */
			newp->map_pmap = *pmap;
		}
	}

	/*
	 * Free any old maps
	 */
	while (oldmapcount) {
		map_info_free(P, mptr);
		oldmapcount--;
		mptr++;
	}

	free(Pmap);
	if (P->mappings != NULL)
		free(P->mappings);
	P->mappings = newmap;
	P->map_count = P->map_alloc = nmap;
	P->info_valid = 1;

	/*
	 * Consult librtld_db to get the load object
	 * names for all of the shared libraries.
	 */
	if (P->rap != NULL)
		(void) rd_loadobj_iter(P->rap, map_iter, P);
}

/*
 * Update all of the mappings and rtld_db as if by Pupdate_maps(), and then
 * forcibly cache all of the symbol tables associated with all object files.
 */
void
Pupdate_syms(struct ps_prochandle *P)
{
	file_info_t *fptr;

	Pupdate_maps(P);

	for (fptr = list_head(&P->file_head); fptr != NULL;
	    fptr = list_next(&P->file_head, fptr)) {
		Pbuild_file_symtab(P, fptr);
		(void) Pbuild_file_ctf(P, fptr);
	}
}

/*
 * Return the librtld_db agent handle for the victim process.
 * The handle will become invalid at the next successful exec() and the
 * client (caller of proc_rd_agent()) must not use it beyond that point.
 * If the process is already dead, we've already tried our best to
 * create the agent during core file initialization.
 */
rd_agent_t *
Prd_agent(struct ps_prochandle *P)
{
	if (P->rap == NULL && P->state != PS_DEAD && P->state != PS_IDLE) {
		Pupdate_maps(P);
		if (P->num_files == 0)
			load_static_maps(P);
		rd_log(_libproc_debug);
		if ((P->rap = rd_new(P)) != NULL)
			(void) rd_loadobj_iter(P->rap, map_iter, P);
	}
	return (P->rap);
}

/*
 * Return the prmap_t structure containing 'addr', but only if it
 * is in the dynamic linker's link map and is the text section.
 */
const prmap_t *
Paddr_to_text_map(struct ps_prochandle *P, uintptr_t addr)
{
	map_info_t *mptr;

	if (!P->info_valid)
		Pupdate_maps(P);

	if ((mptr = Paddr2mptr(P, addr)) != NULL) {
		file_info_t *fptr = build_map_symtab(P, mptr);
		const prmap_t *pmp = &mptr->map_pmap;

		/*
		 * Assume that if rl_data_base is NULL, it means that no
		 * data section was found for this load object, and that
		 * a section must be text. Otherwise, a section will be
		 * text unless it ends above the start of the data
		 * section.
		 */
		if (fptr != NULL && fptr->file_lo != NULL &&
		    (fptr->file_lo->rl_data_base == (uintptr_t)NULL ||
		    pmp->pr_vaddr + pmp->pr_size <=
		    fptr->file_lo->rl_data_base))
			return (pmp);
	}

	return (NULL);
}

/*
 * Return the prmap_t structure containing 'addr' (no restrictions on
 * the type of mapping).
 */
const prmap_t *
Paddr_to_map(struct ps_prochandle *P, uintptr_t addr)
{
	map_info_t *mptr;

	if (!P->info_valid)
		Pupdate_maps(P);

	if ((mptr = Paddr2mptr(P, addr)) != NULL)
		return (&mptr->map_pmap);

	return (NULL);
}

/*
 * Convert a full or partial load object name to the prmap_t for its
 * corresponding primary text mapping.
 */
const prmap_t *
Plmid_to_map(struct ps_prochandle *P, Lmid_t lmid, const char *name)
{
	map_info_t *mptr;

	if (name == PR_OBJ_EVERY)
		return (NULL); /* A reasonable mistake */

	if ((mptr = object_name_to_map(P, lmid, name)) != NULL)
		return (&mptr->map_pmap);

	return (NULL);
}

const prmap_t *
Pname_to_map(struct ps_prochandle *P, const char *name)
{
	return (Plmid_to_map(P, PR_LMID_EVERY, name));
}

const rd_loadobj_t *
Paddr_to_loadobj(struct ps_prochandle *P, uintptr_t addr)
{
	map_info_t *mptr;

	if (!P->info_valid)
		Pupdate_maps(P);

	if ((mptr = Paddr2mptr(P, addr)) == NULL)
		return (NULL);

	/*
	 * By building the symbol table, we implicitly bring the PLT
	 * information up to date in the load object.
	 */
	(void) build_map_symtab(P, mptr);

	return (mptr->map_file->file_lo);
}

const rd_loadobj_t *
Plmid_to_loadobj(struct ps_prochandle *P, Lmid_t lmid, const char *name)
{
	map_info_t *mptr;

	if (name == PR_OBJ_EVERY)
		return (NULL);

	if ((mptr = object_name_to_map(P, lmid, name)) == NULL)
		return (NULL);

	/*
	 * By building the symbol table, we implicitly bring the PLT
	 * information up to date in the load object.
	 */
	(void) build_map_symtab(P, mptr);

	return (mptr->map_file->file_lo);
}

const rd_loadobj_t *
Pname_to_loadobj(struct ps_prochandle *P, const char *name)
{
	return (Plmid_to_loadobj(P, PR_LMID_EVERY, name));
}

/*
 * We've been given a file_info_t which doesn't have any CTF. However, it may
 * have information that's in a format that we could convert if on the fly.
 * We'll first try to convert the alternate debug file, if present, and then
 * move onto the default file. The reason we prefer the alternate debug file is
 * that if both exist, then it likely has any usable debugging information.
 */
static ctf_file_t *
Pconvert_file_ctf(file_info_t *fptr)
{
	int err;
	ctf_convert_t *cch;
	ctf_file_t *fp;
	char errmsg[1024];

	/*
	 * Provide an opt in.
	 */
	if (getenv("LIBPROC_CTFCONVERT") == NULL)
		return (NULL);

	/*
	 * If we've already attempted to call this, then that's it. No reason to
	 * pretend we'll be more successful again another time.
	 */
	if (fptr->file_cvt == B_TRUE)
		return (NULL);

	cch = ctf_convert_init(&err);
	if (cch == NULL)
		return (NULL);

	fptr->file_cvt = B_TRUE;

	fp = NULL;
	if (fptr->file_dbgelf != NULL) {
		fp = ctf_elfconvert(cch, fptr->file_fd, fptr->file_dbgelf, &err,
		    errmsg, sizeof (errmsg));
		if (fp == NULL) {
			dprintf("failed to convert %s: %s\n", fptr->file_pname,
			    err == ECTF_CONVBKERR ? errmsg : ctf_errmsg(err));
		}
	}
	if (fp == NULL) {
		fp = ctf_elfconvert(cch, fptr->file_fd, fptr->file_elf, &err,
		    errmsg, sizeof (errmsg));
		if (fp == NULL) {
			dprintf("failed to convert %s: %s\n", fptr->file_pname,
			    err == ECTF_CONVBKERR ? errmsg : ctf_errmsg(err));
		}
	}
	if (fp != NULL) {
		fptr->file_ctfp = fp;
	}

	ctf_convert_fini(cch);
	return (NULL);
}

ctf_file_t *
Pbuild_file_ctf(struct ps_prochandle *P, file_info_t *fptr)
{
	ctf_sect_t ctdata, symtab, strtab;
	sym_tbl_t *symp;
	int err;

	if (fptr->file_ctfp != NULL)
		return (fptr->file_ctfp);

	Pbuild_file_symtab(P, fptr);

	if (fptr->file_ctf_size == 0) {
		return (Pconvert_file_ctf(fptr));
	}

	symp = fptr->file_ctf_dyn ? &fptr->file_dynsym : &fptr->file_symtab;
	if (symp->sym_data_pri == NULL)
		return (NULL);

	/*
	 * The buffer may alread be allocated if this is a core file that
	 * contained CTF data for this file.
	 */
	if (fptr->file_ctf_buf == NULL) {
		fptr->file_ctf_buf = malloc(fptr->file_ctf_size);
		if (fptr->file_ctf_buf == NULL) {
			dprintf("failed to allocate ctf buffer\n");
			return (NULL);
		}

		if (pread(fptr->file_fd, fptr->file_ctf_buf,
		    fptr->file_ctf_size, fptr->file_ctf_off) !=
		    fptr->file_ctf_size) {
			free(fptr->file_ctf_buf);
			fptr->file_ctf_buf = NULL;
			dprintf("failed to read ctf data\n");
			return (NULL);
		}
	}

	ctdata.cts_name = ".SUNW_ctf";
	ctdata.cts_type = SHT_PROGBITS;
	ctdata.cts_flags = 0;
	ctdata.cts_data = fptr->file_ctf_buf;
	ctdata.cts_size = fptr->file_ctf_size;
	ctdata.cts_entsize = 1;
	ctdata.cts_offset = 0;

	symtab.cts_name = fptr->file_ctf_dyn ? ".dynsym" : ".symtab";
	symtab.cts_type = symp->sym_hdr_pri.sh_type;
	symtab.cts_flags = symp->sym_hdr_pri.sh_flags;
	symtab.cts_data = symp->sym_data_pri->d_buf;
	symtab.cts_size = symp->sym_hdr_pri.sh_size;
	symtab.cts_entsize = symp->sym_hdr_pri.sh_entsize;
	symtab.cts_offset = symp->sym_hdr_pri.sh_offset;

	strtab.cts_name = fptr->file_ctf_dyn ? ".dynstr" : ".strtab";
	strtab.cts_type = symp->sym_strhdr.sh_type;
	strtab.cts_flags = symp->sym_strhdr.sh_flags;
	strtab.cts_data = symp->sym_strs;
	strtab.cts_size = symp->sym_strhdr.sh_size;
	strtab.cts_entsize = symp->sym_strhdr.sh_entsize;
	strtab.cts_offset = symp->sym_strhdr.sh_offset;

	fptr->file_ctfp = ctf_bufopen(&ctdata, &symtab, &strtab, &err);
	if (fptr->file_ctfp == NULL) {
		dprintf("ctf_bufopen() failed, error code %d\n", err);
		free(fptr->file_ctf_buf);
		fptr->file_ctf_buf = NULL;
		return (NULL);
	}

	dprintf("loaded %lu bytes of CTF data for %s\n",
	    (ulong_t)fptr->file_ctf_size, fptr->file_pname);

	return (fptr->file_ctfp);
}

ctf_file_t *
Paddr_to_ctf(struct ps_prochandle *P, uintptr_t addr)
{
	map_info_t *mptr;
	file_info_t *fptr;

	if (!P->info_valid)
		Pupdate_maps(P);

	if ((mptr = Paddr2mptr(P, addr)) == NULL ||
	    (fptr = mptr->map_file) == NULL)
		return (NULL);

	return (Pbuild_file_ctf(P, fptr));
}

ctf_file_t *
Plmid_to_ctf(struct ps_prochandle *P, Lmid_t lmid, const char *name)
{
	map_info_t *mptr;
	file_info_t *fptr = NULL;

	if (name == PR_OBJ_EVERY)
		return (NULL);

	/*
	 * While most idle files are all ELF objects, not all of them have
	 * mapping information available. There's nothing which would make
	 * sense to fake up for ET_REL. Instead, if we're being asked for their
	 * executable object and we know that the information is valid and they
	 * only have a single file, we jump straight to that file pointer.
	 */
	if (P->state == PS_IDLE && name == PR_OBJ_EXEC && P->info_valid == 1 &&
	    P->num_files == 1 && P->mappings == NULL) {
		fptr = list_head(&P->file_head);
	}

	if (fptr == NULL) {
		if ((mptr = object_name_to_map(P, lmid, name)) == NULL ||
		    (fptr = mptr->map_file) == NULL)
			return (NULL);
	}

	return (Pbuild_file_ctf(P, fptr));
}

ctf_file_t *
Pname_to_ctf(struct ps_prochandle *P, const char *name)
{
	return (Plmid_to_ctf(P, PR_LMID_EVERY, name));
}

void
Preadauxvec(struct ps_prochandle *P)
{
	if (P->auxv != NULL) {
		free(P->auxv);
		P->auxv = NULL;
		P->nauxv = 0;
	}

	P->ops.pop_read_aux(P, &P->auxv, &P->nauxv, P->data);
}

/*
 * Return a requested element from the process's aux vector.
 * Return -1 on failure (this is adequate for our purposes).
 */
long
Pgetauxval(struct ps_prochandle *P, int type)
{
	auxv_t *auxv;

	if (P->auxv == NULL)
		Preadauxvec(P);

	if (P->auxv == NULL)
		return (-1);

	for (auxv = P->auxv; auxv->a_type != AT_NULL; auxv++) {
		if (auxv->a_type == type)
			return (auxv->a_un.a_val);
	}

	return (-1);
}

/*
 * Return a pointer to our internal copy of the process's aux vector.
 * The caller should not hold on to this pointer across any libproc calls.
 */
const auxv_t *
Pgetauxvec(struct ps_prochandle *P)
{
	static const auxv_t empty = { AT_NULL, 0L };

	if (P->auxv == NULL)
		Preadauxvec(P);

	if (P->auxv == NULL)
		return (&empty);

	return (P->auxv);
}

/*
 * Return 1 if the given mapping corresponds to the given file_info_t's
 * load object; return 0 otherwise.
 */
static int
is_mapping_in_file(struct ps_prochandle *P, map_info_t *mptr, file_info_t *fptr)
{
	prmap_t *pmap = &mptr->map_pmap;
	rd_loadobj_t *lop = fptr->file_lo;
	uint_t i;
	uintptr_t mstart, mend, sstart, send;

	/*
	 * We can get for free the start address of the text and data
	 * sections of the load object. Start by seeing if the mapping
	 * encloses either of these.
	 */
	if ((pmap->pr_vaddr <= lop->rl_base &&
	    lop->rl_base < pmap->pr_vaddr + pmap->pr_size) ||
	    (pmap->pr_vaddr <= lop->rl_data_base &&
	    lop->rl_data_base < pmap->pr_vaddr + pmap->pr_size))
		return (1);

	/*
	 * It's still possible that this mapping correponds to the load
	 * object. Consider the example of a mapping whose start and end
	 * addresses correspond to those of the load object's text section.
	 * If the mapping splits, e.g. as a result of a segment demotion,
	 * then although both mappings are still backed by the same section,
	 * only one will be seen to enclose that section's start address.
	 * Thus, to be rigorous, we ask not whether this mapping encloses
	 * the start of a section, but whether there exists a section that
	 * overlaps this mapping.
	 *
	 * If we don't already have the section addresses, and we successfully
	 * get them, then we cache them in case we come here again.
	 */
	if (fptr->file_saddrs == NULL &&
	    (fptr->file_saddrs = get_saddrs(P,
	    fptr->file_map->map_pmap.pr_vaddr, &fptr->file_nsaddrs)) == NULL)
		return (0);

	mstart = mptr->map_pmap.pr_vaddr;
	mend = mptr->map_pmap.pr_vaddr + mptr->map_pmap.pr_size;
	for (i = 0; i < fptr->file_nsaddrs; i += 2) {
		/* Does this section overlap the mapping? */
		sstart = fptr->file_saddrs[i];
		send = fptr->file_saddrs[i + 1];
		if (!(mend <= sstart || mstart >= send))
			return (1);
	}

	return (0);
}

/*
 * Find or build the symbol table for the given mapping.
 */
static file_info_t *
build_map_symtab(struct ps_prochandle *P, map_info_t *mptr)
{
	prmap_t *pmap = &mptr->map_pmap;
	file_info_t *fptr;

	if ((fptr = mptr->map_file) != NULL) {
		Pbuild_file_symtab(P, fptr);
		return (fptr);
	}

	if (pmap->pr_mapname[0] == '\0')
		return (NULL);

	/*
	 * Attempt to find a matching file.
	 * (A file can be mapped at several different addresses.)
	 */
	for (fptr = list_head(&P->file_head); fptr != NULL;
	    fptr = list_next(&P->file_head, fptr)) {
		if (strcmp(fptr->file_pname, pmap->pr_mapname) == 0 &&
		    fptr->file_lo && is_mapping_in_file(P, mptr, fptr)) {
			mptr->map_file = fptr;
			fptr->file_ref++;
			Pbuild_file_symtab(P, fptr);
			return (fptr);
		}
	}

	/*
	 * If we need to create a new file_info structure, iterate
	 * through the load objects in order to attempt to connect
	 * this new file with its primary text mapping.  We again
	 * need to handle ld.so as a special case because we need
	 * to be able to bootstrap librtld_db.
	 */
	if ((fptr = file_info_new(P, mptr)) == NULL)
		return (NULL);

	if (P->map_ldso != mptr) {
		if (P->rap != NULL)
			(void) rd_loadobj_iter(P->rap, map_iter, P);
		else
			(void) Prd_agent(P);
	} else {
		fptr->file_map = mptr;
	}

	/*
	 * If librtld_db wasn't able to help us connect the file to a primary
	 * text mapping, set file_map to the current mapping because we require
	 * fptr->file_map to be set in Pbuild_file_symtab.  librtld_db may be
	 * unaware of what's going on in the rare case that a legitimate ELF
	 * file has been mmap(2)ed into the process address space *without*
	 * the use of dlopen(3x).
	 */
	if (fptr->file_map == NULL)
		fptr->file_map = mptr;

	Pbuild_file_symtab(P, fptr);

	return (fptr);
}

static int
read_ehdr32(struct ps_prochandle *P, Elf32_Ehdr *ehdr, uint_t *phnum,
    uintptr_t addr)
{
	if (Pread(P, ehdr, sizeof (*ehdr), addr) != sizeof (*ehdr))
		return (-1);

	if (ehdr->e_ident[EI_MAG0] != ELFMAG0 ||
	    ehdr->e_ident[EI_MAG1] != ELFMAG1 ||
	    ehdr->e_ident[EI_MAG2] != ELFMAG2 ||
	    ehdr->e_ident[EI_MAG3] != ELFMAG3 ||
	    ehdr->e_ident[EI_CLASS] != ELFCLASS32 ||
#ifdef _BIG_ENDIAN
	    ehdr->e_ident[EI_DATA] != ELFDATA2MSB ||
#else
	    ehdr->e_ident[EI_DATA] != ELFDATA2LSB ||
#endif
	    ehdr->e_ident[EI_VERSION] != EV_CURRENT)
		return (-1);

	if ((*phnum = ehdr->e_phnum) == PN_XNUM) {
		Elf32_Shdr shdr0;

		if (ehdr->e_shoff == 0 || ehdr->e_shentsize < sizeof (shdr0) ||
		    Pread(P, &shdr0, sizeof (shdr0), addr + ehdr->e_shoff) !=
		    sizeof (shdr0))
			return (-1);

		if (shdr0.sh_info != 0)
			*phnum = shdr0.sh_info;
	}

	return (0);
}

static int
read_dynamic_phdr32(struct ps_prochandle *P, const Elf32_Ehdr *ehdr,
    uint_t phnum, Elf32_Phdr *phdr, uintptr_t addr)
{
	uint_t i;

	for (i = 0; i < phnum; i++) {
		uintptr_t a = addr + ehdr->e_phoff + i * ehdr->e_phentsize;
		if (Pread(P, phdr, sizeof (*phdr), a) != sizeof (*phdr))
			return (-1);

		if (phdr->p_type == PT_DYNAMIC)
			return (0);
	}

	return (-1);
}

#ifdef _LP64
static int
read_ehdr64(struct ps_prochandle *P, Elf64_Ehdr *ehdr, uint_t *phnum,
    uintptr_t addr)
{
	if (Pread(P, ehdr, sizeof (Elf64_Ehdr), addr) != sizeof (Elf64_Ehdr))
		return (-1);

	if (ehdr->e_ident[EI_MAG0] != ELFMAG0 ||
	    ehdr->e_ident[EI_MAG1] != ELFMAG1 ||
	    ehdr->e_ident[EI_MAG2] != ELFMAG2 ||
	    ehdr->e_ident[EI_MAG3] != ELFMAG3 ||
	    ehdr->e_ident[EI_CLASS] != ELFCLASS64 ||
#ifdef _BIG_ENDIAN
	    ehdr->e_ident[EI_DATA] != ELFDATA2MSB ||
#else
	    ehdr->e_ident[EI_DATA] != ELFDATA2LSB ||
#endif
	    ehdr->e_ident[EI_VERSION] != EV_CURRENT)
		return (-1);

	if ((*phnum = ehdr->e_phnum) == PN_XNUM) {
		Elf64_Shdr shdr0;

		if (ehdr->e_shoff == 0 || ehdr->e_shentsize < sizeof (shdr0) ||
		    Pread(P, &shdr0, sizeof (shdr0), addr + ehdr->e_shoff) !=
		    sizeof (shdr0))
			return (-1);

		if (shdr0.sh_info != 0)
			*phnum = shdr0.sh_info;
	}

	return (0);
}

static int
read_dynamic_phdr64(struct ps_prochandle *P, const Elf64_Ehdr *ehdr,
    uint_t phnum, Elf64_Phdr *phdr, uintptr_t addr)
{
	uint_t i;

	for (i = 0; i < phnum; i++) {
		uintptr_t a = addr + ehdr->e_phoff + i * ehdr->e_phentsize;
		if (Pread(P, phdr, sizeof (*phdr), a) != sizeof (*phdr))
			return (-1);

		if (phdr->p_type == PT_DYNAMIC)
			return (0);
	}

	return (-1);
}
#endif	/* _LP64 */

/*
 * The text segment for each load object contains the elf header and
 * program headers. We can use this information to determine if the
 * file that corresponds to the load object is the same file that
 * was loaded into the process's address space. There can be a discrepency
 * if a file is recompiled after the process is started or if the target
 * represents a core file from a differently configured system -- two
 * common examples. The DT_CHECKSUM entry in the dynamic section
 * provides an easy method of comparison. It is important to note that
 * the dynamic section usually lives in the data segment, but the meta
 * data we use to find the dynamic section lives in the text segment so
 * if either of those segments is absent we can't proceed.
 *
 * We're looking through the elf file for several items: the symbol tables
 * (both dynsym and symtab), the procedure linkage table (PLT) base,
 * size, and relocation base, and the CTF information. Most of this can
 * be recovered from the loaded image of the file itself, the exceptions
 * being the symtab and CTF data.
 *
 * First we try to open the file that we think corresponds to the load
 * object, if the DT_CHECKSUM values match, we're all set, and can simply
 * recover all the information we need from the file. If the values of
 * DT_CHECKSUM don't match, or if we can't access the file for whatever
 * reasaon, we fake up a elf file to use in its stead. If we can't read
 * the elf data in the process's address space, we fall back to using
 * the file even though it may give inaccurate information.
 *
 * The elf file that we fake up has to consist of sections for the
 * dynsym, the PLT and the dynamic section. Note that in the case of a
 * core file, we'll get the CTF data in the file_info_t later on from
 * a section embedded the core file (if it's present).
 *
 * file_differs() conservatively looks for mismatched files, identifying
 * a match when there is any ambiguity (since that's the legacy behavior).
 */
static int
file_differs(struct ps_prochandle *P, Elf *elf, file_info_t *fptr)
{
	Elf_Scn *scn;
	GElf_Shdr shdr;
	GElf_Dyn dyn;
	Elf_Data *data;
	uint_t i, ndyn;
	GElf_Xword cksum;
	uintptr_t addr;

	if (fptr->file_map == NULL)
		return (0);

	if ((Pcontent(P) & (CC_CONTENT_TEXT | CC_CONTENT_DATA)) !=
	    (CC_CONTENT_TEXT | CC_CONTENT_DATA))
		return (0);

	/*
	 * First, we find the checksum value in the elf file.
	 */
	scn = NULL;
	while ((scn = elf_nextscn(elf, scn)) != NULL) {
		if (gelf_getshdr(scn, &shdr) != NULL &&
		    shdr.sh_type == SHT_DYNAMIC)
			goto found_shdr;
	}
	return (0);

found_shdr:
	if ((data = elf_getdata(scn, NULL)) == NULL)
		return (0);

	if (P->status.pr_dmodel == PR_MODEL_ILP32)
		ndyn = shdr.sh_size / sizeof (Elf32_Dyn);
#ifdef _LP64
	else if (P->status.pr_dmodel == PR_MODEL_LP64)
		ndyn = shdr.sh_size / sizeof (Elf64_Dyn);
#endif
	else
		return (0);

	for (i = 0; i < ndyn; i++) {
		if (gelf_getdyn(data, i, &dyn) != NULL &&
		    dyn.d_tag == DT_CHECKSUM)
			goto found_cksum;
	}

	/*
	 * The in-memory ELF has no DT_CHECKSUM section, but we will report it
	 * as matching the file anyhow.
	 */
	return (0);

found_cksum:
	cksum = dyn.d_un.d_val;
	dprintf("elf cksum value is %llx\n", (u_longlong_t)cksum);

	/*
	 * Get the base of the text mapping that corresponds to this file.
	 */
	addr = fptr->file_map->map_pmap.pr_vaddr;

	if (P->status.pr_dmodel == PR_MODEL_ILP32) {
		Elf32_Ehdr ehdr;
		Elf32_Phdr phdr;
		Elf32_Dyn dync, *dynp;
		uint_t phnum, i;

		if (read_ehdr32(P, &ehdr, &phnum, addr) != 0 ||
		    read_dynamic_phdr32(P, &ehdr, phnum, &phdr, addr) != 0)
			return (0);

		if (ehdr.e_type == ET_DYN)
			phdr.p_vaddr += addr;
		if ((dynp = malloc(phdr.p_filesz)) == NULL)
			return (0);
		dync.d_tag = DT_NULL;
		if (Pread(P, dynp, phdr.p_filesz, phdr.p_vaddr) !=
		    phdr.p_filesz) {
			free(dynp);
			return (0);
		}

		for (i = 0; i < phdr.p_filesz / sizeof (Elf32_Dyn); i++) {
			if (dynp[i].d_tag == DT_CHECKSUM)
				dync = dynp[i];
		}

		free(dynp);

		if (dync.d_tag != DT_CHECKSUM)
			return (0);

		dprintf("image cksum value is %llx\n",
		    (u_longlong_t)dync.d_un.d_val);
		return (dync.d_un.d_val != cksum);
#ifdef _LP64
	} else if (P->status.pr_dmodel == PR_MODEL_LP64) {
		Elf64_Ehdr ehdr;
		Elf64_Phdr phdr;
		Elf64_Dyn dync, *dynp;
		uint_t phnum, i;

		if (read_ehdr64(P, &ehdr, &phnum, addr) != 0 ||
		    read_dynamic_phdr64(P, &ehdr, phnum, &phdr, addr) != 0)
			return (0);

		if (ehdr.e_type == ET_DYN)
			phdr.p_vaddr += addr;
		if ((dynp = malloc(phdr.p_filesz)) == NULL)
			return (0);
		dync.d_tag = DT_NULL;
		if (Pread(P, dynp, phdr.p_filesz, phdr.p_vaddr) !=
		    phdr.p_filesz) {
			free(dynp);
			return (0);
		}

		for (i = 0; i < phdr.p_filesz / sizeof (Elf64_Dyn); i++) {
			if (dynp[i].d_tag == DT_CHECKSUM)
				dync = dynp[i];
		}

		free(dynp);

		if (dync.d_tag != DT_CHECKSUM)
			return (0);

		dprintf("image cksum value is %llx\n",
		    (u_longlong_t)dync.d_un.d_val);
		return (dync.d_un.d_val != cksum);
#endif	/* _LP64 */
	}

	return (0);
}

/*
 * Read data from the specified process and construct an in memory
 * image of an ELF file that represents it well enough to let
 * us probe it for information.
 */
static Elf *
fake_elf(struct ps_prochandle *P, file_info_t *fptr)
{
	Elf *elf;
	uintptr_t addr;
	uint_t phnum;

	if (fptr->file_map == NULL)
		return (NULL);

	if ((Pcontent(P) & (CC_CONTENT_TEXT | CC_CONTENT_DATA)) !=
	    (CC_CONTENT_TEXT | CC_CONTENT_DATA))
		return (NULL);

	addr = fptr->file_map->map_pmap.pr_vaddr;

	if (P->status.pr_dmodel == PR_MODEL_ILP32) {
		Elf32_Ehdr ehdr;
		Elf32_Phdr phdr;

		if ((read_ehdr32(P, &ehdr, &phnum, addr) != 0) ||
		    read_dynamic_phdr32(P, &ehdr, phnum, &phdr, addr) != 0)
			return (NULL);

		elf = fake_elf32(P, fptr, addr, &ehdr, phnum, &phdr);
#ifdef _LP64
	} else {
		Elf64_Ehdr ehdr;
		Elf64_Phdr phdr;

		if (read_ehdr64(P, &ehdr, &phnum, addr) != 0 ||
		    read_dynamic_phdr64(P, &ehdr, phnum, &phdr, addr) != 0)
			return (NULL);

		elf = fake_elf64(P, fptr, addr, &ehdr, phnum, &phdr);
#endif
	}

	return (elf);
}

/*
 * We wouldn't need these if qsort(3C) took an argument for the callback...
 */
static mutex_t sort_mtx = DEFAULTMUTEX;
static char *sort_strs;
static GElf_Sym *sort_syms;

int
byaddr_cmp_common(GElf_Sym *a, char *aname, GElf_Sym *b, char *bname)
{
	if (a->st_value < b->st_value)
		return (-1);
	if (a->st_value > b->st_value)
		return (1);

	/*
	 * Prefer the function to the non-function.
	 */
	if (GELF_ST_TYPE(a->st_info) != GELF_ST_TYPE(b->st_info)) {
		if (GELF_ST_TYPE(a->st_info) == STT_FUNC)
			return (-1);
		if (GELF_ST_TYPE(b->st_info) == STT_FUNC)
			return (1);
	}

	/*
	 * Prefer the weak or strong global symbol to the local symbol.
	 */
	if (GELF_ST_BIND(a->st_info) != GELF_ST_BIND(b->st_info)) {
		if (GELF_ST_BIND(b->st_info) == STB_LOCAL)
			return (-1);
		if (GELF_ST_BIND(a->st_info) == STB_LOCAL)
			return (1);
	}

	/*
	 * Prefer the symbol that doesn't begin with a '$' since compilers and
	 * other symbol generators often use it as a prefix.
	 */
	if (*bname == '$')
		return (-1);
	if (*aname == '$')
		return (1);

	/*
	 * Prefer the name with fewer leading underscores in the name.
	 */
	while (*aname == '_' && *bname == '_') {
		aname++;
		bname++;
	}

	if (*bname == '_')
		return (-1);
	if (*aname == '_')
		return (1);

	/*
	 * Prefer the symbol with the smaller size.
	 */
	if (a->st_size < b->st_size)
		return (-1);
	if (a->st_size > b->st_size)
		return (1);

	/*
	 * All other factors being equal, fall back to lexicographic order.
	 */
	return (strcmp(aname, bname));
}

static int
byaddr_cmp(const void *aa, const void *bb)
{
	GElf_Sym *a = &sort_syms[*(uint_t *)aa];
	GElf_Sym *b = &sort_syms[*(uint_t *)bb];
	char *aname = sort_strs + a->st_name;
	char *bname = sort_strs + b->st_name;

	return (byaddr_cmp_common(a, aname, b, bname));
}

static int
byname_cmp(const void *aa, const void *bb)
{
	GElf_Sym *a = &sort_syms[*(uint_t *)aa];
	GElf_Sym *b = &sort_syms[*(uint_t *)bb];
	char *aname = sort_strs + a->st_name;
	char *bname = sort_strs + b->st_name;

	return (strcmp(aname, bname));
}

/*
 * Given a symbol index, look up the corresponding symbol from the
 * given symbol table.
 *
 * This function allows the caller to treat the symbol table as a single
 * logical entity even though there may be 2 actual ELF symbol tables
 * involved. See the comments in Pcontrol.h for details.
 */
static GElf_Sym *
symtab_getsym(sym_tbl_t *symtab, int ndx, GElf_Sym *dst)
{
	/* If index is in range of primary symtab, look it up there */
	if (ndx >= symtab->sym_symn_aux) {
		return (gelf_getsym(symtab->sym_data_pri,
		    ndx - symtab->sym_symn_aux, dst));
	}

	/* Not in primary: Look it up in the auxiliary symtab */
	return (gelf_getsym(symtab->sym_data_aux, ndx, dst));
}

void
optimize_symtab(sym_tbl_t *symtab)
{
	GElf_Sym *symp, *syms;
	uint_t i, *indexa, *indexb;
	size_t symn, strsz, count;

	if (symtab == NULL || symtab->sym_data_pri == NULL ||
	    symtab->sym_byaddr != NULL)
		return;

	symn = symtab->sym_symn;
	strsz = symtab->sym_strsz;

	symp = syms = malloc(sizeof (GElf_Sym) * symn);
	if (symp == NULL) {
		dprintf("optimize_symtab: failed to malloc symbol array");
		return;
	}

	/*
	 * First record all the symbols into a table and count up the ones
	 * that we're interested in. We mark symbols as invalid by setting
	 * the st_name to an illegal value.
	 */
	for (i = 0, count = 0; i < symn; i++, symp++) {
		if (symtab_getsym(symtab, i, symp) != NULL &&
		    symp->st_name < strsz &&
		    IS_DATA_TYPE(GELF_ST_TYPE(symp->st_info)))
			count++;
		else
			symp->st_name = strsz;
	}

	/*
	 * Allocate sufficient space for both tables and populate them
	 * with the same symbols we just counted.
	 */
	symtab->sym_count = count;
	indexa = symtab->sym_byaddr = calloc(sizeof (uint_t), count);
	indexb = symtab->sym_byname = calloc(sizeof (uint_t), count);
	if (indexa == NULL || indexb == NULL) {
		dprintf(
		    "optimize_symtab: failed to malloc symbol index arrays");
		symtab->sym_count = 0;
		if (indexa != NULL) {	/* First alloc succeeded. Free it */
			free(indexa);
			symtab->sym_byaddr = NULL;
		}
		free(syms);
		return;
	}
	for (i = 0, symp = syms; i < symn; i++, symp++) {
		if (symp->st_name < strsz)
			*indexa++ = *indexb++ = i;
	}

	/*
	 * Sort the two tables according to the appropriate criteria,
	 * unless the user has overridden this behaviour.
	 *
	 * An example where we might not sort the tables is the relatively
	 * unusual case of a process with very large symbol tables in which
	 * we perform few lookups. In such a case the total time would be
	 * dominated by the sort. It is difficult to determine a priori
	 * how many lookups an arbitrary client will perform, and
	 * hence whether the symbol tables should be sorted. We therefore
	 * sort the tables by default, but provide the user with a
	 * "chicken switch" in the form of the LIBPROC_NO_QSORT
	 * environment variable.
	 */
	if (!_libproc_no_qsort) {
		(void) mutex_lock(&sort_mtx);
		sort_strs = symtab->sym_strs;
		sort_syms = syms;

		qsort(symtab->sym_byaddr, count, sizeof (uint_t), byaddr_cmp);
		qsort(symtab->sym_byname, count, sizeof (uint_t), byname_cmp);

		sort_strs = NULL;
		sort_syms = NULL;
		(void) mutex_unlock(&sort_mtx);
	}

	free(syms);
}


static Elf *
build_fake_elf(struct ps_prochandle *P, file_info_t *fptr, GElf_Ehdr *ehdr,
    size_t *nshdrs, Elf_Data **shdata)
{
	size_t shstrndx;
	Elf_Scn *scn;
	Elf *elf;

	if ((elf = fake_elf(P, fptr)) == NULL ||
	    elf_kind(elf) != ELF_K_ELF ||
	    gelf_getehdr(elf, ehdr) == NULL ||
	    elf_getshdrnum(elf, nshdrs) == -1 ||
	    elf_getshdrstrndx(elf, &shstrndx) == -1 ||
	    (scn = elf_getscn(elf, shstrndx)) == NULL ||
	    (*shdata = elf_getdata(scn, NULL)) == NULL) {
		if (elf != NULL)
			(void) elf_end(elf);
		dprintf("failed to fake up ELF file\n");
		return (NULL);
	}

	return (elf);
}

/*
 * Try and find the file described by path in the file system and validate that
 * it matches our CRC before we try and process it for symbol information. If we
 * instead have an ELF data section, then that means we're checking a build-id
 * section instead. In that case we just need to find and bcmp the corresponding
 * section.
 *
 * Before we validate if it's a valid CRC or data section, we check to ensure
 * that it's a normal file and not anything else.
 */
static boolean_t
build_alt_debug(file_info_t *fptr, const char *path, uint32_t crc,
    Elf_Data *data)
{
	int fd;
	struct stat st;
	Elf *elf;
	Elf_Scn *scn;
	GElf_Shdr symshdr, strshdr;
	Elf_Data *symdata, *strdata;
	boolean_t valid;
	uint32_t c = -1U;

	if ((fd = open(path, O_RDONLY)) < 0)
		return (B_FALSE);

	if (fstat(fd, &st) != 0) {
		(void) close(fd);
		return (B_FALSE);
	}

	if (S_ISREG(st.st_mode) == 0) {
		(void) close(fd);
		return (B_FALSE);
	}

	/*
	 * Only check the CRC if we've come here through a GNU debug link
	 * section as opposed to the build id. This is indicated by having the
	 * value of data be NULL.
	 */
	if (data == NULL) {
		for (;;) {
			char buf[4096];
			ssize_t ret = read(fd, buf, sizeof (buf));
			if (ret == -1) {
				if (ret == EINTR)
					continue;
				(void) close(fd);
				return (B_FALSE);
			}
			if (ret == 0) {
				c = ~c;
				if (c != crc) {
					dprintf("crc mismatch, found: 0x%x "
					    "expected 0x%x\n", c, crc);
					(void) close(fd);
					return (B_FALSE);
				}
				break;
			}
			CRC32(c, buf, ret, c, psym_crc32);
		}
	}

	elf = elf_begin(fd, ELF_C_READ, NULL);
	if (elf == NULL) {
		(void) close(fd);
		return (B_FALSE);
	}

	if (elf_kind(elf) != ELF_K_ELF) {
		goto fail;
	}

	/*
	 * If we have a data section, that indicates we have a build-id which
	 * means we need to find the corresponding build-id section and compare
	 * it.
	 */
	scn = NULL;
	valid = B_FALSE;
	for (scn = elf_nextscn(elf, scn); data != NULL && scn != NULL;
	    scn = elf_nextscn(elf, scn)) {
		GElf_Shdr hdr;
		Elf_Data *ntdata;

		if (gelf_getshdr(scn, &hdr) == NULL)
			goto fail;

		if (hdr.sh_type != SHT_NOTE)
			continue;

		if ((ntdata = elf_getdata(scn, NULL)) == NULL)
			goto fail;

		/*
		 * First verify the data section sizes are equal, then the
		 * section name. If that's all true, then we can just do a bcmp.
		 */
		if (data->d_size != ntdata->d_size)
			continue;

		dprintf("found corresponding section in alternate file\n");
		if (bcmp(ntdata->d_buf, data->d_buf, data->d_size) != 0)
			goto fail;

		valid = B_TRUE;
		break;
	}
	if (data != NULL && valid == B_FALSE) {
		dprintf("failed to find a matching %s section in %s\n",
		    BUILDID_NAME, path);
		goto fail;
	}


	/*
	 * Do two passes, first see if we have a symbol header, then see if we
	 * can find the corresponding linked string table.
	 */
	scn = NULL;
	for (scn = elf_nextscn(elf, scn); scn != NULL;
	    scn = elf_nextscn(elf, scn)) {

		if (gelf_getshdr(scn, &symshdr) == NULL)
			goto fail;

		if (symshdr.sh_type != SHT_SYMTAB)
			continue;

		if ((symdata = elf_getdata(scn, NULL)) == NULL)
			goto fail;

		break;
	}
	if (scn == NULL)
		goto fail;

	if ((scn = elf_getscn(elf, symshdr.sh_link)) == NULL)
		goto fail;

	if (gelf_getshdr(scn, &strshdr) == NULL)
		goto fail;

	if ((strdata = elf_getdata(scn, NULL)) == NULL)
		goto fail;

	fptr->file_symtab.sym_data_pri = symdata;
	fptr->file_symtab.sym_symn += symshdr.sh_size / symshdr.sh_entsize;
	fptr->file_symtab.sym_strs = strdata->d_buf;
	fptr->file_symtab.sym_strsz = strdata->d_size;
	fptr->file_symtab.sym_hdr_pri = symshdr;
	fptr->file_symtab.sym_strhdr = strshdr;

	dprintf("successfully loaded additional debug symbols for %s from %s\n",
	    fptr->file_rname, path);

	fptr->file_dbgfile = fd;
	fptr->file_dbgelf = elf;
	return (B_TRUE);
fail:
	(void) elf_end(elf);
	(void) close(fd);
	return (B_FALSE);
}

/*
 * We're here because the object in question has no symbol information, that's a
 * bit unfortunate. However, we've found that there's a .gnu_debuglink sitting
 * around. By convention that means that given the current location of the
 * object on disk, and the debug name that we found in the binary we need to
 * search the following locations for a matching file.
 *
 * <dirname>/.debug/<debug-name>
 * /usr/lib/debug/<dirname>/<debug-name>
 *
 * In the future, we should consider supporting looking in the prefix's
 * lib/debug directory for a matching object or supporting an arbitrary user
 * defined set of places to look.
 */
static void
find_alt_debuglink(file_info_t *fptr, const char *name, uint32_t crc)
{
	boolean_t r;
	char *dup = NULL, *path = NULL, *dname;

	dprintf("find_alt_debug: looking for %s, crc 0x%x\n", name, crc);
	if (fptr->file_rname == NULL) {
		dprintf("find_alt_debug: encountered null file_rname\n");
		return;
	}

	dup = strdup(fptr->file_rname);
	if (dup == NULL)
		return;

	dname = dirname(dup);
	if (asprintf(&path, "%s/.debug/%s", dname, name) != -1) {
		dprintf("attempting to load alternate debug information "
		    "from %s\n", path);
		r = build_alt_debug(fptr, path, crc, NULL);
		free(path);
		if (r == B_TRUE)
			goto out;
	}

	if (asprintf(&path, "/usr/lib/debug/%s/%s", dname, name) != -1) {
		dprintf("attempting to load alternate debug information "
		    "from %s\n", path);
		r = build_alt_debug(fptr, path, crc, NULL);
		free(path);
		if (r == B_TRUE)
			goto out;
	}
out:
	free(dup);
}

/*
 * Build the symbol table for the given mapped file.
 */
void
Pbuild_file_symtab(struct ps_prochandle *P, file_info_t *fptr)
{
	char objectfile[PATH_MAX];
	uint_t i;

	GElf_Ehdr ehdr;
	GElf_Sym s;

	Elf_Data *shdata;
	Elf_Scn *scn;
	Elf *elf;
	size_t nshdrs, shstrndx;

	struct {
		GElf_Shdr c_shdr;
		Elf_Data *c_data;
		const char *c_name;
	} *cp, *cache = NULL, *dyn = NULL, *plt = NULL, *ctf = NULL,
	*dbglink = NULL, *buildid = NULL;

	if (fptr->file_init)
		return;	/* We've already processed this file */

	/*
	 * Mark the file_info struct as having the symbol table initialized
	 * even if we fail below.  We tried once; we don't try again.
	 */
	fptr->file_init = 1;

	if (elf_version(EV_CURRENT) == EV_NONE) {
		dprintf("libproc ELF version is more recent than libelf\n");
		return;
	}

	if (P->state == PS_DEAD || P->state == PS_IDLE) {
		char *name;
		/*
		 * If we're a not live, we can't open files from the /proc
		 * object directory; we have only the mapping and file names
		 * to guide us.  We prefer the file_lname, but need to handle
		 * the case of it being NULL in order to bootstrap: we first
		 * come here during rd_new() when the only information we have
		 * is interpreter name associated with the AT_BASE mapping.
		 *
		 * Also, if the zone associated with the core file seems
		 * to exists on this machine we'll try to open the object
		 * file within the zone.
		 */
		if (fptr->file_rname != NULL)
			name = fptr->file_rname;
		else if (fptr->file_lname != NULL)
			name = fptr->file_lname;
		else
			name = fptr->file_pname;
		(void) strlcpy(objectfile, name, sizeof (objectfile));
	} else {
		(void) snprintf(objectfile, sizeof (objectfile),
		    "%s/%d/object/%s",
		    procfs_path, (int)P->pid, fptr->file_pname);
	}

	/*
	 * Open the object file, create the elf file, and then get the elf
	 * header and .shstrtab data buffer so we can process sections by
	 * name. If anything goes wrong try to fake up an elf file from
	 * the in-core elf image.
	 */

	if (_libproc_incore_elf || (P->flags & INCORE)) {
		dprintf("Pbuild_file_symtab: using in-core data for: %s\n",
		    fptr->file_pname);

		if ((elf = build_fake_elf(P, fptr, &ehdr, &nshdrs, &shdata)) ==
		    NULL)
			return;

	} else if ((fptr->file_fd = open(objectfile, O_RDONLY)) < 0) {
		dprintf("Pbuild_file_symtab: failed to open %s: %s\n",
		    objectfile, strerror(errno));

		if ((elf = build_fake_elf(P, fptr, &ehdr, &nshdrs, &shdata)) ==
		    NULL)
			return;

	} else if ((elf = elf_begin(fptr->file_fd, ELF_C_READ, NULL)) == NULL ||
	    elf_kind(elf) != ELF_K_ELF ||
	    gelf_getehdr(elf, &ehdr) == NULL ||
	    elf_getshdrnum(elf, &nshdrs) == -1 ||
	    elf_getshdrstrndx(elf, &shstrndx) == -1 ||
	    (scn = elf_getscn(elf, shstrndx)) == NULL ||
	    (shdata = elf_getdata(scn, NULL)) == NULL) {
		int err = elf_errno();

		dprintf("failed to process ELF file %s: %s\n",
		    objectfile, (err == 0) ? "<null>" : elf_errmsg(err));
		(void) elf_end(elf);

		if ((elf = build_fake_elf(P, fptr, &ehdr, &nshdrs, &shdata)) ==
		    NULL)
			return;

	} else if (file_differs(P, elf, fptr)) {
		Elf *newelf;

		/*
		 * Before we get too excited about this elf file, we'll check
		 * its checksum value against the value we have in memory. If
		 * they don't agree, we try to fake up a new elf file and
		 * proceed with that instead.
		 */
		dprintf("ELF file %s (%lx) doesn't match in-core image\n",
		    fptr->file_pname,
		    (ulong_t)fptr->file_map->map_pmap.pr_vaddr);

		if ((newelf = build_fake_elf(P, fptr, &ehdr, &nshdrs, &shdata))
		    != NULL) {
			(void) elf_end(elf);
			elf = newelf;
			dprintf("switched to faked up ELF file\n");

			/*
			 * Check to see if the file that we just discovered
			 * to be an imposter matches the execname that was
			 * determined by Pfindexec().  If it does, we (clearly)
			 * don't have the right binary, and we zero out
			 * execname before anyone gets hurt.
			 */
			if (fptr->file_rname != NULL && P->execname != NULL &&
			    strcmp(fptr->file_rname, P->execname) == 0) {
				dprintf("file/in-core image mismatch was "
				    "on P->execname; discarding\n");
				free(P->execname);
				P->execname = NULL;
			}
		}
	}

	if ((cache = malloc(nshdrs * sizeof (*cache))) == NULL) {
		dprintf("failed to malloc section cache for %s\n", objectfile);
		goto bad;
	}

	dprintf("processing ELF file %s\n", objectfile);
	fptr->file_class = ehdr.e_ident[EI_CLASS];
	fptr->file_etype = ehdr.e_type;
	fptr->file_elf = elf;
	fptr->file_shstrs = shdata->d_buf;
	fptr->file_shstrsz = shdata->d_size;

	/*
	 * Iterate through each section, caching its section header, data
	 * pointer, and name.  We use this for handling sh_link values below.
	 */
	for (cp = cache + 1, scn = NULL; scn = elf_nextscn(elf, scn); cp++) {
		if (gelf_getshdr(scn, &cp->c_shdr) == NULL) {
			dprintf("Pbuild_file_symtab: Failed to get section "
			    "header\n");
			goto bad; /* Failed to get section header */
		}

		if ((cp->c_data = elf_getdata(scn, NULL)) == NULL) {
			dprintf("Pbuild_file_symtab: Failed to get section "
			    "data\n");
			goto bad; /* Failed to get section data */
		}

		if (cp->c_shdr.sh_name >= shdata->d_size) {
			dprintf("Pbuild_file_symtab: corrupt section name");
			goto bad; /* Corrupt section name */
		}

		cp->c_name = (const char *)shdata->d_buf + cp->c_shdr.sh_name;
	}

	/*
	 * Now iterate through the section cache in order to locate info
	 * for the .symtab, .dynsym, .SUNW_ldynsym, .dynamic, .plt,
	 * and .SUNW_ctf sections:
	 */
	for (i = 1, cp = cache + 1; i < nshdrs; i++, cp++) {
		GElf_Shdr *shp = &cp->c_shdr;

		if (shp->sh_type == SHT_SYMTAB || shp->sh_type == SHT_DYNSYM) {
			sym_tbl_t *symp = shp->sh_type == SHT_SYMTAB ?
			    &fptr->file_symtab : &fptr->file_dynsym;
			/*
			 * It's possible that the we already got the symbol
			 * table from the core file itself. Either the file
			 * differs in which case our faked up elf file will
			 * only contain the dynsym (not the symtab) or the
			 * file matches in which case we'll just be replacing
			 * the symbol table we pulled out of the core file
			 * with an equivalent one. In either case, this
			 * check isn't essential, but it's a good idea.
			 */
			if (symp->sym_data_pri == NULL) {
				dprintf("Symbol table found for %s\n",
				    objectfile);
				symp->sym_data_pri = cp->c_data;
				symp->sym_symn +=
				    shp->sh_size / shp->sh_entsize;
				symp->sym_strs =
				    cache[shp->sh_link].c_data->d_buf;
				symp->sym_strsz =
				    cache[shp->sh_link].c_data->d_size;
				symp->sym_hdr_pri = cp->c_shdr;
				symp->sym_strhdr = cache[shp->sh_link].c_shdr;
			} else {
				dprintf("Symbol table already there for %s\n",
				    objectfile);
			}
		} else if (shp->sh_type == SHT_SUNW_LDYNSYM) {
			/* .SUNW_ldynsym section is auxiliary to .dynsym */
			if (fptr->file_dynsym.sym_data_aux == NULL) {
				dprintf(".SUNW_ldynsym symbol table"
				    " found for %s\n", objectfile);
				fptr->file_dynsym.sym_data_aux = cp->c_data;
				fptr->file_dynsym.sym_symn_aux =
				    shp->sh_size / shp->sh_entsize;
				fptr->file_dynsym.sym_symn +=
				    fptr->file_dynsym.sym_symn_aux;
				fptr->file_dynsym.sym_hdr_aux = cp->c_shdr;
			} else {
				dprintf(".SUNW_ldynsym symbol table already"
				    " there for %s\n", objectfile);
			}
		} else if (shp->sh_type == SHT_DYNAMIC) {
			dyn = cp;
		} else if (strcmp(cp->c_name, ".plt") == 0) {
			plt = cp;
		} else if (strcmp(cp->c_name, ".SUNW_ctf") == 0) {
			/*
			 * Skip over bogus CTF sections so they don't come back
			 * to haunt us later.
			 */
			if (shp->sh_link == 0 ||
			    shp->sh_link >= nshdrs ||
			    (cache[shp->sh_link].c_shdr.sh_type != SHT_DYNSYM &&
			    cache[shp->sh_link].c_shdr.sh_type != SHT_SYMTAB)) {
				dprintf("Bad sh_link %d for "
				    "CTF\n", shp->sh_link);
				continue;
			}
			ctf = cp;
		} else if (strcmp(cp->c_name, BUILDID_NAME) == 0) {
			dprintf("Found a %s section for %s\n", BUILDID_NAME,
			    fptr->file_rname);
			/* The ElfXX_Nhdr is 32/64-bit neutral */
			if (cp->c_shdr.sh_type == SHT_NOTE &&
			    cp->c_data->d_buf != NULL &&
			    cp->c_data->d_size >= sizeof (Elf32_Nhdr)) {
				Elf32_Nhdr *hdr = cp->c_data->d_buf;
				if (hdr->n_type != 3)
					continue;
				if (hdr->n_namesz != 4)
					continue;
				if (hdr->n_descsz < MINBUILDID)
					continue;
				/* Set a reasonable upper bound */
				if (hdr->n_descsz > MAXBUILDID) {
					dprintf("Skipped %s as too large "
					    "(%ld)\n", BUILDID_NAME,
					    (unsigned long)hdr->n_descsz);
					continue;
				}

				if (cp->c_data->d_size < sizeof (hdr) +
				    hdr->n_namesz + hdr->n_descsz)
					continue;
				buildid = cp;
			}
		} else if (strcmp(cp->c_name, DBGLINK_NAME) == 0) {
			dprintf("found %s section for %s\n", DBGLINK_NAME,
			    fptr->file_rname);
			/*
			 * Let's make sure of a few things before we do this.
			 */
			if (cp->c_shdr.sh_type == SHT_PROGBITS &&
			    cp->c_data->d_buf != NULL &&
			    cp->c_data->d_size) {
				dbglink = cp;
			}
		}
	}

	/*
	 * If we haven't found any symbol table information and we have found
	 * either a .note.gnu.build-id or a .gnu_debuglink, it's time to try and
	 * figure out where we might find this. Originally, GNU used the
	 * .gnu_debuglink solely, but then they added a .note.gnu.build-id. The
	 * build-id is some size, usually 16 or 20 bytes, often a SHA1 sum of
	 * parts of the original file. This is maintained across all versions of
	 * the subsequent file.
	 *
	 * For the .note.gnu.build-id, we're going to check a few things before
	 * using it, first that the name is 4 bytes, and is GNU and that the
	 * type is 3, which they say is the build-id identifier.
	 *
	 * To verify that the elf data for the .gnu_debuglink seems somewhat
	 * sane, eg. the elf data should be a string, so we want to verify we
	 * have a null-terminator.
	 */
	if (fptr->file_symtab.sym_data_pri == NULL && buildid != NULL) {
		int i, bo;
		uint8_t *dp;
		char buf[BUILDID_STRLEN], *path;
		Elf32_Nhdr *hdr = buildid->c_data->d_buf;

		/*
		 * This was checked for validity when assigning the buildid
		 * variable.
		 */
		bzero(buf, sizeof (buf));
		dp = (uint8_t *)((uintptr_t)hdr + sizeof (*hdr) +
		    hdr->n_namesz);
		for (i = 0, bo = 0; i < hdr->n_descsz; i++, bo += 2, dp++) {
			assert(sizeof (buf) - bo > 0);

			/*
			 * Recall that the build-id is structured as a series of
			 * bytes. However, the first two characters are supposed
			 * to represent a directory. Hence, once we reach offset
			 * two, we insert a '/' character.
			 */
			if (bo == 2) {
				buf[bo] = '/';
				bo++;
			}
			(void) snprintf(buf + bo, sizeof (buf) - bo, "%2x",
			    *dp);
		}

		if (asprintf(&path, "/usr/lib/debug/.build-id/%s.debug",
		    buf) != -1) {
			boolean_t r;
			dprintf("attempting to find build id alternate debug "
			    "file at %s\n", path);
			r = build_alt_debug(fptr, path, 0, buildid->c_data);
			dprintf("attempt %s\n", r == B_TRUE ?
			    "succeeded" : "failed");
			free(path);
		} else {
			dprintf("failed to construct build id path: %s\n",
			    strerror(errno));
		}
	}

	if (fptr->file_symtab.sym_data_pri == NULL && dbglink != NULL) {
		char *c = dbglink->c_data->d_buf;
		size_t i;
		boolean_t found = B_FALSE;
		Elf_Data *ed = dbglink->c_data;
		uint32_t crc;

		for (i = 0; i < ed->d_size; i++) {
			if (c[i] == '\0') {
				uintptr_t off;
				dprintf("got .gnu_debuglink terminator at "
				    "offset %lu\n", (unsigned long)i);
				/*
				 * After the null terminator, there should be
				 * padding, followed by a 4 byte CRC of the
				 * file. If we don't see this, we're going to
				 * assume this is bogus.
				 */
				if ((i % sizeof (uint32_t)) == 0) {
					i += 4;
				} else {
					i += sizeof (uint32_t) -
					    (i % sizeof (uint32_t));
				}
				if (i + sizeof (uint32_t) ==
				    dbglink->c_data->d_size) {
					found = B_TRUE;
					off = (uintptr_t)ed->d_buf + i;
					crc = *(uint32_t *)off;
				} else {
					dprintf(".gnu_debuglink size mismatch, "
					    "expected: %lu, found: %lu\n",
					    (unsigned long)i,
					    (unsigned long)ed->d_size);
				}
				break;
			}
		}

		if (found == B_TRUE)
			find_alt_debuglink(fptr, dbglink->c_data->d_buf, crc);
	}

	/*
	 * At this point, we've found all the symbol tables we're ever going
	 * to find: the ones in the loop above and possibly the symtab that
	 * was included in the core file. Before we perform any lookups, we
	 * create sorted versions to optimize for lookups.
	 */
	optimize_symtab(&fptr->file_symtab);
	optimize_symtab(&fptr->file_dynsym);

	/*
	 * Fill in the base address of the text mapping for shared libraries.
	 * This allows us to translate symbols before librtld_db is ready.
	 */
	if (fptr->file_etype == ET_DYN) {
		fptr->file_dyn_base = fptr->file_map->map_pmap.pr_vaddr -
		    fptr->file_map->map_pmap.pr_offset;
		dprintf("setting file_dyn_base for %s to %lx\n",
		    objectfile, (long)fptr->file_dyn_base);
	}

	/*
	 * Record the CTF section information in the file info structure.
	 */
	if (ctf != NULL) {
		fptr->file_ctf_off = ctf->c_shdr.sh_offset;
		fptr->file_ctf_size = ctf->c_shdr.sh_size;
		if (ctf->c_shdr.sh_link != 0 &&
		    cache[ctf->c_shdr.sh_link].c_shdr.sh_type == SHT_DYNSYM)
			fptr->file_ctf_dyn = 1;
	}

	if (fptr->file_lo == NULL)
		goto done; /* Nothing else to do if no load object info */

	/*
	 * If the object is a shared library and we have a different rl_base
	 * value, reset file_dyn_base according to librtld_db's information.
	 */
	if (fptr->file_etype == ET_DYN &&
	    fptr->file_lo->rl_base != fptr->file_dyn_base) {
		dprintf("resetting file_dyn_base for %s to %lx\n",
		    objectfile, (long)fptr->file_lo->rl_base);
		fptr->file_dyn_base = fptr->file_lo->rl_base;
	}

	/*
	 * Fill in the PLT information for this file if a PLT symbol is found.
	 */
	if (sym_by_name(&fptr->file_dynsym, "_PROCEDURE_LINKAGE_TABLE_", &s,
	    NULL) != NULL) {
		fptr->file_plt_base = s.st_value + fptr->file_dyn_base;
		fptr->file_plt_size = (plt != NULL) ? plt->c_shdr.sh_size : 0;

		/*
		 * Bring the load object up to date; it is the only way the
		 * user has to access the PLT data. The PLT information in the
		 * rd_loadobj_t is not set in the call to map_iter() (the
		 * callback for rd_loadobj_iter) where we set file_lo.
		 */
		fptr->file_lo->rl_plt_base = fptr->file_plt_base;
		fptr->file_lo->rl_plt_size = fptr->file_plt_size;

		dprintf("PLT found at %p, size = %lu\n",
		    (void *)fptr->file_plt_base, (ulong_t)fptr->file_plt_size);
	}

	/*
	 * Fill in the PLT information.
	 */
	if (dyn != NULL) {
		uintptr_t dynaddr = dyn->c_shdr.sh_addr + fptr->file_dyn_base;
		size_t ndyn = dyn->c_shdr.sh_size / dyn->c_shdr.sh_entsize;
		GElf_Dyn d;

		for (i = 0; i < ndyn; i++) {
			if (gelf_getdyn(dyn->c_data, i, &d) == NULL)
				continue;

			switch (d.d_tag) {
			case DT_JMPREL:
				dprintf("DT_JMPREL is %p\n",
				    (void *)(uintptr_t)d.d_un.d_ptr);
				fptr->file_jmp_rel =
				    d.d_un.d_ptr + fptr->file_dyn_base;
				break;
			case DT_STRTAB:
				dprintf("DT_STRTAB is %p\n",
				    (void *)(uintptr_t)d.d_un.d_ptr);
				break;
			case DT_PLTGOT:
				dprintf("DT_PLTGOT is %p\n",
				    (void *)(uintptr_t)d.d_un.d_ptr);
				break;
			case DT_SUNW_SYMTAB:
				dprintf("DT_SUNW_SYMTAB is %p\n",
				    (void *)(uintptr_t)d.d_un.d_ptr);
				break;
			case DT_SYMTAB:
				dprintf("DT_SYMTAB is %p\n",
				    (void *)(uintptr_t)d.d_un.d_ptr);
				break;
			case DT_HASH:
				dprintf("DT_HASH is %p\n",
				    (void *)(uintptr_t)d.d_un.d_ptr);
				break;
			}
		}

		dprintf("_DYNAMIC found at %p, %lu entries, DT_JMPREL = %p\n",
		    (void *)dynaddr, (ulong_t)ndyn, (void *)fptr->file_jmp_rel);
	}

done:
	free(cache);
	return;

bad:
	if (cache != NULL)
		free(cache);

	(void) elf_end(elf);
	fptr->file_elf = NULL;
	if (fptr->file_elfmem != NULL) {
		free(fptr->file_elfmem);
		fptr->file_elfmem = NULL;
	}
	(void) close(fptr->file_fd);
	if (fptr->file_dbgelf != NULL)
		(void) elf_end(fptr->file_dbgelf);
	fptr->file_dbgelf = NULL;
	if (fptr->file_dbgfile >= 0)
		(void) close(fptr->file_dbgfile);
	fptr->file_fd = -1;
	fptr->file_dbgfile = -1;
}

/*
 * Given a process virtual address, return the map_info_t containing it.
 * If none found, return NULL.
 */
map_info_t *
Paddr2mptr(struct ps_prochandle *P, uintptr_t addr)
{
	int lo = 0;
	int hi = P->map_count - 1;
	int mid;
	map_info_t *mp;

	while (lo <= hi) {

		mid = (lo + hi) / 2;
		mp = &P->mappings[mid];

		/* check that addr is in [vaddr, vaddr + size) */
		if ((addr - mp->map_pmap.pr_vaddr) < mp->map_pmap.pr_size)
			return (mp);

		if (addr < mp->map_pmap.pr_vaddr)
			hi = mid - 1;
		else
			lo = mid + 1;
	}

	return (NULL);
}

/*
 * Return the map_info_t for the executable file.
 * If not found, return NULL.
 */
static map_info_t *
exec_map(struct ps_prochandle *P)
{
	uint_t i;
	map_info_t *mptr;
	map_info_t *mold = NULL;
	file_info_t *fptr;
	uintptr_t base;

	for (i = 0, mptr = P->mappings; i < P->map_count; i++, mptr++) {
		if (mptr->map_pmap.pr_mapname[0] == '\0')
			continue;
		if (strcmp(mptr->map_pmap.pr_mapname, "a.out") == 0) {
			if ((fptr = mptr->map_file) != NULL &&
			    fptr->file_lo != NULL) {
				base = fptr->file_lo->rl_base;
				if (base >= mptr->map_pmap.pr_vaddr &&
				    base < mptr->map_pmap.pr_vaddr +
				    mptr->map_pmap.pr_size)	/* text space */
					return (mptr);
				mold = mptr;	/* must be the data */
				continue;
			}
			/* This is a poor way to test for text space */
			if (!(mptr->map_pmap.pr_mflags & MA_EXEC) ||
			    (mptr->map_pmap.pr_mflags & MA_WRITE)) {
				mold = mptr;
				continue;
			}
			return (mptr);
		}
	}

	return (mold);
}

/*
 * Given a shared object name, return the map_info_t for it.  If no matching
 * object is found, return NULL.  Normally, the link maps contain the full
 * object pathname, e.g. /usr/lib/libc.so.1.  We allow the object name to
 * take one of the following forms:
 *
 * 1. An exact match (i.e. a full pathname): "/usr/lib/libc.so.1"
 * 2. An exact basename match: "libc.so.1"
 * 3. An initial basename match up to a '.' suffix: "libc.so" or "libc"
 * 4. The literal string "a.out" is an alias for the executable mapping
 *
 * The third case is a convenience for callers and may not be necessary.
 *
 * As the exact same object name may be loaded on different link maps (see
 * dlmopen(3DL)), we also allow the caller to resolve the object name by
 * specifying a particular link map id.  If lmid is PR_LMID_EVERY, the
 * first matching name will be returned, regardless of the link map id.
 */
static map_info_t *
object_to_map(struct ps_prochandle *P, Lmid_t lmid, const char *objname)
{
	map_info_t *mp;
	file_info_t *fp;
	size_t objlen;
	uint_t i;

	/*
	 * If we have no rtld_db, then always treat a request as one for all
	 * link maps.
	 */
	if (P->rap == NULL)
		lmid = PR_LMID_EVERY;

	/*
	 * First pass: look for exact matches of the entire pathname or
	 * basename (cases 1 and 2 above):
	 */
	for (i = 0, mp = P->mappings; i < P->map_count; i++, mp++) {

		if (mp->map_pmap.pr_mapname[0] == '\0' ||
		    (fp = mp->map_file) == NULL ||
		    ((fp->file_lname == NULL) && (fp->file_rname == NULL)))
			continue;

		if (lmid != PR_LMID_EVERY &&
		    (fp->file_lo == NULL || lmid != fp->file_lo->rl_lmident))
			continue;

		/*
		 * If we match, return the primary text mapping; otherwise
		 * just return the mapping we matched.
		 */
		if ((fp->file_lbase && strcmp(fp->file_lbase, objname) == 0) ||
		    (fp->file_rbase && strcmp(fp->file_rbase, objname) == 0) ||
		    (fp->file_lname && strcmp(fp->file_lname, objname) == 0) ||
		    (fp->file_rname && strcmp(fp->file_rname, objname) == 0))
			return (fp->file_map ? fp->file_map : mp);
	}

	objlen = strlen(objname);

	/*
	 * Second pass: look for partial matches (case 3 above):
	 */
	for (i = 0, mp = P->mappings; i < P->map_count; i++, mp++) {

		if (mp->map_pmap.pr_mapname[0] == '\0' ||
		    (fp = mp->map_file) == NULL ||
		    ((fp->file_lname == NULL) && (fp->file_rname == NULL)))
			continue;

		if (lmid != PR_LMID_EVERY &&
		    (fp->file_lo == NULL || lmid != fp->file_lo->rl_lmident))
			continue;

		/*
		 * If we match, return the primary text mapping; otherwise
		 * just return the mapping we matched.
		 */
		if ((fp->file_lbase != NULL) &&
		    (strncmp(fp->file_lbase, objname, objlen) == 0) &&
		    (fp->file_lbase[objlen] == '.'))
			return (fp->file_map ? fp->file_map : mp);
		if ((fp->file_rbase != NULL) &&
		    (strncmp(fp->file_rbase, objname, objlen) == 0) &&
		    (fp->file_rbase[objlen] == '.'))
			return (fp->file_map ? fp->file_map : mp);
	}

	/*
	 * One last check: we allow "a.out" to always alias the executable,
	 * assuming this name was not in use for something else.
	 */
	if ((lmid == PR_LMID_EVERY || lmid == LM_ID_BASE) &&
	    (strcmp(objname, "a.out") == 0))
		return (P->map_exec);

	return (NULL);
}

static map_info_t *
object_name_to_map(struct ps_prochandle *P, Lmid_t lmid, const char *name)
{
	map_info_t *mptr;

	if (!P->info_valid)
		Pupdate_maps(P);

	if (P->map_exec == NULL && ((mptr = Paddr2mptr(P,
	    Pgetauxval(P, AT_ENTRY))) != NULL || (mptr = exec_map(P)) != NULL))
		P->map_exec = mptr;

	if (P->map_ldso == NULL && (mptr = Paddr2mptr(P,
	    Pgetauxval(P, AT_BASE))) != NULL)
		P->map_ldso = mptr;

	if (name == PR_OBJ_EXEC)
		mptr = P->map_exec;
	else if (name == PR_OBJ_LDSO)
		mptr = P->map_ldso;
	else if (Prd_agent(P) != NULL || P->state == PS_IDLE)
		mptr = object_to_map(P, lmid, name);
	else
		mptr = NULL;

	return (mptr);
}

/*
 * When two symbols are found by address, decide which one is to be preferred.
 */
static GElf_Sym *
sym_prefer(GElf_Sym *sym1, char *name1, GElf_Sym *sym2, char *name2)
{
	/*
	 * Prefer the non-NULL symbol.
	 */
	if (sym1 == NULL)
		return (sym2);
	if (sym2 == NULL)
		return (sym1);

	/*
	 * Defer to the sort ordering...
	 */
	return (byaddr_cmp_common(sym1, name1, sym2, name2) <= 0 ? sym1 : sym2);
}

/*
 * Use a binary search to do the work of sym_by_addr().
 */
static GElf_Sym *
sym_by_addr_binary(sym_tbl_t *symtab, GElf_Addr addr, GElf_Sym *symp,
    uint_t *idp)
{
	GElf_Sym sym, osym;
	uint_t i, oid, *byaddr = symtab->sym_byaddr;
	int min, max, mid, omid, found = 0;

	if (symtab->sym_data_pri == NULL || symtab->sym_count == 0)
		return (NULL);

	min = 0;
	max = symtab->sym_count - 1;
	osym.st_value = 0;

	/*
	 * We can't return when we've found a match, we have to continue
	 * searching for the closest matching symbol.
	 */
	while (min <= max) {
		mid = (max + min) / 2;

		i = byaddr[mid];
		(void) symtab_getsym(symtab, i, &sym);

		if (addr >= sym.st_value &&
		    addr < sym.st_value + sym.st_size &&
		    (!found || sym.st_value > osym.st_value)) {
			osym = sym;
			omid = mid;
			oid = i;
			found = 1;
		}

		if (addr < sym.st_value)
			max = mid - 1;
		else
			min = mid + 1;
	}

	if (!found)
		return (NULL);

	/*
	 * There may be many symbols with identical values so we walk
	 * backward in the byaddr table to find the best match.
	 */
	do {
		sym = osym;
		i = oid;

		if (omid == 0)
			break;

		oid = byaddr[--omid];
		(void) symtab_getsym(symtab, oid, &osym);
	} while (addr >= osym.st_value &&
	    addr < sym.st_value + osym.st_size &&
	    osym.st_value == sym.st_value);

	*symp = sym;
	if (idp != NULL)
		*idp = i;
	return (symp);
}

/*
 * Use a linear search to do the work of sym_by_addr().
 */
static GElf_Sym *
sym_by_addr_linear(sym_tbl_t *symtab, GElf_Addr addr, GElf_Sym *symbolp,
    uint_t *idp)
{
	size_t symn = symtab->sym_symn;
	char *strs = symtab->sym_strs;
	GElf_Sym sym, *symp = NULL;
	GElf_Sym osym, *osymp = NULL;
	int i, id;

	if (symtab->sym_data_pri == NULL || symn == 0 || strs == NULL)
		return (NULL);

	for (i = 0; i < symn; i++) {
		if ((symp = symtab_getsym(symtab, i, &sym)) != NULL) {
			if (addr >= sym.st_value &&
			    addr < sym.st_value + sym.st_size) {
				if (osymp)
					symp = sym_prefer(
					    symp, strs + symp->st_name,
					    osymp, strs + osymp->st_name);
				if (symp != osymp) {
					osym = sym;
					osymp = &osym;
					id = i;
				}
			}
		}
	}
	if (osymp) {
		*symbolp = osym;
		if (idp)
			*idp = id;
		return (symbolp);
	}
	return (NULL);
}

/*
 * Look up a symbol by address in the specified symbol table.
 * Adjustment to 'addr' must already have been made for the
 * offset of the symbol if this is a dynamic library symbol table.
 *
 * Use a linear or a binary search depending on whether or not we
 * chose to sort the table in optimize_symtab().
 */
static GElf_Sym *
sym_by_addr(sym_tbl_t *symtab, GElf_Addr addr, GElf_Sym *symp, uint_t *idp)
{
	if (_libproc_no_qsort) {
		return (sym_by_addr_linear(symtab, addr, symp, idp));
	} else {
		return (sym_by_addr_binary(symtab, addr, symp, idp));
	}
}

/*
 * Use a binary search to do the work of sym_by_name().
 */
static GElf_Sym *
sym_by_name_binary(sym_tbl_t *symtab, const char *name, GElf_Sym *symp,
    uint_t *idp)
{
	char *strs = symtab->sym_strs;
	uint_t i, *byname = symtab->sym_byname;
	int min, mid, max, cmp;

	if (symtab->sym_data_pri == NULL || strs == NULL ||
	    symtab->sym_count == 0)
		return (NULL);

	min = 0;
	max = symtab->sym_count - 1;

	while (min <= max) {
		mid = (max + min) / 2;

		i = byname[mid];
		(void) symtab_getsym(symtab, i, symp);

		if ((cmp = strcmp(name, strs + symp->st_name)) == 0) {
			if (idp != NULL)
				*idp = i;
			return (symp);
		}

		if (cmp < 0)
			max = mid - 1;
		else
			min = mid + 1;
	}

	return (NULL);
}

/*
 * Use a linear search to do the work of sym_by_name().
 */
static GElf_Sym *
sym_by_name_linear(sym_tbl_t *symtab, const char *name, GElf_Sym *symp,
    uint_t *idp)
{
	size_t symn = symtab->sym_symn;
	char *strs = symtab->sym_strs;
	int i;

	if (symtab->sym_data_pri == NULL || symn == 0 || strs == NULL)
		return (NULL);

	for (i = 0; i < symn; i++) {
		if (symtab_getsym(symtab, i, symp) &&
		    strcmp(name, strs + symp->st_name) == 0) {
			if (idp)
				*idp = i;
			return (symp);
		}
	}

	return (NULL);
}

/*
 * Look up a symbol by name in the specified symbol table.
 *
 * Use a linear or a binary search depending on whether or not we
 * chose to sort the table in optimize_symtab().
 */
static GElf_Sym *
sym_by_name(sym_tbl_t *symtab, const char *name, GElf_Sym *symp, uint_t *idp)
{
	if (_libproc_no_qsort) {
		return (sym_by_name_linear(symtab, name, symp, idp));
	} else {
		return (sym_by_name_binary(symtab, name, symp, idp));
	}
}

/*
 * Search the process symbol tables looking for a symbol whose
 * value to value+size contain the address specified by addr.
 * Return values are:
 *	sym_name_buffer containing the symbol name
 *	GElf_Sym symbol table entry
 *	prsyminfo_t ancillary symbol information
 * Returns 0 on success, -1 on failure.
 */
static int
i_Pxlookup_by_addr(
	struct ps_prochandle *P,
	int lmresolve,			/* use resolve linker object names */
	uintptr_t addr,			/* process address being sought */
	char *sym_name_buffer,		/* buffer for the symbol name */
	size_t bufsize,			/* size of sym_name_buffer */
	GElf_Sym *symbolp,		/* returned symbol table entry */
	prsyminfo_t *sip)		/* returned symbol info */
{
	GElf_Sym	*symp;
	char		*name;
	GElf_Sym	sym1, *sym1p = NULL;
	GElf_Sym	sym2, *sym2p = NULL;
	char		*name1 = NULL;
	char		*name2 = NULL;
	uint_t		i1;
	uint_t		i2;
	map_info_t	*mptr;
	file_info_t	*fptr;

	(void) Prd_agent(P);

	if ((mptr = Paddr2mptr(P, addr)) == NULL ||	/* no such address */
	    (fptr = build_map_symtab(P, mptr)) == NULL || /* no mapped file */
	    fptr->file_elf == NULL)			/* not an ELF file */
		return (-1);

	/*
	 * Adjust the address by the load object base address in
	 * case the address turns out to be in a shared library.
	 */
	addr -= fptr->file_dyn_base;

	/*
	 * Search both symbol tables, symtab first, then dynsym.
	 */
	if ((sym1p = sym_by_addr(&fptr->file_symtab, addr, &sym1, &i1)) != NULL)
		name1 = fptr->file_symtab.sym_strs + sym1.st_name;
	if ((sym2p = sym_by_addr(&fptr->file_dynsym, addr, &sym2, &i2)) != NULL)
		name2 = fptr->file_dynsym.sym_strs + sym2.st_name;

	if ((symp = sym_prefer(sym1p, name1, sym2p, name2)) == NULL)
		return (-1);

	name = (symp == sym1p) ? name1 : name2;
	if (bufsize > 0) {
		(void) strncpy(sym_name_buffer, name, bufsize);
		sym_name_buffer[bufsize - 1] = '\0';
	}

	*symbolp = *symp;
	if (sip != NULL) {
		sip->prs_name = bufsize == 0 ? NULL : sym_name_buffer;
		if (lmresolve && (fptr->file_rname != NULL))
			sip->prs_object = fptr->file_rbase;
		else
			sip->prs_object = fptr->file_lbase;
		sip->prs_id = (symp == sym1p) ? i1 : i2;
		sip->prs_table = (symp == sym1p) ? PR_SYMTAB : PR_DYNSYM;
		sip->prs_lmid = (fptr->file_lo == NULL) ? LM_ID_BASE :
		    fptr->file_lo->rl_lmident;
	}

	if (GELF_ST_TYPE(symbolp->st_info) != STT_TLS)
		symbolp->st_value += fptr->file_dyn_base;

	return (0);
}

int
Pxlookup_by_addr(struct ps_prochandle *P, uintptr_t addr, char *buf,
    size_t bufsize, GElf_Sym *symp, prsyminfo_t *sip)
{
	return (i_Pxlookup_by_addr(P, B_FALSE, addr, buf, bufsize, symp, sip));
}

int
Pxlookup_by_addr_resolved(struct ps_prochandle *P, uintptr_t addr, char *buf,
    size_t bufsize, GElf_Sym *symp, prsyminfo_t *sip)
{
	return (i_Pxlookup_by_addr(P, B_TRUE, addr, buf, bufsize, symp, sip));
}

int
Plookup_by_addr(struct ps_prochandle *P, uintptr_t addr, char *buf,
    size_t size, GElf_Sym *symp)
{
	return (i_Pxlookup_by_addr(P, B_FALSE, addr, buf, size, symp, NULL));
}

/*
 * Search the process symbol tables looking for a symbol whose name matches the
 * specified name and whose object and link map optionally match the specified
 * parameters.  On success, the function returns 0 and fills in the GElf_Sym
 * symbol table entry.  On failure, -1 is returned.
 */
int
Pxlookup_by_name(
	struct ps_prochandle *P,
	Lmid_t lmid,			/* link map to match, or -1 for any */
	const char *oname,		/* load object name */
	const char *sname,		/* symbol name */
	GElf_Sym *symp,			/* returned symbol table entry */
	prsyminfo_t *sip)		/* returned symbol info */
{
	map_info_t *mptr;
	file_info_t *fptr;
	int cnt;

	GElf_Sym sym;
	prsyminfo_t si;
	int rv = -1;
	uint_t id;

	if (oname == PR_OBJ_EVERY) {
		/* create all the file_info_t's for all the mappings */
		(void) Prd_agent(P);
		cnt = P->num_files;
		fptr = list_head(&P->file_head);
	} else {
		cnt = 1;
		if ((mptr = object_name_to_map(P, lmid, oname)) == NULL ||
		    (fptr = build_map_symtab(P, mptr)) == NULL)
			return (-1);
	}

	/*
	 * Iterate through the loaded object files and look for the symbol
	 * name in the .symtab and .dynsym of each.  If we encounter a match
	 * with SHN_UNDEF, keep looking in hopes of finding a better match.
	 * This means that a name such as "puts" will match the puts function
	 * in libc instead of matching the puts PLT entry in the a.out file.
	 */
	for (; cnt > 0; cnt--, fptr = list_next(&P->file_head, fptr)) {
		Pbuild_file_symtab(P, fptr);

		if (fptr->file_elf == NULL)
			continue;

		if (lmid != PR_LMID_EVERY && fptr->file_lo != NULL &&
		    lmid != fptr->file_lo->rl_lmident)
			continue;

		if (fptr->file_symtab.sym_data_pri != NULL &&
		    sym_by_name(&fptr->file_symtab, sname, symp, &id)) {
			if (sip != NULL) {
				sip->prs_id = id;
				sip->prs_table = PR_SYMTAB;
				sip->prs_object = oname;
				sip->prs_name = sname;
				sip->prs_lmid = fptr->file_lo == NULL ?
				    LM_ID_BASE : fptr->file_lo->rl_lmident;
			}
		} else if (fptr->file_dynsym.sym_data_pri != NULL &&
		    sym_by_name(&fptr->file_dynsym, sname, symp, &id)) {
			if (sip != NULL) {
				sip->prs_id = id;
				sip->prs_table = PR_DYNSYM;
				sip->prs_object = oname;
				sip->prs_name = sname;
				sip->prs_lmid = fptr->file_lo == NULL ?
				    LM_ID_BASE : fptr->file_lo->rl_lmident;
			}
		} else {
			continue;
		}

		if (GELF_ST_TYPE(symp->st_info) != STT_TLS)
			symp->st_value += fptr->file_dyn_base;

		if (symp->st_shndx != SHN_UNDEF)
			return (0);

		if (rv != 0) {
			if (sip != NULL)
				si = *sip;
			sym = *symp;
			rv = 0;
		}
	}

	if (rv == 0) {
		if (sip != NULL)
			*sip = si;
		*symp = sym;
	}

	return (rv);
}

/*
 * Search the process symbol tables looking for a symbol whose name matches the
 * specified name, but without any restriction on the link map id.
 */
int
Plookup_by_name(struct ps_prochandle *P, const char *object,
    const char *symbol, GElf_Sym *symp)
{
	return (Pxlookup_by_name(P, PR_LMID_EVERY, object, symbol, symp, NULL));
}

/*
 * Iterate over the process's address space mappings.
 */
static int
i_Pmapping_iter(struct ps_prochandle *P, boolean_t lmresolve,
    proc_map_f *func, void *cd)
{
	map_info_t *mptr;
	file_info_t *fptr;
	char *object_name;
	int rc = 0;
	int i;

	/* create all the file_info_t's for all the mappings */
	(void) Prd_agent(P);

	for (i = 0, mptr = P->mappings; i < P->map_count; i++, mptr++) {
		if ((fptr = mptr->map_file) == NULL)
			object_name = NULL;
		else if (lmresolve && (fptr->file_rname != NULL))
			object_name = fptr->file_rname;
		else
			object_name = fptr->file_lname;
		if ((rc = func(cd, &mptr->map_pmap, object_name)) != 0)
			return (rc);
	}
	return (0);
}

int
Pmapping_iter(struct ps_prochandle *P, proc_map_f *func, void *cd)
{
	return (i_Pmapping_iter(P, B_FALSE, func, cd));
}

int
Pmapping_iter_resolved(struct ps_prochandle *P, proc_map_f *func, void *cd)
{
	return (i_Pmapping_iter(P, B_TRUE, func, cd));
}

/*
 * Iterate over the process's mapped objects.
 */
static int
i_Pobject_iter(struct ps_prochandle *P, boolean_t lmresolve,
    proc_map_f *func, void *cd)
{
	map_info_t *mptr;
	file_info_t *fptr;
	int rc = 0;

	(void) Prd_agent(P); /* create file_info_t's for all the mappings */
	Pupdate_maps(P);

	for (fptr = list_head(&P->file_head); fptr != NULL;
	    fptr = list_next(&P->file_head, fptr)) {
		const char *lname;

		if (lmresolve && (fptr->file_rname != NULL))
			lname = fptr->file_rname;
		else if (fptr->file_lname != NULL)
			lname = fptr->file_lname;
		else
			lname = "";

		if ((mptr = fptr->file_map) == NULL)
			continue;

		if ((rc = func(cd, &mptr->map_pmap, lname)) != 0)
			return (rc);

		if (!P->info_valid)
			Pupdate_maps(P);
	}
	return (0);
}

int
Pobject_iter(struct ps_prochandle *P, proc_map_f *func, void *cd)
{
	return (i_Pobject_iter(P, B_FALSE, func, cd));
}

int
Pobject_iter_resolved(struct ps_prochandle *P, proc_map_f *func, void *cd)
{
	return (i_Pobject_iter(P, B_TRUE, func, cd));
}

static char *
i_Pobjname(struct ps_prochandle *P, boolean_t lmresolve, uintptr_t addr,
    char *buffer, size_t bufsize)
{
	map_info_t *mptr;
	file_info_t *fptr;

	/* create all the file_info_t's for all the mappings */
	(void) Prd_agent(P);

	if ((mptr = Paddr2mptr(P, addr)) == NULL)
		return (NULL);

	if (!lmresolve) {
		if (((fptr = mptr->map_file) == NULL) ||
		    (fptr->file_lname == NULL))
			return (NULL);
		(void) strlcpy(buffer, fptr->file_lname, bufsize);
		return (buffer);
	}

	/* Check for a cached copy of the resolved path */
	if (Pfindmap(P, mptr, buffer, bufsize) != NULL)
		return (buffer);

	return (NULL);
}

/*
 * Given a virtual address, return the name of the underlying
 * mapped object (file) as provided by the dynamic linker.
 * Return NULL if we can't find any name information for the object.
 */
char *
Pobjname(struct ps_prochandle *P, uintptr_t addr,
    char *buffer, size_t bufsize)
{
	return (i_Pobjname(P, B_FALSE, addr, buffer, bufsize));
}

/*
 * Given a virtual address, try to return a filesystem path to the
 * underlying mapped object (file).  If we're in the global zone,
 * this path could resolve to an object in another zone.  If we're
 * unable return a valid filesystem path, we'll fall back to providing
 * the mapped object (file) name provided by the dynamic linker in
 * the target process (ie, the object reported by Pobjname()).
 */
char *
Pobjname_resolved(struct ps_prochandle *P, uintptr_t addr,
    char *buffer, size_t bufsize)
{
	return (i_Pobjname(P, B_TRUE, addr, buffer, bufsize));
}

/*
 * Given a virtual address, return the link map id of the underlying mapped
 * object (file), as provided by the dynamic linker.  Return -1 on failure.
 */
int
Plmid(struct ps_prochandle *P, uintptr_t addr, Lmid_t *lmidp)
{
	map_info_t *mptr;
	file_info_t *fptr;

	/* create all the file_info_t's for all the mappings */
	(void) Prd_agent(P);

	if ((mptr = Paddr2mptr(P, addr)) != NULL &&
	    (fptr = mptr->map_file) != NULL && fptr->file_lo != NULL) {
		*lmidp = fptr->file_lo->rl_lmident;
		return (0);
	}

	return (-1);
}

/*
 * Given an object name and optional lmid, iterate over the object's symbols.
 * If which == PR_SYMTAB, search the normal symbol table.
 * If which == PR_DYNSYM, search the dynamic symbol table.
 */
static int
Psymbol_iter_com(struct ps_prochandle *P, Lmid_t lmid, const char *object_name,
    int which, int mask, pr_order_t order, proc_xsym_f *func, void *cd)
{
#if STT_NUM != (STT_TLS + 1)
#error "STT_NUM has grown. update Psymbol_iter_com()"
#endif

	GElf_Sym sym;
	GElf_Shdr shdr;
	map_info_t *mptr;
	file_info_t *fptr;
	sym_tbl_t *symtab;
	size_t symn;
	const char *strs;
	size_t strsz;
	prsyminfo_t si;
	int rv;
	uint_t *map, i, count, ndx;

	if ((mptr = object_name_to_map(P, lmid, object_name)) == NULL)
		return (-1);

	if ((fptr = build_map_symtab(P, mptr)) == NULL || /* no mapped file */
	    fptr->file_elf == NULL)			/* not an ELF file */
		return (-1);

	/*
	 * Search the specified symbol table.
	 */
	switch (which) {
	case PR_SYMTAB:
		symtab = &fptr->file_symtab;
		si.prs_table = PR_SYMTAB;
		break;
	case PR_DYNSYM:
		symtab = &fptr->file_dynsym;
		si.prs_table = PR_DYNSYM;
		break;
	default:
		return (-1);
	}

	si.prs_object = object_name;
	si.prs_lmid = fptr->file_lo == NULL ?
	    LM_ID_BASE : fptr->file_lo->rl_lmident;

	symn = symtab->sym_symn;
	strs = symtab->sym_strs;
	strsz = symtab->sym_strsz;

	switch (order) {
	case PRO_NATURAL:
		map = NULL;
		count = symn;
		break;
	case PRO_BYNAME:
		map = symtab->sym_byname;
		count = symtab->sym_count;
		break;
	case PRO_BYADDR:
		map = symtab->sym_byaddr;
		count = symtab->sym_count;
		break;
	default:
		return (-1);
	}

	if (symtab->sym_data_pri == NULL || strs == NULL || count == 0)
		return (-1);

	rv = 0;

	for (i = 0; i < count; i++) {
		ndx = map == NULL ? i : map[i];
		if (symtab_getsym(symtab, ndx, &sym) != NULL) {
			uint_t s_bind, s_type, type;

			if (sym.st_name >= strsz)	/* invalid st_name */
				continue;

			s_bind = GELF_ST_BIND(sym.st_info);
			s_type = GELF_ST_TYPE(sym.st_info);

			/*
			 * In case you haven't already guessed, this relies on
			 * the bitmask used in <libproc.h> for encoding symbol
			 * type and binding matching the order of STB and STT
			 * constants in <sys/elf.h>.  Changes to ELF must
			 * maintain binary compatibility, so I think this is
			 * reasonably fair game.
			 */
			if (s_bind < STB_NUM && s_type < STT_NUM) {
				type = (1 << (s_type + 8)) | (1 << s_bind);
				if ((type & ~mask) != 0)
					continue;
			} else
				continue; /* Invalid type or binding */

			if (GELF_ST_TYPE(sym.st_info) != STT_TLS)
				sym.st_value += fptr->file_dyn_base;

			si.prs_name = strs + sym.st_name;

			/*
			 * If symbol's type is STT_SECTION, then try to lookup
			 * the name of the corresponding section.
			 */
			if (GELF_ST_TYPE(sym.st_info) == STT_SECTION &&
			    fptr->file_shstrs != NULL &&
			    gelf_getshdr(elf_getscn(fptr->file_elf,
			    sym.st_shndx), &shdr) != NULL &&
			    shdr.sh_name != 0 &&
			    shdr.sh_name < fptr->file_shstrsz)
				si.prs_name = fptr->file_shstrs + shdr.sh_name;

			si.prs_id = ndx;
			if ((rv = func(cd, &sym, si.prs_name, &si)) != 0)
				break;
		}
	}

	return (rv);
}

int
Pxsymbol_iter(struct ps_prochandle *P, Lmid_t lmid, const char *object_name,
    int which, int mask, proc_xsym_f *func, void *cd)
{
	return (Psymbol_iter_com(P, lmid, object_name, which, mask,
	    PRO_NATURAL, func, cd));
}

int
Psymbol_iter_by_lmid(struct ps_prochandle *P, Lmid_t lmid,
    const char *object_name, int which, int mask, proc_sym_f *func, void *cd)
{
	return (Psymbol_iter_com(P, lmid, object_name, which, mask,
	    PRO_NATURAL, (proc_xsym_f *)(uintptr_t)func, cd));
}

int
Psymbol_iter(struct ps_prochandle *P,
    const char *object_name, int which, int mask, proc_sym_f *func, void *cd)
{
	return (Psymbol_iter_com(P, PR_LMID_EVERY, object_name, which, mask,
	    PRO_NATURAL, (proc_xsym_f *)(uintptr_t)func, cd));
}

int
Psymbol_iter_by_addr(struct ps_prochandle *P,
    const char *object_name, int which, int mask, proc_sym_f *func, void *cd)
{
	return (Psymbol_iter_com(P, PR_LMID_EVERY, object_name, which, mask,
	    PRO_BYADDR, (proc_xsym_f *)(uintptr_t)func, cd));
}

int
Psymbol_iter_by_name(struct ps_prochandle *P,
    const char *object_name, int which, int mask, proc_sym_f *func, void *cd)
{
	return (Psymbol_iter_com(P, PR_LMID_EVERY, object_name, which, mask,
	    PRO_BYNAME, (proc_xsym_f *)(uintptr_t)func, cd));
}

/*
 * Get the platform string.
 */
char *
Pplatform(struct ps_prochandle *P, char *s, size_t n)
{
	return (P->ops.pop_platform(P, s, n, P->data));
}

/*
 * Get the uname(2) information.
 */
int
Puname(struct ps_prochandle *P, struct utsname *u)
{
	return (P->ops.pop_uname(P, u, P->data));
}

/*
 * Called from Pcreate(), Pgrab(), and Pfgrab_core() to initialize
 * the symbol table heads in the new ps_prochandle.
 */
void
Pinitsym(struct ps_prochandle *P)
{
	P->num_files = 0;
	list_create(&P->file_head, sizeof (file_info_t),
	    offsetof(file_info_t, file_list));
}

/*
 * Called from Prelease() to destroy the symbol tables.
 * Must be called by the client after an exec() in the victim process.
 */
void
Preset_maps(struct ps_prochandle *P)
{
	int i;

	if (P->rap != NULL) {
		rd_delete(P->rap);
		P->rap = NULL;
	}

	if (P->execname != NULL) {
		free(P->execname);
		P->execname = NULL;
	}

	if (P->auxv != NULL) {
		free(P->auxv);
		P->auxv = NULL;
		P->nauxv = 0;
	}

	for (i = 0; i < P->map_count; i++)
		map_info_free(P, &P->mappings[i]);

	if (P->mappings != NULL) {
		free(P->mappings);
		P->mappings = NULL;
	}
	P->map_count = P->map_alloc = 0;

	P->info_valid = 0;
}

typedef struct getenv_data {
	char *buf;
	size_t bufsize;
	const char *search;
	size_t searchlen;
} getenv_data_t;

/*ARGSUSED*/
static int
getenv_func(void *data, struct ps_prochandle *P, uintptr_t addr,
    const char *nameval)
{
	getenv_data_t *d = data;
	size_t len;

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

	if (d->searchlen < strlen(nameval) &&
	    strncmp(nameval, d->search, d->searchlen) == 0 &&
	    nameval[d->searchlen] == '=') {
		len = MIN(strlen(nameval), d->bufsize - 1);
		(void) strncpy(d->buf, nameval, len);
		d->buf[len] = '\0';
		return (1);
	}

	return (0);
}

char *
Pgetenv(struct ps_prochandle *P, const char *name, char *buf, size_t buflen)
{
	getenv_data_t d;

	d.buf = buf;
	d.bufsize = buflen;
	d.search = name;
	d.searchlen = strlen(name);

	if (Penv_iter(P, getenv_func, &d) == 1) {
		char *equals = strchr(d.buf, '=');

		if (equals != NULL) {
			(void) memmove(d.buf, equals + 1,
			    d.buf + buflen - equals - 1);
			d.buf[d.buf + buflen - equals] = '\0';

			return (buf);
		}
	}

	return (NULL);
}

/* number of argument or environment pointers to read all at once */
#define	NARG	100

int
Penv_iter(struct ps_prochandle *P, proc_env_f *func, void *data)
{
	const psinfo_t *psp;
	uintptr_t envpoff;
	GElf_Sym sym;
	int ret;
	char *buf, *nameval;
	size_t buflen;

	int nenv = NARG;
	long envp[NARG];

	/*
	 * Attempt to find the "_environ" variable in the process.
	 * Failing that, use the original value provided by Ppsinfo().
	 */
	if ((psp = Ppsinfo(P)) == NULL)
		return (-1);

	envpoff = psp->pr_envp; /* Default if no _environ found */

	if (Plookup_by_name(P, PR_OBJ_EXEC, "_environ", &sym) == 0) {
		if (P->status.pr_dmodel == PR_MODEL_NATIVE) {
			if (Pread(P, &envpoff, sizeof (envpoff),
			    sym.st_value) != sizeof (envpoff))
				envpoff = psp->pr_envp;
		} else if (P->status.pr_dmodel == PR_MODEL_ILP32) {
			uint32_t envpoff32;

			if (Pread(P, &envpoff32, sizeof (envpoff32),
			    sym.st_value) != sizeof (envpoff32))
				envpoff = psp->pr_envp;
			else
				envpoff = envpoff32;
		}
	}

	buflen = 128;
	buf = malloc(buflen);

	ret = 0;
	for (;;) {
		uintptr_t envoff;

		if (nenv == NARG) {
			(void) memset(envp, 0, sizeof (envp));
			if (P->status.pr_dmodel == PR_MODEL_NATIVE) {
				if (Pread(P, envp,
				    sizeof (envp), envpoff) <= 0) {
					ret = -1;
					break;
				}
			} else if (P->status.pr_dmodel == PR_MODEL_ILP32) {
				uint32_t e32[NARG];
				int i;

				(void) memset(e32, 0, sizeof (e32));
				if (Pread(P, e32, sizeof (e32), envpoff) <= 0) {
					ret = -1;
					break;
				}
				for (i = 0; i < NARG; i++)
					envp[i] = e32[i];
			}
			nenv = 0;
		}

		if ((envoff = envp[nenv++]) == (uintptr_t)NULL)
			break;

		/*
		 * Attempt to read the string from the process.
		 */
again:
		ret = Pread_string(P, buf, buflen, envoff);

		if (ret <= 0) {
			nameval = NULL;
		} else if (ret == buflen - 1) {
			free(buf);
			/*
			 * Bail if we have a corrupted environment
			 */
			if (buflen >= ARG_MAX)
				return (-1);
			buflen *= 2;
			buf = malloc(buflen);
			goto again;
		} else {
			nameval = buf;
		}

		if ((ret = func(data, P, envoff, nameval)) != 0)
			break;

		envpoff += (P->status.pr_dmodel == PR_MODEL_LP64)? 8 : 4;
	}

	free(buf);

	return (ret);
}