|
root / base / usr / src / cmd / sgs / ar
ar Plain Text 3371 lines 85.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
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
#
# 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
#
#
#ident	"%Z%%M%	%I%	%E% SMI"
#
# Copyright (c) 1996 by Sun Microsystems, Inc.
# All Rights Reserved.
#
# cmd/sgs/ar/Makefile
#

include		$(SRC)/cmd/sgs/Makefile.sub
#
# 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) 1996, 2010, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 2018, Joyent, Inc.
# Copyright 2019 OmniOS Community Edition (OmniOSce) Association.
#

PROG=		ar
XPG4PROG=	ar

include		$(SRC)/cmd/Makefile.cmd
include		$(SRC)/cmd/sgs/Makefile.com

COMOBJ=		main.o		file.o		cmd.o

BLTOBJ =	msg.o

OBJS=		$(BLTOBJ:%=objs/%) $(COMOBJ:%=objs/%)
XPG4OBJS=	$(BLTOBJ:%=objs.xpg4/%) $(COMOBJ:%=objs.xpg4/%)

LLDFLAGS =	'-R$$ORIGIN/../../lib'
LLDFLAGS64 =	'-R$$ORIGIN/../../../lib/$(MACH64)'
CPPFLAGS=	-I. -I../../include $(CPPFLAGS.master) -I$(ELFCAP)
CFLAGS +=	$(CCVERBOSE)
CSTD=	$(CSTD_GNU99)

CERRWARN +=	$(CNOWARN_UNINIT)

SMOFF += signed

LDLIBS +=	-lelf $(CONVLIBDIR) -lconv -lsendfile

$(XPG4) :	CPPFLAGS += -DXPG4

BLTDEFS =	msg.h
BLTDATA =	msg.c
BLTMESG =	$(SGSMSGDIR)/ar

BLTFILES =	$(BLTDEFS) $(BLTDATA) $(BLTMESG)

SGSMSGCOM =	../common/ar.msg
SGSMSGTARG =	$(SGSMSGCOM)
SGSMSGALL =	$(SGSMSGCOM)

SGSMSGFLAGS +=	-h $(BLTDEFS) -d $(BLTDATA) -m $(BLTMESG) -n ar_msg

SRCS=		$(COMOBJ:%.o=../common/%.c) $(BLTDATA:%.o=$(SGSCOMMON)/%.c)

CLEANFILES +=	$(BLTFILES)
#
# 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) 1996, 2010, Oracle and/or its affiliates. All rights reserved.
# Copyright 2019 OmniOS Community Edition (OmniOSce) Association.

objs/%.o \
objs.xpg4/%.o:	../common/%.c
		$(COMPILE.c) -o $@ $<
		$(POST_PROCESS_O)

objs/%.o \
objs.xpg4/%.o:	%.c
		$(COMPILE.c) -o $@ $<
		$(POST_PROCESS_O)

clean:
		$(RM) $(OBJS) $(XPG4OBJS) $(CLEANFILES)

catalog:	$(BLTMESG)

$(PROG):	$(OBJS)
		$(LINK.c) -o $@ $(LLDFLAGS) $(OBJS) $(LDLIBS)
		$(POST_PROCESS)

$(XPG4):	$(XPG4OBJS)
		$(LINK.c) -o $@ $(XPG4OBJS) $(LDLIBS)
		$(POST_PROCESS)

$(OBJS):	objs

$(XPG4OBJS):	objs.xpg4

objs objs.xpg4:
		-@ mkdir -p $@

include		$(SRC)/cmd/Makefile.targ

# Derived source and header files (messaging).

catalog:	$(BLTMESG)

chkmsg:		$(SRCS)
		sh $(CHKMSG) $(CHKMSGFLAGS) $(SRCS)

# Hammerhead: GNU Make grouped target syntax (&:) - was dmake + syntax
$(BLTDEFS) $(BLTDATA) $(BLTMESG) &: $(SGSMSGALL)
		$(SGSMSG) $(SGSMSGFLAGS) $(SGSMSGALL)
#
# 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) 2010, Oracle and/or its affiliates. All rights reserved.
# Copyright 2019 OmniOS Community Edition (OmniOSce) Association.
#

include		../Makefile.com

.KEEP_STATE:

LLDFLAGS =	$(LLDFLAGS64)
CONVLIBDIR =	$(CONVLIBDIR64)
ELFLIBDIR =	$(ELFLIBDIR64)
LDDBGLIBDIR =	$(LDDBGLIBDIR64)

ROOTPROG =	$(ROOTPROG64)

all:		$(PROG)

install:	all $(ROOTPROG64) $(ROOTCCSBINLINK64)


include		../Makefile.targ
include		$(SRC)/Makefile.master.64
#
# 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) 2010, Oracle and/or its affiliates. All rights reserved.
# Copyright 2022 Oxide Computer Company
#

@ _START_

# Message file for cmd/sgs/ar.

@ MSG_ID_AR

@ MSG_USAGE		"usage: ar -d[-SvV] archive file ...\n       \
			 ar -m[-abiSvV] [posname] archive file ...\n       \
			 ar -p[-vV][-sS] archive [file ...]\n       \
			 ar -q[-csuvSV] [file ...]\n       \
			 ar -r[-cuvSV] [-abi] [posname] [file ...]\n       \
			 ar -s[-vV] archive\n       \
			 ar -t[-vV][-sS] archive [file ...]\n       \
			 ar -x[-vV][-sSCT] archive [file ...]\n"

@ MSG_MALLOC		"ar: could not allocate memory: %s\n"
@ MSG_TOOBIG4G		"ar: archive size exceeds capabilities of 32-bit \
			 process\n"

@ MSG_USAGE_REQ_FLAG	"ar: one of [drqstpmx] must be specified\n"
@ MSG_USAGE_OPERAND	"ar: -%c requires an operand\n"
@ MSG_USAGE_OPTION	"ar: bad option: -%c\n"
@ MSG_USAGE_TOO_MANY	"ar: only one of [drqstpmx] allowed\n"
@ MSG_USAGE_Q_BAD_ARG	"ar: abi not allowed with q\n"
@ MSG_USAGE_POSNAME	"ar: %s taken as mandatory 'posname' with keys 'abi'\n"
@ MSG_USAGE_S_BAD_ARG	"ar: bad option with -s, only -v and -V allowed\n"
@ MSG_USAGE_S_EXTRA_AR	"ar: -s only supports a single archive file\n"

@ MSG_INTERNAL_01	"ar: internal error: cannot tell whether file is \
			 included in archive or not\n"
@ MSG_INTERNAL_02	"ar: internal header generation error\n"

@ MSG_BAD_CREATE	"ar: failed to create %s: %s, is the path correct?\n"

@ MSG_SYS_OPEN		"ar: cannot open %s: %s\n"
@ MSG_SYS_CLOSE		"ar: cannot close %s: %s\n"
@ MSG_SYS_WRITE		"ar: %s: cannot write: %s\n"
@ MSG_SYS_STAT		"ar: cannot stat %s: %s\n"
@ MSG_SYS_RENAME	"ar: cannot rename %s to %s: %s\n"

@ MSG_NOT_FOUND_AR	"ar: archive %s not found\n"
@ MSG_NOT_FOUND_POSNAM	"ar: posname %s: not found\n"
@ MSG_NOT_FOUND_FILE	"ar: %s not found\n"

@ MSG_ELF_LIB_FILE	"ar: %s caused libelf error: %s\n"
@ MSG_ELF_LIB_AR	"ar: %s(%s) libelf error: %s\n"
@ MSG_ELF_BEGIN_FILE	"ar: cannot elf_begin() %s: %s\n"
@ MSG_ELF_GETDATA_FILE	"ar: %s has bad elf format: %s\n"
@ MSG_ELF_GETDATA_AR	"ar: %s(%s) has bad elf format: %s\n"
@ MSG_ELF_GETSCN_FILE	"ar: %s has no section header or bad elf format: %s\n"
@ MSG_ELF_GETSCN_AR	"ar: %s(%s) has no section header or bad elf \
			 format: %s\n"
@ MSG_ELF_GETSHSTRNDX_FILE "ar: %s has no string table index: %s\n"
@ MSG_ELF_GETSHSTRNDX_AR "ar: %s(%s) has no string table index: %s\n"
@ MSG_ELF_MALARCHIVE	"ar: %s: offset %lld: malformed archive: %s\n"
@ MSG_ELF_RAWFILE	"ar: elf_rawfile() failed: %s\n"
@ MSG_ELF_VERSION	"ar: libelf.a out of date: %s\n"
@ MSG_W_ELF_NODATA_FILE	"ar: %s has no data in section header table\n"
@ MSG_W_ELF_NODATA_AR	"ar: %s(%s) has no data in section header table\n"

@ MSG_BER_MES_CREATE	"ar: creating %s\n"
@ MSG_BER_MES_WRITE	"ar: writing %s\n"

@ MSG_SYMTAB_01		"ar: symbol table entry size is 0\n"
@ MSG_SYMTAB_NOSTR_FILE	"ar: %s has no string table for symbol names\n"
@ MSG_SYMTAB_NOSTR_AR	"ar: %s(%s) has no string table for symbol names\n"
@ MSG_SYMTAB_NODAT_FILE	"ar: %s has no data in string table\n"
@ MSG_SYMTAB_NODAT_AR	"ar: %s(%s) no data in string table\n"
@ MSG_SYMTAB_ZDAT_FILE	"ar: %s has no data in string table: size is 0\n"
@ MSG_SYMTAB_ZDAT_AR	"ar: %s(%s) no data in string table: size is 0\n"


@ MSG_PATHCONF		"ar: -T failed to calculate file name length: %s\n"
@ MSG_LOCALTIME		"ar: don't have enough space to store the date\n"
@ MSG_NOT_ARCHIVE	"ar: %s not in archive format\n"
@ MSG_OVERRIDE_WARN	"ar: %s already exists. Will not be extracted\n"

@ MSG_ERR_LONGSTRTBLSZ	"ar: archive format limit: long name string table \
			 would exceed 4GB\n"
@ MSG_ERR_MEMBER4G	"ar: archive format limit: individual archive \
			 members are limited to 4GB: %s\n"

@ _END_

# The following strings represent reserved words, files, pathnames and symbols.
# Reference to this strings is via the MSG_ORIG() macro, and thus no message
# translation is required.

@ MSG_STR_OPTIONS	":a:b:i:vucsrdxtplmqVCTzMS"
@ MSG_SUNW_OST_SGS	"SUNW_OST_SGS"

@ MSG_STR_EMPTY		""
@ MSG_STR_HYPHEN	"-"
@ MSG_STR_PERIOD	"."
@ MSG_STR_LCR		"r"
@ MSG_STR_SLASH		"/"
@ MSG_STR_DSLASH	"//"
@ MSG_STR_SYM64		"/SYM64/"

# Format for full member header
#
@ MSG_MH_FORMAT		"%-16s%-12d%-6u%-6u%-8o%-10lld%-2s"

@ MSG_FMT_VERSION	"ar: %s %s\n"
@ MSG_FMT_P_TITLE	"\n<%s>\n\n"
@ MSG_FMT_T_IDSZ	"%6d/%6d%7lld"
@ MSG_FMT_T_DATE	"%b %e %H:%M %Y"
@ MSG_FMT_SPSTRSP	" %s "
@ MSG_FMT_STRNL		"%s\n"
@ MSG_FMT_FILE		"%c - %s\n"
@ MSG_FMT_LLINT		"/%lld"

@ MSG_CMD_SWAP		"/sbin/swap -s"

# Template for use with mktemp()
@ MSG_STR_MKTEMP	"arXXXXXX"
/*
 * 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) 1995, 2010, Oracle and/or its affiliates. All rights reserved.
 * Copyright 2021 Oxide Computer Company
 */

/*
 *	Copyright (c) 1988 AT&T
 *	  All Rights Reserved
 *
 */

/*
 * Incompatible Archive Header
 *
 * The archive file member header used in SunOS 4.1 archive files and
 * Solaris archive files are incompatible. The header file is:
 *	/usr/include/ar.h, struct ar_hdr.
 * The member ar_name[] in Solaris comforms with Standard and the
 * member name terminates with '/'. The SunOS's member does not terminate
 * with '/' character. A bug 4046054 was filed:
 *	The ar command in Solaris 2.5.1 is incompatible with archives
 *	created on 4.x.
 *
 * To handle archive files created in SunOS 4.1 system on Solaris, the
 * following changes were made:
 *
 *	1. file.c/writefile()
 *		Before writing each member files into the output
 *		archive file, ar_name[] is checked. If it is NULL,
 *		it means that the original archive header for this
 *		member was incompatible with Solaris format.
 *
 *		The original Solaris ar command ended up having
 *		NULL name for the header. The change here uses the
 *		ar_rawname, which is much closer to the original
 *		name.
 *
 *	2. cmd.c
 *		For the p command, the code used to use only ar_longname
 *		to seach the matching name. The member is set to NULL
 *		if the archive member header was incompatible.
 *		The ar_rawname is also used to find the matching member name.
 *
 *		For commands to update the archive file, we do not
 *		use ar_rawname, and just use the ar_longname. The commands are
 *		r (replace), m (modify the position) and d (delete).
 */

