|
root / base / usr / src / cmd / sgs / rtld / amd64
amd64 Plain Text 2525 lines 67.0 KB
   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
#
# 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) 2004, 2010, Oracle and/or its affiliates. All rights reserved.
# Copyright 2019 OmniOS Community Edition (OmniOSce) Association.
#

BASEPLAT =	amd64

# Object lists are organized into primary (most frequently used code) and
# secondary lists (less frequently used code).

P_COMOBJS=	debugdata.o \
		analyze.o	elf.o		external.o	globals.o \
		malloc.o	paths.o		setup.o		util.o \
		dlfcns.o	config_elf.o	locale.o	tsort.o \
		remove.o	move.o		tls.o		cap.o

S_COMOBJS=	debug.o		audit.o		object.o

G_MACHOBJS=	doreloc.o

P_MACHOBJS=	amd64_elf.o	_setup.o	dlamd64getunwind.o

CP_MACHOBJS=

S_MACHOBJS=

P_ASOBJS=	boot.o		boot_elf.o	caller.o

S_ASOBJS=

CRTSRCS=	../../../../lib/crt/amd64
CRTI=		pics/crti.o
CRTN=		pics/crtn.o
CRTS=		$(CRTI)		$(CRTN)

include		$(SRC)/cmd/sgs/rtld/Makefile.com
include		$(SRC)/lib/Makefile.lib.64

MAPFILE-ORDER =	../common/mapfile-order-gcc

# Add any machine specific flags.

ASFLAGS +=	-D__amd64 -D_ELF64 $(amd64_ASFLAGS)
ADBGENFLAGS +=	-mlp64
ADBSUB=		$(ADBSUB64)
CPPFLAGS +=	-D_ELF64
# Hammerhead: 64-bit only - runtime linker at flattened path
SONAME=		/lib/ld.so.1

SGSMSGTARG +=	$(SGSMSGINTEL) $(SGSMSGINTEL64) $(SGSMSG64)

LDLIB =		-L ../../libld/$(MACH64)
RTLDLIB =	-L ../../librtld/$(MACH64)

CPICLIB =	$(CPICLIB64)
LDDBGLIBDIR =	$(LDDBGLIBDIR64)
CONVLIBDIR =	$(CONVLIBDIR64)

.KEEP_STATE:

all:		$(RTLD)

install:	all $(ROOTDYNLIB64) $(ROOTCOMPATLINKS) $(ROOTCOMPATLINKS64)

adbmacros:	adb .WAIT $(ADBSCRIPTS)

adbinstall:	adbmacros .WAIT $(ROOTADB64)

include		$(SRC)/cmd/sgs/rtld/Makefile.targ
include		$(SRC)/Makefile.master.64

# Hammerhead: ld.so.1 MUST be linked by illumos ld (sunld), not GNU ld.
# GNU ld produces ELFOSABI_NONE, missing PT_SUNWDTRACE/PT_SUNW_UNWIND program
# headers, and wrong segment alignment — the kernel cannot properly map the
# result. Override LD after Makefile.master.64 (which resets LD=$(LD64)).
#
# `unexport LD_ALTEXEC` does NOT reliably prevent sunld from seeing the
# variable in recipe subshells (gmake may still pass it through).  When
# LD_ALTEXEC is set to gnu-ld-wrapper, sunld re-execs that wrapper,
# which silently ignores `-z dtrace=dtrace_data` — the resulting
# ld.so.1 has PT_SUNWDTRACE with p_memsz=0, and the kernel's
# dtrace_safe_phdr() rejects it with silent ENOEXEC when exec'ing any
# binary that uses ld.so.1 as its interpreter (including /sbin/init).
#
# Use the same wrapper script kernel linking uses: a single-token path
# that unsets LD_ALTEXEC before exec'ing /usr/bin/sunld.  See
# `usr/src/tools/scripts/sunld-kernel.sh`.
unexport LD_ALTEXEC
LD = $(SRC)/tools/scripts/sunld-kernel.sh
GSHARED = -G

# Redefine DYNFLAGS in illumos ld native syntax (no -Wl, prefix).
# The Makefile.targ link rule calls $(LD) directly, not $(CC).
# Note: illumos ld requires space between -z and the keyword.
DYNFLAGS = -h $(SONAME) -z textoff -z defs \
	$(MAPFILES:%=-M %) $(MAPFILE.PGA:%=-M %) \
	-i -e _rt_boot $(VERSREF) $(ZNODLOPEN) \
	$(ZINTERPOSE) -z dtrace=dtrace_data '-R$$ORIGIN' \
	-Bsymbolic
ZNODLOPEN = -z nodlopen
ZINTERPOSE = -z interpose

# Hammerhead: GNU strip corrupts ld.so.1 in two places.
#
# 1. POST_PROCESS_SO runs STRIP_STABS ($(STRIP) -x $@) after the link
#    rule in Makefile.targ.  On Hammerhead $(STRIP) is GNU strip.
# 2. INS.file in Makefile.master passes `-s` to install(1), which
#    invokes GNU strip again at install time.
#
# GNU strip handles the Solaris PT_SUNWDTRACE program header
# incorrectly:
#
#   - sunld with `-z dtrace=dtrace_data` creates a PT_SUNWDTRACE
#     program header with p_filesz=0 (NOBITS — dtrace_data is in
#     .bss), p_memsz=0x40 (= FASTTRAP_SUNWDTRACE_SIZE), p_vaddr set to
#     the symbol address.
#   - GNU strip sees p_filesz=0 and 'optimizes' by zeroing p_memsz as
#     well, and drops the `dtrace_data` symbol entirely.
#   - The kernel's dtrace_safe_phdr() at elf.c:123 rejects any
#     interpreter whose PT_SUNWDTRACE p_memsz < PT_SUNWDTRACE_SIZE (64).
#   - Result: every exec() of a dynamic binary that uses ld.so.1 as
#     its interpreter fails with ENOEXEC (including /sbin/init).
#
# Disable both strip calls.  The rest of POST_PROCESS_SO (mcs -d,
# elfsign) still runs.  ld.so.1 ends up larger (~1.4 MB unstripped vs
# ~474 KB stripped) but exec works.
STRIP_STABS = :
INS.file = $(RM) $@; $(INS) -m $(FILEMODE) -f $(@D) $<
/*
 * 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 2009 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */
/*
 * Copyright (c) 2018, Joyent, Inc.
 * Copyright 2022 Oxide Computer Company
 */

/*
 * amd64 specific setup routine  -  relocate ld.so's symbols, setup its
 * environment, map in loadable sections of the executable.
 *
 * Takes base address ld.so was loaded at, address of ld.so's dynamic
 * structure, address of process environment pointers, address of auxiliary
 * vector and * argv[0] (process name).
 * If errors occur, send process signal - otherwise
 * return executable's entry point to the bootstrap routine.
 */

#include	<signal.h>
#include	<stdlib.h>
#include	<sys/auxv.h>
#include	<sys/types.h>
#include	<sys/stat.h>
#include	<link.h>
#include	<dlfcn.h>
#include	"_rtld.h"
#include	"_audit.h"
#include	"msg.h"

/*
 * Number of bytes to save for register usage.
 */
uint_t _plt_save_size;
void (*_plt_fp_save)(void *);
void (*_plt_fp_restore)(void *);

extern void _elf_rtbndr_fp_save_orig(void *);
extern void _elf_rtbndr_fp_restore_orig(void *);
extern void _elf_rtbndr_fp_fxsave(void *);
extern void _elf_rtbndr_fp_fxrestore(void *);
extern void _elf_rtbndr_fp_xsave(void *);
extern void _elf_rtbndr_fp_xrestore(void *);

/*
 * Based on what the kernel has told us, go through and set up the various
 * pointers that we'll need for elf_rtbndr for the FPU.
 */
static void
_setup_plt_fpu(int kind, size_t len)
{
	/*
	 * If we didn't get a length for some reason, fall back to the old
	 * implementation.
	 */
	if (len == 0)
		kind = -1;

	switch (kind) {
	case AT_386_FPINFO_FXSAVE:
		_plt_fp_save = _elf_rtbndr_fp_fxsave;
		_plt_fp_restore = _elf_rtbndr_fp_fxrestore;
		_plt_save_size = len;
		break;
	/*
	 * We can treat processors that don't correctly handle the exception
	 * information in xsave the same way we do others. The information
	 * that may or may not be properly saved and restored should not be
	 * relevant to us because of the ABI.
	 */
	case AT_386_FPINFO_XSAVE:
	case AT_386_FPINFO_XSAVE_AMD:
		_plt_fp_save = _elf_rtbndr_fp_xsave;
		_plt_fp_restore = _elf_rtbndr_fp_xrestore;
		_plt_save_size = len;
		break;
	default:
		_plt_fp_save = _elf_rtbndr_fp_save_orig;
		_plt_fp_restore = _elf_rtbndr_fp_restore_orig;
		/*
		 * The ABI says that 8 floating point registers are used for
		 * passing arguments (%xmm0 through %xmm7). Because these
		 * registers on some platforms may shadow the %ymm and %zmm
		 * registers, we end up needing to size this for the maximally
		 * sized register we care about, a 512-bit (64-byte) zmm
		 * register.
		 */
		_plt_save_size = 64 * 8;
		break;
	}
}