#include "inc.h"

/*
 * Forward Declarations
 */
static void	ar_select(int *, unsigned long);
static void	cleanup(Cmd_info *);
static int	create_extract(ARFILE *, int, int, Cmd_info *);
static char	*match(char *, Cmd_info *);
static void	mesg(int, char *, Cmd_info *);
static void	movefil(ARFILE *, struct stat *);
static FILE	*stats(char *, struct stat *);

/*
 * Commands
 */
void
rcmd(Cmd_info *cmd_info)
{
	FILE		*f;
	ARFILE		*fileptr;
	ARFILE		*abifile = NULL;
	ARFILE		*backptr = NULL;
	ARFILE		*endptr;
	ARFILE		*moved_files;
	ARFILE		*prev_entry, *new_listhead, *new_listend;
	int		deleted;
	struct stat	stbuf;
	char		*gfile;

	new_listhead  = NULL;
	new_listend   = NULL;
	prev_entry    = NULL;

	for (fileptr = getfile(cmd_info);
	    fileptr; fileptr = getfile(cmd_info)) {
		deleted = 0;
		if (!abifile && cmd_info->ponam &&
		    strcmp(fileptr->ar_longname, cmd_info->ponam) == 0)
			abifile = fileptr;
		else if (!abifile)
			backptr = fileptr;

		if (cmd_info->namc == 0 ||
		    (gfile = match(fileptr->ar_longname, cmd_info)) != NULL) {
			/*
			 * NOTE:
			 *	Refer to "Incompatible Archive Header"
			 *	blocked comment at the beginning of this file.
			 */
			f = stats(gfile, &stbuf); /* gfile is set by match */
			if (f == NULL) {
				if (cmd_info->namc) {
					int err = errno;
					(void) fprintf(stderr,
					    MSG_INTL(MSG_SYS_OPEN),
					    gfile, strerror(err));
				}
				/*
				 * Created
				 */
				mesg('c', gfile, cmd_info);
			} else {
				if ((cmd_info->opt_flgs & u_FLAG) &&
				    stbuf.st_mtime <= fileptr->ar_date) {
					(void) fclose(f);
					continue;
				}
				/*
				 * Replaced
				 */
				mesg('r', fileptr->ar_longname, cmd_info);
				movefil(fileptr, &stbuf);
				/*
				 * Clear the previous contents.
				 */
				if (fileptr->ar_flag & F_ELFRAW) {
					/*
					 * clear ar_elf
					 */
					(void) elf_end(fileptr->ar_elf);
					fileptr->ar_elf = 0;
				}
				/* clear 'ar_flag' */
				fileptr->ar_flag &= ~F_ELFRAW;

				/*
				 * Defer reading contents until needed, and
				 * then use an in-kernel file-to-file transfer
				 * to avoid excessive in-process memory use.
				 */
				fileptr->ar_contents = NULL;

				if (fileptr->ar_pathname != NULL)
					free(fileptr->ar_pathname);
				if ((fileptr->ar_pathname =
				    malloc(strlen(gfile) + 1)) == NULL) {
					int err = errno;
					(void) fprintf(stderr,
					    MSG_INTL(MSG_MALLOC),
					    strerror(err));
					exit(1);
				}

				(void) strcpy(fileptr->ar_pathname, gfile);
				(void) fclose(f);

				if (cmd_info->ponam && (abifile != fileptr)) {
					deleted = 1;
					/* remove from archive list */
					if (prev_entry != NULL)
						prev_entry->ar_next = NULL;
					else
						listhead = NULL;
					listend = prev_entry;

					/* add to moved list */
					if (new_listhead == NULL)
						new_listhead = fileptr;
					else
						new_listend->ar_next = fileptr;
					new_listend = fileptr;
				}
				cmd_info->modified++;
			}
		}
		else
			/*
			 * Unchaged
			 */
			mesg('u', fileptr->ar_longname, cmd_info);

		if (deleted)
			deleted = 0;
		else
			prev_entry = fileptr;
	}

	endptr = listend;
	cleanup(cmd_info);
	if (cmd_info->ponam && endptr &&
	    (((moved_files = endptr->ar_next) != NULL) || new_listhead)) {
		if (!abifile) {
			(void) fprintf(stderr, MSG_INTL(MSG_NOT_FOUND_POSNAM),
			    cmd_info->ponam);
			exit(2);
		}
		endptr->ar_next = NULL;

		/*
		 * link new/moved files into archive entry list...
		 * 1: prepend newlist to moved/appended list
		 */
		if (new_listhead) {
			if (!moved_files)
				listend = new_listend;
			new_listend->ar_next = moved_files;
			moved_files = new_listhead;
		}
		/* 2: insert at appropriate position... */
		if (cmd_info->opt_flgs & b_FLAG)
			abifile = backptr;
		if (abifile) {
			listend->ar_next = abifile->ar_next;
			abifile->ar_next = moved_files;
		} else {
			listend->ar_next = listhead;
			listhead = moved_files;
		}
		listend = endptr;
	} else if (cmd_info->ponam && !abifile)
		(void) fprintf(stderr, MSG_INTL(MSG_NOT_FOUND_POSNAM),
		    cmd_info->ponam);
}

void
dcmd(Cmd_info *cmd_info)
{
	ARFILE	*fptr;
	ARFILE *backptr = NULL;

	for (fptr = getfile(cmd_info); fptr; fptr = getfile(cmd_info)) {
		if (match(fptr->ar_longname, cmd_info) != NULL) {
			/*
			 * NOTE:
			 *	Refer to "Incompatible Archive Header"
			 *	blocked comment at the beginning of this file.
			 */

			/*
			 * Deleted
			 */
			mesg('d', fptr->ar_longname, cmd_info);
			if (backptr == NULL) {
				listhead = NULL;
				listend = NULL;
			} else {
				backptr->ar_next = NULL;
				listend = backptr;
			}
			cmd_info->modified = 1;
		} else {
			/*
			 * Unchaged
			 */
			mesg('u', fptr->ar_longname, cmd_info);
			backptr = fptr;
		}
	}
}

void
xcmd(Cmd_info *cmd_info)
{
	int	f;
	ARFILE	*next;
	int	rawname = 0;
	long	f_len = 0;

	/*
	 * If -T is specified, get the maximum file name length.
	 */
	if (cmd_info->opt_flgs & T_FLAG) {
		f_len = pathconf(MSG_ORIG(MSG_STR_PERIOD), _PC_NAME_MAX);
		if (f_len == -1) {
			int err = errno;
			(void) fprintf(stderr, MSG_INTL(MSG_PATHCONF),
			    strerror(err));
			exit(1);
		}
	}
	for (next = getfile(cmd_info); next; next = getfile(cmd_info)) {
		if ((next->ar_longname[0] == 0) && (next->ar_rawname[0] != 0))
			rawname = 1;
		if (cmd_info->namc == 0 ||
		    match(next->ar_longname, cmd_info) != NULL ||
		    match(next->ar_rawname, cmd_info) != NULL) {
			/*
			 * NOTE:
			 *	Refer to "Incompatible Archive Header"
			 *	blocked comment at the beginning of this file.
			 */
			f = create_extract(next, rawname, f_len, cmd_info);
			if (f >= 0) {
				if (rawname) {
					/*
					 * eXtracted
					 */
					mesg('x', next->ar_rawname, cmd_info);
					if (write(f, next->ar_contents,
					    (unsigned)next->ar_size) !=
					    next->ar_size) {
						int err = errno;
						(void) fprintf(stderr,
						    MSG_INTL(MSG_SYS_WRITE),
						    next->ar_rawname,
						    strerror(err));
						exit(1);
					}
				} else {
					/*
					 * eXtracted
					 */
					mesg('x', next->ar_longname, cmd_info);
					if (write(f, next->ar_contents,
					    (unsigned)next->ar_size) !=
					    next->ar_size) {
						int err = errno;
						(void) fprintf(stderr,
						    MSG_INTL(MSG_SYS_WRITE),
						    next->ar_longname,
						    strerror(err));
						exit(1);
					}
				}
				(void) close(f);
			} else
				exit(1);
		}
		rawname = 0;
	} /* for */
}

void
pcmd(Cmd_info *cmd_info)
{
	ARFILE	*next;

	for (next = getfile(cmd_info); next; next = getfile(cmd_info)) {
		if (cmd_info->namc == 0 ||
		    match(next->ar_longname, cmd_info) != NULL ||
		    match(next->ar_rawname, cmd_info) != NULL) {
			/*
			 * NOTE:
			 *	Refer to "Incompatible Archive Header"
			 *	blocked comment at the beginning of this file.
			 */
			if (cmd_info->opt_flgs & v_FLAG) {
				(void) fprintf(stdout,
				    MSG_ORIG(MSG_FMT_P_TITLE),
				    next->ar_longname);
				(void) fflush(stdout);
			}
			(void) fwrite(next->ar_contents, sizeof (char),
			    next->ar_size, stdout);
		}
	}
}

void
mcmd(Cmd_info *cmd_info)
{
	ARFILE	*fileptr;
	ARFILE	*abifile = NULL;
	ARFILE	*tmphead = NULL;
	ARFILE	*tmpend = NULL;
	ARFILE	*backptr1 = NULL;
	ARFILE	*backptr2 = NULL;

	for (fileptr = getfile(cmd_info);
	    fileptr; fileptr = getfile(cmd_info)) {
		if (match(fileptr->ar_longname, cmd_info) != NULL) {
			/*
			 * position Modified
			 */
			mesg('m', fileptr->ar_longname, cmd_info);
			if (tmphead)
				tmpend->ar_next = fileptr;
			else
				tmphead = fileptr;
			tmpend = fileptr;
			if (backptr1) {
				listend = backptr1;
				listend->ar_next = NULL;
			}
			else
				listhead = NULL;
			continue;
		}
		/*
		 * position Unchaged
		 */
		mesg('u', fileptr->ar_longname, cmd_info);
		backptr1 = fileptr;
		if (cmd_info->ponam && !abifile) {
			if (strcmp(fileptr->ar_longname, cmd_info->ponam) == 0)
				abifile = fileptr;
			else
				backptr2 = fileptr;
		}
	}

	if (!tmphead)
		return;

	if (!cmd_info->ponam)
		listend->ar_next = tmphead;
	else {
		if (!abifile) {
			(void) fprintf(stderr, MSG_INTL(MSG_NOT_FOUND_POSNAM),
			    cmd_info->ponam);
			exit(2);
		}
		if (cmd_info->opt_flgs & b_FLAG)
			abifile = backptr2;
		if (abifile) {
			tmpend->ar_next = abifile->ar_next;
			abifile->ar_next = tmphead;
		} else {
			tmphead->ar_next = listhead;
			listhead = tmphead;
		}
	}
	(cmd_info->modified)++;
}

void
tcmd(Cmd_info *cmd_info)
{
	ARFILE	*next;
	int	**mp;
	char   buf[DATESIZE];
	int m1[] = {1, S_IRUSR, 'r', '-'};
	int m2[] = {1, S_IWUSR, 'w', '-'};
	int m3[] = {2, S_ISUID, 's', S_IXUSR, 'x', '-'};
	int m4[] = {1, S_IRGRP, 'r', '-'};
	int m5[] = {1, S_IWGRP, 'w', '-'};
	int m6[] = {2, S_ISGID, 's', S_IXGRP, 'x', '-'};
	int m7[] = {1, S_IROTH, 'r', '-'};
	int m8[] = {1, S_IWOTH, 'w', '-'};
	int m9[] = {2, S_ISVTX, 't', S_IXOTH, 'x', '-'};
	int *m[10];

	m[0] = m1;
	m[1] = m2;
	m[2] = m3;
	m[3] = m4;
	m[4] = m5;
	m[5] = m6;
	m[6] = m7;
	m[7] = m8;
	m[8] = m9;
	m[9] = 0;

	for (next = getfile(cmd_info); next; next = getfile(cmd_info)) {
		if (cmd_info->namc == 0 ||
		    match(next->ar_longname, cmd_info) != NULL ||
		    match(next->ar_rawname, cmd_info) != NULL) {
			/*
			 * NOTE:
			 *	Refer to "Incompatible Archive Header"
			 *	blocked comment at the beginning of this file.
			 */
			if ((cmd_info->opt_flgs & (t_FLAG | v_FLAG)) ==
			    (t_FLAG | v_FLAG)) {
				for (mp = &m[0]; mp < &m[9]; )
					ar_select(*mp++, next->ar_mode);

				(void) fprintf(stdout, MSG_ORIG(MSG_FMT_T_IDSZ),
				    next->ar_uid, next->ar_gid,
				    EC_XWORD(next->ar_size));
				if ((strftime(buf,
				    DATESIZE, MSG_ORIG(MSG_FMT_T_DATE),
				    localtime(&(next->ar_date)))) == 0) {
					(void) fprintf(stderr,
					    MSG_INTL(MSG_LOCALTIME));
					exit(1);
				}
				(void) fprintf(stdout,
				    MSG_ORIG(MSG_FMT_SPSTRSP), buf);
			}
			if (cmd_info->opt_flgs & t_FLAG) {
				if ((next->ar_longname[0] == 0) &&
				    (next->ar_rawname[0] != 0)) {
					(void) fprintf(stdout,
					    MSG_ORIG(MSG_FMT_STRNL),
					    trim(next->ar_rawname));
				} else {
					(void) fprintf(stdout,
					    MSG_ORIG(MSG_FMT_STRNL),
					    trim(next->ar_longname));
				}
			}
		}
	}
}

void
qcmd(Cmd_info *cmd_info)
{
	ARFILE *fptr;

	if (cmd_info->opt_flgs & (a_FLAG | b_FLAG)) {
		(void) fprintf(stderr, MSG_INTL(MSG_USAGE_Q_BAD_ARG));
		exit(1);
	}
	for (fptr = getfile(cmd_info); fptr; fptr = getfile(cmd_info))
		;
	cleanup(cmd_info);
}

/*
 * Supplementary functions
 */
static char *
match(char *file, Cmd_info *cmd_info)
{
	int i;

	for (i = 0; i < cmd_info->namc; i++) {
		if (cmd_info->namv[i] == 0)
			continue;
		if (strcmp(trim(cmd_info->namv[i]), file) == 0) {
			file = cmd_info->namv[i];
			cmd_info->namv[i] = 0;
			return (file);
		}
	}
	return (NULL);
}

/*
 * puts the file which was in the list in the linked list
 */
static void
cleanup(Cmd_info *cmd_info)
{
	int i;
	FILE	*f;
	ARFILE	*fileptr;
	struct stat stbuf;

	for (i = 0; i < cmd_info->namc; i++) {
		if (cmd_info->namv[i] == 0)
			continue;
		/*
		 * Appended
		 */
		mesg('a', cmd_info->namv[i], cmd_info);
		f = stats(cmd_info->namv[i], &stbuf);
		if (f == NULL) {
			int err = errno;
			(void) fprintf(stderr, MSG_INTL(MSG_SYS_OPEN),
			    cmd_info->namv[i], strerror(err));
		} else {
			fileptr = newfile();
			/* if short name */
			(void) strncpy(fileptr->ar_name,
			    trim(cmd_info->namv[i]), SNAME);

			if ((fileptr->ar_longname =
			    malloc(strlen(trim(cmd_info->namv[i])) + 1)) ==
			    NULL) {
				int err = errno;
				(void) fprintf(stderr, MSG_INTL(MSG_MALLOC),
				    strerror(err));
				exit(1);
			}

			(void) strcpy(fileptr->ar_longname,
			    trim(cmd_info->namv[i]));

			if ((fileptr->ar_pathname =
			    malloc(strlen(cmd_info->namv[i]) + 1)) == NULL) {
				int err = errno;
				(void) fprintf(stderr, MSG_INTL(MSG_MALLOC),
				    strerror(err));
				exit(1);
			}

			(void) strcpy(fileptr->ar_pathname, cmd_info->namv[i]);

			movefil(fileptr, &stbuf);

			/* clear 'ar_flag' */
			fileptr->ar_flag &= ~F_ELFRAW;

			/*
			 * Defer reading contents until needed, and then use
			 * an in-kernel file-to-file transfer to avoid
			 * excessive in-process memory use.
			 */
			fileptr->ar_contents = NULL;

			(void) fclose(f);
			(cmd_info->modified)++;
			cmd_info->namv[i] = 0;
		}
	}
}

/*
 * insert the file 'file' into the temporary file
 */
static void
movefil(ARFILE *fileptr, struct stat *stbuf)
{
	fileptr->ar_size = stbuf->st_size;
	fileptr->ar_date = stbuf->st_mtime;
	fileptr->ar_mode = stbuf->st_mode;

	/*
	 * The format of an 'ar' file includes a 6 character
	 * decimal string to contain the uid.
	 *
	 * If the uid or gid is too big to fit, then set it to
	 * nobody (for want of a better value).  Clear the
	 * setuid/setgid bits in the mode to avoid setuid nobody
	 * or setgid nobody files unexpectedly coming into existence.
	 */
	if ((fileptr->ar_uid = stbuf->st_uid) > 999999) {
		fileptr->ar_uid = UID_NOBODY;
		if (S_ISREG(fileptr->ar_mode))
			fileptr->ar_mode &= ~S_ISUID;
	}
	if ((fileptr->ar_gid = stbuf->st_gid) > 999999) {
		fileptr->ar_gid = GID_NOBODY;
		if (S_ISREG(fileptr->ar_mode))
			fileptr->ar_mode &= ~S_ISGID;
	}
}

static FILE *
stats(char *file, struct stat *stbuf)
{
	FILE *f;

	f = fopen(file, MSG_ORIG(MSG_STR_LCR));
	if (f == NULL)
		return (f);
	if (stat(file, stbuf) < 0) {
		(void) fclose(f);
		return (NULL);
	}
	return (f);
}

/*
 * Used by xcmd()
 */
int
create_extract(ARFILE *a, int rawname, int f_len, Cmd_info *cmd_info)
{

	int f;
	char *f_name;
	char *dup = NULL;
	if (rawname)
		f_name = a->ar_rawname;
	else
		f_name = a->ar_longname;

	/*
	 * If -T is specified, check the file length.
	 */
	if (cmd_info->opt_flgs & T_FLAG) {
		int len;
		len = strlen(f_name);
		if (f_len <= len) {
			dup = malloc(f_len+1);
			if (dup == NULL) {
				int err = errno;
				(void) fprintf(stderr, MSG_INTL(MSG_MALLOC),
				    strerror(err));
				exit(1);
			}
			(void) strncpy(dup, f_name, f_len);
		}
		f_name = dup;
	}

	/*
	 * Bug 4052067 - If a file to be extracted has the same
	 * filename as the archive, the archive gets overwritten
	 * which can lead to a corrupted archive or worse, a ufs
	 * deadlock because libelf has mmap'ed the archive!  We
	 * can't rely on strcmp() to test for this case because
	 * the archive could be prefixed with a partial or full
	 * path (and we could be using the rawname from the archive)
	 * This means we have to do the same thing we did for mv,
	 * which is to explicitly check if the file we would extract
	 * to is identical to the archive.  Because part of this
	 * test is essentially what the -C flag does, I've merged
	 * the code together.
	 */
	if (access(f_name, F_OK) != -1) {
		struct stat s1, s2;

		/*
		 * If -C is specified, this is an error anyway
		 */
		if (cmd_info->opt_flgs & C_FLAG) {
			(void) fprintf(stderr, MSG_INTL(MSG_OVERRIDE_WARN),
			    f_name);
			if (dup != NULL)
				free(dup);
			return (-1);
		}

		/*
		 * Okay, -C wasn't specified.  However, now we do
		 * the check to see if the archive would be overwritten
		 * by extracting this file.  stat() both objects and
		 * test to see if their identical.
		 */
		if ((stat(f_name, &s1) == 0) &&
		    (stat(cmd_info->arnam, &s2) == 0)) {

			if ((s1.st_dev == s2.st_dev) &&
			    (s1.st_ino == s2.st_ino)) {

				(void) fprintf(stderr,
				    MSG_INTL(MSG_OVERRIDE_WARN), f_name);
				if (dup != NULL)
					free(dup);
				return (-1);
			}
		}
	}

	/*
	 * Okay to create extraction file...
	 */
	f = creat(f_name, (mode_t)a->ar_mode & 0777);
	if (f < 0) {
		int err = errno;
		(void) fprintf(stderr, MSG_INTL(MSG_SYS_OPEN), f_name,
		    strerror(err));
		/*
		 * Created
		 */
		mesg('c', f_name, cmd_info);
	}
	if (dup)
		free(dup);
	return (f);
}

static void
mesg(int c, char *file, Cmd_info *cmd_info)
{
#ifdef XPG4
	/*
	 * XPG4 does not have any message defined for
	 * 'c' operation.
	 * In fact, XPG only defines messages for
	 *	d, r, a and x at the present. (03/05/'96)
	 */
	if (c == 'c' || c == 'u' || c == 'm')
		return;
#endif
	/*
	 * If 'u' is passed, convert it to 'c'.
	 * 'u' makes more sense since the operation did not
	 * do anything, Unchanged, but 'c' has been used so
	 * I do no want to break the compatibility at this moment.
	 * (03/05/'96).
	 */
	if (c == 'u')
		c = 'c';
	if (cmd_info->opt_flgs & v_FLAG)
		if (c != 'c')
			(void) fprintf(stdout, MSG_ORIG(MSG_FMT_FILE), c, file);
}

static void
ar_select(int *pairp, unsigned long mode)
{
	int n, *ap;

	ap = pairp;
	n = *ap++;
	while (--n >= 0 && (mode & *ap++) == 0)
		ap++;
	(void) putchar(*ap);
}
/*
 * 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) 1995, 2010, Oracle and/or its affiliates. All rights reserved.
 * Copyright 2022 Oxide Computer Company
 */

/*
 *	Copyright (c) 1988 AT&T
 *	  All Rights Reserved
 *
 */

#include <sys/sendfile.h>
#include "inc.h"
#include "gelf.h"

/*
 * List of archive members, accessed globally by cmd and file.
 */
ARFILE	*listhead, *listend;

/*
 * Type used to manage string tables. Archives can have two of these:
 *
 * sym_strtbl: String table included at the end of the symbol table
 *	archive member, following the offset array.
 *
 * long_strtbl: String table used to hold member names that exceed 15
 *	characters in length, found in the long names archive member.
 */
typedef struct {
	char	*base;		/* Base of string table memory */
	size_t	used;		/* # bytes used from allocation */
	size_t	size;		/* Size of allocation */
} ARSTRTBL;

static ARSTRTBL	sym_strtbl;
static ARSTRTBL	long_strtbl;


/*
 * Name and file descriptor used when creating a new archive.
 * If this variable references an open file when exit_cleanup()
 * executes, it will close and remove the file, preventing incomplete
 * temporary files from being left behind in the case of a failure
 * or interruption.
 */
static struct {
	int		fd;	/* -1, or open file descriptor */
	const char	*path;	/* Path to open file */
} ar_outfile;

/*
 * The ar file format requires objects to be padded to an even size.
 * We do that, but it turns out to be beneficial to go farther.
 *
 * ld(1) accesses archives by mmapping them into memory. If the mapped
 * objects (member data) have the proper alignment, we can access them
 * directly. If the data alignment is wrong, libelf "slides" them over the
 * archive header to correct the misalignment. This is expensive in time
 * (to copy memory) and space (it causes swap to be allocated by the system
 * to back the now-modified pages). Hence, we really want to ensure that
 * the alignment is right.
 *
 * We used to align 32-bit objects at 4-byte boundaries, and 64-bit objects
 * at 8-byte. More recently, an elf section type has appeared that has
 * 8-byte alignment requirements (SUNW_move) even in 32-bit objects. So,
 * the current strategy is to align all objects to 8-bytes.
 *
 * There are two important things to consider when setting this value:
 *	1) If a new elf section that ld(1) accesses in memory appears
 *	   with a greater than 8-byte alignment requirement, this value
 *	   will need to be raised. Or, alternatively, the entire approach may
 *	   need reconsideration.
 *	2) The size of this padding must be smaller than the size of the
 *	   smallest possible ELF section. Otherwise, the logic contained
 *	   in recover_padding() can be tricked.
 */
#define	PADSZ 8

/*
 * Forward Declarations
 */
static void		arwrite(const char *, int, const char *, size_t);
static size_t		mklong_tab();
static size_t		mksymtab(const char *, ARFILEP **, int *);
static const char	*make_tmpname(const char *);
static size_t		sizeof_symtbl(size_t, int, size_t);
static void		savelongname(ARFILE *);
static void		savename(char *);
static int		search_sym_tab(const char *, ARFILE *, Elf *,
			    Elf_Scn *, size_t *, ARFILEP **, size_t *);