/* VARARGS */
unsigned long
_setup(Boot *ebp, Dyn *ld_dyn)
{
	ulong_t		reladdr, relacount, ld_base = 0;
	ulong_t		relaent = 0, pltrelsz = 0;
	ulong_t		strtab, soname, interp_base = 0;
	char		*_rt_name, **_envp, **_argv;
	int		_syspagsz = 0, fd = -1;
	uint_t		_flags = 0;
	uint_t		hwcap[3] = { 0, 0, 0 };
	Dyn		*dyn_ptr;
	Phdr		*phdr = NULL;
	Rt_map		*lmp;
	auxv_t		*auxv, *_auxv;
	uid_t		uid = (uid_t)-1, euid = (uid_t)-1;
	gid_t		gid = (gid_t)-1, egid = (gid_t)-1;
	char		*_platform = NULL, *_execname = NULL, *_emulator = NULL;
	int		auxflags = -1, fpkind = -1;
	size_t		fpsize = 0;

	/*
	 * Scan the bootstrap structure to pick up the basics.
	 */
	for (; ebp->eb_tag != EB_NULL; ebp++)
		switch (ebp->eb_tag) {
		case EB_LDSO_BASE:
			ld_base = (unsigned long)ebp->eb_un.eb_val;
			break;
		case EB_ARGV:
			_argv = (char **)ebp->eb_un.eb_ptr;
			break;
		case EB_ENVP:
			_envp = (char **)ebp->eb_un.eb_ptr;
			break;
		case EB_AUXV:
			_auxv = (auxv_t *)ebp->eb_un.eb_ptr;
			break;
		case EB_PAGESIZE:
			_syspagsz = (int)ebp->eb_un.eb_val;
			break;
		}

	/*
	 * Search the aux. vector for the information passed by exec.
	 */
	for (auxv = _auxv; auxv->a_type != AT_NULL; auxv++) {
		switch (auxv->a_type) {
		case AT_EXECFD:
			/* this is the old exec that passes a file descriptor */
			fd = (int)auxv->a_un.a_val;
			break;
		case AT_FLAGS:
			/* processor flags (MAU available, etc) */
			_flags = auxv->a_un.a_val;
			break;
		case AT_PAGESZ:
			/* system page size */
			_syspagsz = (int)auxv->a_un.a_val;
			break;
		case AT_PHDR:
			/* address of the segment table */
			phdr = (Phdr *)auxv->a_un.a_ptr;
			break;
		case AT_BASE:
			/* interpreter base address */
			if (ld_base == 0)
				ld_base = auxv->a_un.a_val;
			interp_base = auxv->a_un.a_val;
			break;
		case AT_SUN_UID:
			/* effective user id for the executable */
			euid = (uid_t)auxv->a_un.a_val;
			break;
		case AT_SUN_RUID:
			/* real user id for the executable */
			uid = (uid_t)auxv->a_un.a_val;
			break;
		case AT_SUN_GID:
			/* effective group id for the executable */
			egid = (gid_t)auxv->a_un.a_val;
			break;
		case AT_SUN_RGID:
			/* real group id for the executable */
			gid = (gid_t)auxv->a_un.a_val;
			break;
		case AT_SUN_PLATFORM:
			/* platform name */
			_platform = auxv->a_un.a_ptr;
			break;
		case AT_SUN_EXECNAME:
			/* full pathname of execed object */
			_execname = auxv->a_un.a_ptr;
			break;
		case AT_SUN_AUXFLAGS:
			/* auxiliary flags */
			auxflags = (int)auxv->a_un.a_val;
			break;
		case AT_SUN_HWCAP:
			/* hardware capabilities */
			hwcap[0] = (uint_t)auxv->a_un.a_val;
			break;
		case AT_SUN_HWCAP2:
			/* hardware capabilities */
			hwcap[1] = (uint_t)auxv->a_un.a_val;
			break;
		case AT_SUN_HWCAP3:
			/* hardware capabilities */
			hwcap[2] = (uint_t)auxv->a_un.a_val;
			break;
		case AT_SUN_EMULATOR:
			/* name of emulation library, if any */
			_emulator = auxv->a_un.a_ptr;
			break;
		case AT_SUN_FPTYPE:
			fpkind = (int)auxv->a_un.a_val;
			break;
		case AT_SUN_FPSIZE:
			fpsize = (size_t)auxv->a_un.a_val;
			break;
		}
	}

	/*
	 * Get needed info from ld.so's dynamic structure.
	 */
	/* LINTED */
	dyn_ptr = (Dyn *)((char *)ld_dyn + ld_base);
	for (ld_dyn = dyn_ptr; ld_dyn->d_tag != DT_NULL; ld_dyn++) {
		switch (ld_dyn->d_tag) {
		case DT_RELA:
			reladdr = ld_dyn->d_un.d_ptr + ld_base;
			break;
		case DT_RELACOUNT:
			relacount = ld_dyn->d_un.d_val;
			break;
		case DT_RELAENT:
			relaent = ld_dyn->d_un.d_val;
			break;
		case DT_PLTRELSZ:
			pltrelsz = ld_dyn->d_un.d_val;
			break;
		case DT_STRTAB:
			strtab = ld_dyn->d_un.d_ptr + ld_base;
			break;
		case DT_SONAME:
			soname = ld_dyn->d_un.d_val;
			break;
		}
	}
	_rt_name = (char *)strtab + soname;

	/*
	 * If we don't have a RELAENT, just assume the size.
	 */
	if (relaent == 0)
		relaent = sizeof (Rela);

	/*
	 * As all global symbol references within ld.so.1 are protected
	 * (symbolic), only RELATIVE and JMPSLOT relocations should be left
	 * to process at runtime.  Process all relocations now.
	 */
	relacount += (pltrelsz / relaent);
	for (; relacount; relacount--) {
		ulong_t	roffset;

		roffset = ((Rela *)reladdr)->r_offset + ld_base;
		*((ulong_t *)roffset) += ld_base +
		    ((Rela *)reladdr)->r_addend;
		reladdr += relaent;
	}

	/*
	 * If an emulation library is being used, use that as the linker's
	 * effective executable name. The real executable is not linked by this
	 * linker.
	 */
	if (_emulator != NULL) {
		_execname = _emulator;
		rtld_flags2 |= RT_FL2_BRANDED;
	}

	/*
	 * Initialize the dyn_plt_ent_size field.  It currently contains the
	 * size of the dyn_plt_template.  It still needs to be aligned and have
	 * space for the 'dyn_data' area added.
	 */
	dyn_plt_ent_size = ROUND(dyn_plt_ent_size, M_WORD_ALIGN) +
	    sizeof (uintptr_t) + sizeof (uintptr_t) + sizeof (ulong_t) +
	    sizeof (ulong_t) + sizeof (Sym);

	/*
	 * Initialize the amd64 specific PLT relocation constants based on the
	 * FP information that we have.
	 */
	_setup_plt_fpu(fpkind, fpsize);

	/*
	 * Continue with generic startup processing.
	 */
	if ((lmp = setup((char **)_envp, (auxv_t *)_auxv, _flags, _platform,
	    _syspagsz, _rt_name, ld_base, interp_base, fd, phdr,
	    _execname, _argv, uid, euid, gid, egid, auxflags,
	    hwcap)) == NULL) {
		rtldexit(&lml_main, 1);
	}

	return (LM_ENTRY_PT(lmp)());
}
/*
 * 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) 2004, 2010, Oracle and/or its affiliates. All rights reserved.
 * Copyright (c) 2012, Joyent, Inc. All rights reserved.
 */

/*
 * amd64 machine dependent and ELF file class dependent functions.
 * Contains routines for performing function binding and symbol relocations.
 */

#include	<stdio.h>
#include	<sys/elf.h>
#include	<sys/elf_amd64.h>
#include	<sys/mman.h>
#include	<dlfcn.h>
#include	<synch.h>
#include	<string.h>
#include	<debug.h>
#include	<reloc.h>
#include	<conv.h>
#include	"_rtld.h"
#include	"_audit.h"
#include	"_elf.h"
#include	"_inline_gen.h"
#include	"_inline_reloc.h"
#include	"msg.h"

extern void	elf_rtbndr(Rt_map *, ulong_t, caddr_t);

int
elf_mach_flags_check(Rej_desc *rej, Ehdr *ehdr)
{
	/*
	 * Check machine type and flags.
	 */
	if (ehdr->e_flags != 0) {
		rej->rej_type = SGS_REJ_BADFLAG;
		rej->rej_info = (uint_t)ehdr->e_flags;
		return (0);
	}
	return (1);
}

void
ldso_plt_init(Rt_map *lmp)
{
	/*
	 * There is no need to analyze ld.so because we don't map in any of
	 * its dependencies.  However we may map these dependencies in later
	 * (as if ld.so had dlopened them), so initialize the plt and the
	 * permission information.
	 */
	if (PLTGOT(lmp))
		elf_plt_init((PLTGOT(lmp)), (caddr_t)lmp);
}

static const uchar_t dyn_plt_template[] = {
/* 0x00 */  0x55,			/* pushq %rbp */
/* 0x01 */  0x48, 0x89, 0xe5,		/* movq  %rsp, %rbp */
/* 0x04 */  0x48, 0x83, 0xec, 0x10,	/* subq	 $0x10, %rsp */
/* 0x08 */  0x4c, 0x8d, 0x1d, 0x00,	/* leaq  trace_fields(%rip), %r11 */
		0x00, 0x00, 0x00,
/* 0x0f */  0x4c, 0x89, 0x5d, 0xf8,	/* movq  %r11, -0x8(%rbp) */
/* 0x13 */  0x49, 0xbb, 0x00, 0x00, 	/* movq  $elf_plt_trace, %r11 */
		0x00, 0x00, 0x00,
		0x00, 0x00, 0x00,
/* 0x1d */  0x41, 0xff, 0xe3		/* jmp   *%r11 */
/* 0x20 */
};

/*
 * And the virutal outstanding relocations against the
 * above block are:
 *
 *	reloc		offset	Addend	symbol
 *	R_AMD64_PC32	0x0b	-4	trace_fields
 *	R_AMD64_64	0x15	0	elf_plt_trace
 */

#define	TRCREL1OFF	0x0b
#define	TRCREL2OFF	0x15

int	dyn_plt_ent_size = sizeof (dyn_plt_template);

/*
 * the dynamic plt entry is:
 *
 *	pushq	%rbp
 *	movq	%rsp, %rbp
 *	subq	$0x10, %rsp
 *	leaq	trace_fields(%rip), %r11
 *	movq	%r11, -0x8(%rbp)
 *	movq	$elf_plt_trace, %r11
 *	jmp	*%r11
 * dyn_data:
 *	.align  8
 *	uintptr_t	reflmp
 *	uintptr_t	deflmp
 *	uint_t		symndx
 *	uint_t		sb_flags
 *	Sym		symdef
 */