static size_t		sizeofmembers(size_t);
static char		*sputl32(uint32_t, char *);
static char		*sputl64(uint64_t, char *);
static void		strtbl_pad(ARSTRTBL *, size_t, int);
static char		*trimslash(char *s);
static void		writesymtab(const char *, int fd, size_t, ARFILEP *,
			    size_t);


/*
 * Function to be called on exit to clean up incomplete new archive.
 */
static void
exit_cleanup(void)
{
	if (ar_outfile.fd != -1) {
		/* Both of these system calls are Async-Signal-Safe */
		(void)  close(ar_outfile.fd);
		(void) unlink(ar_outfile.path);
	}
}

/*
 * Open an existing archive.
 */
int
getaf(Cmd_info *cmd_info)
{
	Elf_Cmd cmd;
	int fd;
	char *arnam = cmd_info->arnam;

	if (elf_version(EV_CURRENT) == EV_NONE) {
		(void) fprintf(stderr, MSG_INTL(MSG_ELF_VERSION),
		    elf_errmsg(-1));
		exit(1);
	}

	if ((cmd_info->afd = fd = open(arnam, O_RDONLY)) == -1) {
		int err = errno;

		if (err == ENOENT) {
			/* archive does not exist yet, may have to create one */
			return (fd);
		} else {
			/* problem other than "does not exist" */
			(void) fprintf(stderr, MSG_INTL(MSG_SYS_OPEN),
			    arnam, strerror(err));
			exit(1);
		}
	}

	cmd = ELF_C_READ;
	cmd_info->arf = elf_begin(fd, cmd, (Elf *)0);

	if (elf_kind(cmd_info->arf) != ELF_K_AR) {
		(void) fprintf(stderr, MSG_INTL(MSG_NOT_ARCHIVE), arnam);
		if (cmd_info->opt_flgs & (a_FLAG | b_FLAG))
			(void) fprintf(stderr, MSG_INTL(MSG_USAGE_POSNAME),
			    cmd_info->ponam);
		exit(1);
	}
	return (fd);
}

/*
 * Given a value, and a pad alignment, return the number of bytes
 * required to pad the value to the next alignment boundary.
 */
static size_t
pad(size_t n, size_t align)
{
	size_t r;

	r = n % align;
	if (r)
		r = align - r;

	return (r);
}

/*
 * If the current archive item is an ELF object, then ar(1) may have added
 * newline padding at the end in order to bring the following object
 * into PADSZ alignment within the file. This padding cannot be
 * distinguished from data using the information kept in the member header.
 * This routine examines the objects, using knowledge of
 * ELF and how our tools lay out objects to determine whether padding was
 * added to an archive item. If so, it adjusts the st_size and
 * st_padding fields of the file argument to reflect it.
 */
static void
recover_padding(Elf *elf, ARFILE *file)
{
	size_t		extent;
	size_t		padding;
	size_t		shnum;
	GElf_Ehdr	ehdr;


	/* ar(1) only pads objects, so bail if not looking at one */
	if (gelf_getclass(elf) == ELFCLASSNONE)
		return;

	/*
	 * libelf always puts the section header array at the end
	 * of the object, and all of our compilers and other tools
	 * use libelf or follow this convention. So, it is extremely
	 * likely that the section header array is at the end of this
	 * object: Find the address at the end of the array and compare
	 * it to the archive ar_size. If they are within PADSZ bytes, then
	 * we've found the end, and the difference is padding (We assume
	 * that no ELF section can fit into PADSZ bytes).
	 */
	if (elf_getshdrnum(elf, &shnum) == -1)
		return;

	extent = gelf_getehdr(elf, &ehdr)
	    ? (ehdr.e_shoff + (shnum * ehdr.e_shentsize)) : 0;

	/*
	 * If the extent exceeds the end of the archive member
	 * (negative padding), then we don't know what is going on
	 * and simply leave things alone.
	 */
	if (extent > file->ar_size)
		return;

	padding = file->ar_size - extent;
	if (padding >= PADSZ) {
		/*
		 * The section header array is not at the end of the object.
		 * Traverse the section headers and look for the one with
		 * the highest used address. If this address is within
		 * PADSZ bytes of ar_size, then this is the end of the object.
		 */
		Elf_Scn *scn = NULL;

		do {
			scn = elf_nextscn(elf, scn);
			if (scn) {
				GElf_Shdr shdr;

				if (gelf_getshdr(scn, &shdr)) {
					size_t t;

					t = shdr.sh_offset + shdr.sh_size;
					if (t > extent)
						extent = t;
				}
			}
		} while (scn);

		if (extent > file->ar_size)
			return;
		padding = file->ar_size - extent;
	}

	/*
	 * Now, test the padding. We only act on padding in the range
	 * (0 < pad < PADSZ) (ar(1) will never add more than this). A pad
	 * of 0 requires no action, and any other size above (PADSZ-1) means
	 * that we don't understand the layout of this object, and as such,
	 * cannot do anything.
	 *
	 * If the padding is in range, and the raw data for the
	 * object is available, then we perform one additional sanity
	 * check before moving forward: ar(1) always pads with newline
	 * characters. If anything else is seen, it is not padding so
	 * leave it alone.
	 */
	if (padding < PADSZ) {
		if (file->ar_contents) {
			size_t cnt = padding;
			char *p = file->ar_contents + extent;

			while (cnt--) {
				if (*p++ != '\n') {   /* No padding */
					padding = 0;
					break;
				}
			}
		}

		/* Remove the padding from the size */
		file->ar_size -= padding;
		file->ar_padding = padding;
	}
}

/*
 * Each call to getfile() returns the next unread archive member
 * from the archive opened by getaf(). Returns NULL if no more
 * archive members are left.
 */
ARFILE *
getfile(Cmd_info *cmd_info)
{
	Elf_Arhdr *mem_header = NULL;
	ARFILE	*file;
	char *tmp_rawname, *file_rawname;
	Elf *elf;
	char *arnam = cmd_info->arnam;
	int fd = cmd_info->afd;
	Elf *arf = cmd_info->arf;

	if (fd == -1)
		return (NULL); /* the archive doesn't exist */

	while (mem_header == NULL) {
		if ((elf = elf_begin(fd, ELF_C_READ, arf)) == 0)
			return (NULL);  /* archive is empty or have hit end */

		if ((mem_header = elf_getarhdr(elf)) == NULL) {
			(void) fprintf(stderr, MSG_INTL(MSG_ELF_MALARCHIVE),
			    arnam, EC_XWORD(elf_getbase(elf)), elf_errmsg(-1));
			exit(1);
		}

		/* Ignore special members like the symbol and string tables */
		if (mem_header->ar_name[0] == '/') {
			(void) elf_next(elf);
			(void) elf_end(elf);
			mem_header = NULL;
		}
	}

	/*
	 * NOTE:
	 *	The mem_header->ar_name[] is set to a NULL string
	 *	if the archive member header has some error.
	 *	(See elf_getarhdr() man page.)
	 *	It is set to NULL for example, the ar command reads
	 *	the archive files created by SunOS 4.1 system.
	 *	See c block comment in cmd.c, "Incompatible Archive Header".
	 */
	file = newfile();
	(void) strncpy(file->ar_name, mem_header->ar_name, SNAME);

	if ((file->ar_longname = malloc(strlen(mem_header->ar_name) + 1))
	    == NULL) {
		int err = errno;
		(void) fprintf(stderr, MSG_INTL(MSG_MALLOC), strerror(err));
		exit(1);
	}
	(void) strcpy(file->ar_longname, mem_header->ar_name);
	if ((file->ar_rawname = malloc(strlen(mem_header->ar_rawname) + 1))
	    == NULL) {
		int err = errno;
		(void) fprintf(stderr, MSG_INTL(MSG_MALLOC), strerror(err));
		exit(1);
	}
	tmp_rawname = mem_header->ar_rawname;
	file_rawname = file->ar_rawname;
	while (!isspace(*tmp_rawname) &&
	    ((*file_rawname = *tmp_rawname) != '\0')) {
		file_rawname++;
		tmp_rawname++;
	}
	if (!(*tmp_rawname == '\0'))
		*file_rawname = '\0';

	file->ar_date = mem_header->ar_date;
	file->ar_uid  = mem_header->ar_uid;
	file->ar_gid  = mem_header->ar_gid;
	file->ar_mode = (unsigned long) mem_header->ar_mode;
	file->ar_size = mem_header->ar_size;

	/* reverse logic */
	if ((cmd_info->opt_flgs & (t_FLAG | s_FLAG)) != t_FLAG) {
		size_t ptr;
		file->ar_flag = F_ELFRAW;
		if ((file->ar_contents = elf_rawfile(elf, &ptr))
		    == NULL) {
			if (ptr != 0) {
				(void) fprintf(stderr,
				    MSG_INTL(MSG_ELF_RAWFILE), elf_errmsg(-1));
				exit(1);
			}
		}
		file->ar_elf = elf;
	}

	recover_padding(elf, file);

	(void) elf_next(elf);
	return (file);
}

/*
 * Allocate a new archive member descriptor and add it to the list.
 */
ARFILE *
newfile(void)
{
	static ARFILE	*buffer =  NULL;
	static size_t	count = 0;
	ARFILE		*fileptr;

	if (count == 0) {
		if ((buffer = (ARFILE *) calloc(CHUNK, sizeof (ARFILE)))
		    == NULL) {
			int err = errno;
			(void) fprintf(stderr, MSG_INTL(MSG_MALLOC),
			    strerror(err));
			exit(1);
		}
		count = CHUNK;
	}
	count--;
	fileptr = buffer++;

	if (listhead)
		listend->ar_next = fileptr;
	else
		listhead = fileptr;
	listend = fileptr;
	return (fileptr);
}

static char *
trimslash(char *s)
{
	static char buf[SNAME];

	(void) strncpy(buf, trim(s), SNAME - 2);
	buf[SNAME - 2] = '\0';
	return (strcat(buf, MSG_ORIG(MSG_STR_SLASH)));
}

char *
trim(char *s)
{
	char *p1, *p2;

	for (p1 = s; *p1; p1++)
		;
	while (p1 > s) {
		if (*--p1 != '/')
			break;
		*p1 = 0;
	}
	p2 = s;
	for (p1 = s; *p1; p1++)
		if (*p1 == '/')
			p2 = p1 + 1;
	return (p2);
}


/*
 * Find all the global symbols exported by ELF archive members, and
 * build a list associating each one with the archive member that
 * provides it.
 *
 * exit:
 *	*symlist is set to the list of symbols. If any ELF object was
 *	found, *found_obj is set to TRUE (1). Returns the number of symbols
 *	located.
 */
static size_t
mksymtab(const char *arname, ARFILEP **symlist, int *found_obj)
{
	ARFILE		*fptr;
	size_t		mem_offset = 0;
	Elf		*elf;
	Elf_Scn		*scn;
	GElf_Ehdr	ehdr;
	int		newfd;
	size_t		nsyms = 0;
	int		class = 0;
	Elf_Data	*data;
	size_t		num_errs = 0;

	newfd = 0;
	for (fptr = listhead; fptr; fptr = fptr->ar_next) {
		/* determine if file is coming from the archive or not */
		if ((fptr->ar_elf != NULL) && (fptr->ar_pathname == NULL)) {
			/*
			 * I can use the saved elf descriptor.
			 */
			elf = fptr->ar_elf;
		} else if ((fptr->ar_elf == NULL) &&
		    (fptr->ar_pathname != NULL)) {
#ifdef _LP64
			/*
			 * The archive member header ar_size field is 10
			 * decimal digits, sufficient to represent a 32-bit
			 * value, but not a 64-bit one. Hence, we reject
			 * attempts to insert a member larger than 4GB.
			 *
			 * One obvious way to extend the format without altering
			 * the ar_hdr struct is to use the same mechanism used
			 * for ar_name: Put the size string into the long name
			 * string table and write a string /xxx into ar_size,
			 * where xxx is the string table offset.
			 *
			 * At the time of this writing (June 2010), the largest
			 * relocatable objects are measured in 10s or 100s
			 * of megabytes, so we still have many years to go
			 * before this becomes limiting. By that time, it may
			 * turn out that a completely new archive format is
			 * a better solution, as the current format has many
			 * warts and inefficiencies. In the meantime, we
			 * won't burden the current implementation with support
			 * for a bandaid feature that will have little use.
			 */
			if (fptr->ar_size > 0xffffffff) {
				(void) fprintf(stderr,
				    MSG_INTL(MSG_ERR_MEMBER4G),
				    fptr->ar_pathname);
				num_errs++;
				continue;
			}
#endif
			if ((newfd  =
			    open(fptr->ar_pathname, O_RDONLY)) == -1) {
				int err = errno;
				(void) fprintf(stderr, MSG_INTL(MSG_SYS_OPEN),
				    fptr->ar_pathname, strerror(err));
				num_errs++;
				continue;
			}

			if ((elf = elf_begin(newfd,
			    ELF_C_READ, (Elf *)0)) == 0) {
				(void) fprintf(stderr,
				    MSG_INTL(MSG_ELF_BEGIN_FILE),
				    fptr->ar_pathname, elf_errmsg(-1));
				(void) close(newfd);
				newfd = 0;
				num_errs++;
				continue;
			}
			if (elf_kind(elf) == ELF_K_AR) {
				if (newfd) {
					(void) close(newfd);
					newfd = 0;
				}
				(void) elf_end(elf);
				continue;
			}
		} else {
			(void) fprintf(stderr, MSG_INTL(MSG_INTERNAL_01));
			exit(1);
		}
		if (gelf_getehdr(elf, &ehdr) != 0) {
			size_t shstrndx = 0;
			if ((class = gelf_getclass(elf)) == ELFCLASS64) {
				fptr->ar_flag |= F_CLASS64;
			} else if (class == ELFCLASS32)
				fptr->ar_flag |= F_CLASS32;

			if (elf_getshdrstrndx(elf, &shstrndx) == -1) {
				if (fptr->ar_pathname != NULL) {
					(void) fprintf(stderr,
					    MSG_INTL(MSG_ELF_GETSHSTRNDX_FILE),
					    fptr->ar_pathname, elf_errmsg(-1));
				} else {
					(void) fprintf(stderr,
					    MSG_INTL(MSG_ELF_GETSHSTRNDX_AR),
					    arname, fptr->ar_longname,
					    elf_errmsg(-1));
				}
				num_errs++;
				if (newfd) {
					(void) close(newfd);
					newfd = 0;
				}
				(void) elf_end(elf);
				continue;
			}

			scn = elf_getscn(elf, shstrndx);
			if (scn == NULL) {
				if (fptr->ar_pathname != NULL)
					(void) fprintf(stderr,
					    MSG_INTL(MSG_ELF_GETSCN_FILE),
					    fptr->ar_pathname, elf_errmsg(-1));
				else
					(void) fprintf(stderr,
					    MSG_INTL(MSG_ELF_GETSCN_AR),
					    arname, fptr->ar_longname,
					    elf_errmsg(-1));
				num_errs++;
				if (newfd) {
					(void) close(newfd);
					newfd = 0;
				}
				(void) elf_end(elf);
				continue;
			}

			data = 0;
			data = elf_getdata(scn, data);
			if (data == NULL) {
				if (fptr->ar_pathname != NULL)
					(void) fprintf(stderr,
					    MSG_INTL(MSG_ELF_GETDATA_FILE),
					    fptr->ar_pathname, elf_errmsg(-1));
				else
					(void) fprintf(stderr,
					    MSG_INTL(MSG_ELF_GETDATA_AR),
					    arname, fptr->ar_longname,
					    elf_errmsg(-1));
				num_errs++;
				if (newfd) {
					(void) close(newfd);
					newfd = 0;
				}
				(void) elf_end(elf);
				continue;
			}
			if (data->d_size == 0) {
				if (fptr->ar_pathname != NULL)
					(void) fprintf(stderr,
					    MSG_INTL(MSG_W_ELF_NODATA_FILE),
					    fptr->ar_pathname);
				else
					(void) fprintf(stderr,
					    MSG_INTL(MSG_W_ELF_NODATA_AR),
					    arname, fptr->ar_longname);
				if (newfd) {
					(void) close(newfd);
					newfd = 0;
				}
				(void) elf_end(elf);
				num_errs++;
				continue;
			}

			/* loop through sections to find symbol table */
			scn = 0;
			while ((scn = elf_nextscn(elf, scn)) != 0) {
				GElf_Shdr shdr;
				if (gelf_getshdr(scn, &shdr) == NULL) {
					/* BEGIN CSTYLED */
					if (fptr->ar_pathname != NULL)
					    (void) fprintf(stderr,
						MSG_INTL(MSG_ELF_GETDATA_FILE),
						fptr->ar_pathname,
						elf_errmsg(-1));
					else
					    (void) fprintf(stderr,
						MSG_INTL(MSG_ELF_GETDATA_AR),
						arname, fptr->ar_longname,
						elf_errmsg(-1));
					/* END CSTYLED */
					if (newfd) {
						(void) close(newfd);
						newfd = 0;
					}
					num_errs++;
					(void) elf_end(elf);
					continue;
				}
				*found_obj = 1;
				if (shdr.sh_type == SHT_SYMTAB) {
					if (search_sym_tab(arname, fptr, elf,
					    scn, &nsyms, symlist,
					    &num_errs) == -1) {
						if (newfd) {
							(void) close(newfd);
							newfd = 0;
						}
						continue;
					}
				}
			}
		}
		mem_offset += sizeof (struct ar_hdr) + fptr->ar_size;
		if (fptr->ar_size & 01)
			mem_offset++;
		(void) elf_end(elf);
		if (newfd) {
			(void) close(newfd);
			newfd = 0;
		}
	}
	if (num_errs)
		exit(1);

	if (found_obj) {
		if (nsyms == 0) {
			/*
			 * It is possible, though rare, to have ELF objects
			 * that do not export any global symbols. Presumably
			 * such objects operate via their .init/.fini
			 * sections. In this case, we produce an empty
			 * symbol table, so that applications that rely
			 * on a successful call to elf_getarsym() to determine
			 * if ELF objects are present will succeed. To do this,
			 * we require a small empty symbol string table.
			 */
			strtbl_pad(&sym_strtbl, 4, '\0');
		} else {
			/*
			 * Historical behavior is to pad string tables
			 * to a multiple of 4.
			 */
			strtbl_pad(&sym_strtbl, pad(sym_strtbl.used, 4), '\0');
		}

	}

	return (nsyms);
}

/*
 * Output a member header.
 */
/*ARGSUSED*/
static void
write_member_header(const char *filename, int fd, int is_elf,
    const char *name, time_t timestamp, uid_t uid, gid_t gid, mode_t mode,
    size_t size)
{
	char	buf[sizeof (struct ar_hdr) + 1];
	int	len;

	len = snprintf(buf, sizeof (buf), MSG_ORIG(MSG_MH_FORMAT), name,
	    EC_WORD(timestamp), EC_WORD(uid), EC_WORD(gid), EC_WORD(mode),
	    EC_XWORD(size), ARFMAG);

	/*
	 * If snprintf() reports that it needed more space than we gave
	 * it, it means that the caller fed us a long name, which is a
	 * fatal internal error.
	 */
	if (len != sizeof (struct ar_hdr)) {
		(void) fprintf(stderr, MSG_INTL(MSG_INTERNAL_02));
		exit(1);
	}

	arwrite(filename, fd, buf, len);

	/*
	 * We inject inter-member padding to ensure that ELF object
	 * member data is aligned on PADSZ. If this is a debug build,
	 * verify that the computations were right.
	 */
	assert(!is_elf || (pad(lseek(fd, 0, SEEK_CUR), PADSZ) == 0));
}

/*
 * Write the archive symbol table member to the output archive file.
 *
 * note:
 *	sizeofmembers() must have been called to establish member offset
 *	and padding values before writesymtab() is used.
 */
static void
writesymtab(const char *filename, int fd, size_t nsyms, ARFILEP *symlist,
    size_t eltsize)
{
	size_t	i, j;
	ARFILEP	*ptr;
	size_t	tblsize;
	char	*buf, *dst;
	int	is64 = (eltsize == 8);

	/*
	 * We require a buffer large enough to hold a symbol table count,
	 * plus one offset for each symbol.
	 */
	tblsize = (nsyms + 1) * eltsize;
	if ((buf = dst = malloc(tblsize)) == NULL) {
		int err = errno;
		(void) fprintf(stderr, MSG_INTL(MSG_MALLOC), strerror(err));
		exit(1);
	}

	write_member_header(filename, fd, 0,
	    (is64 ? MSG_ORIG(MSG_STR_SYM64) : MSG_ORIG(MSG_STR_SLASH)),
	    time(0), 0, 0, 0, tblsize + sym_strtbl.used);

	dst = is64 ? sputl64(nsyms, dst) : sputl32(nsyms, dst);

	for (i = 0, j = SYMCHUNK, ptr = symlist; i < nsyms; i++, j--, ptr++) {
		if (!j) {
			j = SYMCHUNK;
			ptr = (ARFILEP *)*ptr;
		}
		dst = is64 ? sputl64((*ptr)->ar_offset, dst) :
		    sputl32((*ptr)->ar_offset, dst);
	}
	arwrite(filename, fd, buf, tblsize);
	free(buf);
	arwrite(filename, fd, sym_strtbl.base, sym_strtbl.used);
}

/*
 * Grow the size of the given string table so that there is room
 * for at least need bytes.
 *
 * entry:
 *	strtbl - String table to grow
 *	need - Amount of space required by caller
 */
static void
strtbl_alloc(ARSTRTBL *strtbl, size_t need)
{
#define	STRTBL_INITSZ	8196

	/*
	 * On 32-bit systems, we require a larger integer type in order
	 * to avoid overflow and wraparound when doing our computations.
	 */
	uint64_t	need64 = need;
	uint64_t	used64 = strtbl->used;
	uint64_t	size64 = strtbl->size;
	uint64_t	target = need64 + used64;

	int		sys32, tbl32;

	if (target <= size64)
		return;

	/*
	 * Detect 32-bit system. We might usually do this with the preprocessor,
	 * but it can serve as a predicate in tests that also apply to 64-bit
	 * systems.
	 */
	sys32 = (sizeof (size_t) == 4);

	/*
	 * The symbol string table can be larger than 32-bits on a 64-bit
	 * system. However, the long name table must stay below that limit.
	 * The reason for this is that there is not enough room in the ar_name
	 * field of the member header to represent 64-bit offsets.
	 */
	tbl32 = (strtbl == &long_strtbl);

	/*
	 * If request is larger than 4GB and we can't do it because we
	 * are a 32-bit program, or because the table is format limited,
	 * we can go no further.
	 */
	if ((target > 0xffffffff) && (sys32 || tbl32))
		goto limit_fail;

	/* Default starting size */
	if (strtbl->base == NULL)
		size64 = STRTBL_INITSZ;

	/*
	 * Our strategy is to double the size until we find a size that
	 * exceeds the request. However, if this table cannot exceed 4GB,
	 * then once we exceed 2GB, we switch to a strategy of taking the
	 * current request and rounding it up to STRTBL_INITSZ.
	 */
	while (target > size64) {
		if ((target > 0x7fffffff) && (sys32 || tbl32)) {
			size64 = ((target + STRTBL_INITSZ) / STRTBL_INITSZ) *
			    STRTBL_INITSZ;

			/*
			 * If we are so close to the line that this small
			 * increment exceeds 4GB, give it up.
			 */
			if ((size64 > 0xffffffff) && (sys32 || tbl32))
				goto limit_fail;

			break;
		}

		size64 *= 2;
	}

	strtbl->base = realloc(strtbl->base, size64);
	if (strtbl->base == NULL) {
		int err = errno;
		(void) fprintf(stderr, MSG_INTL(MSG_MALLOC), strerror(err));
		exit(1);
	}
	strtbl->size = (size_t)size64;
	return;

limit_fail:
	/*
	 * Control comes here if we are unable to allocate more than 4GB of
	 * memory for the string table due to one of the following reasons:
	 *
	 * - A 32-bit process is attempting to be larger than 4GB
	 *
	 * - A 64-bit process is attempting to grow the long names string
	 *	table beyond the ar format limit of 32-bits.
	 */
	if (sys32)
		(void) fprintf(stderr, MSG_INTL(MSG_MALLOC), strerror(ENOMEM));
	else
		(void) fprintf(stderr, MSG_INTL(MSG_ERR_LONGSTRTBLSZ));
	exit(1);

#undef STRTBL_INITSZ
}

/*
 * Add the specified number of pad characters to the end of the
 * given string table.
 *
 * entry:
 *	strtbl - String table to pad
 *	n - # of pad characters to add
 *	ch - Pad character to use
 */
static void
strtbl_pad(ARSTRTBL *strtbl, size_t n, int ch)
{
	if (n == 0)
		return;

	if ((n + strtbl->used) > strtbl->size)
		strtbl_alloc(strtbl, n);

	while (n--)
		strtbl->base[strtbl->used++] = ch;
}

/*
 * Enter a symbol name into the symbol string table.
 */
static void
savename(char *symbol)
{
	size_t need;

	need = strlen(symbol) + 1;
	if ((need + sym_strtbl.used) > sym_strtbl.size)
		strtbl_alloc(&sym_strtbl, need);

	(void) strcpy(sym_strtbl.base + sym_strtbl.used, symbol);
	sym_strtbl.used += need;
}