static caddr_t
elf_plt_trace_write(ulong_t roffset, Rt_map *rlmp, Rt_map *dlmp, Sym *sym,
    uint_t symndx, uint_t pltndx, caddr_t to, uint_t sb_flags, int *fail)
{
	extern int	elf_plt_trace();
	ulong_t		got_entry;
	uchar_t		*dyn_plt;
	uintptr_t	*dyndata;

	/*
	 * We only need to add the glue code if there is an auditing
	 * library that is interested in this binding.
	 */
	dyn_plt = (uchar_t *)((uintptr_t)AUDINFO(rlmp)->ai_dynplts +
	    (pltndx * dyn_plt_ent_size));

	/*
	 * Have we initialized this dynamic plt entry yet?  If we haven't do it
	 * now.  Otherwise this function has been called before, but from a
	 * different plt (ie. from another shared object).  In that case
	 * we just set the plt to point to the new dyn_plt.
	 */
	if (*dyn_plt == 0) {
		Sym	*symp;
		Xword	symvalue;
		Lm_list	*lml = LIST(rlmp);

		(void) memcpy((void *)dyn_plt, dyn_plt_template,
		    sizeof (dyn_plt_template));
		dyndata = (uintptr_t *)((uintptr_t)dyn_plt +
		    ROUND(sizeof (dyn_plt_template), M_WORD_ALIGN));

		/*
		 * relocate:
		 *	leaq	trace_fields(%rip), %r11
		 *	R_AMD64_PC32	0x0b	-4	trace_fields
		 */
		symvalue = (Xword)((uintptr_t)dyndata -
		    (uintptr_t)(&dyn_plt[TRCREL1OFF]) - 4);
		if (do_reloc_rtld(R_AMD64_PC32, &dyn_plt[TRCREL1OFF],
		    &symvalue, MSG_ORIG(MSG_SYM_LADYNDATA),
		    MSG_ORIG(MSG_SPECFIL_DYNPLT), lml) == 0) {
			*fail = 1;
			return (0);
		}

		/*
		 * relocating:
		 *	movq	$elf_plt_trace, %r11
		 *	R_AMD64_64	0x15	0	elf_plt_trace
		 */
		symvalue = (Xword)elf_plt_trace;
		if (do_reloc_rtld(R_AMD64_64, &dyn_plt[TRCREL2OFF],
		    &symvalue, MSG_ORIG(MSG_SYM_ELFPLTTRACE),
		    MSG_ORIG(MSG_SPECFIL_DYNPLT), lml) == 0) {
			*fail = 1;
			return (0);
		}

		*dyndata++ = (uintptr_t)rlmp;
		*dyndata++ = (uintptr_t)dlmp;
		*dyndata = (uintptr_t)(((uint64_t)sb_flags << 32) | symndx);
		dyndata++;
		symp = (Sym *)dyndata;
		*symp = *sym;
		symp->st_value = (Addr)to;
	}

	got_entry = (ulong_t)roffset;
	*(ulong_t *)got_entry = (ulong_t)dyn_plt;
	return ((caddr_t)dyn_plt);
}

/*
 * Function binding routine - invoked on the first call to a function through
 * the procedure linkage table;
 * passes first through an assembly language interface.
 *
 * Takes the offset into the relocation table of the associated
 * relocation entry and the address of the link map (rt_private_map struct)
 * for the entry.
 *
 * Returns the address of the function referenced after re-writing the PLT
 * entry to invoke the function directly.
 *
 * On error, causes process to terminate with a signal.
 */
ulong_t
elf_bndr(Rt_map *lmp, ulong_t pltndx, caddr_t from)
{
	Rt_map		*nlmp, *llmp;
	ulong_t		addr, reloff, symval, rsymndx;
	char		*name;
	Rela		*rptr;
	Sym		*rsym, *nsym;
	uint_t		binfo, sb_flags = 0, dbg_class;
	Slookup		sl;
	Sresult		sr;
	int		entry, lmflags;
	Lm_list		*lml;

	/*
	 * For compatibility with libthread (TI_VERSION 1) we track the entry
	 * value.  A zero value indicates we have recursed into ld.so.1 to
	 * further process a locking request.  Under this recursion we disable
	 * tsort and cleanup activities.
	 */
	entry = enter(0);

	lml = LIST(lmp);
	if ((lmflags = lml->lm_flags) & LML_FLG_RTLDLM) {
		dbg_class = dbg_desc->d_class;
		dbg_desc->d_class = 0;
	}

	/*
	 * Perform some basic sanity checks.  If we didn't get a load map or
	 * the relocation offset is invalid then its possible someone has walked
	 * over the .got entries or jumped to plt0 out of the blue.
	 */
	if ((!lmp) && (pltndx <=
	    (ulong_t)PLTRELSZ(lmp) / (ulong_t)RELENT(lmp))) {
		Conv_inv_buf_t inv_buf;

		eprintf(lml, ERR_FATAL, MSG_INTL(MSG_REL_PLTREF),
		    conv_reloc_amd64_type(R_AMD64_JUMP_SLOT, 0, &inv_buf),
		    EC_NATPTR(lmp), EC_XWORD(pltndx), EC_NATPTR(from));
		rtldexit(lml, 1);
	}
	reloff = pltndx * (ulong_t)RELENT(lmp);

	/*
	 * Use relocation entry to get symbol table entry and symbol name.
	 */
	addr = (ulong_t)JMPREL(lmp);
	rptr = (Rela *)(addr + reloff);
	rsymndx = ELF_R_SYM(rptr->r_info);
	rsym = (Sym *)((ulong_t)SYMTAB(lmp) + (rsymndx * SYMENT(lmp)));
	name = (char *)(STRTAB(lmp) + rsym->st_name);

	/*
	 * Determine the last link-map of this list, this'll be the starting
	 * point for any tsort() processing.
	 */
	llmp = lml->lm_tail;

	/*
	 * Find definition for symbol.  Initialize the symbol lookup, and
	 * symbol result, data structures.
	 */
	SLOOKUP_INIT(sl, name, lmp, lml->lm_head, ld_entry_cnt, 0,
	    rsymndx, rsym, 0, LKUP_DEFT);
	SRESULT_INIT(sr, name);

	if (lookup_sym(&sl, &sr, &binfo, NULL) == 0) {
		eprintf(lml, ERR_FATAL, MSG_INTL(MSG_REL_NOSYM), NAME(lmp),
		    demangle(name));
		rtldexit(lml, 1);
	}

	name = (char *)sr.sr_name;
	nlmp = sr.sr_dmap;
	nsym = sr.sr_sym;

	symval = nsym->st_value;

	if (!(FLAGS(nlmp) & FLG_RT_FIXED) &&
	    (nsym->st_shndx != SHN_ABS))
		symval += ADDR(nlmp);
	if ((lmp != nlmp) && ((FLAGS1(nlmp) & FL1_RT_NOINIFIN) == 0)) {
		/*
		 * Record that this new link map is now bound to the caller.
		 */
		if (bind_one(lmp, nlmp, BND_REFER) == 0)
			rtldexit(lml, 1);
	}

	if ((lml->lm_tflags | AFLAGS(lmp) | AFLAGS(nlmp)) &
	    LML_TFLG_AUD_SYMBIND) {
		uint_t	symndx = (((uintptr_t)nsym -
		    (uintptr_t)SYMTAB(nlmp)) / SYMENT(nlmp));
		symval = audit_symbind(lmp, nlmp, nsym, symndx, symval,
		    &sb_flags);
	}

	if (!(rtld_flags & RT_FL_NOBIND)) {
		addr = rptr->r_offset;
		if (!(FLAGS(lmp) & FLG_RT_FIXED))
			addr += ADDR(lmp);
		if (((lml->lm_tflags | AFLAGS(lmp)) &
		    (LML_TFLG_AUD_PLTENTER | LML_TFLG_AUD_PLTEXIT)) &&
		    AUDINFO(lmp)->ai_dynplts) {
			int	fail = 0;
			uint_t	pltndx = reloff / sizeof (Rela);
			uint_t	symndx = (((uintptr_t)nsym -
			    (uintptr_t)SYMTAB(nlmp)) / SYMENT(nlmp));

			symval = (ulong_t)elf_plt_trace_write(addr, lmp, nlmp,
			    nsym, symndx, pltndx, (caddr_t)symval, sb_flags,
			    &fail);
			if (fail)
				rtldexit(lml, 1);
		} else {
			/*
			 * Write standard PLT entry to jump directly
			 * to newly bound function.
			 */
			*(ulong_t *)addr = symval;
		}
	}

	/*
	 * Print binding information and rebuild PLT entry.
	 */
	DBG_CALL(Dbg_bind_global(lmp, (Addr)from, (Off)(from - ADDR(lmp)),
	    (Xword)(reloff / sizeof (Rela)), PLT_T_FULL, nlmp, (Addr)symval,
	    nsym->st_value, name, binfo));

	/*
	 * Complete any processing for newly loaded objects.  Note we don't
	 * know exactly where any new objects are loaded (we know the object
	 * that supplied the symbol, but others may have been loaded lazily as
	 * we searched for the symbol), so sorting starts from the last
	 * link-map know on entry to this routine.
	 */
	if (entry)
		load_completion(llmp);

	/*
	 * Some operations like dldump() or dlopen()'ing a relocatable object
	 * result in objects being loaded on rtld's link-map, make sure these
	 * objects are initialized also.
	 */
	if ((LIST(nlmp)->lm_flags & LML_FLG_RTLDLM) && LIST(nlmp)->lm_init)
		load_completion(nlmp);

	/*
	 * Make sure the object to which we've bound has had it's .init fired.
	 * Cleanup before return to user code.
	 */
	if (entry) {
		is_dep_init(nlmp, lmp);
		leave(lml, 0);
	}

	if (lmflags & LML_FLG_RTLDLM)
		dbg_desc->d_class = dbg_class;

	return (symval);
}

/*
 * Read and process the relocations for one link object, we assume all
 * relocation sections for loadable segments are stored contiguously in
 * the file.
 */
int
elf_reloc(Rt_map *lmp, uint_t plt, int *in_nfavl, APlist **textrel)
{
	ulong_t		relbgn, relend, relsiz, basebgn;
	ulong_t		pltbgn, pltend, _pltbgn, _pltend;
	ulong_t		roffset, rsymndx, psymndx = 0;
	ulong_t		dsymndx;
	uchar_t		rtype;
	long		reladd, value, pvalue;
	Sym		*symref, *psymref, *symdef, *psymdef;
	Syminfo		*sip;
	char		*name, *pname;
	Rt_map		*_lmp, *plmp;
	int		ret = 1, noplt = 0;
	int		relacount = RELACOUNT(lmp), plthint = 0;
	Rela		*rel;
	uint_t		binfo, pbinfo;
	APlist		*bound = NULL;

	/*
	 * Although only necessary for lazy binding, initialize the first
	 * global offset entry to go to elf_rtbndr().  dbx(1) seems
	 * to find this useful.
	 */
	if ((plt == 0) && PLTGOT(lmp)) {
		mmapobj_result_t	*mpp;

		/*
		 * Make sure the segment is writable.
		 */
		if ((((mpp =
		    find_segment((caddr_t)PLTGOT(lmp), lmp)) != NULL) &&
		    ((mpp->mr_prot & PROT_WRITE) == 0)) &&
		    ((set_prot(lmp, mpp, 1) == 0) ||
		    (aplist_append(textrel, mpp, AL_CNT_TEXTREL) == NULL)))
			return (0);

		elf_plt_init(PLTGOT(lmp), (caddr_t)lmp);
	}

	/*
	 * Initialize the plt start and end addresses.
	 */
	if ((pltbgn = (ulong_t)JMPREL(lmp)) != 0)
		pltend = pltbgn + (ulong_t)(PLTRELSZ(lmp));

	relsiz = (ulong_t)(RELENT(lmp));
	basebgn = ADDR(lmp);

	if (PLTRELSZ(lmp))
		plthint = PLTRELSZ(lmp) / relsiz;

	/*
	 * If we've been called upon to promote an RTLD_LAZY object to an
	 * RTLD_NOW then we're only interested in scaning the .plt table.
	 * An uninitialized .plt is the case where the associated got entry
	 * points back to the plt itself.  Determine the range of the real .plt
	 * entries using the _PROCEDURE_LINKAGE_TABLE_ symbol.
	 */
	if (plt) {
		Slookup	sl;
		Sresult	sr;

		relbgn = pltbgn;
		relend = pltend;
		if (!relbgn || (relbgn == relend))
			return (1);

		/*
		 * Initialize the symbol lookup, and symbol result, data
		 * structures.
		 */
		SLOOKUP_INIT(sl, MSG_ORIG(MSG_SYM_PLT), lmp, lmp, ld_entry_cnt,
		    elf_hash(MSG_ORIG(MSG_SYM_PLT)), 0, 0, 0, LKUP_DEFT);
		SRESULT_INIT(sr, MSG_ORIG(MSG_SYM_PLT));

		if (elf_find_sym(&sl, &sr, &binfo, NULL) == 0)
			return (1);

		symdef = sr.sr_sym;
		_pltbgn = symdef->st_value;
		if (!(FLAGS(lmp) & FLG_RT_FIXED) &&
		    (symdef->st_shndx != SHN_ABS))
			_pltbgn += basebgn;
		_pltend = _pltbgn + (((PLTRELSZ(lmp) / relsiz)) *
		    M_PLT_ENTSIZE) + M_PLT_RESERVSZ;

	} else {
		/*
		 * The relocation sections appear to the run-time linker as a
		 * single table.  Determine the address of the beginning and end
		 * of this table.  There are two different interpretations of
		 * the ABI at this point:
		 *
		 *   o	The REL table and its associated RELSZ indicate the
		 *	concatenation of *all* relocation sections (this is the
		 *	model our link-editor constructs).
		 *
		 *   o	The REL table and its associated RELSZ indicate the
		 *	concatenation of all *but* the .plt relocations.  These
		 *	relocations are specified individually by the JMPREL and
		 *	PLTRELSZ entries.
		 *
		 * Determine from our knowledege of the relocation range and
		 * .plt range, the range of the total relocation table.  Note
		 * that one other ABI assumption seems to be that the .plt
		 * relocations always follow any other relocations, the
		 * following range checking drops that assumption.
		 */
		relbgn = (ulong_t)(REL(lmp));
		relend = relbgn + (ulong_t)(RELSZ(lmp));
		if (pltbgn) {
			if (!relbgn || (relbgn > pltbgn))
				relbgn = pltbgn;
			if (!relbgn || (relend < pltend))
				relend = pltend;
		}
	}
	if (!relbgn || (relbgn == relend)) {
		DBG_CALL(Dbg_reloc_run(lmp, 0, plt, DBG_REL_NONE));
		return (1);
	}
	DBG_CALL(Dbg_reloc_run(lmp, M_REL_SHT_TYPE, plt, DBG_REL_START));

	/*
	 * If we're processing a dynamic executable in lazy mode there is no
	 * need to scan the .rel.plt table, however if we're processing a shared
	 * object in lazy mode the .got addresses associated to each .plt must
	 * be relocated to reflect the location of the shared object.
	 */
	if (pltbgn && ((MODE(lmp) & RTLD_NOW) == 0) &&
	    (FLAGS(lmp) & FLG_RT_FIXED))
		noplt = 1;

	sip = SYMINFO(lmp);
	/*
	 * Loop through relocations.
	 */
	while (relbgn < relend) {
		mmapobj_result_t	*mpp;
		uint_t			sb_flags = 0;

		rtype = ELF_R_TYPE(((Rela *)relbgn)->r_info, M_MACH);

		/*
		 * If this is a RELATIVE relocation in a shared object (the
		 * common case), and if we are not debugging, then jump into a
		 * tighter relocation loop (elf_reloc_relative).
		 */
		if ((rtype == R_AMD64_RELATIVE) &&
		    ((FLAGS(lmp) & FLG_RT_FIXED) == 0) && (DBG_ENABLED == 0)) {
			if (relacount) {
				relbgn = elf_reloc_relative_count(relbgn,
				    relacount, relsiz, basebgn, lmp,
				    textrel, 0);
				relacount = 0;
			} else {
				relbgn = elf_reloc_relative(relbgn, relend,
				    relsiz, basebgn, lmp, textrel, 0);
			}
			if (relbgn >= relend)
				break;
			rtype = ELF_R_TYPE(((Rela *)relbgn)->r_info, M_MACH);
		}

		roffset = ((Rela *)relbgn)->r_offset;

		/*
		 * If this is a shared object, add the base address to offset.
		 */
		if (!(FLAGS(lmp) & FLG_RT_FIXED)) {
			/*
			 * If we're processing lazy bindings, we have to step
			 * through the plt entries and add the base address
			 * to the corresponding got entry.
			 */
			if (plthint && (plt == 0) &&
			    (rtype == R_AMD64_JUMP_SLOT) &&
			    ((MODE(lmp) & RTLD_NOW) == 0)) {
				relbgn = elf_reloc_relative_count(relbgn,
				    plthint, relsiz, basebgn, lmp, textrel, 1);
				plthint = 0;
				continue;
			}
			roffset += basebgn;
		}

		reladd = (long)(((Rela *)relbgn)->r_addend);
		rsymndx = ELF_R_SYM(((Rela *)relbgn)->r_info);
		rel = (Rela *)relbgn;
		relbgn += relsiz;

		/*
		 * Optimizations.
		 */
		if (rtype == R_AMD64_NONE)
			continue;
		if (noplt && ((ulong_t)rel >= pltbgn) &&
		    ((ulong_t)rel < pltend)) {
			relbgn = pltend;
			continue;
		}

		/*
		 * If we're promoting plts, determine if this one has already
		 * been written.
		 */
		if (plt && ((*(ulong_t *)roffset < _pltbgn) ||
		    (*(ulong_t *)roffset > _pltend)))
			continue;

		/*
		 * If this relocation is not against part of the image
		 * mapped into memory we skip it.
		 */
		if ((mpp = find_segment((caddr_t)roffset, lmp)) == NULL) {
			elf_reloc_bad(lmp, (void *)rel, rtype, roffset,
			    rsymndx);
			continue;
		}

		binfo = 0;
		/*
		 * If a symbol index is specified then get the symbol table
		 * entry, locate the symbol definition, and determine its
		 * address.
		 */
		if (rsymndx) {
			/*
			 * If a Syminfo section is provided, determine if this
			 * symbol is deferred, and if so, skip this relocation.
			 */
			if (sip && is_sym_deferred((ulong_t)rel, basebgn, lmp,
			    textrel, sip, rsymndx))
				continue;

			/*
			 * Get the local symbol table entry.
			 */
			symref = (Sym *)((ulong_t)SYMTAB(lmp) +
			    (rsymndx * SYMENT(lmp)));

			/*
			 * If this is a local symbol, just use the base address.
			 * (we should have no local relocations in the
			 * executable).
			 */
			if (ELF_ST_BIND(symref->st_info) == STB_LOCAL) {
				value = basebgn;
				name = NULL;

				/*
				 * Special case TLS relocations.
				 */
				if (rtype == R_AMD64_DTPMOD64) {
					/*
					 * Use the TLS modid.
					 */
					value = TLSMODID(lmp);

				} else if ((rtype == R_AMD64_TPOFF64) ||
				    (rtype == R_AMD64_TPOFF32)) {
					if ((value = elf_static_tls(lmp, symref,
					    rel, rtype, 0, roffset, 0)) == 0) {
						ret = 0;
						break;
					}
				}
			} else {
				/*
				 * If the symbol index is equal to the previous
				 * symbol index relocation we processed then
				 * reuse the previous values. (Note that there
				 * have been cases where a relocation exists
				 * against a copy relocation symbol, our ld(1)
				 * should optimize this away, but make sure we
				 * don't use the same symbol information should
				 * this case exist).
				 */
				if ((rsymndx == psymndx) &&
				    (rtype != R_AMD64_COPY)) {
					/* LINTED */
					if (psymdef == 0) {
						DBG_CALL(Dbg_bind_weak(lmp,
						    (Addr)roffset, (Addr)
						    (roffset - basebgn), name));
						continue;
					}
					/* LINTED */
					value = pvalue;
					/* LINTED */
					name = pname;
					/* LINTED */
					symdef = psymdef;
					/* LINTED */
					symref = psymref;
					/* LINTED */
					_lmp = plmp;
					/* LINTED */
					binfo = pbinfo;

					if ((LIST(_lmp)->lm_tflags |
					    AFLAGS(_lmp)) &
					    LML_TFLG_AUD_SYMBIND) {
						value = audit_symbind(lmp, _lmp,
						    /* LINTED */
						    symdef, dsymndx, value,
						    &sb_flags);
					}
				} else {
					Slookup		sl;
					Sresult		sr;

					/*
					 * Lookup the symbol definition.
					 * Initialize the symbol lookup, and
					 * symbol result, data structure.
					 */
					name = (char *)(STRTAB(lmp) +
					    symref->st_name);

					SLOOKUP_INIT(sl, name, lmp, 0,
					    ld_entry_cnt, 0, rsymndx, symref,
					    rtype, LKUP_STDRELOC);
					SRESULT_INIT(sr, name);
					symdef = NULL;

					if (lookup_sym(&sl, &sr, &binfo,
					    in_nfavl)) {
						name = (char *)sr.sr_name;
						_lmp = sr.sr_dmap;
						symdef = sr.sr_sym;
					}

					/*
					 * If the symbol is not found and the
					 * reference was not to a weak symbol,
					 * report an error.  Weak references
					 * may be unresolved.
					 */
					/* BEGIN CSTYLED */
					if (symdef == 0) {
					    if (sl.sl_bind != STB_WEAK) {
						if (elf_reloc_error(lmp, name,
						    rel, binfo))
							continue;

						ret = 0;
						break;

					    } else {
						psymndx = rsymndx;
						psymdef = 0;

						DBG_CALL(Dbg_bind_weak(lmp,
						    (Addr)roffset, (Addr)
						    (roffset - basebgn), name));
						continue;
					    }
					}
					/* END CSTYLED */

					/*
					 * If symbol was found in an object
					 * other than the referencing object
					 * then record the binding.
					 */
					if ((lmp != _lmp) && ((FLAGS1(_lmp) &
					    FL1_RT_NOINIFIN) == 0)) {
						if (aplist_test(&bound, _lmp,
						    AL_CNT_RELBIND) == 0) {
							ret = 0;
							break;
						}
					}

					/*
					 * Calculate the location of definition;
					 * symbol value plus base address of
					 * containing shared object.
					 */
					if (IS_SIZE(rtype))
						value = symdef->st_size;
					else
						value = symdef->st_value;

					if (!(FLAGS(_lmp) & FLG_RT_FIXED) &&
					    !(IS_SIZE(rtype)) &&
					    (symdef->st_shndx != SHN_ABS) &&
					    (ELF_ST_TYPE(symdef->st_info) !=
					    STT_TLS))
						value += ADDR(_lmp);

					/*
					 * Retain this symbol index and the
					 * value in case it can be used for the
					 * subsequent relocations.
					 */
					if (rtype != R_AMD64_COPY) {
						psymndx = rsymndx;
						pvalue = value;
						pname = name;
						psymdef = symdef;
						psymref = symref;
						plmp = _lmp;
						pbinfo = binfo;
					}
					if ((LIST(_lmp)->lm_tflags |
					    AFLAGS(_lmp)) &
					    LML_TFLG_AUD_SYMBIND) {
						dsymndx = (((uintptr_t)symdef -
						    (uintptr_t)SYMTAB(_lmp)) /
						    SYMENT(_lmp));
						value = audit_symbind(lmp, _lmp,
						    symdef, dsymndx, value,
						    &sb_flags);
					}
				}

				/*
				 * If relocation is PC-relative, subtract
				 * offset address.
				 */
				if (IS_PC_RELATIVE(rtype))
					value -= roffset;

				/*
				 * Special case TLS relocations.
				 */
				if (rtype == R_AMD64_DTPMOD64) {
					/*
					 * Relocation value is the TLS modid.
					 */
					value = TLSMODID(_lmp);

				} else if ((rtype == R_AMD64_TPOFF64) ||
				    (rtype == R_AMD64_TPOFF32)) {
					if ((value = elf_static_tls(_lmp,
					    symdef, rel, rtype, name, roffset,
					    value)) == 0) {
						ret = 0;
						break;
					}
				}
			}
		} else {
			/*
			 * Special cases.
			 */
			if (rtype == R_AMD64_DTPMOD64) {
				/*
				 * TLS relocation value is the TLS modid.
				 */
				value = TLSMODID(lmp);
			} else
				value = basebgn;

			name = NULL;
		}

		DBG_CALL(Dbg_reloc_in(LIST(lmp), ELF_DBG_RTLD, M_MACH,
		    M_REL_SHT_TYPE, rel, NULL, 0, name));

		/*
		 * Make sure the segment is writable.
		 */
		if (((mpp->mr_prot & PROT_WRITE) == 0) &&
		    ((set_prot(lmp, mpp, 1) == 0) ||
		    (aplist_append(textrel, mpp, AL_CNT_TEXTREL) == NULL))) {
			ret = 0;
			break;
		}

		/*
		 * Call relocation routine to perform required relocation.
		 */
		switch (rtype) {
		case R_AMD64_COPY:
			if (elf_copy_reloc(name, symref, lmp, (void *)roffset,
			    symdef, _lmp, (const void *)value) == 0)
				ret = 0;
			break;
		case R_AMD64_JUMP_SLOT:
			if (((LIST(lmp)->lm_tflags | AFLAGS(lmp)) &
			    (LML_TFLG_AUD_PLTENTER | LML_TFLG_AUD_PLTEXIT)) &&
			    AUDINFO(lmp)->ai_dynplts) {
				int	fail = 0;
				int	pltndx = (((ulong_t)rel -
				    (uintptr_t)JMPREL(lmp)) / relsiz);
				int	symndx = (((uintptr_t)symdef -
				    (uintptr_t)SYMTAB(_lmp)) / SYMENT(_lmp));

				(void) elf_plt_trace_write(roffset, lmp, _lmp,
				    symdef, symndx, pltndx, (caddr_t)value,
				    sb_flags, &fail);
				if (fail)
					ret = 0;
			} else {
				/*
				 * Write standard PLT entry to jump directly
				 * to newly bound function.
				 */
				DBG_CALL(Dbg_reloc_apply_val(LIST(lmp),
				    ELF_DBG_RTLD, (Xword)roffset,
				    (Xword)value));
				*(ulong_t *)roffset = value;
			}
			break;
		default:
			value += reladd;
			/*
			 * Write the relocation out.
			 */
			if (do_reloc_rtld(rtype, (uchar_t *)roffset,
			    (Xword *)&value, name, NAME(lmp), LIST(lmp)) == 0)
				ret = 0;

			DBG_CALL(Dbg_reloc_apply_val(LIST(lmp), ELF_DBG_RTLD,
			    (Xword)roffset, (Xword)value));
		}

		if ((ret == 0) &&
		    ((LIST(lmp)->lm_flags & LML_FLG_TRC_WARN) == 0))
			break;

		if (binfo) {
			DBG_CALL(Dbg_bind_global(lmp, (Addr)roffset,
			    (Off)(roffset - basebgn), (Xword)(-1), PLT_T_FULL,
			    _lmp, (Addr)value, symdef->st_value, name, binfo));
		}
	}

	return (relocate_finish(lmp, bound, ret));
}