/*
 * Prepare an archive member with a long (>15 characters) name for
 * the output archive.
 *
 * entry:
 *	fptr - pointer to archive member with long name
 *
 * exit:
 *	The long name is entered into the long name string table,
 *	and fptr->ar_name has been replaced with the special /xxx
 *	name used to indicate that the real name is in the string table
 *	at offset xxx.
 */
static void
savelongname(ARFILE *fptr)
{
	size_t	len, need;
	char	*p;

	/* Size of new item to add */
	len = strlen(fptr->ar_longname);
	need = len + 2;

	/* Ensure there's room */
	if ((need + long_strtbl.used) > long_strtbl.size)
		strtbl_alloc(&long_strtbl, need);

	/*
	 * Generate the index string to be written into the member header
	 *
	 * This will not overflow the ar_name field because that field is
	 * 16 characters in size, and a 32-bit unsigned value can be formatted
	 * in 10 characters. Allowing a character for the leading '/', and one
	 * for the NULL termination, that leaves us with 4 extra spaces.
	 */
	(void) snprintf(fptr->ar_name, sizeof (fptr->ar_name),
	    MSG_ORIG(MSG_FMT_LLINT), EC_XWORD(long_strtbl.used));

	/*
	 * Enter long name into reserved spot, terminated with a slash
	 * and a newline character.
	 */
	p = long_strtbl.base + long_strtbl.used;
	long_strtbl.used += need;
	(void) strcpy(p, fptr->ar_longname);
	p += len;
	*p++ = '/';
	*p++ = '\n';
}

/*
 * Determine if the archive we're about to write will exceed the
 * 32-bit limit of 4GB.
 *
 * entry:
 *      mksymtab() and mklong_tab() have been called to set up
 *	the string tables.
 *
 * exit:
 *	Returns TRUE (1) if the 64-bit symbol table is needed, and
 *	FALSE (0) otherwise.
 *
 */
static int
require64(size_t nsyms, int found_obj, size_t longnames)
{
	ARFILE		*fptr;
	uint64_t	size;

	/*
	 * If there are more than 4GB symbols, we have to use
	 * the 64-bit form. Note that longnames cannot exceed 4GB
	 * because that symbol table is limited to a length of 4GB by
	 * the archive format.
	 */
	if (nsyms > 0xffffffff)
		return (1);

	/*
	 * Make a worst case estimate for the size of the resulting
	 * archive by assuming full padding between members.
	 */
	size = SARMAG;
	if (longnames)
		size += sizeof (struct ar_hdr) + long_strtbl.used + PADSZ;

	if (found_obj)
		size += sizeof_symtbl(nsyms, found_obj, 4) + PADSZ;

	if (size > 0xffffffff)
		return (1);

	for (fptr = listhead; fptr; fptr = fptr->ar_next) {
		size += sizeof (struct ar_hdr) + fptr->ar_size + PADSZ;

		if (size > 0xffffffff)
			return (1);
	}

	/* 32-bit symbol table will suffice */
	return (0);
}

void
writefile(Cmd_info *cmd_info)
{
	ARFILE		*fptr;
	ARFILEP		*symlist = 0;
	size_t		longnames;
	size_t		nsyms;
	int		new_archive = 0;
	char		*name = cmd_info->arnam;
	size_t		arsize;	/* Size of magic # and special members */
	size_t		symtbl_eltsize = 4;
	int		found_obj = 0;
	int		fd;
	off_t		off;
	struct stat	stbuf, ar_stbuf;
	char		pad_bytes[PADSZ];
	size_t		pad_cnt;
	int		is_elf;

	/*
	 * Gather the list of symbols and associate each one to the
	 * ARFILE descriptor of the object it belongs to. At the same
	 * time, tag each ELF object with the appropriate F_CLASSxx
	 * flag.
	 */
	nsyms = mksymtab(name, &symlist, &found_obj);

	/* Generate the string table for long member names */
	longnames = mklong_tab();

	/*
	 * Will this archive exceed 4GB? If we're a 32-bit process, we can't
	 * do it. If we're a 64-bit process, then we'll have to use a
	 * 64-bit symbol table.
	 */
	if (require64(nsyms, found_obj, longnames)) {
#ifdef _LP64
		symtbl_eltsize = 8;
#else
		(void) fprintf(stderr, MSG_INTL(MSG_TOOBIG4G));
		exit(1);
#endif
	}

	/*
	 * If the user requested it, use the 64-bit symbol table even if
	 * a 32-bit one would suffice. 32-bit tables are more portable and
	 * take up less room, so this feature is primarily for testing.
	 */
	if (cmd_info->opt_flgs & S_FLAG)
		symtbl_eltsize = 8;

	/*
	 * If the first non-special archive member is an ELF object, then we
	 * need to arrange for its data to have an alignment of PADSZ. The
	 * preceeding special member will be the symbol table, or the long
	 * name string table. We pad the string table that precedes the
	 * ELF member in order to achive the desired alignment.
	 */
	is_elf = listhead && (listhead->ar_flag & (F_CLASS32 | F_CLASS64));
	arsize = SARMAG;
	if (found_obj) {
		arsize += sizeof_symtbl(nsyms, found_obj, symtbl_eltsize);
		if (is_elf && (longnames == 0)) {
			pad_cnt = pad(arsize + sizeof (struct ar_hdr), PADSZ);
			strtbl_pad(&sym_strtbl, pad_cnt, '\0');
			arsize += pad_cnt;
		}
	}
	if (longnames > 0) {
		arsize += sizeof (struct ar_hdr) + long_strtbl.used;
		if (is_elf) {
			pad_cnt = pad(arsize + sizeof (struct ar_hdr), PADSZ);
			strtbl_pad(&long_strtbl, pad_cnt, '\0');
			arsize += pad_cnt;
		}
	}

	/*
	 * For each user visible (non-special) archive member, determine
	 * the header offset, and the size of any required padding.
	 */
	(void) sizeofmembers(arsize);

	/*
	 * Is this a new archive, or are we updating an existing one?
	 *
	 * A subtlety here is that POSIX says we are not supposed
	 * to replace a non-writable file. The only 100% reliable test
	 * against this is to open the file for non-destructive
	 * write access. If the open succeeds, we are clear to
	 * replace it, and if not, then the error generated is
	 * the error we need to report.
	 */
	if ((fd = open(name, O_RDWR)) < 0) {
		int	err = errno;

		if (err != ENOENT) {
			(void) fprintf(stderr, MSG_INTL(MSG_SYS_OPEN),
			    name, strerror(err));
			exit(1);
		}
		new_archive = 1;
		if ((cmd_info->opt_flgs & c_FLAG) == 0) {
			(void) fprintf(stderr, MSG_INTL(MSG_BER_MES_CREATE),
			    cmd_info->arnam);
		}
	} else {
		/* Capture mode and owner information to apply to replacement */
		if (fstat(fd, &ar_stbuf) < 0) {
			int err = errno;
			(void) fprintf(stderr, MSG_INTL(MSG_SYS_STAT),
			    name, strerror(err));
			(void) close(fd);
			exit(1);
		}
		(void) close(fd);
		new_archive = 0;
	}


	/*
	 * Register exit handler function to clean up after us if we exit
	 * before completing the new archive. atexit() is defined as
	 * only being able to fail due to memory exhaustion.
	 */
	if (atexit(exit_cleanup) != 0) {
		(void) fprintf(stderr, MSG_INTL(MSG_MALLOC), strerror(ENOMEM));
		exit(1);
	}

	/*
	 * If a new archive, create it in place. If updating an archive,
	 * create the replacement under a temporary name and then rename it
	 * into place.
	 */
	ar_outfile.path = new_archive ? name : make_tmpname(name);
	ar_outfile.fd = open(ar_outfile.path, O_RDWR|O_CREAT|O_LARGEFILE, 0666);
	if (ar_outfile.fd == -1) {
		int err = errno;
		(void) fprintf(stderr, new_archive ?
		    MSG_INTL(MSG_BAD_CREATE) : MSG_INTL(MSG_SYS_OPEN),
		    ar_outfile.path, strerror(err));
		exit(1);
	}

	/* Output magic string */
	arwrite(name, ar_outfile.fd, ARMAG, SARMAG);

	/*
	 * The symbol table member is always first if present. Note that
	 * writesymtab() uses the member offsets computed by sizeofmembers()
	 * above.
	 */
	if (found_obj)
		writesymtab(name, ar_outfile.fd, nsyms, symlist,
		    symtbl_eltsize);

	if (longnames) {
		write_member_header(name, ar_outfile.fd, 0,
		    MSG_ORIG(MSG_STR_DSLASH), time(0), 0, 0, 0,
		    long_strtbl.used);
		arwrite(name, ar_outfile.fd, long_strtbl.base,
		    long_strtbl.used);
	}

	/*
	 * The accuracy of the symbol table depends on our having calculated
	 * the size of the archive accurately to this point. If this is a
	 * debug build, verify it.
	 */
	assert(arsize == lseek(ar_outfile.fd, 0, SEEK_CUR));

#ifndef XPG4
	if (cmd_info->opt_flgs & v_FLAG) {
		(void) fprintf(stderr, MSG_INTL(MSG_BER_MES_WRITE),
		    cmd_info->arnam);
	}
#endif

	/*
	 * Fill pad_bytes array with newline characters. This array
	 * is used to supply padding bytes at the end of ELF objects.
	 * There can never be more tha PADSZ such bytes, so this number
	 * will always suffice.
	 */
	for (pad_cnt = 0; pad_cnt < PADSZ; pad_cnt++)
		pad_bytes[pad_cnt] = '\n';

	for (fptr = listhead; fptr; fptr = fptr->ar_next) {
		/*
		 * We computed the expected offset for each ELF member and
		 * used those offsets to fill the symbol table. If this is
		 * a debug build, verify that the computed offset was right.
		 */
		is_elf = (fptr->ar_flag & (F_CLASS32 | F_CLASS64)) != 0;
		assert(!is_elf ||
		    (fptr->ar_offset == lseek(ar_outfile.fd, 0, SEEK_CUR)));

		/*
		 * NOTE:
		 * The mem_header->ar_name[] is set to a NULL string
		 * if the archive member header has some error.
		 * (See elf_getarhdr() man page.)
		 * It is set to NULL for example, the ar command reads
		 * the archive files created by SunOS 4.1 system.
		 * See c block comment in cmd.c, "Incompatible Archive Header".
		 */
		if (fptr->ar_name[0] == 0) {
			fptr->ar_longname = fptr->ar_rawname;
			(void) strncpy(fptr->ar_name, fptr->ar_rawname, SNAME);
		}
		write_member_header(name, ar_outfile.fd, is_elf,
		    (strlen(fptr->ar_longname) <= (unsigned)SNAME-2) ?
		    trimslash(fptr->ar_longname) : fptr->ar_name,
		    EC_WORD(fptr->ar_date), fptr->ar_uid, fptr->ar_gid,
		    fptr->ar_mode, fptr->ar_size + fptr->ar_padding);


		if ((fptr->ar_flag & F_ELFRAW) == 0) {
			/*
			 * The file doesn't come from the archive, and is
			 * therefore not already in memory(fptr->ar_contents)
			 * so open it and do a direct file-to-file transfer of
			 * its contents. We use the sendfile() system call
			 * to make the kernel do the transfer, so we don't have
			 * to buffer data in process, and we trust that the
			 * kernel will use an optimal transfer strategy.
			 */
			if ((fd = open(fptr->ar_pathname, O_RDONLY)) == -1) {
				int err = errno;
				(void) fprintf(stderr, MSG_INTL(MSG_SYS_OPEN),
				    fptr->ar_longname, strerror(err));
				exit(1);
			}
			if (stat(fptr->ar_pathname, &stbuf) < 0) {
				int err = errno;
				(void) fprintf(stderr, MSG_INTL(MSG_SYS_OPEN),
				    fptr->ar_longname, strerror(err));
				(void) close(fd);
				exit(1);
			}
			off = 0;
			if (sendfile(ar_outfile.fd, fd, &off,
			    stbuf.st_size) != stbuf.st_size) {
				int err = errno;
				(void) fprintf(stderr, MSG_INTL(MSG_SYS_WRITE),
				    name, strerror(err));
				exit(2);
			}
			(void) close(fd);
		} else {
			/* Archive member is in memory. Write it out */
			arwrite(name, ar_outfile.fd, fptr->ar_contents,
			    fptr->ar_size);
		}

		/*
		 * All archive members are padded to at least a boundary of 2.
		 * The expression ((fptr->ar_size & 0x1) != 0) yields 1 for
		 * odd boundaries, and 0 for even ones. To this, we add
		 * whatever padding is needed for ELF objects.
		 */
		pad_cnt = ((fptr->ar_size & 0x1) != 0) + fptr->ar_padding;
		if (pad_cnt > 0)
			arwrite(name, ar_outfile.fd, pad_bytes, pad_cnt);
	}

	/*
	 * All archive output is done.
	 */
	if (close(ar_outfile.fd) < 0) {
		int err = errno;
		(void) fprintf(stderr, MSG_INTL(MSG_SYS_CLOSE), ar_outfile.path,
		    strerror(err));
		exit(1);
	}
	ar_outfile.fd = -1;	/* Prevent removal on exit */
	(void) elf_end(cmd_info->arf);
	(void) close(cmd_info->afd);

	/*
	 * If updating an existing archive, rename the new version on
	 * top of the original.
	 */
	if (!new_archive) {
		/*
		 * Prevent the replacement of the original archive from
		 * being interrupted, to lower the possibility of an
		 * interrupt destroying a pre-existing archive.
		 */
		establish_sighandler(SIG_IGN);

		if (rename(ar_outfile.path, name) < 0) {
			int err = errno;
			(void) fprintf(stderr, MSG_INTL(MSG_SYS_RENAME),
			    ar_outfile.path, name, strerror(err));
			(void) unlink(ar_outfile.path);
			exit(1);
		}
		(void) chmod(name, ar_stbuf.st_mode & 0777);
		if (chown(name, ar_stbuf.st_uid, ar_stbuf.st_gid) >= 0)
			(void) chmod(name, ar_stbuf.st_mode & 07777);

	}
}