/*
 * Initialize the first few got entries so that function calls go to
 * elf_rtbndr:
 *
 *	GOT[GOT_XLINKMAP] =	the address of the link map
 *	GOT[GOT_XRTLD] =	the address of rtbinder
 */
void
elf_plt_init(void *got, caddr_t l)
{
	uint64_t	*_got;
	/* LINTED */
	Rt_map		*lmp = (Rt_map *)l;

	_got = (uint64_t *)got + M_GOT_XLINKMAP;
	*_got = (uint64_t)lmp;
	_got = (uint64_t *)got + M_GOT_XRTLD;
	*_got = (uint64_t)elf_rtbndr;
}

/*
 * Plt writing interface to allow debugging initialization to be generic.
 */
Pltbindtype
/* ARGSUSED1 */
elf_plt_write(uintptr_t addr, uintptr_t vaddr, void *rptr, uintptr_t symval,
	Xword pltndx)
{
	Rela		*rel = (Rela*)rptr;
	uintptr_t	pltaddr;

	pltaddr = addr + rel->r_offset;
	*(ulong_t *)pltaddr = (ulong_t)symval + rel->r_addend;
	DBG_CALL(pltcntfull++);
	return (PLT_T_FULL);
}

/*
 * Provide a machine specific interface to the conversion routine.  By calling
 * the machine specific version, rather than the generic version, we insure that
 * the data tables/strings for all known machine versions aren't dragged into
 * ld.so.1.
 */
const char *
_conv_reloc_type(uint_t rel)
{
	static Conv_inv_buf_t	inv_buf;

	return (conv_reloc_amd64_type(rel, 0, &inv_buf));
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (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) 1988 AT&T
 *	  All Rights Reserved
 *
 *
 * Copyright 2004 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * Bootstrap routine for run-time linker.
 * We get control from exec which has loaded our text and
 * data into the process' address space and created the process
 * stack.
 *
 * On entry, the process stack looks like this:
 *
 *	#			# <- %rsp
 *	#_______________________#  high addresses
 *	#	strings		#
 *	#_______________________#
 *	#	0 word		#
 *	#_______________________#
 *	#	Auxiliary	#
 *	#	entries		#
 *	#	...		#
 *	#	(size varies)	#
 *	#_______________________#
 *	#	0 word		#
 *	#_______________________#
 *	#	Environment	#
 *	#	pointers	#
 *	#	...		#
 *	#	(one word each)	#
 *	#_______________________#
 *	#	0 word		#
 *	#_______________________#
 *	#	Argument	# low addresses
 *	#	pointers	#
 *	#	Argc words	#
 *	#_______________________#
 *	#	argc		#
 *	#_______________________# <- %rbp
 *
 *
 * We must calculate the address at which ld.so was loaded,
 * find the addr of the dynamic section of ld.so, of argv[0], and  of
 * the process' environment pointers - and pass the thing to _setup
 * to handle.  We then call _rtld - on return we jump to the entry
 * point for the executable.
 */

#if	defined(lint)

extern	unsigned long	_setup();
extern	void		atexit_fini();
void
main()
{
	(void) _setup();
	atexit_fini();
}

#else

#include	<link.h>

	.file	"boot.s"
	.text
	.globl	_rt_boot
	.globl	_setup
	.globl	_GLOBAL_OFFSET_TABLE_
	.type	_rt_boot,@function
	.align	4

_rt_alias:
	/ in case we were invoked from libc.so
	jmp	.get_got
_rt_boot:
	/ save for referencing args
	movq	%rsp,%rbp
	/ make room for a max sized boot vector
	subq	$EB_MAX_SIZE64,%rsp
	/ use esi as a pointer to &eb[0]
	movq	%rsp,%rsi
	/ set up tag for argv
	movq	$EB_ARGV,0(%rsi)
	/ get address of argv
	leaq	8(%rbp),%rax
	/ put after tag
	movq	%rax,8(%rsi)
	/ set up tag for envp
	movq	$EB_ENVP,16(%rsi)
	/ get # of args
	movq	(%rbp),%rax
	/ one for the zero & one for argc
	addq	$2,%rax
	/ now points past args & @ envp
	leaq	(%rbp,%rax,8),%rdi
	/ set envp
	movq	%rdi,24(%rsi)
	/ next
.L0:	addq	$8,%rdi
	/ search for 0 at end of env
	cmpq	$0,-8(%rdi)
	jne	.L0
	/ set up tag for auxv
	movq	$EB_AUXV,32(%rsi)
	/ point to auxv
	movq	%rdi,40(%rsi)
	/ set up NULL tag
	movq	$EB_NULL,48(%rsi)

	/ arg1 - address of &eb[0]
	movq	%rsi, %rdi
.get_got:
	leaq	_GLOBAL_OFFSET_TABLE_(%rip), %rbx
	/ addq	$_GLOBAL_OFFSET_TABLE_, %rbx
	movq	%rbx,%r9
	// addq	$[.L2-.L1], %rbx
	movq	%rbx,%r10

	movq	(%rbx),%rsi

	/ _setup(&eb[0], _DYNAMIC)
	call	_setup@PLT
	/ release stack frame
	movq	%rbp,%rsp

	movq	atexit_fini@GOTPCREL(%rip), %rdx
	/ transfer control to the executable
	jmp	*%rax
	.size	_rt_boot,.-_rt_boot
#endif
/*
 * 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 2008 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 * Copyright (c) 2018 Joyent, Inc. All rights reserved.
 */

/*
 * Welcome to the magic behind the PLT (procedure linkage table). When rtld
 * fills out the PLT entries, it will refer initially to the functions in this
 * file. As such our goal is simple:
 *
 *     The lie of the function call must be preserved at all costs.
 *
 * This means that we need to prepare the system for an arbitrary series of
 * instructions to be called. For example, as a side effect of resolving a
 * symbol we may need to open a shared object which will cause any _init
 * functions to be called. Those functions can use any and all of the ABI state
 * that they desire (for example, the FPU registers). Therefore we must save and
 * restore all the ABI mandated registers here.
 *
 * For the full information about what we need to save and restore and why,
 * please see the System V amd64 PS ABI '3.2.3 Parameter Passing'. For general
 * purpose registers, we need to take care of the following:
 *
 * 	%rax	- Used for information about the number of vector arguments
 *	%rdi	- arg0
 *	%rsi	- arg1
 *	%rdx	- arg2
 *	%rcx	- arg3
 *	%r8	- arg4
 *	%r9	- arg5
 *	%r10	- static chain pointer
 *
 * Unfortunately, the world of the FPU is more complicated.
 *
 * The ABI mandates that we must save %xmm0-%xmm7. On newer Intel processors,
 * %xmm0-%xmm7 shadow %ymm0-%ymm7 and %zmm0-%zmm7. Historically, when saving the
 * FPU, we only saved and restored these eight registers. Unfortunately, this
 * process itself ended up having side effects. Because the registers shadow one
 * another, if we saved a full %zmm register when only a %xmm register was
 * valid, we would end up causing the processor to think that the full %zmm
 * register was valid. Once it believed that this was the case, it would then
 * degrade performance of code that only used the %xmm registers.
 *
 * One way to tackle this problem would have been to use xgetbv with ecx=1 to
 * get information about what was actually in use and only save and restore
 * that. You can imagine that this logic roughly ends up as something like:
 *
 *         if (zmm_inuse)
 *		save_zmm()
 *         if (ymm_inuse)
 *		save_ymm()
 *         save_xmm()
 *
 * However, this logic leaves us at the mercy of the branch predictor. This
 * means that all of our efforts can end up still causing the CPU to execute
 * things to make it think that some of these other FPU registers are in use and
 * thus defeat the optimizations that it has.
 *
 * To deal with this problem, Intel has suggested using the xsave family of
 * instructions. The kernel provides information about the size required for the
 * floating point registers as well as which of several methods we need to
 * employ through the aux vector. This gets us out of trying to look at the
 * hardware capabilities and make decisions every time. As part of the
 * amd64-specific portion of rtld, it will process those values and determine
 * the functions on an as-needed basis.
 *
 * There are two different functions that we export. The first is elf_rtbndr().
 * This is basically the glue that gets us into the PLT and to perform
 * relocations. elf_rtbndr() determines the address of the function that we must
 * call and arranges its stack such that when we return from elf_rtbndr() we
 * will instead jump to the actual relocated function which will return to the
 * original caller. Because of this, we must preserve all of the registers that
 * are used for arguments and restore them before returning.
 *
 * The second function we export is elf_plt_trace(). This is used to add support
 * for audit libraries among other things. elf_plt_trace() may or may not call
 * the underlying function as a side effect or merely set up its return to it.
 * This changes how we handle %rax. If we call the function ourself, then we end
 * up making sure that %rax is the return value versus the initial value. In
 * addition, because we get %r11 from the surrounding PLT code, we opt to
 * preserve it in case some of the relocation logic ever ends up calling back
 * into us again.
 */

#if	defined(lint)

#include	<sys/types.h>
#include	<_rtld.h>
#include	<_audit.h>
#include	<_elf.h>
#include	<sys/regset.h>
#include	<sys/auxv_386.h>

#else

#include	<link.h>
#include	<_audit.h>
#include	<sys/asm_linkage.h>
#include	<sys/auxv_386.h>
#include	<sys/x86_archext.h>

/*
 * This macro is used to zero the xsave header. The contents of scratchreg will
 * be destroyed. locreg should contain the starting address of the xsave header.
 */
#define	XSAVE_HEADER_ZERO(scratch, loc) \
	xorq	scratch, scratch;	\
	movq	scratch, 0x200(loc);	\
	movq	scratch, 0x208(loc);	\
	movq	scratch, 0x210(loc);	\
	movq	scratch, 0x218(loc);	\
	movq	scratch, 0x220(loc);	\
	movq	scratch, 0x228(loc);	\
	movq	scratch, 0x230(loc);	\
	movq	scratch, 0x238(loc)


	.file	"boot_elf.s"
	.text

/*
 * This section of the code contains glue functions that are used to take care
 * of saving and restoring the FPU. We deal with this in a few different ways
 * based on the hardware support and what exists. Historically we've only saved
 * and restored the first 8 floating point registers rather than the entire FPU.
 * That implementation still exists here and is kept around mostly as an
 * insurance policy.
 */
	ENTRY(_elf_rtbndr_fp_save_orig)
	movq	org_scapset@GOTPCREL(%rip),%r11
	movq	(%r11),%r11		/* Syscapset_t pointer */
	movl	8(%r11),%edx		/* sc_hw_2 */
	testl	$AV_386_2_AVX512F,%edx
	jne	.save_zmm
	movl	(%r11),%edx		/* sc_hw_1 */
	testl	$AV_386_AVX,%edx
	jne	.save_ymm
	movdqa	%xmm0, (%rdi)
	movdqa	%xmm1, 64(%rdi)
	movdqa	%xmm2, 128(%rdi)
	movdqa	%xmm3, 192(%rdi)
	movdqa	%xmm4, 256(%rdi)
	movdqa	%xmm5, 320(%rdi)
	movdqa	%xmm6, 384(%rdi)
	movdqa	%xmm7, 448(%rdi)
	jmp	.save_finish

.save_ymm:
	vmovdqa	%ymm0, (%rdi)
	vmovdqa	%ymm1, 64(%rdi)
	vmovdqa	%ymm2, 128(%rdi)
	vmovdqa	%ymm3, 192(%rdi)
	vmovdqa	%ymm4, 256(%rdi)
	vmovdqa	%ymm5, 320(%rdi)
	vmovdqa	%ymm6, 384(%rdi)
	vmovdqa	%ymm7, 448(%rdi)
	jmp	.save_finish

.save_zmm:
	vmovdqa64	%zmm0, (%rdi)
	vmovdqa64	%zmm1, 64(%rdi)
	vmovdqa64	%zmm2, 128(%rdi)
	vmovdqa64	%zmm3, 192(%rdi)
	vmovdqa64	%zmm4, 256(%rdi)
	vmovdqa64	%zmm5, 320(%rdi)
	vmovdqa64	%zmm6, 384(%rdi)
	vmovdqa64	%zmm7, 448(%rdi)

.save_finish:
	ret
	SET_SIZE(_elf_rtbndr_fp_save_orig)

	ENTRY(_elf_rtbndr_fp_restore_orig)
	movq	org_scapset@GOTPCREL(%rip),%r11
	movq	(%r11),%r11		/* Syscapset_t pointer */
	movl	8(%r11),%edx		/* sc_hw_2 */
	testl	$AV_386_2_AVX512F,%edx
	jne	.restore_zmm
	movl	(%r11),%edx		/* sc_hw_1 */
	testl	$AV_386_AVX,%edx
	jne	.restore_ymm

	movdqa	(%rdi), %xmm0
	movdqa	64(%rdi), %xmm1
	movdqa	128(%rdi), %xmm2
	movdqa	192(%rdi), %xmm3
	movdqa	256(%rdi), %xmm4
	movdqa	320(%rdi), %xmm5
	movdqa	384(%rdi), %xmm6
	movdqa	448(%rdi), %xmm7
	jmp	.restore_finish

.restore_ymm:
	vmovdqa	(%rdi), %ymm0
	vmovdqa	64(%rdi), %ymm1
	vmovdqa	128(%rdi), %ymm2
	vmovdqa	192(%rdi), %ymm3
	vmovdqa	256(%rdi), %ymm4
	vmovdqa	320(%rdi), %ymm5
	vmovdqa	384(%rdi), %ymm6
	vmovdqa	448(%rdi), %ymm7
	jmp	.restore_finish

.restore_zmm:
	vmovdqa64	(%rdi), %zmm0
	vmovdqa64	64(%rdi), %zmm1
	vmovdqa64	128(%rdi), %zmm2
	vmovdqa64	192(%rdi), %zmm3
	vmovdqa64	256(%rdi), %zmm4
	vmovdqa64	320(%rdi), %zmm5
	vmovdqa64	384(%rdi), %zmm6
	vmovdqa64	448(%rdi), %zmm7

.restore_finish:
	ret
	SET_SIZE(_elf_rtbndr_fp_restore_orig)

	ENTRY(_elf_rtbndr_fp_fxsave)
	fxsaveq	(%rdi)
	ret
	SET_SIZE(_elf_rtbndr_fp_fxsave)

	ENTRY(_elf_rtbndr_fp_fxrestore)
	fxrstor	(%rdi)
	ret
	SET_SIZE(_elf_rtbndr_fp_fxrestore)

	ENTRY(_elf_rtbndr_fp_xsave)
	XSAVE_HEADER_ZERO(%rdx, %rdi)
	movq	$_CONST(XFEATURE_FP_ALL), %rdx
	movl	%edx, %eax
	shrq	$32, %rdx
	xsave	(%rdi)			/* save data */
	ret
	SET_SIZE(_elf_rtbndr_fp_xsave)

	ENTRY(_elf_rtbndr_fp_xrestore)
	movq	$_CONST(XFEATURE_FP_ALL), %rdx
	movl	%edx, %eax
	shrq	$32, %rdx
	xrstor	(%rdi)			/* save data */
	ret
	SET_SIZE(_elf_rtbndr_fp_xrestore)

#endif

#if	defined(lint)

/* ARGSUSED0 */
int
elf_plt_trace()
{
	return (0);
}

#else

/*
 * On entry the 'glue code' has already  done the following:
 *
 *	pushq	%rbp
 *	movq	%rsp, %rbp
 *	subq	$0x10, %rsp
 *	leaq	trace_fields(%rip), %r11
 *	movq	%r11, -0x8(%rbp)
 *	movq	$elf_plt_trace, %r11
 *	jmp	*%r11
 *
 * so - -8(%rbp) contains the dyndata ptr
 *
 *	0x0	Addr		*reflmp
 *	0x8	Addr		*deflmp
 *	0x10	Word		symndx
 *	0x14	Word		sb_flags
 *	0x18	Sym		symdef.st_name
 *	0x1c			symdef.st_info
 *	0x1d			symdef.st_other
 *	0x1e			symdef.st_shndx
 *	0x20			symdef.st_value
 *	0x28			symdef.st_size
 *
 * Also note - on entry 16 bytes have already been subtracted
 * from the %rsp.  The first 8 bytes is for the dyn_data_ptr,
 * the second 8 bytes are to align the stack and are available
 * for use.
 */
#define	REFLMP_OFF		0x0
#define	DEFLMP_OFF		0x8
#define	SYMNDX_OFF		0x10
#define	SBFLAGS_OFF		0x14
#define	SYMDEF_OFF		0x18
#define	SYMDEF_VALUE_OFF	0x20

/*
 * Next, we need to create a bunch of local storage. First, we have to preserve
 * the standard registers per the amd64 ABI. This means we need to deal with:
 *	%rax	- Used for information about the number of vector arguments
 *	%rdi	- arg0
 *	%rsi	- arg1
 *	%rdx	- arg2
 *	%rcx	- arg3
 *	%r8	- arg4
 *	%r9	- arg5
 *	%r10	- static chain pointer
 *	%r11	- PLT Interwork register, our caller is using this, so it's not
 *		  a temporary for us.
 *
 * In addition, we need to save the amd64 ABI floating point arguments. Finally,
 * we need to deal with our local storage. We need a La_amd64_regs and a
 * uint64_t for the previous stack size.
 *
 * To deal with this and the potentially variable size of the FPU regs, we have
 * to play a few different games. We refer to all of the standard registers, the
 * previous stack size, and La_amd64_regs structure off of %rbp. These are all
 * values that are below %rbp.
 */
#define	SPDYNOFF	-8
#define	SPDESTOFF	-16
#define	SPPRVSTKOFF	-24
#define	SPLAREGOFF	-88
#define	ORIG_RDI	-96
#define	ORIG_RSI	-104
#define	ORIG_RDX	-112
#define	ORIG_RCX	-120
#define	ORIG_R8		-128
#define	ORIG_R9		-136
#define	ORIG_R10	-144
#define	ORIG_R11	-152
#define	ORIG_RAX	-160
#define	PLT_SAVE_OFF	168

	ENTRY(elf_plt_trace)
	/*
	 * Save our static registers. After that 64-byte align us and subtract
	 * the appropriate amount for the FPU. The frame pointer has already
	 * been pushed for us by the glue code.
	 */
	movq	%rdi, ORIG_RDI(%rbp)
	movq	%rsi, ORIG_RSI(%rbp)
	movq	%rdx, ORIG_RDX(%rbp)
	movq	%rcx, ORIG_RCX(%rbp)
	movq	%r8, ORIG_R8(%rbp)
	movq	%r9, ORIG_R9(%rbp)
	movq	%r10, ORIG_R10(%rbp)
	movq	%r11, ORIG_R11(%rbp)
	movq	%rax, ORIG_RAX(%rbp)

	subq	$PLT_SAVE_OFF, %rsp

	movq	_plt_save_size@GOTPCREL(%rip),%r9
	movq	_plt_fp_save@GOTPCREL(%rip),%r10
	subq	(%r9), %rsp
	andq	$-64, %rsp
	movq	%rsp, %rdi
	call	*(%r10)

	/*
	 * Now that we've saved all of our registers, figure out what we need to
	 * do next.
	 */
	movq	SPDYNOFF(%rbp), %rax			/ %rax = dyndata
	testb	$LA_SYMB_NOPLTENTER, SBFLAGS_OFF(%rax)	/ <link.h>
	je	.start_pltenter
	movq	SYMDEF_VALUE_OFF(%rax), %rdi
	movq	%rdi, SPDESTOFF(%rbp)		/ save destination address
	jmp	.end_pltenter

.start_pltenter:
	/*
	 * save all registers into La_amd64_regs
	 */
	leaq	SPLAREGOFF(%rbp), %rsi	/ %rsi = &La_amd64_regs
	leaq	8(%rbp), %rdi
	movq	%rdi, 0(%rsi)		/ la_rsp
	movq	0(%rbp), %rdi
	movq	%rdi, 8(%rsi)		/ la_rbp
	movq	ORIG_RDI(%rbp), %rdi
	movq	%rdi, 16(%rsi)		/ la_rdi
	movq	ORIG_RSI(%rbp), %rdi
	movq	%rdi, 24(%rsi)		/ la_rsi
	movq	ORIG_RDX(%rbp), %rdi
	movq	%rdi, 32(%rsi)		/ la_rdx
	movq	ORIG_RCX(%rbp), %rdi
	movq	%rdi, 40(%rsi)		/ la_rcx
	movq	ORIG_R8(%rbp), %rdi
	movq	%rdi, 48(%rsi)		/ la_r8
	movq	ORIG_R9(%rbp), %rdi
	movq	%rdi, 56(%rsi)		/ la_r9

	/*
	 * prepare for call to la_pltenter
	 */
	movq	SPDYNOFF(%rbp), %r11		/ %r11 = &dyndata
	leaq	SBFLAGS_OFF(%r11), %r9		/ arg6 (&sb_flags)
	leaq	SPLAREGOFF(%rbp), %r8		/ arg5 (&La_amd64_regs)
	movl	SYMNDX_OFF(%r11), %ecx		/ arg4 (symndx)
	leaq	SYMDEF_OFF(%r11), %rdx		/ arg3 (&Sym)
	movq	DEFLMP_OFF(%r11), %rsi		/ arg2 (dlmp)
	movq	REFLMP_OFF(%r11), %rdi		/ arg1 (rlmp)
	call	audit_pltenter@PLT
	movq	%rax, SPDESTOFF(%rbp)		/ save calling address
.end_pltenter:

	/*
	 * If *no* la_pltexit() routines exist
	 * we do not need to keep the stack frame
	 * before we call the actual routine.  Instead we
	 * jump to it and remove our stack from the stack
	 * at the same time.
	 */
	movl	audit_flags(%rip), %eax
	andl	$AF_PLTEXIT, %eax		/ value of audit.h:AF_PLTEXIT
	cmpl	$0, %eax
	je	.bypass_pltexit
	/*
	 * Has the *nopltexit* flag been set for this entry point
	 */
	movq	SPDYNOFF(%rbp), %r11		/ %r11 = &dyndata
	testb	$LA_SYMB_NOPLTEXIT, SBFLAGS_OFF(%r11)
	je	.start_pltexit

.bypass_pltexit:
	/*
	 * No PLTEXIT processing required.
	 */
	movq	0(%rbp), %r11
	movq	%r11, -8(%rbp)			/ move prev %rbp
	movq	SPDESTOFF(%rbp), %r11		/ r11 == calling destination
	movq	%r11, 0(%rbp)			/ store destination at top

	/* Restore FPU */
	movq	_plt_fp_restore@GOTPCREL(%rip),%r10

	movq	%rsp, %rdi
	call	*(%r10)

	movq	ORIG_RDI(%rbp), %rdi
	movq	ORIG_RSI(%rbp), %rsi
	movq	ORIG_RDX(%rbp), %rdx
	movq	ORIG_RCX(%rbp), %rcx
	movq	ORIG_R8(%rbp), %r8
	movq	ORIG_R9(%rbp), %r9
	movq	ORIG_R10(%rbp), %r10
	movq	ORIG_R11(%rbp), %r11
	movq	ORIG_RAX(%rbp), %rax

	subq	$8, %rbp			/ adjust %rbp for 'ret'
	movq	%rbp, %rsp			/
	/*
	 * At this point, after a little doctoring, we should
	 * have the following on the stack:
	 *
	 *	16(%rsp):  ret addr
	 *	8(%rsp):  dest_addr
	 *	0(%rsp):  Previous %rbp
	 *
	 * So - we pop the previous %rbp, and then
	 * ret to our final destination.
	 */
	popq	%rbp				/
	ret					/ jmp to final destination
						/ and clean up stack :)