/*
 * Examine all the archive members, enter any member names longer than
 * 15 characters into the long name string table, and count the number
 * of names found.
 *
 * Returns the size of the resulting archive member, including the
 * member header.
 */
static size_t
mklong_tab(void)
{
	ARFILE  *fptr;
	size_t longnames = 0;

	for (fptr = listhead; fptr; fptr = fptr->ar_next) {
		if (strlen(fptr->ar_longname) >= (unsigned)SNAME-1) {
			longnames++;
			savelongname(fptr);
		}
	}

	/* round up table that keeps the long filenames */
	if (longnames > 0)
		strtbl_pad(&long_strtbl, pad(long_strtbl.used, 4), '\n');

	return (longnames);
}

/*
 * Write 32/64-bit words into buffer in archive symbol table
 * standard byte order (MSB).
 */
static char *
sputl32(uint32_t n, char *cp)
{
	*cp++ = n >> 24;
	*cp++ = n >> 16;
	*cp++ = n >> 8;

	*cp++ = n & 255;

	return (cp);
}

static char *
sputl64(uint64_t n, char *cp)
{
	*cp++ = n >> 56;
	*cp++ = n >> 48;
	*cp++ = n >> 40;
	*cp++ = n >> 32;

	*cp++ = n >> 24;
	*cp++ = n >> 16;
	*cp++ = n >> 8;

	*cp++ = n & 255;

	return (cp);
}

static int
search_sym_tab(const char *arname, ARFILE *fptr, Elf *elf, Elf_Scn *scn,
    size_t *nsyms, ARFILEP **symlist, size_t *num_errs)
{
	Elf_Data *str_data, *sym_data; /* string table, symbol table */
	Elf_Scn *str_scn;
	GElf_Sxword no_of_symbols;
	GElf_Shdr shdr;
	int counter;
	int str_shtype;
	char *symname;
	static ARFILEP *sym_ptr = 0;
	static ARFILEP *nextsym = NULL;
	static int syms_left = 0;
	char *fname = fptr->ar_pathname;

	(void) gelf_getshdr(scn, &shdr);
	str_scn = elf_getscn(elf, shdr.sh_link); /* index for string table */
	if (str_scn == NULL) {
		if (fname != NULL)
			(void) fprintf(stderr, MSG_INTL(MSG_ELF_GETDATA_FILE),
			    fname, elf_errmsg(-1));
		else
			(void) fprintf(stderr, MSG_INTL(MSG_ELF_GETDATA_AR),
			    arname, fptr->ar_longname, elf_errmsg(-1));
		(*num_errs)++;
		return (-1);
	}

	no_of_symbols = shdr.sh_size / shdr.sh_entsize;
	if (no_of_symbols == -1) {
		(void) fprintf(stderr, MSG_INTL(MSG_SYMTAB_01));
		return (-1);
	}

	(void) gelf_getshdr(str_scn, &shdr);
	str_shtype = shdr.sh_type;
	if (str_shtype == -1) {
		if (fname != NULL)
			(void) fprintf(stderr, MSG_INTL(MSG_ELF_GETDATA_FILE),
			    fname, elf_errmsg(-1));
		else
			(void) fprintf(stderr, MSG_INTL(MSG_ELF_GETDATA_AR),
			    arname, fptr->ar_longname, elf_errmsg(-1));
		(*num_errs)++;
		return (-1);
	}

	/* This test must happen before testing the string table. */
	if (no_of_symbols == 1)
		return (0);	/* no symbols; 0th symbol is the non-symbol */

	if (str_shtype != SHT_STRTAB) {
		if (fname != NULL)
			(void) fprintf(stderr, MSG_INTL(MSG_SYMTAB_NOSTR_FILE),
			    fname);
		else
			(void) fprintf(stderr, MSG_INTL(MSG_SYMTAB_NOSTR_AR),
			    arname, fptr->ar_longname);
		return (0);
	}
	str_data = 0;
	if ((str_data = elf_getdata(str_scn, str_data)) == 0) {
		if (fname != NULL)
			(void) fprintf(stderr, MSG_INTL(MSG_SYMTAB_NODAT_FILE),
			    fname);
		else
			(void) fprintf(stderr, MSG_INTL(MSG_SYMTAB_NODAT_AR),
			    arname, fptr->ar_longname);
		return (0);
	}
	if (str_data->d_size == 0) {
		if (fname != NULL)
			(void) fprintf(stderr, MSG_INTL(MSG_SYMTAB_ZDAT_FILE),
			    fname);
		else
			(void) fprintf(stderr, MSG_INTL(MSG_SYMTAB_ZDAT_AR),
			    arname, fptr->ar_longname);
		return (0);
	}
	sym_data = 0;
	if ((sym_data = elf_getdata(scn, sym_data)) == NULL) {
		if (fname != NULL)
			(void) fprintf(stderr, MSG_INTL(MSG_ELF_LIB_FILE),
			    fname, elf_errmsg(-1));
		else
			(void) fprintf(stderr, MSG_INTL(MSG_ELF_LIB_AR),
			    arname, fptr->ar_longname, elf_errmsg(-1));
		return (0);
	}

	/* start at 1, first symbol entry is ignored */
	for (counter = 1; counter < no_of_symbols; counter++) {
		GElf_Sym sym;
		(void) gelf_getsym(sym_data, counter, &sym);

		symname = (char *)(str_data->d_buf) + sym.st_name;

		if (((GELF_ST_BIND(sym.st_info) == STB_GLOBAL) ||
		    (GELF_ST_BIND(sym.st_info) == STB_WEAK)) &&
		    (sym.st_shndx != SHN_UNDEF)) {
			if (!syms_left) {
				sym_ptr = malloc((SYMCHUNK+1)
				    * sizeof (ARFILEP));
				if (sym_ptr == NULL) {
					int err = errno;
					(void) fprintf(stderr,
					    MSG_INTL(MSG_MALLOC),
					    strerror(err));
					exit(1);
				}
				syms_left = SYMCHUNK;
				if (nextsym)
					*nextsym = (ARFILEP)sym_ptr;
				else
					*symlist = sym_ptr;
				nextsym = sym_ptr;
			}
			sym_ptr = nextsym;
			nextsym++;
			syms_left--;
			(*nsyms)++;
			*sym_ptr = fptr;
			savename(symname);	/* put name in the archiver's */
						/* symbol table string table */
		}
	}
	return (0);
}

/*
 * Get the output file size
 */
static size_t
sizeofmembers(size_t psum)
{
	size_t	sum = 0;
	ARFILE	*fptr;
	size_t	hdrsize = sizeof (struct ar_hdr);

	for (fptr = listhead; fptr; fptr = fptr->ar_next) {
		fptr->ar_offset = psum + sum;
		sum += fptr->ar_size;
		if (fptr->ar_size & 01)
			sum++;
		sum += hdrsize;

		/*
		 * If the current item, and the next item are both ELF
		 * objects, then add padding to current item so that the
		 * data in the next item will have PADSZ alignment.
		 *
		 * In any other case, set the padding to 0. If the
		 * item comes from another archive, it may be carrying
		 * a non-zero padding value from that archive that does
		 * not apply to the one we are about to build.
		 */
		if ((fptr->ar_flag & (F_CLASS32 | F_CLASS64)) &&
		    fptr->ar_next &&
		    (fptr->ar_next->ar_flag & (F_CLASS32 | F_CLASS64))) {
			fptr->ar_padding = pad(psum + sum + hdrsize, PADSZ);
			sum += fptr->ar_padding;
		} else {
			fptr->ar_padding = 0;
		}
	}
	return (sum);
}

/*
 * Compute the size of the symbol table archive member.
 *
 * entry:
 *	nsyms - # of symbols in the table
 *	found_obj - TRUE if the archive contains any ELF objects
 *	eltsize - Size of the integer type to use for the symbol
 *		table. 4 for 32-bit tables, and 8 for 64-bit tables.
 */
static size_t
sizeof_symtbl(size_t nsyms, int found_obj, size_t eltsize)
{
	size_t sum = 0;

	if (found_obj) {
		/* Member header, symbol count, and one slot per symbol */
		sum += sizeof (struct ar_hdr) + ((nsyms + 1) * eltsize);
		sum += sym_strtbl.used;
	}

	return (sum);
}

static void
arwrite(const char *name, int nfd, const char *dst, size_t size)
{
	if (write(nfd, dst, size) != size) {
		int err = errno;
		(void) fprintf(stderr, MSG_INTL(MSG_SYS_WRITE),
		    name, strerror(err));
		exit(2);
	}
}

static const char *
make_tmpname(const char *filename)
{
	char	*slash, *tmpname;
	size_t	prefix_cnt = 0;

	/*
	 * If there is a path prefix in front of the filename, we
	 * want to put the temporary file in the same directory.
	 * Determine the length of the path.
	 */
	slash = strrchr(filename, '/');
	if (slash != NULL)
		prefix_cnt = slash - filename + 1;
	tmpname = malloc(prefix_cnt + MSG_STR_MKTEMP_SIZE + 1);
	if (tmpname == NULL) {
		int err = errno;
		(void) fprintf(stderr, MSG_INTL(MSG_MALLOC), strerror(err));
		exit(1);
	}

	if (prefix_cnt > 0)
		(void) strncpy(tmpname, filename, prefix_cnt);
	(void) strcpy(tmpname + prefix_cnt, MSG_ORIG(MSG_STR_MKTEMP));
	(void) mktemp(tmpname);

	return (tmpname);
}
/*
 * 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) 1995, 2010, Oracle and/or its affiliates. All rights reserved.
 */

/*
 *	Copyright (c) 1988 AT&T
 *	  All Rights Reserved
 *
 */

#ifndef	_INC_H
#define	_INC_H

#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <errno.h>
#include <ctype.h>
#include <unistd.h>
#include <signal.h>
#include <sys/stat.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/param.h>
#include <time.h>
#include <locale.h>
#include <ar.h>
#include <libelf.h>
#include "sgs.h"
#include "msg.h"

#define	CHUNK		500
#define	SYMCHUNK	1000
#define	SNAME		16
#define	ROUNDUP(x)	(((x) + 1) & ~1)

#define	DATESIZE	60	 /*  sizeof (struct ar_hdr)  */

typedef struct arfile ARFILE;
typedef ARFILE *ARFILEP;

/*
 * Per-member state, help on listhead/listend list.
 */
struct arfile {
	char		ar_name[SNAME];	/* info from archive member header */
	time_t		ar_date;
	int		ar_uid;
	int		ar_gid;
	unsigned long	ar_mode;
	size_t		ar_size;
	char    	*ar_longname;
	char    	*ar_rawname;
	Elf 		*ar_elf;	/* My elf descriptor */
	char		*ar_pathname;
	char		*ar_contents;
	size_t		ar_offset;	/* The member offset */
	unsigned char	ar_flag;
	unsigned char	ar_padding;	/* # padding bytes following data */
	ARFILE		*ar_next;	/* Next member in linked list or NULL */
};

/*
 * Command function. There is one of these for each operation
 * ar can perform (r, x, etc).
 */
struct cmd_info;
typedef void Cmd_func(struct cmd_info *);