.start_pltexit:
	/*
	 * In order to call the destination procedure and then return
	 * to audit_pltexit() for post analysis we must first grow
	 * our stack frame and then duplicate the original callers
	 * stack state.  This duplicates all of the arguements
	 * that were to be passed to the destination procedure.
	 */
	movq	%rbp, %rdi			/
	addq	$16, %rdi			/    %rdi = src
	movq	(%rbp), %rdx			/
	subq	%rdi, %rdx			/    %rdx == prev frame sz
	/*
	 * If audit_argcnt > 0 then we limit the number of
	 * arguements that will be duplicated to audit_argcnt.
	 *
	 * If (prev_stack_size > (audit_argcnt * 8))
	 *	prev_stack_size = audit_argcnt * 8;
	 */
	movl	audit_argcnt(%rip),%eax		/   %eax = audit_argcnt
	cmpl	$0, %eax
	jle	.grow_stack
	leaq	(,%rax,8), %rax			/    %eax = %eax * 4
	cmpq	%rax,%rdx
	jle	.grow_stack
	movq	%rax, %rdx
	/*
	 * Grow the stack and duplicate the arguements of the
	 * original caller.
	 */
.grow_stack:
	movq	%rsp, %r11
	subq	%rdx, %rsp			/    grow the stack
	movq	%rdx, SPPRVSTKOFF(%rbp)		/    -88(%rbp) == prev frame sz
	movq	%rsp, %rcx			/    %rcx = dest
	addq	%rcx, %rdx			/    %rdx == tail of dest
.while_base:
	cmpq	%rdx, %rcx			/   while (base+size >= src++) {
	jge	.end_while			/
	movq	(%rdi), %rsi
	movq	%rsi,(%rcx)			/        *dest = *src
	addq	$8, %rdi			/	 src++
	addq	$8, %rcx			/        dest++
	jmp	.while_base			/    }

	/*
	 * The above stack is now an exact duplicate of
	 * the stack of the original calling procedure.
	 */
.end_while:
	/
	/ Restore registers using %r11 which contains our old %rsp value
	/ before growing the stack.
	/
	movq	_plt_fp_restore@GOTPCREL(%rip),%r10
	movq	%r11, %rdi
	call	*(%r10)

.trace_r2_finish:
	movq	ORIG_RDI(%rbp), %rdi
	movq	ORIG_RSI(%rbp), %rsi
	movq	ORIG_RDX(%rbp), %rdx
	movq	ORIG_RCX(%rbp), %rcx
	movq	ORIG_R8(%rbp), %r8
	movq	ORIG_R9(%rbp), %r9
	movq	ORIG_R10(%rbp), %r10
	movq	ORIG_RAX(%rbp), %rax
	movq	ORIG_R11(%rbp), %r11

	/*
	 * Call to desitnation function - we'll return here
	 * for pltexit monitoring.
	 */
	call	*SPDESTOFF(%rbp)

	addq	SPPRVSTKOFF(%rbp), %rsp	/ cleanup dupped stack

	/
	/ prepare for call to audit_pltenter()
	/
	movq	SPDYNOFF(%rbp), %r11		/ %r11 = &dyndata
	movq	SYMNDX_OFF(%r11), %r8		/ arg5 (symndx)
	leaq	SYMDEF_OFF(%r11), %rcx		/ arg4 (&Sym)
	movq	DEFLMP_OFF(%r11), %rdx		/ arg3 (dlmp)
	movq	REFLMP_OFF(%r11), %rsi		/ arg2 (rlmp)
	movq	%rax, %rdi			/ arg1 (returnval)
	call	audit_pltexit@PLT

	/*
	 * Clean up after ourselves and return to the
	 * original calling procedure. Make sure to restore
	 * registers.
	 */

	movq	_plt_fp_restore@GOTPCREL(%rip),%r10
	movq	%rsp, %rdi
	movq	%rax, SPPRVSTKOFF(%rbp)
	call	*(%r10)

	movq	ORIG_RDI(%rbp), %rdi
	movq	ORIG_RSI(%rbp), %rsi
	movq	ORIG_RDX(%rbp), %rdx
	movq	ORIG_RCX(%rbp), %rcx
	movq	ORIG_R8(%rbp), %r8
	movq	ORIG_R9(%rbp), %r9
	movq	ORIG_R10(%rbp), %r10
	movq	ORIG_R11(%rbp), %r11
	movq	SPPRVSTKOFF(%rbp), %rax

	movq	%rbp, %rsp			/
	popq	%rbp				/
	ret					/ return to caller
	SET_SIZE(elf_plt_trace)
#endif

/*
 * We got here because a call to a function resolved to a procedure
 * linkage table entry.  That entry did a JMPL to the first PLT entry, which
 * in turn did a call to elf_rtbndr.
 *
 * the code sequence that got us here was:
 *
 * .PLT0:
 *	pushq	GOT+8(%rip)	#GOT[1]
 *	jmp	*GOT+16(%rip)	#GOT[2]
 *	nop
 *	nop
 *	nop
 *	nop
 *	...
 * PLT entry for foo:
 *	jmp	*name1@GOTPCREL(%rip)
 *	pushl	$rel.plt.foo
 *	jmp	PLT0
 *
 * At entry, the stack looks like this:
 *
 *	return address			16(%rsp)
 *	$rel.plt.foo	(plt index)	8(%rsp)
 *	lmp				0(%rsp)
 *
 */
#if defined(lint)

extern unsigned long	elf_bndr(Rt_map *, unsigned long, caddr_t);

void
elf_rtbndr(Rt_map * lmp, unsigned long reloc, caddr_t pc)
{
	(void) elf_bndr(lmp, reloc, pc);
}

#else

/*
 * The PLT code that landed us here placed 2 arguments on the stack as
 * arguments to elf_rtbndr.
 * Additionally the pc of caller is below these 2 args.
 * Our stack will look like this after we establish a stack frame with
 * push %rbp; movq %rsp, %rbp sequence:
 *
 *	8(%rbp)			arg1 - *lmp
 *	16(%rbp), %rsi		arg2 - reloc index
 *	24(%rbp), %rdx		arg3 - pc of caller
 */
#define	LBPLMPOFF	8	/* arg1 - *lmp */
#define	LBPRELOCOFF	16	/* arg2 - reloc index */
#define	LBRPCOFF	24	/* arg3 - pc of caller */

/*
 * With the above in place, we must now proceed to preserve all temporary
 * registers that are also used for passing arguments. Specifically this
 * means:
 *
 *	%rax	- Used for information about the number of vector arguments
 *	%rdi	- arg0
 *	%rsi	- arg1
 *	%rdx	- arg2
 *	%rcx	- arg3
 *	%r8	- arg4
 *	%r9	- arg5
 *	%r10	- static chain pointer
 *
 * While we don't have to preserve %r11, we do have to preserve the FPU
 * registers. The FPU logic is delegated to a specific function that we'll call.
 * However, it requires that its stack is 64-byte aligned. We defer the
 * alignment to that point. This will also take care of the fact that a caller
 * may not call us with a correctly aligned stack pointer per the amd64 ABI.
 */

	.extern _plt_save_size
	.extern _plt_fp_save
	.extern plt_fp_restore

	.weak	_elf_rtbndr
	_elf_rtbndr = elf_rtbndr

	ENTRY(elf_rtbndr)
	pushq	%rbp		/* Establish stack frame */
	movq	%rsp, %rbp

	/*
	 * Save basic regs.
	 */
	pushq	%rax
	pushq	%rdi
	pushq	%rsi
	pushq	%rdx
	pushq	%rcx
	pushq	%r8
	pushq	%r9
	pushq	%r10
	pushq	%r12

	/*
	 * Save the amount of space we need for the FPU registers and call that
	 * function. Save %rsp before we manipulate it to make restore easier.
	 */
	movq	%rsp, %r12
	movq	_plt_save_size@GOTPCREL(%rip),%r9
	movq	_plt_fp_save@GOTPCREL(%rip),%r10
	subq	(%r9), %rsp
	andq	$-64, %rsp

	movq	%rsp, %rdi
	call	*(%r10)

	/*
	 * Perform actual PLT logic. Note that the plt related arguments are
	 * located at an offset relative to %rbp.
	 */
	movq	LBPLMPOFF(%rbp), %rdi	/* arg1 - *lmp */
	movq	LBPRELOCOFF(%rbp), %rsi	/* arg2 - reloc index */
	movq	LBRPCOFF(%rbp), %rdx	/* arg3 - pc of caller */
	call	elf_bndr@PLT		/* call elf_rtbndr(lmp, relndx, pc) */
	movq	%rax, LBPRELOCOFF(%rbp)	/* store final destination */

	/* Restore FPU */
	movq	_plt_fp_restore@GOTPCREL(%rip),%r10

	movq	%rsp, %rdi
	call	*(%r10)

	movq	%r12, %rsp
	popq	%r12
	popq	%r10
	popq	%r9
	popq	%r8
	popq	%rcx
	popq	%rdx
	popq	%rsi
	popq	%rdi
	popq	%rax

	movq	%rbp, %rsp	/* Restore our stack frame */
	popq	%rbp

	addq	$8, %rsp	/* pop 1st plt-pushed args */
				/* the second arguement is used */
				/* for the 'return' address to our */
				/* final destination */

	ret			/* invoke resolved function */

	SET_SIZE(elf_rtbndr)
#endif
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (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 2005 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 *
 * Return the pc of the calling routine.
 */

#if	defined(lint)

#include	<sys/types.h>

caddr_t
caller()
{
	return (0);
}

#else

#include	<sys/asm_linkage.h>

	.file	"caller.s"

	ENTRY(caller)
	movq	8(%rbp),%rax
	ret
	SET_SIZE(caller)
#endif
/*
 * 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) 2004, 2010, Oracle and/or its affiliates. All rights reserved.
 */

#include	<string.h>
#include	<dlfcn.h>
#include	<stdio.h>
#include	<debug.h>
#include	"_rtld.h"
#include	"_elf.h"
#include	"_inline_gen.h"
#include	"msg.h"


static Dl_amd64_unwindinfo *
getunwind_core(Lm_list *lml, void *pc, Dl_amd64_unwindinfo *unwindinfo)
{
	Rt_map	*lmp;

	/*
	 * Validate the version information.
	 */
	if (unwindinfo == NULL) {
		eprintf(lml, ERR_FATAL, MSG_INTL(MSG_ARG_ILLVAL));
		return (0);
	}
	if ((unwindinfo->dlui_version < DLUI_VERS_1) ||
	    (unwindinfo->dlui_version > DLUI_VERS_CURRENT)) {
		eprintf(lml, ERR_FATAL, MSG_INTL(MSG_UNW_BADVERS),
		    unwindinfo->dlui_version, DLUI_VERS_CURRENT);
		return (0);
	}

	/*
	 * Clean out the structure.
	 */
	unwindinfo->dlui_flags = 0;
	unwindinfo->dlui_objname = 0;
	unwindinfo->dlui_unwindstart = 0;
	unwindinfo->dlui_unwindend = 0;
	unwindinfo->dlui_segstart = 0;
	unwindinfo->dlui_segend = 0;

	/*
	 * Identify the link-map associated with the exception "pc".  Note,
	 * the "pc" might not correspond to a link-map (as can happen with a
	 * "pc" fabricated by a debugger such as dbx).  In this case, the
	 * unwind data buffer will be filled with flags set to indicate an
	 * unknown caller.
	 */
	lmp = _caller(pc, CL_NONE);

	if (lmp) {
		mmapobj_result_t	*mpp;

		/*
		 * Determine the associated segment.
		 */
		if ((mpp = find_segment(pc, lmp)) == NULL)
			return (0);

		unwindinfo->dlui_objname = (char *)PATHNAME(lmp);
		unwindinfo->dlui_segstart = mpp->mr_addr;
		unwindinfo->dlui_segend = mpp->mr_addr + mpp->mr_msize;

		if (PTUNWIND(lmp) && (mpp->mr_addr)) {
			uintptr_t   base;

			if (FLAGS(lmp) & FLG_RT_FIXED)
				base = 0;
			else
				base = ADDR(lmp);

			unwindinfo->dlui_unwindstart =
			    (void *)(PTUNWIND(lmp)->p_vaddr + base);
			unwindinfo->dlui_unwindend =
			    (void *)(PTUNWIND(lmp)->p_vaddr +
			    PTUNWIND(lmp)->p_memsz + base);

		} else if (mpp->mr_addr)
			unwindinfo->dlui_flags |= DLUI_FLG_NOUNWIND;
		else
			unwindinfo->dlui_flags |=
			    DLUI_FLG_NOUNWIND | DLUI_FLG_NOOBJ;
	} else {
		/*
		 * No object found.
		 */
		unwindinfo->dlui_flags = DLUI_FLG_NOOBJ | DLUI_FLG_NOUNWIND;
	}
	return (unwindinfo);
}

#pragma weak _dlamd64getunwind = dlamd64getunwind

Dl_amd64_unwindinfo *
dlamd64getunwind(void *pc, Dl_amd64_unwindinfo *unwindinfo)
{
	Rt_map	*lmp;
	Lm_list	*lml;
	int	entry = enter(0);

	lmp = _caller(caller(), CL_EXECDEF);
	lml = LIST(lmp);

	unwindinfo = getunwind_core(lml, pc, unwindinfo);

	if (entry)
		leave(lml, 0);
	return (unwindinfo);
}