/* Command information block */
typedef struct cmd_info {
	char		*arnam;		/* Archive file name */
	int		afd;		/* fd for the archive file */
	Elf		*arf;		/* Elf descriptor for the archive */
	char		*ponam;		/* Position Name (-a, -b/-i) */
	char		**namv;		/* Member names from command line */
	int		namc;		/* # of member names in namv */
	int		opt_flgs;	/* options */
	Cmd_func	*comfun;	/* function to carry out command */
	int		modified;	/* Set if need to write archive */
} Cmd_info;

/*
 * options (Cmd_info opt_flgs)
 */
#define	a_FLAG	0x00000001
#define	b_FLAG	0x00000002
#define	c_FLAG	0x00000004
#define	C_FLAG	0x00000008
#define	d_FLAG	0x00000010
#define	m_FLAG	0x00000020
#define	p_FLAG	0x00000040
#define	q_FLAG	0x00000080
#define	r_FLAG	0x00000100
#define	s_FLAG	0x00000200
#define	S_FLAG	0x00000400
#define	t_FLAG	0x00000800
#define	T_FLAG	0x00001000
#define	u_FLAG	0x00002000
#define	v_FLAG	0x00004000
#define	x_FLAG	0x00008000
#define	z_FLAG	0x00010000

/*
 * Member flags (ARFILE ar_flag)
 */
#define	F_ELFRAW	0x01		/* ar_contents data via elf_rawfile */
#define	F_CLASS32	0x02		/* ELFCLASS32 */
#define	F_CLASS64	0x04		/* ELFCLASS64 */

/*
 * Function prototypes
 */
Cmd_func	qcmd;
Cmd_func	rcmd;
Cmd_func	dcmd;
Cmd_func	xcmd;
Cmd_func	pcmd;
Cmd_func	mcmd;
Cmd_func	tcmd;

extern ARFILE	*listhead, *listend;

extern	void	establish_sighandler(void (*)());
extern	int	getaf(Cmd_info *);
extern	ARFILE	*getfile(Cmd_info *);
extern	ARFILE	*newfile(void);
extern	char	*trim(char *);
extern	void	writefile(Cmd_info *cmd_info);


#endif	/* _INC_H */
/*
 * 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) 1988 AT&T	*/
/*	  All Rights Reserved   */

/*
 * Copyright (c) 1995, 2010, Oracle and/or its affiliates. All rights reserved.
 */

/*
 * Copyright (c) 2018, Joyent, Inc.
 * Copyright 2022 Oxide Computer Company
 */

#include "inc.h"
#include "conv.h"

/*
 * Forward declarations
 */
static void setup(int, char **, Cmd_info *);
static void setcom(Cmd_info *, Cmd_func);
static void usage(void);
static void sigexit(int sig);
static int notfound(Cmd_info *);
static void check_swap();

const char *
_ar_msg(Msg mid)
{
	return (gettext(MSG_ORIG(mid)));
}


void
establish_sighandler(void (*handler)())
{
	static const int signum[] = {SIGHUP, SIGINT, SIGQUIT, 0};
	int i;

	if (handler == SIG_IGN) {
		/* Ignore all the specified signals */
		for (i = 0; signum[i]; i++)
			(void) signal(signum[i], SIG_IGN);

	} else {
		/*
		 * Set any signal that doesn't default to being ignored
		 * to our signal handler.
		 */
		for (i = 0; signum[i]; i++)
			if (signal(signum[i], SIG_IGN) != SIG_IGN)
				(void) signal(signum[i], handler);
	}
}

int
main(int argc, char **argv, char *envp[])
{
	int fd;
	Cmd_info *cmd_info;
	int ret;
	char *new = NULL;

#ifndef	XPG4
	/*
	 * Check for a binary that better fits this architecture.
	 */
	(void) conv_check_native(argv, envp);
#endif

	/*
	 * Establish locale.
	 */
	(void) setlocale(LC_ALL, MSG_ORIG(MSG_STR_EMPTY));
	(void) textdomain(MSG_ORIG(MSG_SUNW_OST_SGS));

	/* Allow a graceful exit up until we start to write an archive */
	establish_sighandler(sigexit);

	/*
	 * Initialize cmd_info
	 */
	cmd_info = (Cmd_info *)calloc(1, sizeof (Cmd_info));
	if (cmd_info == NULL) {
		int err = errno;
		(void) fprintf(stderr, MSG_INTL(MSG_MALLOC), strerror(err));
		exit(1);
	}

	if (argc < 2)
		usage();

	/*
	 * Option handling.
	 */
	if (argv[1][0] != '-') {
		new = (char *)malloc(strlen(argv[1]) + 2);
		if (new == NULL) {
			int err = errno;
			(void) fprintf(stderr, MSG_INTL(MSG_MALLOC),
			    strerror(err));
			exit(1);
		}
		(void) strcpy(new, MSG_ORIG(MSG_STR_HYPHEN));
		(void) strcat(new, argv[1]);
		argv[1] = new;
	}
	setup(argc, argv, cmd_info);

	/*
	 * Check SWAP
	 */
	if (cmd_info->opt_flgs & z_FLAG)
		check_swap();

	cmd_info->modified = (cmd_info->opt_flgs & s_FLAG);
	fd = getaf(cmd_info);

	if (fd == -1) {
		boolean_t req_arg = (cmd_info->opt_flgs & (d_FLAG | m_FLAG |
		    p_FLAG | t_FLAG | x_FLAG)) != 0;
		boolean_t req_r = (cmd_info->opt_flgs & r_FLAG) &&
		    (cmd_info->opt_flgs & (a_FLAG | b_FLAG));
		boolean_t req_s = (cmd_info->opt_flgs & s_FLAG) &&
		    (cmd_info->opt_flgs & (r_FLAG | q_FLAG)) == 0;

		if (req_arg || req_r || req_s) {
			(void) fprintf(stderr, MSG_INTL(MSG_NOT_FOUND_AR),
			    cmd_info->arnam);
			exit(1);
		}
	}

	(*cmd_info->comfun)(cmd_info);
	if (cmd_info->modified) {
		writefile(cmd_info);
	} else
		(void) close(fd);

	ret = notfound(cmd_info);

	/*
	 * Check SWAP
	 */
	if (cmd_info->opt_flgs & z_FLAG)
		check_swap();

	free(new);
	free(cmd_info);
	return (ret);

}

/*
 * Option handing function.
 *	Using getopt(), following xcu4 convention.
 */
static void
setup(int argc, char *argv[], Cmd_info *cmd_info)
{
	int Vflag = 0;
	int c;
	int usage_err = 0;

	while ((c = getopt(argc, argv, MSG_ORIG(MSG_STR_OPTIONS))) != -1) {
		switch (c) {
		case 'a': /* position after named archive member file */
			cmd_info->opt_flgs |= a_FLAG;
			cmd_info->ponam = trim(optarg);
			break;
		case 'b': /* position before named archive member file */
		case 'i': /* position before named archive member: same as b */
			cmd_info->opt_flgs |= b_FLAG;
			cmd_info->ponam = trim(optarg);
			break;
		case 'c': /* supress messages */
			cmd_info->opt_flgs |= c_FLAG;
			break;
		case 'd':
			/*
			 * key operation:
			 * delete files from the archive
			 */
			setcom(cmd_info, dcmd);
			cmd_info->opt_flgs |= d_FLAG;
			break;
		case 'l': /* ignored */
			break;
		case 'm':
			/*
			 * key operation:
			 * move files to end of the archive
			 * or as indicated by position flag
			 */
			setcom(cmd_info, mcmd);
			cmd_info->opt_flgs |= m_FLAG;
			break;
		case 'p':
			/*
			 * key operation:
			 * print files in the archive
			 */
			setcom(cmd_info, pcmd);
			cmd_info->opt_flgs |= p_FLAG;
			break;
		case 'q':
			/*
			 * key operation:
			 * quickly append files to end of the archive
			 */
			setcom(cmd_info, qcmd);
			cmd_info->opt_flgs |= q_FLAG;
			break;
		case 'r':
			/*
			 * key operation:
			 * replace or add files to the archive
			 */
			setcom(cmd_info, rcmd);
			cmd_info->opt_flgs |= r_FLAG;
			break;
		case 's': /* force symbol table regeneration */
			cmd_info->opt_flgs |= s_FLAG;
			break;
		case 'S': /* Build SYM64 symbol table */
			cmd_info->opt_flgs |= S_FLAG;
			break;
		case 't':
			/*
			 * key operation:
			 * print table of contents
			 */
			setcom(cmd_info, tcmd);
			cmd_info->opt_flgs |= t_FLAG;
			break;
		case 'u': /* update: change archive dependent on file dates */
			cmd_info->opt_flgs |= u_FLAG;
			break;
		case 'v': /* verbose */
			cmd_info->opt_flgs |= v_FLAG;
			break;
		case 'x':
			/*
			 * key operation:
			 * extract files from the archive
			 */
			setcom(cmd_info, xcmd);
			cmd_info->opt_flgs |= x_FLAG;
			break;
		case 'z':
			cmd_info->opt_flgs |= z_FLAG;
			break;
		case 'V':
			/*
			 * print version information.
			 * adjust command line access accounting
			 */
			if (Vflag == 0) {
				(void) fprintf(stderr,
				    MSG_ORIG(MSG_FMT_VERSION),
				    (const char *)SGU_PKG,
				    (const char *)SGU_REL);
				Vflag++;
			}
			break;
		case 'C':
			cmd_info->opt_flgs |= C_FLAG;
			break;
		case 'M':
			/*
			 * -M was an original undocumented AT&T feature that
			 * would force the use of mmap() instead of read()
			 * for pulling file data into the process before
			 * writing it to the archive. Ignored.
			 */
			break;
		case 'T':
			cmd_info->opt_flgs |= T_FLAG;
			break;
		case ':':
			(void) fprintf(stderr, MSG_INTL(MSG_USAGE_OPERAND),
			    optopt);
			usage_err++;
			break;
		case '?':
			(void) fprintf(stderr, MSG_INTL(MSG_USAGE_OPTION),
			    optopt);
			usage_err++;
			break;
		}
	}

	if (usage_err || argc - optind < 1)
		usage();

	cmd_info->arnam = argv[optind];
	cmd_info->namv = &argv[optind+1];
	cmd_info->namc = argc - optind - 1;

	/*
	 * GNU ar popularized the use of -s on its own which previously used to
	 * require another command function. As such, we don't set a command
	 * function when we encounter the -s flag because that might otherwise
	 * clobber an existing one being set and would interrupt the detection
	 * of multiple flags being used that way.
	 *
	 * If after processing everything, we find there's no command function
	 * set and the -s flag has been set, then we can finally set a command
	 * function. The command function for -t 'tcmd' is used in this case. It
	 * knows to only print out data if -t has been specified.
	 *
	 * While ar has not traditionally been very stringent about using flags
	 * in circumstances they aren't called for, we go ahead and check for
	 * that now for this newer option.
	 */
	if (cmd_info->comfun == NULL) {
		if ((cmd_info->opt_flgs & s_FLAG) != 0) {
			if ((cmd_info->opt_flgs & ~(s_FLAG | v_FLAG)) != 0) {
				(void) fprintf(stderr,
				    MSG_INTL(MSG_USAGE_S_BAD_ARG));
				exit(1);
			}

			if (cmd_info->namc > 0) {
				(void) fprintf(stderr,
				    MSG_INTL(MSG_USAGE_S_EXTRA_AR));
				exit(1);
			}

			setcom(cmd_info, tcmd);
		} else if ((cmd_info->opt_flgs & (d_FLAG | r_FLAG | q_FLAG |
		    s_FLAG | t_FLAG | p_FLAG | m_FLAG | x_FLAG)) == 0) {
			(void) fprintf(stderr, MSG_INTL(MSG_USAGE_REQ_FLAG));
			exit(1);
		}
	}
}


/*
 * Set the function to be called to do the key operation.
 * Check that only one key is indicated.
 */
static void
setcom(Cmd_info *cmd_info, Cmd_func *fun)
{
	if (cmd_info->comfun != NULL) {
		(void) fprintf(stderr, MSG_INTL(MSG_USAGE_TOO_MANY));
		exit(1);
	}
	cmd_info->comfun = fun;
}

static void
usage(void)
{
	(void) fprintf(stderr, MSG_INTL(MSG_USAGE));
	exit(1);
}

/*ARGSUSED0*/
static void
sigexit(int sig)
{
	exit(100);
}

/* tells the user which of the listed files were not found in the archive */

static int
notfound(Cmd_info *cmd_info)
{
	int i, n;

	n = 0;
	for (i = 0; i < cmd_info->namc; i++)
		if (cmd_info->namv[i]) {
			(void) fprintf(stderr, MSG_INTL(MSG_NOT_FOUND_FILE),
			    cmd_info->namv[i]);
			n++;
		}
	return (n);
}

/*
 * Debugging info
 */
static void
check_swap(void)
{
	(void) system(MSG_ORIG(MSG_CMD_SWAP));
}