|
root / base / usr / src / cmd / ast / libshell
libshell Plain Text 8780 lines 261.9 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
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License (the "License").
# You may not use this file except in compliance with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#

#
# Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#
# Copyright 2021 OmniOS Community Edition (OmniOSce) Association.
#

SHELL= /usr/bin/ksh93

include		$(SRC)/lib/Makefile.lib

# Hammerhead: amd64-only
SUBDIRS= $(MACH64)

all :		TARGET= all
clean :	TARGET= clean
clobber :	TARGET= clobber
install :	TARGET= install
install_h :	TARGET= install_h
_msg :		TARGET= _msg
_feature :	TARGET= _feature

.KEEP_STATE:
.PARALLEL: $(SUBDIRS)

all clean clobber install _feature: $(SUBDIRS)
# Hammerhead: amd64-only
_msg: $(MACH64)

include Makefile.defs
HDRS= $(HEADERINSTALL)
HDRDIR32= $(MACH)/ast
HDRDIR64= $(MACH64)/ast
include ../Makefile.asthdr

install_h: $(SUBDIRS) .WAIT $(ROOTHDRS)
install: install_h

$(SUBDIRS):	FRC
	@cd $@; pwd; $(MAKE) $(TARGET)
FRC:

ASTSRC= $(CONTRIB)/ast/src/cmd/ksh93
include Makefile.tests

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

SHELL= /usr/bin/ksh93

LIBRARY= libshell.a
VERS= .1

include ../Makefile.defs

OBJECTS += $(LIBOBJS)

include $(SRC)/lib/Makefile.lib
include ../../Makefile.ast

MAPFILES= ../mapfile-vers

# Specify the MACH we currently use to build and test ksh
LIBSHELLMACH= $(TARGETMACH)
LIBSHELLBASE=..

LIBS= $(DYNLIB)
LDLIBS += -lcmd -ldll -last -lsocket -lm -lc

# We use "=" here since using $(CPPFLAGS.master) is very tricky in our
# case - it MUST come as the last element but future changes in -D options
# may then cause silent breakage in the AST sources because the last -D
# option specified overrides previous -D options so we prefer the current
# way to explicitly list each single flag.
CPPFLAGS= \
	$(DTEXTDOM) $(DTS_ERRNO) \
	$(LIBSHELLCPPFLAGS) \
	-Iast -I.

CFLAGS += $(ASTCFLAGS)
CFLAGS64 += $(ASTCFLAGS64)

CERRWARN += -Wno-parentheses
CERRWARN += -Wno-unused-value
CERRWARN += -Wno-unused-variable
CERRWARN += -Wno-unused-function
CERRWARN += $(CNOWARN_UNINIT)
CERRWARN += -Wno-clobbered
CERRWARN += -Wno-char-subscripts

pics/bltins/print.o : CERRWARN += -Wno-dangling-pointer

# smatch gets out of memory on common/sh/macro.c
SMATCH= off

.KEEP_STATE:

all: install_h mkpicdirs .WAIT $(LIBS)

mkpicdirs:
	@mkdir -p $(LOBJDIRS:%=pics/%)

include $(SRC)/lib/Makefile.targ

pics/%.o: $(ASTSRC)/%.c
	$(CC) $(CFLAGS) $(CPPFLAGS) -c -o $@ $<
	$(POST_PROCESS_O)

######################################################################
# Header file generation

$(HEADERSRC:%=ast/%): $(HEADERSRC:%=$(ASTSRC)/include/%)
	$(MKDIR) -p $(@D)
	$(CP) $(ASTSRC)/include/$(@F) $@

CLOBBERFILES += ast/*

install_h: $(HEADERSRC:%=ast/%)

_feature: FRC
	$(MAKE) -f Makefile.iffe generate

include ../../Makefile.astmsg

FRC:
#
# This file and its contents are supplied under the terms of the
# Common Development and Distribution License ("CDDL"), version 1.0.
# You may only use this file in accordance with the terms of version
# 1.0 of the CDDL.
#
# A full copy of the text of the CDDL should have accompanied this
# source.  A copy of the CDDL is also available via the Internet at
# http://www.illumos.org/license/CDDL.
#

#
# Copyright 2021 OmniOS Community Edition (OmniOSce) Association.
#

# These macros should be kept synchronised with those in
# usr/src/contrib/ast/src/cmd/ksh93/Makefile

AST_LICENSE = since=1982,author=dgk
ASTLIB= libshell
ASTSRC= $(C_AST)/src/cmd/ksh93
HDRGUARD= ksh93

FEATURES= cmds dynamic externs locale math options poll rlimits setjmp \
	sigfeatures time ttys \
	acct execargs pstat
HEADERSRC= history.h nval.h shell.h
HEADERGEN=
HEADERINSTALL= $(HEADERSRC) $(HEADERGEN)
LOBJDIRS= bltins data edit sh
LIBOBJS= \
	bltins/alarm.o \
	bltins/cd_pwd.o \
	bltins/cflow.o \
	bltins/enum.o \
	bltins/getopts.o \
	bltins/hist.o \
	bltins/lib.o \
	bltins/misc.o \
	bltins/poll_solaris.o \
	bltins/print.o \
	bltins/read.o \
	bltins/regress.o \
	bltins/shiocmd_solaris.o \
	bltins/sleep.o \
	bltins/test.o \
	bltins/trap.o \
	bltins/typeset.o \
	bltins/ulimit.o \
	bltins/umask.o \
	bltins/whence.o \
	data/aliases.o \
	data/builtins.o \
	data/keywords.o \
	data/lexstates.o \
	data/limits.o \
	data/msg.o \
	data/options.o \
	data/signals.o \
	data/strdata.o \
	data/testops.o \
	data/variables.o \
	edit/completion.o \
	edit/edit.o \
	edit/emacs.o \
	edit/hexpand.o \
	edit/history.o \
	edit/vi.o \
	sh/args.o \
	sh/arith.o \
	sh/array.o \
	sh/defs.o \
	sh/deparse.o \
	sh/expand.o \
	sh/fault.o \
	sh/fcin.o \
	sh/init.o \
	sh/io.o \
	sh/jobs.o \
	sh/lex.o \
	sh/macro.o \
	sh/main.o \
	sh/name.o \
	sh/nvdisc.o \
	sh/nvtree.o \
	sh/nvtype.o \
	sh/parse.o \
	sh/path.o \
	sh/streval.o \
	sh/string.o \
	sh/subshell.o \
	sh/tdump.o \
	sh/timers.o \
	sh/trestore.o \
	sh/waitevent.o \
	sh/xec.o
#
# This file and its contents are supplied under the terms of the
# Common Development and Distribution License ("CDDL"), version 1.0.
# You may only use this file in accordance with the terms of version
# 1.0 of the CDDL.
#
# A full copy of the text of the CDDL should have accompanied this
# source.  A copy of the CDDL is also available via the Internet at
# http://www.illumos.org/license/CDDL.
#

#
# Copyright 2021 OmniOS Community Edition (OmniOSce) Association.
#

include ../Makefile.com
include ../../Makefile.iffe

FEATURE/acct FEATURE/execargs FEATURE/pstat:
	PATH=$(IFFEPATH) \
	    $(AST_IFFE) $(IFFEFLAGS) -c '$(IFFEC)' def $(@F)
FEATURE/math : IFFE_EXTRA = $(ASTSRC)/data/math.tab

cleaniffe: FRC
	$(RM) $(FEATURES:%=FEATURE/%)

generate: cleaniffe $(FEATURES:%=FEATURE/%)
#
# 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) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
# Copyright 2021 OmniOS Community Edition (OmniOSce) Association.
#

#
# These are tests that come from usr/src/contrib/ast, and the test driver
# itself.
#
DF_TESTS= \
	shtests \
	tests/alias.sh \
	tests/append.sh \
	tests/arith.sh \
	tests/arrays.sh \
	tests/arrays2.sh \
	tests/attributes.sh \
	tests/basic.sh \
	tests/bracket.sh \
	tests/builtins.sh \
	tests/case.sh \
	tests/comvar.sh \
	tests/comvario.sh \
	tests/coprocess.sh \
	tests/cubetype.sh \
	tests/enum.sh \
	tests/exit.sh \
	tests/expand.sh \
	tests/functions.sh \
	tests/glob.sh \
	tests/grep.sh \
	tests/heredoc.sh \
	tests/io.sh \
	tests/leaks.sh \
	tests/locale.sh \
	tests/math.sh \
	tests/nameref.sh \
	tests/namespace.sh \
	tests/options.sh \
	tests/path.sh \
	tests/pointtype.sh \
	tests/pty.sh \
	tests/quoting.sh \
	tests/quoting2.sh \
	tests/readcsv.sh \
	tests/recttype.sh \
	tests/restricted.sh \
	tests/return.sh \
	tests/select.sh \
	tests/sigchld.sh \
	tests/signal.sh \
	tests/statics.sh \
	tests/subshell.sh \
	tests/substring.sh \
	tests/tilde.sh \
	tests/timetype.sh \
	tests/treemove.sh \
	tests/types.sh \
	tests/variables.sh \
	tests/vartree1.sh \
	tests/vartree2.sh

#
# These are additional illumos tests and the README
#

DF_XTESTS= \
	README.tests \
	tests/illumos_13434_chunked_heredoc.sh \
	tests/illumos_4149_builtin_head.sh \
	tests/sun_solaris_array_default_datatype.sh \
	tests/sun_solaris_builtin_poll.sh \
	tests/sun_solaris_builtin_sum.sh \
	tests/sun_solaris_builtin_tail.sh \
	tests/sun_solaris_command_substitution.sh \
	tests/sun_solaris_compound_misc.sh \
	tests/sun_solaris_compound_nameref.sh \
	tests/sun_solaris_compoundvario.sh \
	tests/sun_solaris_cr_xxxxxxxx_template.sh \
	tests/sun_solaris_cr_6687139_command_substitution_exec_redirection_allocation_loop.sh \
	tests/sun_solaris_cr_6713682_compound_var_bleeds_through_subshell.sh \
	tests/sun_solaris_cr_6722134_background_CHLD_trap.sh \
	tests/sun_solaris_cr_6753538_subshell_leaks_umask.sh \
	tests/sun_solaris_cr_6754020_weird_square_bracket_expansion.sh \
	tests/sun_solaris_cr_6763594_command_failure_execs_twice.sh \
	tests/sun_solaris_cr_6766246_pattern_matching_bug.sh \
	tests/sun_solaris_cr_6769332_substitutions_terminate_shell_after_257_iterations.sh \
	tests/sun_solaris_cr_6777491_lacks_arithmetric_function_iszero.sh \
	tests/sun_solaris_cr_6778077_sigthaw_trap.sh \
	tests/sun_solaris_cr_6789247_printf_hexfloat_rounding.sh \
	tests/sun_solaris_cr_6800929_large_command_substitution_hang.sh \
	tests/sun_solaris_cr_6805792_varmovetest1.sh \
	tests/sun_solaris_cr_6805794_character_to_wchar_not_working.sh \
	tests/sun_solaris_cr_6805795_negative_zero.sh \
	tests/sun_solaris_cr_6807179_shellpattern_uses_getpwnam.sh \
	tests/sun_solaris_cr_6835835_builtin_cat_n_broken.sh \
	tests/sun_solaris_cr_6848486_echo_test_with_test_undefined_executes_test_builtin.sh \
	tests/sun_solaris_cr_6855875_typeset_hexfloat_has_too_few_digits.sh \
	tests/sun_solaris_cr_6862121_shbinexec_kernel_module_defunct.sh \
	tests/sun_solaris_cr_6881017_background_process_in_subshell_hangs_caller.sh \
	tests/sun_solaris_cr_6887363_shell_sometimes_mishandles_return_value_of_its_child_process.sh \
	tests/sun_solaris_cr_6904557_wc_no_longer_counts_number_of_bytes_correctly.sh \
	tests/sun_solaris_cr_6904575_cut_-d_with_multibyte_character_no_longer_works.sh \
	tests/sun_solaris_cr_6904878_join_-t_no_longer_works_with_multibyte_char_separator.sh \
	tests/sun_solaris_cr_6907460_EXIT_trap_handlers_are_sometimes_executed_twice.sh \
	tests/sun_solaris_getconf.sh \
	tests/sun_solaris_locale_misc.sh \
	tests/sun_solaris_local_compound_nameref001.sh \
	tests/sun_solaris_staticvariables.sh \
	tests/sun_solaris_vartree001.sh \
	tests/sun_solaris_vartree002.sh \
	tests/sun_solaris_vartree003.sh

TESTFILES= $(DF_TESTS) $(DF_XTESTS)

TESTFILESRCDIR=		$(ASTSRC)
ROOTTESTDIRBASE=	$(ROOT)/opt/ksh93-tests

# Rules for executables
$(ROOTTESTDIRBASE)/shtests : FILEMODE= 755

$(ROOTTESTDIRBASE)/% $(ROOTTESTDIRBASE)/tests/%: common/tests/%
	$(INS.file)

$(ROOTTESTDIRBASE)/%: $(TESTFILESRCDIR)/%
	$(INS.file)

$(ROOTTESTDIRBASE)/%: $(TESTFILESRCDIR)/tests/%
	$(INS.file)

$(ROOTTESTDIRBASE) $(ROOTTESTDIRBASE)/tests:
	$(INS.dir)

ROOTTESTDIRS= $(ROOTTESTDIRBASE) .WAIT $(ROOTTESTDIRBASE)/tests
ROOTTESTFILES= $(TESTFILES:%=$(ROOTTESTDIRBASE)/%)

_testinstall: $(ROOTTESTDIRS) .WAIT $(ROOTTESTFILES)
install: _testinstall
/* : : generated by iffe version 2012-07-17 : : */
#ifndef _def_acct_amd64
#define _def_acct_amd64	1
#define _sys_types	1	/* #include <sys/types.h> ok */
#define _dat_acct	1	/* acct in default lib(s) */
#define _lib_acct	1	/* acct() in default lib(s) */
#define _sys_acct	1	/* #include <sys/acct.h> ok */
#endif
/* : : generated from contrib/ast/src/cmd/ksh93/features/cmds by iffe version 2012-07-17 : : */
#ifndef _def_cmds_ksh93
#define _def_cmds_ksh93	1
#define _sys_types	1	/* #include <sys/types.h> ok */
#define _cmd_newgrp	1
#define _usr_bin_newgrp	1
#define _cmd_test	1
#define _usr_bin_test	1
#define _cmd_id	1
#define _usr_bin_id	1
#define _cmd_wc	1
#define _usr_bin_wc	1
#define _cmd_cut	1
#define _usr_bin_cut	1
#define _cmd_logname	1
#define _usr_bin_logname	1
#define _cmd_pfexec	1
#define _usr_bin_pfexec	1
#define _cmd_tput	1
#define _usr_bin_tput	1
#define _pth_ed	"/bin/ed"
#endif
/* : : generated from contrib/ast/src/cmd/ksh93/features/dynamic by iffe version 2012-07-17 : : */
#ifndef _def_dynamic_ksh93
#define _def_dynamic_ksh93	1
#define _sys_types	1	/* #include <sys/types.h> ok */
#if SHOPT_DYNAMIC
#include	<dlldefs.h>
#endif
#if !defined(SHOPT_FS_3D) && SHOPT_DYNAMIC
#   define SHOPT_FS_3D	1
#endif /* !SHOPT_FS_3D */
#if SHOPT_FS_3D
#   undef mount
#   include	<fs3d.h>
#endif /* SHOPT_FS_3D */

#endif
/* : : generated by iffe version 2012-07-17 : : */
#ifndef _def_execargs_amd64
#define _def_execargs_amd64	1
#define _sys_types	1	/* #include <sys/types.h> ok */
#endif

/* : : generated by proto : : */
/* : : generated from contrib/ast/src/cmd/ksh93/features/externs by iffe version 2012-07-17 : : */

#ifndef _def_externs_ksh93
#if !defined(__PROTO__)
#  if defined(__STDC__) || defined(__cplusplus) || defined(_proto) || defined(c_plusplus)
#    if defined(__cplusplus)
#      define __LINKAGE__	"C"
#    else
#      define __LINKAGE__
#    endif
#    define __STDARG__
#    define __PROTO__(x)	x
#    define __OTORP__(x)
#    define __PARAM__(n,o)	n
#    if !defined(__STDC__) && !defined(__cplusplus)
#      if !defined(c_plusplus)
#      	define const
#      endif
#      define signed
#      define void		int
#      define volatile
#      define __V_		char
#    else
#      define __V_		void
#    endif
#  else
#    define __PROTO__(x)	()
#    define __OTORP__(x)	x
#    define __PARAM__(n,o)	o
#    define __LINKAGE__
#    define __V_		char
#    define const
#    define signed
#    define void		int
#    define volatile
#  endif
#  define __MANGLE__	__LINKAGE__
#  if defined(__cplusplus) || defined(c_plusplus)
#    define __VARARG__	...
#  else
#    define __VARARG__
#  endif
#  if defined(__STDARG__)
#    define __VA_START__(p,a)	va_start(p,a)
#  else
#    define __VA_START__(p,a)	va_start(p)
#  endif
#  if !defined(__INLINE__)
#    if defined(__cplusplus)
#      define __INLINE__	extern __MANGLE__ inline
#    else
#      if defined(_WIN32) && !defined(__GNUC__)
#      	define __INLINE__	__inline
#      endif
#    endif
#  endif
#endif
#if !defined(__LINKAGE__)
#define __LINKAGE__		/* 2004-08-11 transition */
#endif

#define _def_externs_ksh93	1
#define _sys_types	1	/* #include <sys/types.h> ok */
#define _hdr_exec_attr	1	/* #include <exec_attr.h> ok */
#define _hdr_math	1	/* #include <math.h> ok */
#define _mem_name_exception	1	/* name is a member of struct exception */
#define _lib_setreuid	1	/* setreuid() in default lib(s) */
#define _lib_setregid	1	/* setregid() in default lib(s) */
#define _lib_nice	1	/* nice() in default lib(s) */
#define _lib_fork	1	/* fork() in default lib(s) */
#define _lib_spawnveg	1	/* spawnveg() in default lib(s) */
#define _lib_fchdir	1	/* fchdir() in default lib(s) */
#define _sys_mman	1	/* #include <sys/mman.h> ok */
#define _lib_memcntl	1	/* memcntl() in default lib(s) */
#define _LIB_secdb	1	/* -lsecdb is a library */
#define _lib_getexecuser	1	/* getexecuser() in default lib(s) */
#define _lib_free_execattr	1	/* free_execattr() in default lib(s) */
#endif
/* : : generated from contrib/ast/src/cmd/ksh93/features/locale by iffe version 2012-07-17 : : */
#ifndef _def_locale_ksh93
#define _def_locale_ksh93	1
#define _sys_types	1	/* #include <sys/types.h> ok */
#define _hdr_locale	1	/* #include <locale.h> ok */
#define _hdr_wchar	1	/* #include <wchar.h> ok */
#define _hdr_wctype	1	/* #include <wctype.h> ok */
#define _lib_localeconv	1	/* localeconv() in default lib(s) */
#define _lib_wctype	1	/* wctype() in default lib(s) */
#define _lib_iswctype	1	/* iswctype() in default lib(s) */
#define _lib_iswblank	1	/* iswblank() in default lib(s) */
#define _lib_wctrans	1	/* wctrans() in default lib(s) */
#define _lib_towctrans	1	/* towctrans() in default lib(s) */
#define _hdr_time	1	/* #include <time.h> ok */
#define _sys_time	1	/* #include <sys/time.h> ok */
#define _sys_times	1	/* #include <sys/times.h> ok */
#define _hdr_stddef	1	/* #include <stddef.h> ok */
#define _hdr_stdlib	1	/* #include <stdlib.h> ok */
#define _typ_wctrans_t	1	/* wctrans_t is a type */
#if _PACKAGE_ast
#   undef  _hdr_locale
#   define _hdr_locale 1
#else
#   ifdef _hdr_locale
#	include <locale.h>
#	ifndef LC_MESSAGES
#	    define LC_MESSAGES  LC_ALL
#	endif /* LC_MESSAGES */
#   endif /* _hdr_locale */
#endif /* _PACKAGE_ast */
#ifdef _hdr_locale
#   ifdef _lib_localeconv
	static struct lconv *lp;
#	define GETDECIMAL(x)  (((lp=localeconv()) && lp->decimal_point && *lp->decimal_point) ?  *lp->decimal_point : '.' )
#   else
#	define GETDECIMAL(x)	('.')
#   endif /* _lib_localeconv */
#else
#   define GETDECIMAL(x)	('.')
#endif /* _hdr_locale */

#endif

/* : : generated by proto : : */
/* : : generated from contrib/ast/src/cmd/ksh93/features/math.sh by iffe version 2012-07-17 : : */
#ifndef _def_math_ksh93
#if !defined(__PROTO__)
#  if defined(__STDC__) || defined(__cplusplus) || defined(_proto) || defined(c_plusplus)
#    if defined(__cplusplus)
#      define __LINKAGE__	"C"
#    else
#      define __LINKAGE__
#    endif
#    define __STDARG__
#    define __PROTO__(x)	x
#    define __OTORP__(x)
#    define __PARAM__(n,o)	n
#    if !defined(__STDC__) && !defined(__cplusplus)
#      if !defined(c_plusplus)
#      	define const
#      endif
#      define signed
#      define void		int
#      define volatile
#      define __V_		char
#    else
#      define __V_		void
#    endif
#  else
#    define __PROTO__(x)	()
#    define __OTORP__(x)	x
#    define __PARAM__(n,o)	o
#    define __LINKAGE__
#    define __V_		char
#    define const
#    define signed
#    define void		int
#    define volatile
#  endif
#  define __MANGLE__	__LINKAGE__
#  if defined(__cplusplus) || defined(c_plusplus)
#    define __VARARG__	...
#  else
#    define __VARARG__
#  endif
#  if defined(__STDARG__)
#    define __VA_START__(p,a)	va_start(p,a)
#  else
#    define __VA_START__(p,a)	va_start(p)
#  endif
#  if !defined(__INLINE__)
#    if defined(__cplusplus)
#      define __INLINE__	extern __MANGLE__ inline
#    else
#      if defined(_WIN32) && !defined(__GNUC__)
#      	define __INLINE__	__inline
#      endif
#    endif
#  endif
#endif
#if !defined(__LINKAGE__)
#define __LINKAGE__		/* 2004-08-11 transition */
#endif

#define _def_math_ksh93	1
#define _sys_types	1	/* #include <sys/types.h> ok */


/* : : generated by cmd/ast/tools/iffe from contrib/ast/src/cmd/ksh93/data/math.tab : : */

typedef Sfdouble_t (*Math_f) __PROTO__((Sfdouble_t,...));

#include <math.h>
#include <ieeefp.h>

static Sfdouble_t local_finite __PARAM__((Sfdouble_t a1), (a1)) __OTORP__(Sfdouble_t a1;){return finite(a1);}
static int local_fpclassify __PARAM__((Sfdouble_t a1), (a1)) __OTORP__(Sfdouble_t a1;){return fpclassify(a1);}
static int local_fpclass __PARAM__((Sfdouble_t a1), (a1)) __OTORP__(Sfdouble_t a1;){return fpclass(a1);}
static int local_isfinite __PARAM__((Sfdouble_t a1), (a1)) __OTORP__(Sfdouble_t a1;){return isfinite(a1);}
static int local_isgreater __PARAM__((Sfdouble_t a1,Sfdouble_t a2), (a1, a2)) __OTORP__(Sfdouble_t a1;Sfdouble_t a2;){return isgreater(a1,a2);}
static int local_isgreaterequal __PARAM__((Sfdouble_t a1,Sfdouble_t a2), (a1, a2)) __OTORP__(Sfdouble_t a1;Sfdouble_t a2;){return isgreaterequal(a1,a2);}
static int local_isinf __PARAM__((Sfdouble_t a1), (a1)) __OTORP__(Sfdouble_t a1;){return isinf(a1);}
static int local_isless __PARAM__((Sfdouble_t a1,Sfdouble_t a2), (a1, a2)) __OTORP__(Sfdouble_t a1;Sfdouble_t a2;){return isless(a1,a2);}
static int local_islessequal __PARAM__((Sfdouble_t a1,Sfdouble_t a2), (a1, a2)) __OTORP__(Sfdouble_t a1;Sfdouble_t a2;){return islessequal(a1,a2);}
static int local_islessgreater __PARAM__((Sfdouble_t a1,Sfdouble_t a2), (a1, a2)) __OTORP__(Sfdouble_t a1;Sfdouble_t a2;){return islessgreater(a1,a2);}
static int local_isnormal __PARAM__((Sfdouble_t a1), (a1)) __OTORP__(Sfdouble_t a1;){return isnormal(a1);}
static int local_issubnormal __PARAM__((Sfdouble_t a1), (a1)) __OTORP__(Sfdouble_t a1;){ int q = fpclassify(a1); return q == FP_SUBNORMAL; }
static int local_isunordered __PARAM__((Sfdouble_t a1,Sfdouble_t a2), (a1, a2)) __OTORP__(Sfdouble_t a1;Sfdouble_t a2;){return isunordered(a1,a2);}
static int local_iszero __PARAM__((Sfdouble_t a1), (a1)) __OTORP__(Sfdouble_t a1;){ int q = fpclassify(a1); return q == FP_ZERO; }
static int local_signbit __PARAM__((Sfdouble_t a1), (a1)) __OTORP__(Sfdouble_t a1;){return signbit(a1);}

/*
 * first byte is two-digit octal number.  Last digit is number of args
 * first digit is 0 if return value is double, 1 for integer
 */
const struct mathtab shtab_math[] =
{
	"\001acos",	(Math_f)(uintptr_t)acosl,
	"\001acosh",	(Math_f)(uintptr_t)acoshl,
	"\001asin",	(Math_f)(uintptr_t)asinl,
	"\001asinh",	(Math_f)(uintptr_t)asinhl,
	"\001atan",	(Math_f)(uintptr_t)atanl,
	"\002atan2",	(Math_f)(uintptr_t)atan2l,
	"\001atanh",	(Math_f)(uintptr_t)atanhl,
	"\001cbrt",	(Math_f)(uintptr_t)cbrtl,
	"\001ceil",	(Math_f)(uintptr_t)ceill,
	"\002copysign",	(Math_f)(uintptr_t)copysignl,
	"\001cos",	(Math_f)(uintptr_t)cosl,
	"\001cosh",	(Math_f)(uintptr_t)coshl,
	"\001erf",	(Math_f)(uintptr_t)erfl,
	"\001erfc",	(Math_f)(uintptr_t)erfcl,
	"\001exp",	(Math_f)(uintptr_t)expl,
	"\001exp2",	(Math_f)(uintptr_t)exp2l,
	"\001expm1",	(Math_f)(uintptr_t)expm1l,
	"\001fabs",	(Math_f)(uintptr_t)fabsl,
	"\001abs",	(Math_f)(uintptr_t)fabsl,
	"\002fdim",	(Math_f)(uintptr_t)fdiml,
	"\001finite",	(Math_f)(uintptr_t)local_finite,
	"\001floor",	(Math_f)(uintptr_t)floorl,
	"\001int",	(Math_f)(uintptr_t)floorl,
	"\003fma",	(Math_f)(uintptr_t)fmal,
	"\002fmax",	(Math_f)(uintptr_t)fmaxl,
	"\002fmin",	(Math_f)(uintptr_t)fminl,
	"\002fmod",	(Math_f)(uintptr_t)fmodl,
	"\011fpclassify",	(Math_f)(uintptr_t)local_fpclassify,
	"\011fpclass",	(Math_f)(uintptr_t)local_fpclass,
	"\002hypot",	(Math_f)(uintptr_t)hypotl,
	"\011ilogb",	(Math_f)(uintptr_t)ilogbl,
	"\011isfinite",	(Math_f)(uintptr_t)local_isfinite,
	"\012isgreater",	(Math_f)(uintptr_t)local_isgreater,
	"\012isgreaterequal",	(Math_f)(uintptr_t)local_isgreaterequal,
	"\011isinf",	(Math_f)(uintptr_t)local_isinf,
	"\012isless",	(Math_f)(uintptr_t)local_isless,
	"\012islessequal",	(Math_f)(uintptr_t)local_islessequal,
	"\012islessgreater",	(Math_f)(uintptr_t)local_islessgreater,
	"\011isnan",	(Math_f)(uintptr_t)isnanl,
	"\011isnormal",	(Math_f)(uintptr_t)local_isnormal,
	"\011issubnormal",	(Math_f)(uintptr_t)local_issubnormal,
	"\012isunordered",	(Math_f)(uintptr_t)local_isunordered,
	"\011iszero",	(Math_f)(uintptr_t)local_iszero,
	"\001j0",	(Math_f)(uintptr_t)j0l,
	"\001j1",	(Math_f)(uintptr_t)j1l,
	"\002jn",	(Math_f)(uintptr_t)jnl,
	"\042ldexp",	(Math_f)(uintptr_t)ldexpl,
	"\001lgamma",	(Math_f)(uintptr_t)lgammal,
	"\001log",	(Math_f)(uintptr_t)logl,
	"\001log10",	(Math_f)(uintptr_t)log10l,
	"\001log1p",	(Math_f)(uintptr_t)log1pl,
	"\001log2",	(Math_f)(uintptr_t)log2l,
	"\001logb",	(Math_f)(uintptr_t)logbl,
	"\001nearbyint",	(Math_f)(uintptr_t)nearbyintl,
	"\002nextafter",	(Math_f)(uintptr_t)nextafterl,
	"\002nexttoward",	(Math_f)(uintptr_t)nexttowardl,
	"\002pow",	(Math_f)(uintptr_t)powl,
	"\002remainder",	(Math_f)(uintptr_t)remainderl,
	"\001rint",	(Math_f)(uintptr_t)rintl,
	"\001round",	(Math_f)(uintptr_t)roundl,
	"\002scalb",	(Math_f)(uintptr_t)scalbl,
	"\002scalbn",	(Math_f)(uintptr_t)scalbnl,
	"\011signbit",	(Math_f)(uintptr_t)local_signbit,
	"\001sin",	(Math_f)(uintptr_t)sinl,
	"\001sinh",	(Math_f)(uintptr_t)sinhl,
	"\001sqrt",	(Math_f)(uintptr_t)sqrtl,
	"\001tan",	(Math_f)(uintptr_t)tanl,
	"\001tanh",	(Math_f)(uintptr_t)tanhl,
	"\001tgamma",	(Math_f)(uintptr_t)tgammal,
	"\001trunc",	(Math_f)(uintptr_t)truncl,
	"\001y0",	(Math_f)(uintptr_t)y0l,
	"\001y1",	(Math_f)(uintptr_t)y1l,
	"\002yn",	(Math_f)(uintptr_t)ynl,
	"",		(Math_f)0
};
#endif
/* : : generated from contrib/ast/src/cmd/ksh93/features/options by iffe version 2012-07-17 : : */
#ifndef _def_options_ksh93
#define _def_options_ksh93	1
#define _sys_types	1	/* #include <sys/types.h> ok */
#define SHELLMAGIC	1
#ifndef SHOPT_DEVFD
#   define SHOPT_DEVFD	1
#endif
#ifndef SHOPT_PFSH
#   define SHOPT_PFSH	1
#endif
#undef  SHOPT_TEST_L
#ifndef SHOPT_SYSRC
#   define SHOPT_SYSRC	1
#endif
#undef  SHOPT_UCB
#if !_PACKAGE_ast && ( (MB_LEN_MAX-1)<=0 || !defined(_lib_mbtowc) )
#   undef SHOPT_MULTIBYTE
#endif

#endif

/* : : generated by proto : : */
/* : : generated from contrib/ast/src/cmd/ksh93/features/poll by iffe version 2012-07-17 : : */
#ifndef _def_poll_ksh93
#if !defined(__PROTO__)
#  if defined(__STDC__) || defined(__cplusplus) || defined(_proto) || defined(c_plusplus)
#    if defined(__cplusplus)
#      define __LINKAGE__	"C"
#    else
#      define __LINKAGE__
#    endif
#    define __STDARG__
#    define __PROTO__(x)	x
#    define __OTORP__(x)
#    define __PARAM__(n,o)	n
#    if !defined(__STDC__) && !defined(__cplusplus)
#      if !defined(c_plusplus)
#      	define const
#      endif
#      define signed
#      define void		int
#      define volatile
#      define __V_		char
#    else
#      define __V_		void
#    endif
#  else
#    define __PROTO__(x)	()
#    define __OTORP__(x)	x
#    define __PARAM__(n,o)	o
#    define __LINKAGE__
#    define __V_		char
#    define const
#    define signed
#    define void		int
#    define volatile
#  endif
#  define __MANGLE__	__LINKAGE__
#  if defined(__cplusplus) || defined(c_plusplus)
#    define __VARARG__	...
#  else
#    define __VARARG__
#  endif
#  if defined(__STDARG__)
#    define __VA_START__(p,a)	va_start(p,a)
#  else
#    define __VA_START__(p,a)	va_start(p)
#  endif
#  if !defined(__INLINE__)
#    if defined(__cplusplus)
#      define __INLINE__	extern __MANGLE__ inline
#    else
#      if defined(_WIN32) && !defined(__GNUC__)
#      	define __INLINE__	__inline
#      endif
#    endif
#  endif
#endif
#if !defined(__LINKAGE__)
#define __LINKAGE__		/* 2004-08-11 transition */
#endif

#define _def_poll_ksh93	1
#define _sys_types	1	/* #include <sys/types.h> ok */
#define _LIB_nsl	1	/* -lnsl is a library */
#define _LIB_socket	1	/* -lsocket is a library */
#define _hdr_poll	1	/* #include <poll.h> ok */
#define _hdr_netinet_in	1	/* #include <netinet/in.h> ok */
#define _sys_poll	1	/* #include <sys/poll.h> ok */
#define _sys_socket	1	/* #include <sys/socket.h> ok */
#define _lib_select	1	/* select() in default lib(s) */
#define _lib_poll	1	/* poll() in default lib(s) */
#define _lib_socket	1	/* socket() in default lib(s) */
#define _lib_htons	1	/* htons() in default lib(s) */
#define _lib_htonl	1	/* htonl() in default lib(s) */
#define _hdr_netdb	1	/* #include <netdb.h> ok */
#define _lib_getaddrinfo	1	/* getaddrinfo() in default lib(s) */
#define _hdr_time	1	/* #include <time.h> ok */
#define _sys_time	1	/* #include <sys/time.h> ok */
#define _sys_times	1	/* #include <sys/times.h> ok */
#define _hdr_stddef	1	/* #include <stddef.h> ok */
#define _hdr_stdlib	1	/* #include <stdlib.h> ok */
#define _sys_select	1	/* #include <sys/select.h> ok */
#define _typ_fd_set	1	/* fd_set is a type */
#define _hdr_unistd	1	/* #include <unistd.h> ok */
#define _typ_socklen_t	1	/* socklen_t is a type */

#ifdef _lib_poll
#   define poll _SYS_poll
#else
#   undef _hdr_poll
#   undef _sys_poll
#endif /* _lib_poll */
#ifdef _hdr_poll
#    include    <poll.h>
#else
#   ifdef _sys_poll
#	include    <sys/poll.h>
#   endif /* _sys_poll */
#endif /* _hdr_poll */
#ifdef _lib_poll
#   undef poll
    extern __MANGLE__ int poll __PROTO__((struct pollfd*,unsigned long,int));
#endif /* _lib_poll */
#ifdef _lib_select
#   ifndef FD_ZERO
#	define FD_ZERO(x)	(*(x)=0)
#   endif /* FD_ZERO */
#   ifndef FD_SET
#	define FD_SET(n,x)	(*(x)|=(1L<<(n)))
#   endif /* FD_SET */
#   ifndef _typ_fd_set
	typedef long fd_set;
#   endif /*_typ_fd_set */
#endif /* _lib_select */

#endif
/* : : generated by iffe version 2012-07-17 : : */
#ifndef _def_pstat_amd64
#define _def_pstat_amd64	1
#define _sys_types	1	/* #include <sys/types.h> ok */
#endif
/* : : generated from contrib/ast/src/cmd/ksh93/features/rlimits by iffe version 2012-07-17 : : */
#ifndef _def_rlimits_ksh93
#define _def_rlimits_ksh93	1
#define _sys_types	1	/* #include <sys/types.h> ok */
#define _sys_time	1	/* #include <sys/time.h> ok */
#define _sys_resource	1	/* #include <sys/resource.h> ok */
#define _lib_getrlimit	1	/* getrlimit() in default lib(s) */
#define _lib_ulimit	1	/* ulimit() in default lib(s) */
#define _hdr_time	1	/* #include <time.h> ok */
#define _sys_times	1	/* #include <sys/times.h> ok */
#define _hdr_stddef	1	/* #include <stddef.h> ok */
#define _hdr_stdlib	1	/* #include <stdlib.h> ok */
#define _typ_rlim_t	1	/* rlim_t is a type */
#define _typ_rlim64_t	1	/* rlim64_t is a type */

#if _sys_resource
#	include <sys/resource.h>
#	if _lib_getrlimit64
#		undef	getrlimit
#		define	getrlimit	getrlimit64
#		undef	setrlimit
#		define	setrlimit	setrlimit64
#		if _typ_rlim64_t
#			undef	rlimit
#			define	rlimit	rlimit64
#			undef	rlim_t
#			define	rlim_t	rlim64_t
#		endif
#		ifdef RLIM64_INFINITY
#			undef	RLIM_INFINITY
#			define	RLIM_INFINITY	RLIM64_INFINITY
#		endif
#	endif
#endif


#endif
/* : : generated from contrib/ast/src/cmd/ksh93/features/setjmp by iffe version 2012-07-17 : : */
#ifndef _def_setjmp_ksh93
#define _def_setjmp_ksh93	1
#define _sys_types	1	/* #include <sys/types.h> ok */
#define _lib_sigsetjmp	1	/* sigsetjmp() in default lib(s) */
#define _lib__setjmp	1	/* _setjmp() in default lib(s) */
#define _lib__longjmp	1	/* _longjmp() in default lib(s) */
#define _hdr_time	1	/* #include <time.h> ok */
#define _sys_time	1	/* #include <sys/time.h> ok */
#define _sys_times	1	/* #include <sys/times.h> ok */
#define _hdr_stddef	1	/* #include <stddef.h> ok */
#define _hdr_stdlib	1	/* #include <stdlib.h> ok */
#define _hdr_setjmp	1	/* #include <setjmp.h> ok */
#define _typ_sigjmp_buf	1	/* sigjmp_buf is a type */
#undef sigsetjmp
#undef siglongjmp
#undef sigjmp_buf
#define sigjmp_buf		jmp_buf
#ifdef	_lib__setjmp
#   define sigsetjmp(a,b)	_setjmp(a)
#else
#   define sigsetjmp(a,b)	setjmp(a)
#endif 	/* _lib__setjmp */
#ifdef	_lib__longjmp
#   define siglongjmp(a,b)	_longjmp(a,b)
#else
#   define siglongjmp(a,b)	longjmp(a,b)
#endif 	/* _lib__longjmp */

#endif
/* : : generated from contrib/ast/src/cmd/ksh93/features/sigfeatures by iffe version 2012-07-17 : : */
#ifndef _def_sigfeatures_ksh93
#define _def_sigfeatures_ksh93	1
#define _sys_types	1	/* #include <sys/types.h> ok */
#define _lib_sigrelse	1	/* sigrelse() in default lib(s) */
#define _lib_sigprocmask	1	/* sigprocmask() in default lib(s) */
#define _hdr_time	1	/* #include <time.h> ok */
#define _sys_time	1	/* #include <sys/time.h> ok */
#define _sys_times	1	/* #include <sys/times.h> ok */
#define _hdr_stddef	1	/* #include <stddef.h> ok */
#define _hdr_stdlib	1	/* #include <stdlib.h> ok */
#define _hdr_signal	1	/* #include <signal.h> ok */
#define _typ_sigset_t	1	/* sigset_t is a type */
#ifndef _mem_sigvec_sv_mask
#   undef _lib_sigvec
#endif
#ifdef _lib_sigprocmask
#    define sh_sigaction(s,action) do { sigset_t ss;\
			sigemptyset(&ss); \
			if(s) sigaddset(&ss,(s)); \
			sigprocmask(action,&ss,0); \
			}while(0)
#    define sigrelease(s)	sh_sigaction(s,SIG_UNBLOCK)
#    define sigblock(s)	 	sh_sigaction(s,SIG_BLOCK)
#    define sig_begin()		sh_sigaction(0,SIG_SETMASK)
#else
#   ifndef _lib_sigblock
#	define sigblock(s)
#   endif
#   ifdef _lib_sigsetmask
#       define sigrelease(s)  sigsetmask(0)
#       define sig_begin()    sigsetmask(0)
#   else
#	ifdef _lib_sigrelse
#	    define sigrelease	sigrelse
#	    define sig_begin()
#	else
#	    define sig_begin()		(0)
#	    define sigrelease(s)	(0)
#	endif /* _lib_sigrelse */
#    endif /* _lib_sigsetmask */
#endif /* _lib_sigprocmask */

#undef	_SIGRTMIN
#define _SIGRTMIN	42
#undef	_SIGRTMAX
#define _SIGRTMAX	73
#endif
/* : : generated from contrib/ast/src/cmd/ksh93/features/time by iffe version 2012-07-17 : : */
#ifndef _def_time_ksh93
#define _def_time_ksh93	1
#define _sys_types	1	/* #include <sys/types.h> ok */
#define _hdr_utime	1	/* #include <utime.h> ok */
#define _lib_gettimeofday	1	/* gettimeofday() in default lib(s) */
#define _lib_setitimer	1	/* setitimer() in default lib(s) */
#define _sys_time	1	/* #include <sys/time.h> ok */
#define _mem_tv_usec_timeval	1	/* tv_usec is a member of struct timeval */
#define _lib_2_timeofday	1	/* 2 arg gettimeofday() */
#undef _def_time
#include	<times.h>
#define _def_time	1
#undef timeofday
#if _lib_2_timeofday
#define timeofday(p)	gettimeofday(p,(struct timezone*)0)
#else
#if _lib_1_timeofday
#define timeofday(p)	gettimeofday(p)
#endif
#endif

#endif
/* : : generated from contrib/ast/src/cmd/ksh93/features/ttys by iffe version 2012-07-17 : : */
#ifndef _def_ttys_ksh93
#define _def_ttys_ksh93	1
#define _sys_types	1	/* #include <sys/types.h> ok */
#define _hdr_termios	1	/* #include <termios.h> ok */
#define _hdr_termio	1	/* #include <termio.h> ok */
#define _hdr_sgtty	1	/* #include <sgtty.h> ok */
#define _sys_termios	1	/* #include <sys/termios.h> ok */
#define _sys_termio	1	/* #include <sys/termio.h> ok */
#define _sys_ioctl	1	/* #include <sys/ioctl.h> ok */
#define _sys_filio	1	/* #include <sys/filio.h> ok */
#define _lib_tcgetattr	1	/* tcgetattr() in default lib(s) */
#define _lib_tcgetpgrp	1	/* tcgetpgrp() in default lib(s) */
#endif
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License (the "License").
# You may not use this file except in compliance with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#

#
# Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#

include ../Makefile.com
include $(SRC)/lib/Makefile.lib.64

install: all $(ROOTLIBS64) $(ROOTLINKS64)
#
# This file and its contents are supplied under the terms of the
# Common Development and Distribution License ("CDDL"), version 1.0.
# You may only use this file in accordance with the terms of version
# 1.0 of the CDDL.
#
# A full copy of the text of the CDDL should have accompanied this
# source.  A copy of the CDDL is also available via the Internet at
# http://www.illumos.org/license/CDDL.
#

#
# Copyright 2021 OmniOS Community Edition (OmniOSce) Association.
#

include ../Makefile.iffe
include $(SRC)/lib/Makefile.lib.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) 2006, 2010, Oracle and/or its affiliates. All rights reserved.
 * Copyright 2021 OmniOS Community Edition (OmniOSce) Association.
 */

#ifndef _ILLUMOS_KSH_CMDLIST_H
#define	_ILLUMOS_KSH_CMDLIST_H

#ifdef	__cplusplus
extern "C" {
#endif

/*
 * List builtins for illumos.
 * The list here is partially autogenerated and partially hand-picked
 * based on compatibility with the native illumos versions of these
 * tools
 */

/*
 * Commands which are 100% compatible with native illumos versions (/bin is
 * a softlink to ./usr/bin, ksh93 takes care of the lookup)
 */
#define	BINCMDLIST(f)	\
	{ "/bin/"	#f, NV_BLTIN|NV_BLTINOPT|NV_NOFREE, bltin(f) },
#define	USRBINCMDLIST(f)	\
	{ "/usr/bin/"	#f, NV_BLTIN|NV_BLTINOPT|NV_NOFREE, bltin(f) },
#define	SBINCMDLIST(f)	\
	{ "/sbin/"	#f, NV_BLTIN|NV_BLTINOPT|NV_NOFREE, bltin(f) },
#define	SUSRBINCMDLIST(f)	\
	{ "/usr/sbin/"	#f, NV_BLTIN|NV_BLTINOPT|NV_NOFREE, bltin(f) },
/* POSIX compatible commands */
#define	XPG6CMDLIST(f)	\
	{ "/usr/xpg6/bin/" #f, NV_BLTIN|NV_BLTINOPT|NV_NOFREE, bltin(f) },
#define	XPG4CMDLIST(f)	\
	{ "/usr/xpg4/bin/" #f, NV_BLTIN|NV_BLTINOPT|NV_NOFREE, bltin(f) },
#ifdef SHOPT_USR_GNU_BIN_BUILTINS
/* GNU coreutils compatible commands */
#define	GNUCMDLIST(f)	\
	{ "/usr/gnu/bin/" #f, NV_BLTIN|NV_BLTINOPT|NV_NOFREE, bltin(f) },
#else
#define	GNUCMDLIST(f)
#endif
/*
 * Hammerhead: /usr/ast/bin removed. AST builtins already registered via
 * BINCMDLIST (/bin/) and USRBINCMDLIST (/usr/bin/).
 */
#define	ASTCMDLIST(f)

/* undo ast_map.h #defines to avoid collision */
#undef basename
#undef dirname
#undef mktemp

/* Generated data, do not edit. */
ASTCMDLIST(basename)
GNUCMDLIST(basename)
XPG4CMDLIST(basename)
ASTCMDLIST(cat)
BINCMDLIST(cat)
ASTCMDLIST(chgrp)
// XPG4CMDLIST(chgrp)
ASTCMDLIST(chmod)
ASTCMDLIST(chown)
// XPG4CMDLIST(chown)
// BINCMDLIST(chown)
ASTCMDLIST(cksum)
BINCMDLIST(cksum)
GNUCMDLIST(cksum)
ASTCMDLIST(cmp)
BINCMDLIST(cmp)
ASTCMDLIST(comm)
BINCMDLIST(comm)
GNUCMDLIST(comm)
ASTCMDLIST(cp)
// XPG4CMDLIST(cp)
ASTCMDLIST(cut)
BINCMDLIST(cut)
GNUCMDLIST(cut)
ASTCMDLIST(date)
// XPG4CMDLIST(date)
ASTCMDLIST(dirname)
BINCMDLIST(dirname)
GNUCMDLIST(dirname)
ASTCMDLIST(expr)
GNUCMDLIST(expr)
XPG6CMDLIST(expr)
ASTCMDLIST(fds)
ASTCMDLIST(fmt)
ASTCMDLIST(fold)
BINCMDLIST(fold)
GNUCMDLIST(fold)
ASTCMDLIST(head)
BINCMDLIST(head)
ASTCMDLIST(id)
XPG4CMDLIST(id)
ASTCMDLIST(join)
BINCMDLIST(join)
GNUCMDLIST(join)
ASTCMDLIST(ln)
// XPG4CMDLIST(ln)
ASTCMDLIST(logname)
BINCMDLIST(logname)
GNUCMDLIST(logname)
ASTCMDLIST(md5sum)
ASTCMDLIST(mkdir)
BINCMDLIST(mkdir)
GNUCMDLIST(mkdir)
ASTCMDLIST(mkfifo)
BINCMDLIST(mkfifo)
GNUCMDLIST(mkfifo)
ASTCMDLIST(mktemp)
BINCMDLIST(mktemp)
GNUCMDLIST(mktemp)
ASTCMDLIST(mv)
// XPG4CMDLIST(mv)
ASTCMDLIST(paste)
BINCMDLIST(paste)
GNUCMDLIST(paste)
ASTCMDLIST(pathchk)
BINCMDLIST(pathchk)
GNUCMDLIST(pathchk)
ASTCMDLIST(rev)
BINCMDLIST(rev)
ASTCMDLIST(rm)
XPG4CMDLIST(rm)
ASTCMDLIST(rmdir)
BINCMDLIST(rmdir)
GNUCMDLIST(rmdir)
GNUCMDLIST(sleep)
ASTCMDLIST(stty)
// XPG4CMDLIST(stty)
ASTCMDLIST(sum)
BINCMDLIST(sum)
ASTCMDLIST(sync)
BINCMDLIST(sync)
GNUCMDLIST(sync)
SBINCMDLIST(sync)
SUSRBINCMDLIST(sync)
ASTCMDLIST(tail)
BINCMDLIST(tail)
XPG4CMDLIST(tail)
ASTCMDLIST(tee)
BINCMDLIST(tee)
GNUCMDLIST(tee)
ASTCMDLIST(tty)
BINCMDLIST(tty)
GNUCMDLIST(tty)
ASTCMDLIST(uname)
ASTCMDLIST(uniq)
BINCMDLIST(uniq)
GNUCMDLIST(uniq)
ASTCMDLIST(wc)
BINCMDLIST(wc)
GNUCMDLIST(wc)

/* Mandatory for ksh93 test suite and AST scripts */
BINCMDLIST(getconf)

#ifdef	__cplusplus
}
#endif

#endif /* !_ILLUMOS_KSH_CMDLIST_H */

#### ksh93 test suite

## Introduction

The directory /opt/ksh93-tests/ contains the ksh93 test suite
which is used to verify the correct behaviour of ksh93.

The test suite is split into modules with the ending *.sh
and a frontend called "shtests" which is used to run the tests.

## Basic description:

/opt/ksh93-tests/shtests <options> <varname=value> <testmodule>

By default, with no <options>, each test is run three times:

    o In the posix/C locale;
    o In the C.UTF-8 locale;
    o As a compiled script using $SHCOMP.

<options> may be:
    -c execute test module as compiled shell script only
    -p execute test module as normal shell script in posix/C only
    -u execute test module as normal shell script in c.UTF-8 only
    -t do not print timing information
    -v use VMDEBUG
<varname=value>
    Sets one or more environment variables to value "value".
<testmodule>
    file name of test module

## Basic usage in illumos:

The tests can be executed like this:
$ export SHELL=<path-to-ksh93-executable>
$ export SHCOMP=/usr/bin/shcomp
for t in /opt/ksh93-tests/tests/*.sh; do
    $SHELL /opt/ksh93-tests/shtests "$t"
done

Note that you MUST NOT use "/usr/bin/ksh93" as value for
SHELL since /usr/bin/ksh93 on illumos is a wrapper which
selects a suitable executable in /usr/bin/<isa>/ksh93
based on the hardware capabilities defined via /usr/bin/isalist

Valid values for SHELL are:
- SHELL=/usr/bin/i86/ksh93      # 32-bit i386
- SHELL=/usr/bin/amd64/ksh93    # 64-bit AMD64
- SHELL=/usr/bin/sparcv7/ksh93  # 32-bit SPARC
- SHELL=/usr/bin/sparcv9/ksh93  # 64-bit SPARC
#
# This file and its contents are supplied under the terms of the
# Common Development and Distribution License ("CDDL"), version 1.0.
# You may only use this file in accordance with the terms of version
# 1.0 of the CDDL.
#
# A full copy of the text of the CDDL should have accompanied this
# source.  A copy of the CDDL is also available via the Internet at
# http://www.illumos.org/license/CDDL.
#

#
# Copyright 2021 OmniOS Community Edition (OmniOSce) Association.
#

#
# Test whether ksh mishandles a heredoc that spans a 8K chunk and has
# a backslash as the last character of the first chunk.
# See https://www.illumos.org/issues/13434
#

# test setup
function err_exit
{
	print -u2 -n "\t"
	print -u2 -r ${Command}[$1]: "${@:2}"
	(( Errors++ ))
}
alias err_exit='err_exit $LINENO'

set -o nounset
Command=${0##*/}
integer Errors=0

# .........................................................................
# This comment introduces the correct number of padding characters to that
# the \ in the second heredoc below occurs at byte position 8192 of the
# script.
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................................
# .........................................................

t1=`mktemp`
t2=`mktemp`
if [[ ! -f "$t1" || ! -f "$t2" ]]; then
	# Don't use the global err _ exit function as the test harness uses
	# calls to that to compute the number of tests present in this file.
	echo "Could not create temporary files"
	exit 1
fi

cat > "$t1" << EOF
\$
EOF
cat > "$t2" << EOF
\$
EOF

if ! cmp -s "$t1" "$t2"; then
	err_exit "Shell truncates heredoc over chunk boundary"
	#/bin/od -t x1 "$t1"
	#/bin/od -t x1 "$t2"
fi

rm -f "$t1" "$t2"

# tests done
exit $Errors
#
# This file and its contents are supplied under the terms of the
# Common Development and Distribution License ("CDDL"), version 1.0.
# You may only use this file in accordance with the terms of version
# 1.0 of the CDDL.
#
# A full copy of the text of the CDDL should have accompanied this
# source.  A copy of the CDDL is also available via the Internet at
# http://www.illumos.org/license/CDDL.
#

#
# Copyright 2021 OmniOS Community Edition (OmniOSce) Association.
#

#
# Test whether the builtin head command properly handles files which do
# not have a trailing newline.
#

# test setup
function err_exit
{
	print -u2 -n "\t"
	print -u2 -r ${Command}[$1]: "${@:2}"
	(( Errors++ ))
}
alias err_exit='err_exit $LINENO'

set -o nounset
Command=${0##*/}
integer Errors=0

builtin head tail

t1=`mktemp`
t2=`mktemp`
t3=`mktemp`
if [[ ! -f "$t1" || ! -f "$t2" || ! -f "$t3" ]]; then
	# Don't use the global err _ exit function as the test harness uses
	# calls to that to compute the number of tests present in this file.
	echo "Could not create temporary files"
	rm -f "$t1" "$t2" "$t3"
	exit 1
fi

for f in test{0..4%02d}; do
	echo $f
done | tee $t1 > $t2
printf "nonewline" >> $t2
printf "nonewline" >> $t3

# Standard file, five lines, with trailing newline

[[ $(head -1 $t1) == 'test00' ]] || \
    err_exit "Shell head -1 standard file"

[[ $(head -2 $t1) == $'test00\ntest01' ]] || \
    err_exit "Shell head -2 standard file"

[[ $(head -s 2 -n2 $t1) == $'test02\ntest03' ]] || \
    err_exit "Shell head -s 2 -n 2 standard file"

[[ $(head -5 $t1) == $'test00\ntest01\ntest02\ntest03\ntest04' ]] || \
    err_exit "Shell head -5 standard file"

[[ $(head -10 $t1) == $'test00\ntest01\ntest02\ntest03\ntest04' ]] || \
    err_exit "Shell head -10 standard file"

[[ $(tail -1 $t1) == 'test04' ]] || \
    err_exit "Shell tail -1 standard file"

[[ $(tail -2 $t1) == $'test03\ntest04' ]] || \
    err_exit "Shell tail -2 standard file"

[[ $(tail -10 $t1) == $'test00\ntest01\ntest02\ntest03\ntest04' ]] || \
    err_exit "Shell tail -10 standard file"

# File with a single line, no trailing newline

[[ $(head -1 $t3) == 'nonewline' ]] || \
    err_exit "Shell head -1 one-line file"

[[ $(head -2 $t3) == 'nonewline' ]] || \
    err_exit "Shell head -2 one-line file"

[[ $(tail -1 $t3) == 'nonewline' ]] || \
    err_exit "Shell tail -1 one-line file"

[[ $(tail -2 $t3) == 'nonewline' ]] || \
    err_exit "Shell tail -2 one-line file"

# File with six lines, no trailing newline

[[ $(head -1 $t2) == "test00" ]] || \
    err_exit "Shell head -1 six-line file"

[[ $(head -2 $t2) == $'test00\ntest01' ]] || \
    err_exit "Shell head -2 six-line file"

[[ $(head -s 2 -n2 $t2) == $'test02\ntest03' ]] || \
    err_exit "Shell head -s 2 -n 2 six-line file"

[[ $(head -5 $t2) == $'test00\ntest01\ntest02\ntest03\ntest04' ]] || \
    err_exit "Shell head -5 six-line file"

[[ $(head -6 $t2) == $'test00\ntest01\ntest02\ntest03\ntest04\nnonewline' ]] \
    || err_exit "Shell head -6 six-line file"

[[ $(head -10 $t2) == $'test00\ntest01\ntest02\ntest03\ntest04\nnonewline' ]] \
    || err_exit "Shell head -10 six-line file"

[[ $(tail -1 $t2) == 'nonewline' ]] || \
    err_exit "Shell tail -1 six-line file"

[[ $(tail -2 $t2) == $'test04\nnonewline' ]] || \
    err_exit "Shell tail -2 six-line file"

[[ $(tail -10 $t2) == $'test00\ntest01\ntest02\ntest03\ntest04\nnonewline' ]] \
     || err_exit "Shell tail -10 six-line file"

rm -f "$t1" "$t2" "$t3"

# tests done
exit $Errors
#
# 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) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
#

#
# This test module checks whether indexed+associative arrays
# set the default datatype correctly if someone uses the "+="
# operator to add a value to an array element which does not
# exist yet.
#

# test setup
function err_exit
{
	print -u2 -n "\t"
	print -u2 -r ${Command}[$1]: "${@:2}"
	(( Errors < 127 && Errors++ ))
}
alias err_exit='err_exit $LINENO'

# the test cannot use "nounset"
Command=${0##*/}
integer Errors=0

compound bracketstat=(
	integer bopen=0
	integer bclose=0
)

function count_brackets
{
	typeset x="$1"
	typeset c

	integer i
	(( bracketstat.bopen=0 , bracketstat.bclose=0 ))

	for (( i=0 ; i < ${#x} ; i++ )) ; do
	        c="${x:i:1}"
		[[ "$c" == "(" ]] && (( bracketstat.bopen++ ))
		[[ "$c" == ")" ]] && (( bracketstat.bclose++ ))
	done

	(( bracketstat.bopen != bracketstat.bclose )) && return 1

	return 0
}

# function to add the floating-point value 1.1 to array element "34"
# floating-point datatypes should increment by 1.1, integers by 1
function add_float
{
	nameref arr=$1

	arr[34]+=1.1

	return 0
}

# function to add a compound variable called "val" to array element arr[34]
function add_compound
{
	nameref arr=$1

	arr[34]+=( float val=1.1 )

	return 0
}

# We run the tests in multiple cyles:
# First cycle uses a normal compound variable as basis
# Second cycle uses a nameref to a compound variable as basis
# Third cycle uses a nameref to a nameref to a compound variable as basis
for cycle in \
	c1 c2 c3 c4 \
	c2_sub c3_sub c4_sub \
	c2_indexed_array c3_indexed_array c4_indexed_array \
	c2_associative_array c3_associative_array c4_associative_array; do
	case ${cycle} in
		c1)
			compound mycpv
			;;
		c2)
			compound rootcpv
			nameref mycpv=rootcpv
			;;
		c3)
			compound rootcpv
			nameref namereftoroot=rootcpv
			nameref mycpv=namereftoroot
			;;
		c4)
			compound rootcpv
			nameref namereftoroot0=rootcpv
			nameref namereftoroot1=namereftoroot0
			nameref mycpv=namereftoroot1
			;;
		# same as cX but uses a subvariable of rootcpv
		c2_sub)
			compound rootcpv
			compound rootcpv.sub
			nameref mycpv=rootcpv.sub
			;;
		c3_sub)
			compound rootcpv
			compound rootcpv.sub
			nameref namereftoroot=rootcpv.sub
			nameref mycpv=namereftoroot
			;;
		c4_sub)
			compound rootcpv
			compound rootcpv.sub
			nameref namereftoroot0=rootcpv.sub
			nameref namereftoroot1=namereftoroot0
			nameref mycpv=namereftoroot1
			;;
		# same as cX but uses a subvariable of an indexed array
		c2_indexed_array)
			compound -a rootcpv
			nameref mycpv=rootcpv[4]
			;;
		c3_indexed_array)
			compound -a rootcpv
			nameref namereftoroot=rootcpv[4]
			nameref mycpv=namereftoroot
			;;
		c4_indexed_array)
			compound -a rootcpv
			nameref namereftoroot0=rootcpv[4]
			nameref namereftoroot1=namereftoroot0
			nameref mycpv=namereftoroot1
			;;
		# same as cX but uses a subvariable of an indexed array
		c2_associative_array)
			compound -A rootcpv
			nameref mycpv=rootcpv["hello world"]
			;;
		c3_associative_array)
			compound -A rootcpv
			nameref namereftoroot=rootcpv["hello world"]
			nameref mycpv=namereftoroot
			;;
		c4_associative_array)
			compound -A rootcpv
			nameref namereftoroot0=rootcpv["hello world"]
			nameref namereftoroot1=namereftoroot0
			nameref mycpv=namereftoroot1
			;;
		*)
			err_exit "${cycle}: Should not happen."
			;;
	esac


	# Test 001: Test indexed floating-point array
	float -a mycpv.myindexedfloatarray

	add_float mycpv.myindexedfloatarray
	(( mycpv.myindexedfloatarray[34] == 1.1 )) || err_exit "${cycle}: mycpv.myindexedfloatarray[34] == ${mycpv.myindexedfloatarray[34]}, expected 1.1"
	add_float mycpv.myindexedfloatarray
	(( mycpv.myindexedfloatarray[34] == 2.2 )) || err_exit "${cycle}: mycpv.myindexedfloatarray[34] == ${mycpv.myindexedfloatarray[34]}, expected 2.2"
	unset mycpv.myindexedfloatarray[34]
	(( mycpv.myindexedfloatarray[34] == 0.0 )) || err_exit "${cycle}: mycpv.myindexedfloatarray[34] == ${mycpv.myindexedfloatarray[34]}, expected 0.0"

	# 2nd try (we do this to check whether "unset" works properly)
	add_float mycpv.myindexedfloatarray
	(( mycpv.myindexedfloatarray[34] == 1.1 )) || err_exit "${cycle}: mycpv.myindexedfloatarray[34] == ${mycpv.myindexedfloatarray[34]}, expected 1.1"
	add_float mycpv.myindexedfloatarray
	(( mycpv.myindexedfloatarray[34] == 2.2 )) || err_exit "${cycle}: mycpv.myindexedfloatarray[34] == ${mycpv.myindexedfloatarray[34]}, expected 2.2"
	unset mycpv.myindexedfloatarray[34]
	(( mycpv.myindexedfloatarray[34] == 0.0 )) || err_exit "${cycle}: mycpv.myindexedfloatarray[34] == ${mycpv.myindexedfloatarray[34]}, expected 0.0"



	# Test 002: Test associative floating-point array
	float -A mycpv.myassociativefloatarray
	add_float mycpv.myassociativefloatarray
	(( mycpv.myassociativefloatarray[34] == 1.1 )) || err_exit "${cycle}: mycpv.myassociativefloatarray[34] == ${mycpv.myassociativefloatarray[34]}, expected 1.1"
	add_float mycpv.myassociativefloatarray
	(( mycpv.myassociativefloatarray[34] == 2.2 )) || err_exit "${cycle}: mycpv.myassociativefloatarray[34] == ${mycpv.myassociativefloatarray[34]}, expected 2.2"
	unset mycpv.myassociativefloatarray[34]
	(( mycpv.myassociativefloatarray[34] == 0.0 )) || err_exit "${cycle}: mycpv.myassociativefloatarray[34] == ${mycpv.myassociativefloatarray[34]}, expected 0.0"

	# 2nd try (we do this to check whether "unset" works properly)
	add_float mycpv.myassociativefloatarray
	(( mycpv.myassociativefloatarray[34] == 1.1 )) || err_exit "${cycle}: mycpv.myassociativefloatarray[34] == ${mycpv.myassociativefloatarray[34]}, expected 1.1"
	add_float mycpv.myassociativefloatarray
	(( mycpv.myassociativefloatarray[34] == 2.2 )) || err_exit "${cycle}: mycpv.myassociativefloatarray[34] == ${mycpv.myassociativefloatarray[34]}, expected 2.2"
	unset mycpv.myassociativefloatarray[34]
	(( mycpv.myassociativefloatarray[34] == 0.0 )) || err_exit "${cycle}: mycpv.myassociativefloatarray[34] == ${mycpv.myassociativefloatarray[34]}, expected 0.0"



	# Test 003: Test indexed integer array
	integer -a mycpv.myindexedintegerarray

	add_float mycpv.myindexedintegerarray
	(( mycpv.myindexedintegerarray[34] == 1 )) || err_exit "${cycle}: mycpv.myindexedintegerarray[34] == ${mycpv.myindexedintegerarray[34]}, expected 1"
	add_float mycpv.myindexedintegerarray
	(( mycpv.myindexedintegerarray[34] == 2 )) || err_exit "${cycle}: mycpv.myindexedintegerarray[34] == ${mycpv.myindexedintegerarray[34]}, expected 2"
	unset mycpv.myindexedintegerarray[34]
	(( mycpv.myindexedintegerarray[34] == 0 )) || err_exit "${cycle}: mycpv.myindexedintegerarray[34] == ${mycpv.myindexedintegerarray[34]}, expected 0"

	# 2nd try (we do this to check whether "unset" works properly)
	add_float mycpv.myindexedintegerarray
	(( mycpv.myindexedintegerarray[34] == 1 )) || err_exit "${cycle}: mycpv.myindexedintegerarray[34] == ${mycpv.myindexedintegerarray[34]}, expected 1"
	add_float mycpv.myindexedintegerarray
	(( mycpv.myindexedintegerarray[34] == 2 )) || err_exit "${cycle}: mycpv.myindexedintegerarray[34] == ${mycpv.myindexedintegerarray[34]}, expected 2"
	unset mycpv.myindexedintegerarray[34]
	(( mycpv.myindexedintegerarray[34] == 0 )) || err_exit "${cycle}: mycpv.myindexedintegerarray[34] == ${mycpv.myindexedintegerarray[34]}, expected 0"



	# Test 004: Test associative integer array
	integer -A mycpv.myassociativeintegerarray

	add_float mycpv.myassociativeintegerarray
	(( mycpv.myassociativeintegerarray[34] == 1 )) || err_exit "${cycle}: mycpv.myassociativeintegerarray[34] == ${mycpv.myassociativeintegerarray[34]}, expected 1"
	add_float mycpv.myassociativeintegerarray
	(( mycpv.myassociativeintegerarray[34] == 2 )) || err_exit "${cycle}: mycpv.myassociativeintegerarray[34] == ${mycpv.myassociativeintegerarray[34]}, expected 2"
	unset mycpv.myassociativeintegerarray[34]
	(( mycpv.myassociativeintegerarray[34] == 0 )) || err_exit "${cycle}: mycpv.myassociativeintegerarray[34] == ${mycpv.myassociativeintegerarray[34]}, expected 0"

	# 2nd try (we do this to check whether "unset" works properly)
	add_float mycpv.myassociativeintegerarray
	(( mycpv.myassociativeintegerarray[34] == 1 )) || err_exit "${cycle}: mycpv.myassociativeintegerarray[34] == ${mycpv.myassociativeintegerarray[34]}, expected 1"
	add_float mycpv.myassociativeintegerarray
	(( mycpv.myassociativeintegerarray[34] == 2 )) || err_exit "${cycle}: mycpv.myassociativeintegerarray[34] == ${mycpv.myassociativeintegerarray[34]}, expected 2"
	unset mycpv.myassociativeintegerarray[34]
	(( mycpv.myassociativeintegerarray[34] == 0 )) || err_exit "${cycle}: mycpv.myassociativeintegerarray[34] == ${mycpv.myassociativeintegerarray[34]}, expected 0"



	# Test 005: Tested indexed compound variable array
	compound -a mycpv.myindexedcompoundarray
	add_compound mycpv.myindexedcompoundarray
	(( mycpv.myindexedcompoundarray[34].val == 1.1 )) || err_exit "${cycle}: mycpv.myindexedcompoundarray[34].val == ${mycpv.myindexedcompoundarray[34].val}, expected 1.1"
	# try to add it a 2nd time - since the new element will replace the old
	# one the value will _not_ be incremented (or better: The compound
	# variable value "val" will be added, not the value of the "val"
	# variable)
	add_compound mycpv.myindexedcompoundarray
	(( mycpv.myindexedcompoundarray[34].val == 1.1 )) || err_exit "${cycle}: mycpv.myindexedcompoundarray[34].val == ${mycpv.myindexedcompoundarray[34].val}, expected 1.1"
	unset mycpv.myindexedcompoundarray[34]
	[[ ! -v mycpv.myindexedcompoundarray[34].val ]] || err_exit "${cycle}: [[ ! -v mycpv.myindexedcompoundarray[34].val ]] should return failure, got $?"
	(( mycpv.myindexedcompoundarray[34].val == 0.0 )) || err_exit "${cycle}: mycpv.myindexedcompoundarray[34].val == ${mycpv.myindexedcompoundarray[34].val}, expected 0.0"
	[[ "${mycpv.myindexedcompoundarray[34]}" == "" ]] || err_exit "${cycle}: mycpv.myindexedcompoundarray[34] expected to be equal to an empty string but contains |${mycpv.myindexedcompoundarray[34]}|"



	# Test 006: Tested associative compound variable array
	compound -A mycpv.myassociativecompoundarray
	add_compound mycpv.myassociativecompoundarray
	(( mycpv.myassociativecompoundarray[34].val == 1.1 )) || err_exit "${cycle}: mycpv.myassociativecompoundarray[34].val == ${mycpv.myassociativecompoundarray[34].val}, expected 1.1"
	# try to add it a 2nd time - since the new element will replace the old
	# one the value will _not_ be incremented (or better: The compound
	# variable value "val" will be added, not the value of the "val"
	# variable)
	add_compound mycpv.myassociativecompoundarray
	(( mycpv.myassociativecompoundarray[34].val == 1.1 )) || err_exit "${cycle}: mycpv.myassociativecompoundarray[34].val == ${mycpv.myassociativecompoundarray[34].val}, expected 1.1"
	unset mycpv.myassociativecompoundarray[34]
	[[ ! -v mycpv.myassociativecompoundarray[34].val ]] || err_exit "${cycle}: [[ ! -v mycpv.myassociativecompoundarray[34].val ]] should return failure, got $?"
	(( mycpv.myassociativecompoundarray[34].val == 0.0 )) || err_exit "${cycle}: mycpv.myassociativecompoundarray[34].val == ${mycpv.myassociativecompoundarray[34].val}, expected 0.0"
	[[ "${mycpv.myassociativecompoundarray[34]}" == "" ]] || err_exit "${cycle}: mycpv.myassociativecompoundarray[34] expected to be equal to an empty string but contains |${mycpv.myassociativecompoundarray[34]}|"


	# check whether the compound variable output is still Ok
	count_brackets "${mycpv}" || err_exit "${cycle}: bracket open ${bracketstat.bopen} != bracket close ${bracketstat.bclose}"
	count_brackets "$(print -v mycpv)" || err_exit "${cycle}: print -v mycpy: bracket open ${bracketstat.bopen} != bracket close ${bracketstat.bclose}"
	count_brackets "$(print -C mycpv)" || err_exit "${cycle}: print -C mycpy: bracket open ${bracketstat.bopen} != bracket close ${bracketstat.bclose}"


	# reset
	unset mycpv
	[[ ! -v mycpv ]] || err_exit "${cycle}: mycpy should not exist"
	[[ "${mycpv}" == "" ]] || err_exit "${cycle}: mycpv expected to be empty"
done


# tests done
exit $((Errors))
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License (the "License").
# You may not use this file except in compliance with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#

#
# Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#

#
# Test whether the ksh93/poll builtin works as expected
#

# test setup
function err_exit
{
	print -u2 -n "\t"
	print -u2 -r ${Command}[$1]: "${@:2}"
	(( Errors++ ))
}
alias err_exit='err_exit $LINENO'

set -o nounset
Command=${0##*/}
integer Errors=0


builtin -f libshell.so.1 poll || err_exit "poll builtin not found."

compound d1=(
	compound -A u=(
		[y]=( fd=5 events="POLLIN" revents="" )
		[x]=( fd=5 events="POLLIN" revents="" )
	)
)

# test 1:
cat /dev/zero | { redirect 5<&0 ; poll -e d1.res -t 5. d1.u ; } || err_exit "poll returned non-zero exit code $?"
[[ "${d1.u[x].revents}" == "POLLIN" ]] || err_exit "d1.u[x].revents contains '${d1.u[x].revents}', not POLLIN"
[[ "${d1.u[y].revents}" == "POLLIN" ]] || err_exit "d1.u[y].revents contains '${d1.u[y].revents}', not POLLIN"
[[ "${d1.res[*]}" == "x y" ]] || err_exit "d1.res contains '${d1.res[*]}', not 'x y'"

# test 2:
unset d1.res

d1.u[z]=( fd=5 events="POLLOUT" revents="" )
{ poll -e d1.res -t 5. d1.u ; } 5</dev/null 5>/dev/null || err_exit "poll returned non-zero exit code $?"
[[ "${d1.u[x].revents}" == "POLLIN"             ]] || err_exit "d1.u[x].revents contains '${d1.u[x].revents}', not 'POLLIN'"
[[ "${d1.u[y].revents}" == "POLLIN"             ]] || err_exit "d1.u[y].revents contains '${d1.u[y].revents}', not 'POLLIN'"
[[ "${d1.u[z].revents}" == "POLLOUT|POLLWRNORM" ]] || err_exit "d1.u[z].revents contains '${d1.u[z].revents}', not 'POLLOUT|POLLWRNORM,'"
[[ "${d1.res[*]}" == "x y z" ]] || err_exit "d1.res contains '${d1.res[*]}', not 'x y z'"


# tests done
exit $((Errors))
#
# 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) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
#

#
# Test whether the ksh93/libcmd sum builtin is compatible to
# Solaris/SystemV /usr/bin/sum
#

# test setup
function err_exit
{
	print -u2 -n "\t"
	print -u2 -r ${Command}[$1]: "${@:2}"
	(( Errors < 127 && Errors++ ))
}
alias err_exit='err_exit $LINENO'

set -o nounset
Command=${0##*/}
integer Errors=0


typeset x

builtin sum || err_exit "sum builtin not found"

# Basic tests
x="$(print 'hello' | /usr/bin/sum)" || err_exit "/usr/bin/sum pipe failed."
[[ "$x" == "542 1" ]] || err_exit "print 'hello' | /usr/bin/sum did not return 542 1, got $x"
x="$(print 'hello' | sum)" || err_exit "sum builtin pipe failed."
[[ "$x" == "542 1" ]] || err_exit "print 'hello' | sum builtin did not return 542 1, got $x"
x="$(print 'hello' | sum -x md5)" || err_exit "sum md5 builtin pipe failed."
[[ "$x" == "b1946ac92492d2347c6235b4d2611184" ]] || err_exit "print 'hello' | sum md5 builtin did not return b1946ac92492d2347c6235b4d2611184, got $x"
x="$(print 'hello' | sum -x sha1)" || err_exit "sum sha1 builtin pipe failed."
[[ "$x" == "f572d396fae9206628714fb2ce00f72e94f2258f" ]] || err_exit "print 'hello' | sum sha1 builtin did not return f572d396fae9206628714fb2ce00f72e94f2258f, got $x"
x="$(print 'hello' | sum -x sha256)" || err_exit "sum sha256 builtin pipe failed."
[[ "$x" == "5891b5b522d5df086d0ff0b110fbd9d21bb4fc7163af34d08286a2e846f6be03" ]] || err_exit "print 'hello' | sum sha256 builtin did not return 5891b5b522d5df086d0ff0b110fbd9d21bb4fc7163af34d08286a2e846f6be03, got $x"
x="$(print 'hello' | sum -x sha512)" || err_exit "sum sha512 builtin pipe failed."
[[ "$x" == "e7c22b994c59d9cf2b48e549b1e24666636045930d3da7c1acb299d1c3b7f931f94aae41edda2c2b207a36e10f8bcb8d45223e54878f5b316e7ce3b6bc019629" ]] || err_exit "print 'hello' | sum sha512 builtin did not return e7c22b994c59d9cf2b48e549b1e24666636045930d3da7c1acb299d1c3b7f931f94aae41edda2c2b207a36e10f8bcb8d45223e54878f5b316e7ce3b6bc019629, got $x"
# note that Solaris /usr/bin/cksum outputs $'3015617425\t6' (which may be a bug in Solaris /usr/bin/cksum)
x="$(print 'hello' | sum -x cksum)" || err_exit "sum cksum builtin pipe failed."
[[ "$x" == $'3015617425 6' ]] || err_exit "print 'hello' | sum cksum builtin did not return \$'3015617425 6', got $(printf "%q\n" "$x")"

[[ "$(print 'hello'	| /usr/bin/sum)" == "$(print 'hello'	 | sum)" ]] || err_exit "sum hello != /usr/bin/sum hello"
[[ "$(print 'fish' 	| /usr/bin/sum)" == "$(print 'fish'	 | sum)" ]] || err_exit "sum fish != /usr/bin/sum fish"
[[ "$(print '12345'	| /usr/bin/sum)" == "$(print '12345'	 | sum)" ]] || err_exit "sum 12345 != /usr/bin/sum 12345"
[[ "$(print '\n\r\n \v'	| /usr/bin/sum)" == "$(print '\n\r\n \v' | sum)" ]] || err_exit "sum spaces != /usr/bin/sum spaces"

# Test some binary files...
x="/bin/ls"
[[ "$(cat "$x" | /usr/bin/sum)" == "$(cat "$x" | sum)" ]]	|| err_exit "pipe: /usr/bin/sum $x != sum $x"
[[ "$(/usr/bin/sum "$x")" == "$(sum "$x")" ]]			|| err_exit "file: /usr/bin/sum $x != sum $x"

x="/bin/chmod"
[[ "$(cat "$x" | /usr/bin/sum)" == "$(cat "$x" | sum)" ]]	|| err_exit "pipe: /usr/bin/sum $x != sum $x"
[[ "$(/usr/bin/sum "$x")" == "$(sum "$x")" ]]			|| err_exit "file: /usr/bin/sum $x != sum $x"

x="/usr/bin/tee"
[[ "$(cat "$x" | /usr/bin/sum)" == "$(cat "$x" | sum)" ]]	|| err_exit "pipe: /usr/bin/sum $x != sum $x"
[[ "$(/usr/bin/sum "$x")" == "$(sum "$x")" ]]			|| err_exit "file: /usr/bin/sum $x != sum $x"

x="/bin/grep"
[[ "$(cat "$x" | /usr/bin/sum)" == "$(cat "$x" | sum)" ]]	|| err_exit "pipe: /usr/bin/sum $x != sum $x"
[[ "$(/usr/bin/sum "$x")" == "$(sum "$x")" ]]			|| err_exit "file: /usr/bin/sum $x != sum $x"

x="/bin/egrep"
[[ "$(cat "$x" | /usr/bin/sum)" == "$(cat "$x" | sum)" ]]	|| err_exit "pipe: /usr/bin/sum $x != sum $x"
[[ "$(/usr/bin/sum "$x")" == "$(sum "$x")" ]]			|| err_exit "file: /usr/bin/sum $x != sum $x"

x="/bin/awk"
[[ "$(cat "$x" | /usr/bin/sum)" == "$(cat "$x" | sum)" ]]	|| err_exit "pipe: /usr/bin/sum $x != sum $x"
[[ "$(/usr/bin/sum "$x")" == "$(sum "$x")" ]]			|| err_exit "file: /usr/bin/sum $x != sum $x"

x="/bin/nawk"
[[ "$(cat "$x" | /usr/bin/sum)" == "$(cat "$x" | sum)" ]]	|| err_exit "pipe: /usr/bin/sum $x != sum $x"
[[ "$(/usr/bin/sum "$x")" == "$(sum "$x")" ]]			|| err_exit "file: /usr/bin/sum $x != sum $x"

x="/usr/bin/ksh"
[[ "$(cat "$x" | /usr/bin/sum)" == "$(cat "$x" | sum)" ]]	|| err_exit "pipe: /usr/bin/sum $x != sum $x"
[[ "$(/usr/bin/sum "$x")" == "$(sum "$x")" ]]			|| err_exit "file: /usr/bin/sum $x != sum $x"

x="/usr/bin/sh"
[[ "$(cat "$x" | /usr/bin/sum)" == "$(cat "$x" | sum)" ]]	|| err_exit "pipe: /usr/bin/sum $x != sum $x"
[[ "$(/usr/bin/sum "$x")" == "$(sum "$x")" ]]			|| err_exit "file: /usr/bin/sum $x != sum $x"


# tests done
exit $((Errors))
#
# 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) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
#

#
# Test whether the ksh93/libcmd tail builtin is compatible to
# Solaris/SystemV { /bin/tail, /usr/xpg4/bin/tail } and
# POSIX "tail"
#

# test setup
function err_exit
{
	print -u2 -n "\t"
	print -u2 -r ${Command}[$1]: "${@:2}"
	(( Errors < 127 && Errors++ ))
}
alias err_exit='err_exit $LINENO'

set -o nounset
Command=${0##*/}
integer Errors=0

# common functions
function isvalidpid
{
        kill -0 ${1} 2>/dev/null && return 0
        return 1
}

function waitpidtimeout
{
	integer pid=$1
	float timeout=$2
	float i
	float -r STEP=0.5 # const

	(( timeout=timeout/STEP ))

	for (( i=0 ; i < timeout ; i+=STEP )) ; do
		isvalidpid ${pid} || break
		sleep ${STEP}
	done

	return 0
}

function myintseq
{
        integer i

        case $# in
                1)
                        for (( i=1 ; i <= $1 ; i++ )) ; do
                                printf "%d\n" i
                        done
                        ;;
                2)
                        for (( i=$1 ; i <= $2 ; i++ )) ; do
                                printf "%d\n" i
                        done
                        ;;
                3)
                        for (( i=$1 ; i <= $3 ; i+=$2 )) ; do
                                printf "%d\n" i
                        done
                        ;;
                *)
                        print -u2 -f "%s: Illegal number of arguments %d\n" "$0" $#
			return 1
                        ;;
        esac

        return 0
}

# quote input string but use single-backslash that "err_exit" prints
# the strings correctly
function singlebackslashquote
{
	typeset s
	s="$(printf "%q\n" "$1")"
	print -r "$s"
	return 0
}

# quote input string but use double-backslash that "err_exit" prints
# the strings correctly
function doublebackslashquote
{
	typeset s
	s="$(printf "%q\n" "$1")"
	s="${s//\\/\\\\}"
	print -r "$s"
	return 0
}


# main
builtin mktemp || err_exit "mktemp builtin not found"
builtin rm || err_exit "rm builtin not found"
builtin tail || err_exit "tail builtin not found"

typeset ocwd
typeset tmpdir

# create temporary test directory
ocwd="$PWD"
tmpdir="$(mktemp -t -d "test_sun_solaris_builtin_tail.XXXXXXXX")" || err_exit "Cannot create temporary directory"

cd "${tmpdir}" || { err_exit "cd ${tmpdir} failed." ; exit $((Errors)) ; }


# run tests:

# test1: basic tests
compound -a testcases=(
	(
		name="reverse_n"
		input=$'hello\nworld'
		compound -A tail_args=(
			[legacy]=(   argv=( "-r"  ) )
		)
		expected_output=$'world\nhello'
	)
	(
		name="revlist0n"
		input=$'1\n2\n3\n4'
		compound -A tail_args=(
			[legacy]=(   argv=( "-0"	 ) )
			[std_like]=( argv=( "-n" "0" ) )
		)
		expected_output=$''
	)
	(
		name="revlist0nr"
		input=$'1\n2\n3\n4'
		compound -A tail_args=(
			[legacy]=(       argv=( "-0r"	      ) )
			[std_like]=(     argv=( "-n" "0" "-r" ) )
			[long_options]=( argv=( "--lines" "0" "--reverse" ) )
		)
		expected_output=$'' )
	(
		name="revlist1n"
		input=$'1\n2\n3\n4'
		compound -A tail_args=(
			[legacy]=(       argv=( "-1"     ) )
			[std_like]=(     argv=( "-n" "1" ) )
			[long_options]=( argv=( "--lines" "1" ) )
		)
		expected_output=$'4' )
	(
		name="revlist1nr"
		input=$'1\n2\n3\n4'
		compound -A tail_args=(
			[legacy]=(       argv=( "-1r" ) )
			[std_like]=(     argv=( "-n" "1" "-r" ) )
			[long_options]=( argv=( "--lines" "1" "--reverse" ) )
		)
		expected_output=$'4'
	)
	(
		name="revlist2n"
		input=$'1\n2\n3\n4'
		compound -A tail_args=(
			[legacy]=(   argv=( "-2"  ) )
			[std_like]=( argv=( "-n" "2" ) )
		)
		expected_output=$'3\n4'
	)
	(
		name="revlist2nr"
		input=$'1\n2\n3\n4'
		compound -A tail_args=(
			[legacy]=(   argv=( "-2r" ) )
			[std_like]=( argv=( "-n" "2" "-r" ) )
			)
		expected_output=$'4\n3'
	)
	(
		name="revlist3nr"
		input=$'1\n2\n3\n4'
		compound -A tail_args=(
			[legacy]=(   argv=( "-3r" ) )
			[std_like]=( argv=( "-n" "3" "-r" ) )
		)
		expected_output=$'4\n3\n2'
	)
	(
		name="revlist2p"
		input=$'1\n2\n3\n4'
		compound -A tail_args=(
			[legacy]=(   argv=( "+2"  ) )
			[std_like]=( argv=( "-n" "+2" ) )
			)
		expected_output=$'2\n3\n4'
	)
	(
		name="revlist2pr"
		input=$'1\n2\n3\n4'
		compound -A tail_args=(
			[legacy]=(   argv=( "+2r" ) )
			[std_like]=( argv=( "-n" "+2" "-r" ) )
		)
		expected_output=$'4\n3\n2'
	)
	(
		name="revlist3p"
		input=$'1\n2\n3\n4'
		compound -A tail_args=(
			[legacy]=(   argv=( "+3"  ) )
			[std_like]=( argv=( "-n" "+3"  ) )
		)
		expected_output=$'3\n4'
	)
	(
		name="revlist3pr"
		input=$'1\n2\n3\n4'
		compound -A tail_args=(
			[legacy]=(   argv=( "+3r" ) )
			[std_like]=( argv=( "-n" "+3" "-r" ) )
		)
		expected_output=$'4\n3'
	)
	(
		name="revlist4p"
		input=$'1\n2\n3\n4'
		compound -A tail_args=(
			[legacy]=(   argv=( "+4"  ) )
			[std_like]=( argv=( "-n" "+4"  ) )
		)
		expected_output=$'4'
	)
	(
		name="revlist4pr"
		input=$'1\n2\n3\n4'
		compound -A tail_args=(
			[legacy]=(   argv=( "+4r" ) )
			[std_like]=( argv=( "-n" "+4" "-r" ) )
		)
		expected_output=$'4'
	)
	(
		name="revlist5p"
		input=$'1\n2\n3\n4'
		compound -A tail_args=(
			[legacy]=(   argv=( "+5"  ) )
			[std_like]=( argv=( "-n" "+5"  ) )
		)
		expected_output=$''
	)
	(
		name="revlist5pr"
		input=$'1\n2\n3\n4'
		compound -A tail_args=(
			[legacy]=(   argv=( "+5r" ) )
			[std_like]=( argv=( "-n" "+5" "-r" ) )
		)
		expected_output=$''
	)
)

for testid in "${!testcases[@]}" ; do
	nameref tc=testcases[${testid}]

	for argv_variants in "${!tc.tail_args[@]}" ; do
		nameref argv=tc.tail_args[${argv_variants}].argv
		output=$(
				set -o pipefail
	          		(trap "" PIPE ; print -r -- "${tc.input}") | tail "${argv[@]}"
			) || err_exit "test ${tc.name}/${argv_variants}: command failed with exit code $?"

		[[ "${output}" == "${tc.expected_output}" ]] || err_exit "test ${tc.name}/${argv_variants}: Expected $(doublebackslashquote "${tc.expected_output}"), got $(doublebackslashquote "${output}")"
	done
done


# test2: test "tail -r </etc/profile | rev -l" vs. "cat </etc/profile"
[[ "$(tail -r </etc/profile | rev -l)" == "$( cat /etc/profile )" ]] || err_exit "'tail -r </etc/profile | rev -l' output does not match 'cat /etc/profile'"


# test 3: ast-ksh.2009-05-05 "tail" builtin may crash if we pass unsupported long options
$SHELL -o errexit -c 'builtin tail ; print "hello" | tail --attack_of_chicken_monsters' >/dev/null 2>&1
(( $? == 2 )) || err_exit "expected exit code 2 for unsupported long option, got $?"


# test 4: FIFO tests

# FIFO test functions
# (we use functions here to do propper garbage collection)
function test_tail_fifo_1
{
	typeset tail_cmd="$1"
	integer i
	integer tail_pid=-1

	# cleanup trap
	trap "rm -f tailtestfifo tailout" EXIT

	# create test FIFO
	mkfifo tailtestfifo

	${tail_cmd} -f <tailtestfifo >tailout &
	tail_pid=$!

	myintseq 20 >tailtestfifo

	waitpidtimeout ${tail_pid} 5

	if isvalidpid ${tail_pid} ; then
		err_exit "test_tail_fifo_1: # tail hung (not expected)"
		kill -KILL ${tail_pid}
	fi

	wait || err_exit "tail child returned non-zero exit code=$?"

	[[ "$(cat tailout)" == $'11\n12\n13\n14\n15\n16\n17\n18\n19\n20' ]] || err_exit "test_tail_fifo_1: Expected $(doublebackslashquote '11\n12\n13\n14\n15\n16\n17\n18\n19\n20'), got $(doublebackslashquote "$(cat tailout)")"

	return 0
}

function test_tail_fifo_2
{
	typeset tail_cmd="$1"
	integer i
	integer tail_pid=-1

	# cleanup trap
	trap "rm -f tailtestfifo tailout" EXIT

	# create test FIFO
	mkfifo tailtestfifo

	${tail_cmd} -f tailtestfifo >tailout &
	tail_pid=$!

	myintseq 14 >tailtestfifo

	waitpidtimeout ${tail_pid} 5

	if isvalidpid ${tail_pid} ; then
		[[ "$(cat tailout)" == $'5\n6\n7\n8\n9\n10\n11\n12\n13\n14' ]] || err_exit "test_tail_fifo_2: Expected $(doublebackslashquote $'5\n6\n7\n8\n9\n10\n11\n12\n13\n14'), got $(doublebackslashquote "$(cat tailout)")"

		myintseq 15 >>tailtestfifo

		waitpidtimeout ${tail_pid} 5

		if isvalidpid ${tail_pid} ; then
			kill -KILL ${tail_pid}
		else
			err_exit "test_tail_fifo_2: # tail exit with return code $? (not expected)"
		fi
	fi

	wait || err_exit "tail child returned non-zero exit code=$?"

	[[ "$(cat tailout)" == $'5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15' ]] || err_exit "test_tail_fifo_2: Expected $(doublebackslashquote $'5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15'), got $(doublebackslashquote "$(cat tailout)")"

	return 0
}

# fixme: This should test /bin/tail and /usr/xpg4/bin/tail in Solaris
test_tail_fifo_1 "tail"
test_tail_fifo_2 "tail"


# test 5: "tail -f" tests
function followtest1
{
	typeset -r FOLLOWFILE="followfile.txt"
	typeset -r OUTFILE="outfile.txt"

	typeset title="$1"
	typeset testcmd="$2"
	typeset usenewline=$3
	typeset followstr=""
	typeset newline=""
	integer i
	integer tailchild=-1

	if ${usenewline} ; then
		newline=$'\n'
	fi

	rm -f "${FOLLOWFILE}" "${OUTFILE}"
	print -n "${newline}" > "${FOLLOWFILE}"

	${testcmd} -f "${FOLLOWFILE}" >"${OUTFILE}" &
	(( tailchild=$! ))

	for (( i=0 ; i < 10 ; i++)) ; do
		followstr+="${newline}${i}"
		print -n "${i}${newline}" >>"${FOLLOWFILE}"
		sleep 2

		[[ "$( < "${OUTFILE}")" == "${followstr}" ]] || err_exit "${title}: Expected $(doublebackslashquote "${followstr}"), got "$(doublebackslashquote "$( < "${OUTFILE}")")""
	done

	kill -KILL ${tailchild} 2>/dev/null
	#kill -TERM ${tailchild} 2>/dev/null
	waitpidtimeout ${tailchild} 5

	if isvalidpid ${tailchild} ; then
		err_exit "${title}: tail pid=${tailchild} hung."
		kill -KILL ${tailchild} 2>/dev/null
	fi

	wait ${tailchild} 2>/dev/null

	rm -f "${FOLLOWFILE}" "${OUTFILE}"

	return 0
}

followtest1 "test5a" "tail" true
# fixme: later we should test this, too:
#followtest1 "test5b" "tail" false
#followtest1 "test5c" "/usr/xpg4/bin/tail" true
#followtest1 "test5d" "/usr/xpg4/bin/tail" false
#followtest1 "test5e" "/bin/tail" true
#followtest1 "test5f" "/bin/tail" false


# test 6: "tail -f" tests
function followtest2
{
	typeset -r FOLLOWFILE="followfile.txt"
	typeset -r OUTFILE="outfile.txt"

	typeset title="$1"
	typeset testcmd="$2"
	integer tailchild=-1

	rm -f "${FOLLOWFILE}" "${OUTFILE}"

	myintseq 50000 >"${FOLLOWFILE}"

	${testcmd} -n 60000 -f "${FOLLOWFILE}" >"${OUTFILE}" &
	(( tailchild=$! ))

	sleep 10

	kill -KILL ${tailchild} 2>/dev/null
	#kill -TERM ${tailchild} 2>/dev/null
	waitpidtimeout ${tailchild} 5

	if isvalidpid ${tailchild} ; then
		err_exit "${title}: tail pid=${tailchild} hung."
		kill -KILL ${tailchild} 2>/dev/null
	fi

	wait ${tailchild} 2>/dev/null

	# this tail should be an external process
	outstr=$(/bin/tail "${OUTFILE}") || err_exit "tail returned non-zero exit code $?"
        [[ "${outstr}" == 49991*50000 ]] || err_exit "${title}: Expected match for 49991*50000, got "$(singlebackslashquote "${outstr}")""

	rm -f "${FOLLOWFILE}" "${OUTFILE}"

	return 0
}

followtest2 "test6a" "tail"
followtest2 "test6b" "/usr/xpg4/bin/tail"
# fixme: later we should test this, too:
#followtest2 "test6c" "/bin/tail"


# cleanup
cd "${ocwd}"
rmdir "${tmpdir}" || err_exit "Cannot remove temporary directory ${tmpdir}".


# tests done
exit $((Errors))
#
# 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) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
#

#
# Written by Roland Mainz <roland.mainz@nrubsig.org>
#

# test setup
function err_exit
{
	print -u2 -n "\t"
	print -u2 -r ${Command}[$1]: "${@:2}"
	(( Errors < 127 && Errors++ ))
}
alias err_exit='err_exit $LINENO'

set -o nounset
Command=${0##*/}
integer Errors=0


function isvalidpid
{
	kill -0 ${1} 2>/dev/null && return 0
	return 1
}
integer testfilesize i maxwait
typeset tmpfile
integer testid


########################################################################
#### test set 001:
# run loop and check various temp filesizes
# (Please keep this test syncted with sun_solaris_cr_6800929_large_command_substitution_hang.sh)

# test 1: run loop and check various temp filesizes
tmpfile="$(mktemp -t "ksh93_tests_command_substitution.${PPID}.$$.XXXXXX")" || err_exit "Cannot create temporary file."

compound test1=(
	compound -a testcases=(
		# test 1a: Run test child for $(...)
		# (note the pipe chain has to end in a builtin command, an external command may not trigger the bug)
		( name="test1a" cmd="builtin cat ; print -- \"\$(cat \"${tmpfile}\" | cat)\" ; true" )
		# test 1b: Same as test1a but uses ${... ; } instead if $(...)
		( name="test1b" cmd="builtin cat ; print -- \"\${ cat \"${tmpfile}\" | cat ; }\" ; true" )
		# test 1c: Same as test1a but does not use a pipe
		( name="test1c" cmd="builtin cat ; print -- \"\$(cat \"${tmpfile}\" ; true)\" ; true" )
		# test 1d: Same as test1a but does not use a pipe
		( name="test1d" cmd="builtin cat ; print -- \"\${ cat \"${tmpfile}\" ; true ; }\" ; true" )

		# test 1e: Same as test1a but uses an external "cat" command
		( name="test1e" cmd="builtin -d cat /bin/cat ; print -- \"\$(cat \"${tmpfile}\" | cat)\" ; true" )
		# test 1f: Same as test1a but uses an external "cat" command
		( name="test1f" cmd="builtin -d cat /bin/cat ; print -- \"\${ cat \"${tmpfile}\" | cat ; }\" ; true" )
		# test 1g: Same as test1a but uses an external "cat" command
		( name="test1g" cmd="builtin -d cat /bin/cat ; print -- \"\$(cat \"${tmpfile}\" ; true)\" ; true" )
		# test 1h: Same as test1a but uses an external "cat" command
		( name="test1h" cmd="builtin -d cat /bin/cat ; print -- \"\${ cat \"${tmpfile}\" ; true ; }\" ; true" )
	)
)

for (( testfilesize=1*1024 ; testfilesize <= 1024*1024 ; testfilesize*=2 )) ; do
	# Create temp file
	{
		for (( i=0 ; i < testfilesize ; i+=64 )) ; do
			print "0123456789abcdef01234567890ABCDEF0123456789abcdef01234567890ABCDE"
		done
	} >"${tmpfile}"

	# wait up to log2(i) seconds for the child to terminate
	# (this is 10 seconds for 1KB and 19 seconds for 512KB)
	(( maxwait=log2(testfilesize) ))

	for testid in "${!test1.testcases[@]}" ; do
		nameref currtst=test1.testcases[testid]
		${SHELL} -o errexit -c "${currtst.cmd}" >"${tmpfile}.out" &
		(( childpid=$! ))

		for (( i=0 ; i < maxwait ; i++ )) ; do
			isvalidpid ${childpid} || break
			sleep 0.25
		done

		if isvalidpid ${childpid} ; then
			err_exit "${currtst.name}: child (pid=${childpid}) still busy, filesize=${testfilesize}."
			kill -KILL ${childpid} 2>/dev/null
		fi
		wait || err_exit "${currtst.name}: Child returned non-zero exit code." # wait for child (and/or avoid zombies/slime)

		# compare input/output
		cmp -s "${tmpfile}" "${tmpfile}.out" || err_exit "${currtst.name}: ${tmpfile} and ${tmpfile}.out differ, filesize=${testfilesize}."
		rm "${tmpfile}.out"
	done

	# Cleanup
	rm "${tmpfile}"
done


########################################################################
#### test set 002:
# If a command substitution calls a function and that function contains
# a command substitution which contains a piped command, the original
# command substitution calling the function will return 127 instead of 0.
# This is causing problems in several VSC tests.
# If we remove the piped command from the simple
# case in the attached script, it returns 0.

typeset str
typeset testbody
typeset testout

testbody=$(
# <CS> means command substitution start, <CE> means command substitution end
cat <<EOF
myfunc ()
{
	pipedcmd=<CS> printf "hi" | tr "h" "H" <CE>
	echo \$pipedcmd

	return 0
}

foo=<CS>myfunc<CE>
retval=\$?

if [ "\$foo"X != "HiX" ]; then
	echo "myfunc returned '\${foo}'; expected 'Hi'"
fi

if [ \$retval -ne 0 ]; then
	echo "command substitution calling myfunc returned \"\${retval}\"; expected 0"
else
	echo "command substitution calling myfunc successfully returned 0"
fi
EOF
)


# Test 002/a: Plain test
testout=${ printf "%B\n" testbody | sed 's/<CS>/$(/g;s/<CE>/)/g' | ${SHELL} 2>&1 || err_exit "command returned exit code $?" }
[[ "${testout}" == "command substitution calling myfunc successfully returned 0" ]] || err_exit "Expected 'command substitution calling myfunc successfully returned 0', got ${testout}"

# Test 002/b: Same as test002/a but replaces "$(" with "${"
testout=${ printf "%B\n" testbody | sed 's/<CS>/${ /g;s/<CE>/ ; }/g' | ${SHELL} 2>&1 || err_exit "command returned exit code $?" }
[[ "${testout}" == "command substitution calling myfunc successfully returned 0" ]] || err_exit "Expected 'command substitution calling myfunc successfully returned 0', got ${testout}"

# Test 002/c: Same as test002/a but forces |fork()| for a subshell via "ulimit -c 0"
testout=${ printf "%B\n" testbody | sed 's/<CS>/$( ulimit -c 0 ; /g;s/<CE>/)/g' | ${SHELL} 2>&1 || err_exit "command returned exit code $?" }
[[ "${testout}" == "command substitution calling myfunc successfully returned 0" ]] || err_exit "Expected 'command substitution calling myfunc successfully returned 0', got ${testout}"

# Test 002/d: Same as test002/a but uses extra subshell
testout=${ printf "%B\n" testbody | sed 's/<CS>/$( ( /g;s/<CE>/) )/g' | ${SHELL} 2>&1 || err_exit "command returned exit code $?" }
[[ "${testout}" == "command substitution calling myfunc successfully returned 0" ]] || err_exit "Expected 'command substitution calling myfunc successfully returned 0', got ${testout}"

# Test 002/e: Same as test002/b but uses extra subshell after "${ "
testout=${ printf "%B\n" testbody | sed 's/<CS>/${ ( /g;s/<CE>/) ; }/g' | ${SHELL} 2>&1 || err_exit "command returned exit code $?" }
[[ "${testout}" == "command substitution calling myfunc successfully returned 0" ]] || err_exit "Expected 'command substitution calling myfunc successfully returned 0', got ${testout}"




########################################################################
#### test set 003:
# An expression within backticks which should return false, instead
# returns true (0).

typeset str
typeset testbody
typeset testout

testbody=$(
# <CS> means command substitution start, <CE> means command substitution end
cat <<EOF
if <CS>expr "NOMATCH" : ".*Z" > /dev/null<CE> ; then
        echo "xerror"
else
        echo "xok"
fi
EOF
)


# Test 003/a: Plain test
testout=${ printf "%B\n" testbody | sed 's/<CS>/$(/g;s/<CE>/)/g' | ${SHELL} 2>&1 || err_exit "command returned exit code $?" }
[[ "${testout}" == "xok" ]] || err_exit "Expected 'xok', got ${testout}"

# Test 003/b: Same as test003/a but replaces "$(" with "${"
testout=${ printf "%B\n" testbody | sed 's/<CS>/${ /g;s/<CE>/ ; }/g' | ${SHELL} 2>&1 || err_exit "command returned exit code $?" }
[[ "${testout}" == "xok" ]] || err_exit "Expected 'xok', got ${testout}"

# Test 003/c: Same as test003/a but forces |fork()| for a subshell via "ulimit -c 0"
testout=${ printf "%B\n" testbody | sed 's/<CS>/$( ulimit -c 0 ; /g;s/<CE>/)/g' | ${SHELL} 2>&1 || err_exit "command returned exit code $?" }
[[ "${testout}" == "xok" ]] || err_exit "Expected 'xok', got ${testout}"

# Test 003/d: Same as test003/a but uses extra subshell
testout=${ printf "%B\n" testbody | sed 's/<CS>/$( ( /g;s/<CE>/) )/g' | ${SHELL} 2>&1 || err_exit "command returned exit code $?" }
[[ "${testout}" == "xok" ]] || err_exit "Expected 'xok', got ${testout}"

# Test 003/e: Same as test003/b but uses extra subshell after "${ "
testout=${ printf "%B\n" testbody | sed 's/<CS>/${ ( /g;s/<CE>/) ; }/g' | ${SHELL} 2>&1 || err_exit "command returned exit code $?" }
[[ "${testout}" == "xok" ]] || err_exit "Expected 'xok', got ${testout}"


########################################################################
#### test set 004:
# test pipe within ${... ; } command subtitution ending in a
# non-builtin command (therefore we use "/bin/cat" instead of "cat" below
# to force the use of the external "cat" command). ast-ksh.2009-01-20
# had a bug which caused this test to fail.
testout=$( ${SHELL} -c 'pipedcmd=${ printf "hi" | /bin/cat ; } ; print $pipedcmd' )
[[ "${testout}" == "hi" ]] || err_exit "test004: Expected 'hi', got '${testout}'"


########################################################################
#### test set 005:
# Test whether the shell may hang in a
# 'exec 5>/dev/null; print $(eval ls -d . 2>&1 1>&5)'
# Originally discovered with ast-ksh.2009-05-05 which hung in
# the "configure" script of postgresql-8.3.7.tar.gz (e.g.
# configure --enable-thread-safety --without-readline)
compound test5=(
	compound -a testcases=(
		# gsf's reduced testcase
		( name="test5_a" cmd='exec 5>/dev/null; print $(eval ls -d . 2>&1 1>&5)done' )
		# gisburn's reduced testcase
		( name="test5_b" cmd='exec 5>/dev/null; print $(eval "/bin/printf hello\n" 2>&1 1>&5)done' )

		## The following tests do not trigger the problem but are included here for completeness
		## and to make sure we don't get other incarnations of the same problem later...

		# same as test5_a but uses ${ ... ; } instead of $(...)
		( name="test5_c" cmd='exec 5>/dev/null; print "${ eval ls -d . 2>&1 1>&5 ;}done"' )
		# same as test5_b but uses ${ ... ; } instead of $(...)
		( name="test5_d" cmd='exec 5>/dev/null; print "${ eval "/bin/printf hello\n" 2>&1 1>&5 ;}done"' )
		# same as test5_a but uses "ulimit -c 0" to force the shell to use a seperare process for $(...)
		( name="test5_e" cmd='exec 5>/dev/null; print $(ulimit -c 0 ; eval ls -d . 2>&1 1>&5)done' )
		# same as test5_b but uses "ulimit -c 0" to force the shell to use a seperare process for $(...)
		( name="test5_f" cmd='exec 5>/dev/null; print $(ulimit -c 0 ; eval "/bin/printf hello\n" 2>&1 1>&5)done' )
	)
)

maxwait=5
for testid in "${!test5.testcases[@]}" ; do
	nameref currtst=test5.testcases[testid]
	${SHELL} -o errexit -c "${currtst.cmd}" >"${tmpfile}.out" &
	(( childpid=$! ))

	for (( i=0 ; i < maxwait ; i++ )) ; do
		isvalidpid ${childpid} || break
		sleep 0.25
	done

	if isvalidpid ${childpid} ; then
		err_exit "${currtst.name}: child (pid=${childpid}) still busy."
		kill -KILL ${childpid} 2>/dev/null
	fi
	wait || err_exit "${currtst.name}: Child returned non-zero exit code." # wait for child (and/or avoid zombies/slime)

	testout="$( < "${tmpfile}.out")"
	rm "${tmpfile}.out" || err_exit "File '${tmpfile}.out' could not be removed."
	[[ "${testout}" == "done" ]] || err_exit "test '${currtst.name}' failed, expected 'done', got '${testout}'"
done


# tests done
exit $((Errors))
#
# 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.
#

#
# This test module contains misc compound tests which do not have
# their own module yet.
#
#

# test setup
function err_exit
{
	print -u2 -n "\t"
	print -u2 -r ${Command}[$1]: "${@:2}"
	(( Errors < 127 && Errors++ ))
}
alias err_exit='err_exit $LINENO'

set -o nounset
Command=${0##*/}
integer Errors=0

# global utility functions
compound bracketstat=(
	integer bopen=0
	integer bclose=0
)

function count_brackets
{
	typeset x="$1"
	typeset c

	integer i
	(( bracketstat.bopen=0 , bracketstat.bclose=0 ))

	for (( i=0 ; i < ${#x} ; i++ )) ; do
	        c="${x:i:1}"
		[[ "$c" == "(" ]] && (( bracketstat.bopen++ ))
		[[ "$c" == ")" ]] && (( bracketstat.bclose++ ))
	done

	(( bracketstat.bopen != bracketstat.bclose )) && return 1

	return 0
}


typeset ocwd
typeset tmpdir

# create temporary test directory
ocwd="$PWD"
tmpdir="$(mktemp -t -d "test_sun_solaris_compound_misc.XXXXXXXX")" || err_exit "Cannot create temporary directory"

cd "${tmpdir}" || { err_exit "cd ${tmpdir} failed." ; exit $((Errors)) ; }

# ksh93 <= ast-ksh.2010-03-09 prints garbage for compound x=( compound -a nodes=( [4]=( ) ) );typeset -p x
function test_compound_indexed_array_init_1
{
	compound vx=( compound -a nodes=( [4]=( ) )  )
	compound vy
	compound -a vy.nodes=( [4]=( ) )
	compound vz
	compound -a vz.nodes
	vz.nodes[4]=( )

	cx="$(typeset -p vx)" ; cx="${cx//vx/tt}"
	cy="$(typeset -p vy)" ; cy="${cy//vy/tt}"
	cz="$(typeset -p vz)" ; cz="${cz//vz/tt}"
	[[ "$cx" == "$cy" ]] || err_exit "'$cx' != '$cy'"
	[[ "$cx" == "$cz" ]] || err_exit "'$cx' != '$cz'"
	[[ "$cy" == "$cz" ]] || err_exit "'$cy' != '$cz'"

	count_brackets "$cx" || err_exit "Brackets not balanced for '$cx'"
	count_brackets "$cy" || err_exit "Brackets not balanced for '$cy'"
	count_brackets "$cz" || err_exit "Brackets not balanced for '$cz'"
	count_brackets "$(print -v vx)" || err_exit "Brackets not balanced for '$(print -v vx)'"
	count_brackets "$(print -v vy)" || err_exit "Brackets not balanced for '$(print -v vy)'"
	count_brackets "$(print -v vz)" || err_exit "Brackets not balanced for '$(print -v vz)'"
	count_brackets "$(print -C vx)" || err_exit "Brackets not balanced for '$(print -C vx)'"
	count_brackets "$(print -C vy)" || err_exit "Brackets not balanced for '$(print -C vy)'"
	count_brackets "$(print -C vz)" || err_exit "Brackets not balanced for '$(print -C vz)'"

	cx="$(typeset +p vx.nodes)" ;    [[ "$cx" == *-C* && "$cx" == *-a* ]] || err_exit "'$cx' lacks -C/-a attribute"
	cy="$(typeset +p vy.nodes)" ;    [[ "$cy" == *-C* && "$cy" == *-a* ]] || err_exit "'$cy' lacks -C/-a attribute"
	cz="$(typeset +p vz.nodes)" ;    [[ "$cz" == *-C* && "$cz" == *-a* ]] || err_exit "'$cz' lacks -C/-a attribute"
	cx="$(typeset +p vx.nodes[4])" ; [[ "$cx" == *-C*                  ]] || err_exit "'$cx' lacks -C attribute"
	cy="$(typeset +p vy.nodes[4])" ; [[ "$cy" == *-C*                  ]] || err_exit "'$cy' lacks -C attribute"
	cz="$(typeset +p vz.nodes[4])" ; [[ "$cz" == *-C*                  ]] || err_exit "'$cz' lacks -C attribute"

	return 0
}

# ksh93 <= ast-ksh.2010-03-09 prints garbage for compound x=( compound -a nodes=( [4]=( ) ) );typeset -p x
# this test is the same as test_compound_indexed_array_init_1 but "-a" was replaced with "-A"
function test_compound_associative_array_init_1
{
	compound vx=( compound -A nodes=( [4]=( ) )  )
	compound vy
	compound -A vy.nodes=( [4]=( ) )
	compound vz
	compound -A vz.nodes
	vz.nodes[4]=( )

	cx="$(typeset -p vx)" ; cx="${cx//vx/tt}"
	cy="$(typeset -p vy)" ; cy="${cy//vy/tt}"
	cz="$(typeset -p vz)" ; cz="${cz//vz/tt}"
	[[ "$cx" == "$cy" ]] || err_exit "'$cx' != '$cy'"
	[[ "$cx" == "$cz" ]] || err_exit "'$cx' != '$cz'"
	[[ "$cy" == "$cz" ]] || err_exit "'$cy' != '$cz'"

	count_brackets "$cx" || err_exit "Brackets not balanced for '$cx'"
	count_brackets "$cy" || err_exit "Brackets not balanced for '$cy'"
	count_brackets "$cz" || err_exit "Brackets not balanced for '$cz'"
	count_brackets "$(print -v vx)" || err_exit "Brackets not balanced for '$(print -v vx)'"
	count_brackets "$(print -v vy)" || err_exit "Brackets not balanced for '$(print -v vy)'"
	count_brackets "$(print -v vz)" || err_exit "Brackets not balanced for '$(print -v vz)'"
	count_brackets "$(print -C vx)" || err_exit "Brackets not balanced for '$(print -C vx)'"
	count_brackets "$(print -C vy)" || err_exit "Brackets not balanced for '$(print -C vy)'"
	count_brackets "$(print -C vz)" || err_exit "Brackets not balanced for '$(print -C vz)'"

	cx="$(typeset +p vx.nodes)" ;    [[ "$cx" == *-C* && "$cx" == *-A* ]] || err_exit "'$cx' lacks -C/-A attribute"
	cy="$(typeset +p vy.nodes)" ;    [[ "$cy" == *-C* && "$cy" == *-A* ]] || err_exit "'$cy' lacks -C/-A attribute"
	cz="$(typeset +p vz.nodes)" ;    [[ "$cz" == *-C* && "$cz" == *-A* ]] || err_exit "'$cz' lacks -C/-A attribute"
	cx="$(typeset +p vx.nodes[4])" ; [[ "$cx" == *-C*                  ]] || err_exit "'$cx' lacks -C attribute"
	cy="$(typeset +p vy.nodes[4])" ; [[ "$cy" == *-C*                  ]] || err_exit "'$cy' lacks -C attribute"
	cz="$(typeset +p vz.nodes[4])" ; [[ "$cz" == *-C*                  ]] || err_exit "'$cz' lacks -C attribute"

	return 0
}

# run tests
test_compound_indexed_array_init_1
test_compound_associative_array_init_1

cd "${ocwd}"
rmdir "${tmpdir}" || err_exit "Cannot remove temporary directory ${tmpdir}".

# tests done
exit $((Errors))
#
# 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) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
#



# test setup
function err_exit
{
	print -u2 -n "\t"
	print -u2 -r ${Command}[$1]: "${@:2}"
	(( Errors < 127 && Errors++ ))
}
alias err_exit='err_exit $LINENO'

set -o nounset
Command=${0##*/}
integer Errors=0

#
# name reference test #001
# Note we run this test in a seperate shell to make sure the memory
# corruption originally reported can be reproduced (which precisely
# depends on ordering in the testcase)
(
cat <<EOF
	function err_exit
	{
		print -u2 -n "\t"
		print -u2 -r \${Command}[\$1]: "\${@:2}"
		(( Errors++ ))
	}
	alias err_exit='err_exit \$LINENO'

	function function2
	{
		nameref v=\$1

		v.x=19
		v.y=20
	}

	function function1
	{
		typeset compound_var=()

		function2 compound_var

		printf "x=%d, y=%d\n" compound_var.x compound_var.y
	}

	x="\$(function1)"

	[[ "\$x" == 'x=19, y=20' ]] || err_exit "expected 'x=19, y=20', got '\${x}'"

EOF
) | ${SHELL}
(( Errors+=$? ))


#
# name reference test #002
# Originally derived from the xmldocumenttree1.sh demo which failed
# with ast-ksh.2009-04-15 since the nodepath+nodesnum nameref calls
# were removing the compound variable members nodes+nodesnum (caused
# by a scoping bug)
#
(
cat <<EOF
	compound xdoc
	compound -A xdoc.nodes
	integer xdoc.nodesnum=0

	function test1
	{
        	nameref doc=xdoc
        	nameref nodepath="doc.nodes"
        	nameref nodesnum="doc.nodesnum"
        	print -v doc
	}

	test1
EOF
) | out=$( ${SHELL} ) || err_exit "shell returned exit code $?"

(( ${ wc -l <<<"${out}" ; } == 4 )) || err_exit "Expected four lines of output, got ${out}"
(set -o errexit ; read -C tmp <<<"${out}" ; [[ "$(typeset +p tmp.nodes)" == *-A* ]]) || err_exit "missing variable tmp.nodes"
(set -o errexit ; read -C tmp <<<"${out}" ; [[ -v tmp.nodesnum                   ]]) || err_exit "missing variable tmp.nodesnum"


#
# name reference test #003a
# ast-ksh.2009-06-30 failed with the following compound variable/nameref test
#
(
cat <<EOF
	compound -A addrsp

	nameref sp=addrsp

	sp[14]=( size=1 )

	if [[ -v sp[19] ]] ; then
        	print "should not happen"
	else
        	print "Ok"
	fi
EOF
) | out=$( ${SHELL} ) || err_exit "shell returned exit code $?"
[[ "${out}" == "Ok" ]] || err_exit "Expected 'Ok', got ${out}"


#
# name reference test #003b
# (same as test #003a but uses a function)
# ast-ksh.2009-06-30 failed with the following compound variable/nameref test
#
(
cat <<EOF
	compound -A addrsp

	function t1
	{
		nameref sp=\$1

		sp[14]=( size=1 )

		if [[ -v sp[19] ]] ; then
        		print "should not happen"
		else
        		print "Ok"
		fi
	}

	t1 addrsp
EOF
) | out=$( ${SHELL} ) || err_exit "shell returned exit code $?"
[[ "${out}" == "Ok" ]] || err_exit "Expected 'Ok', got ${out}"


#
# name reference test #004a
# (same as #003a but uses an indexed array instead of an associative one)
# ast-ksh.2009-06-30 failed with the following compound variable/nameref test
#
(
cat <<EOF
	compound -a addrsp

	nameref sp=addrsp

	sp[14]=( size=1 )

	if [[ -v sp[19] ]] ; then
        	print "should not happen"
	else
        	print "Ok"
	fi
EOF
) | out=$( ${SHELL} ) || err_exit "shell returned exit code $?"
[[ "${out}" == "Ok" ]] || err_exit "Expected 'Ok', got ${out}"


#
# name reference test #004b
# (same as test #004a but uses a function)
# ast-ksh.2009-06-30 failed with the following compound variable/nameref test
#
(
cat <<EOF
	compound -a addrsp

	function t1
	{
		nameref sp=\$1

		sp[14]=( size=1 )

		if [[ -v sp[19] ]] ; then
        		print "should not happen"
		else
        		print "Ok"
		fi
	}

	t1 addrsp
EOF
) | out=$( ${SHELL} ) || err_exit "shell returned exit code $?"
[[ "${out}" == "Ok" ]] || err_exit "Expected 'Ok', got ${out}"


# tests done
exit $((Errors))
#
# 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) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
#

# test setup
function err_exit
{
	print -u2 -n "\t"
	print -u2 -r ${Command}[$1]: "${@:2}"
	(( Errors < 127 && Errors++ ))
}
alias err_exit='err_exit $LINENO'

# "nounset" disabled for now
#set -o nounset
Command=${0##*/}
integer Errors=0

compound bracketstat=(
	integer bopen=0
	integer bclose=0
)

function count_brackets
{
	typeset x="$1"
	typeset c

	integer i
	(( bracketstat.bopen=0 , bracketstat.bclose=0 ))

	for (( i=0 ; i < ${#x} ; i++ )) ; do
	        c="${x:i:1}"
		[[ "$c" == "(" ]] && (( bracketstat.bopen++ ))
		[[ "$c" == ")" ]] && (( bracketstat.bclose++ ))
	done

	(( bracketstat.bopen != bracketstat.bclose )) && return 1

	return 0
}

# compound variable "cat" nr.1, using $ print "%B\n" ... #
function cpvcat1
{
	set -o errexit
	compound tmp

	while read -C tmp ; do printf "%B\n" tmp ; done
	return 0
}

# compound variable "cat" nr.2, using $ print "%#B\n" ... #
function cpvcat2
{
	set -o errexit
	compound tmp

	while read -C tmp ; do printf "%#B\n" tmp ; done
	return 0
}

# compound variable "cat" nr.3, using $ print -C ... #
function cpvcat3
{
	set -o errexit
	compound tmp

	while read -C tmp ; do print -C tmp ; done
	return 0
}

# compound variable "cat" nr.4, using $ print -v ... #
function cpvcat4
{
	set -o errexit
	compound tmp

	while read -C tmp ; do print -v tmp ; done
	return 0
}

typeset s

# Test 1:
# Check whether "read -C" leaves the file pointer at the next line
# (and does not read beyond that point).
# Data layout is:
# -- snip --
# <compound var>
# hello
# -- snip --
# (additionally we test some extra stuff like bracket count)
s=${
	compound x=(
		a=1 b=2
		typeset -a myarray=( 1 2 3 4 5 6 7 8 9 10 )
		typeset -A myarray2=( [a]=1 [b]=2 ["c d"]=3 [e]=4 ["f"]=5 [g]=6 [h]=7 [i]=8 [j]=9 [k]=10 )
		typeset -A myarray3=(
			[a]=(
				float m1=0.5
				float m2=0.6
				foo="hello"
			)
			[b]=(
				foo="bar"
			)
			["c d"]=(
				integer at=90
			)
			[e]=(
				compound nested_cpv=(
					typeset -a myarray=( 1 2 3 4 5 6 7 8 9 10 )
					typeset str=$'a \'string'
				)
			)
			[f]=(
				typeset g="f"
			)
			[a_nan]=(
				float my_nan=-nan
			)
			[a_hexfloat]=(
			       typeset -X my_hexfloat=1.1
			)
		)
	)

	{
		printf "%B\n" x
		print "hello"
	} | cpvcat1 | cpvcat2 | cpvcat3 | cpvcat4 | {
		read -C y
		read s
	}
	print "x${s}x"
} || err_exit "test returned exit code $?"

[[ "${s}" == "xhellox" ]] || err_exit "Expected 'xhellox', got ${s}"
count_brackets "$y" || err_exit "y: bracket open ${bracketstat.bopen} != bracket close ${bracketstat.bclose}"
count_brackets "$(print -v y)" || err_exit "y: bracket open ${bracketstat.bopen} != bracket close ${bracketstat.bclose}"
count_brackets "$(print -C y)" || err_exit "y: bracket open ${bracketstat.bopen} != bracket close ${bracketstat.bclose}"

# cleanup
unset x y || err_exit "unset failed"
[[ "$x" == "" ]] || err_exit "cleanup failed for x"
[[ "$y" == "" ]] || err_exit "cleanup failed for y"


# Test 2:
# Same as test 1 except one more compound var following the "hello"
# line.
# Data layout is:
# -- snip --
# <compound var>
# hello
# <compound var>
# -- snip --
s=${
	compound x=(
		a=1 b=2
		typeset -a myarray=( 1 2 3 4 5 6 7 8 9 10 )
		typeset -A myarray2=( [a]=1 [b]=2 ["c d"]=3 [e]=4 ["f"]=5 [g]=6 [h]=7 [i]=8 [j]=9 [k]=10 )
		compound -A myarray3=(
			[a]=(
				float m1=0.5
				float m2=0.6
				foo="hello"
			)
			[b]=(
				foo="bar"
			)
			["c d"]=(
				integer at=90
			)
			[e]=(
				compound nested_cpv=(
					typeset -a myarray=( 1 2 3 4 5 6 7 8 9 10 )
					typeset str=$'a \'string'
				)
			)
			[f]=(
				typeset g="f"
			)
			[a_nan]=(
				float my_nan=-nan
			)
			[a_hexfloat]=(
			       typeset -X my_hexfloat=1.1
			)
		)
	)

	{
		printf "%B\n" x
		print "hello"
		printf "%B\n" x
	} | cpvcat1 | cpvcat2 | cpvcat3 | cpvcat4 | {
		read -C y1
		read s
		read -C y2
	}

	print "x${s}x"
} || err_exit "test returned exit code $?"

[[ "${s}" == "xhellox" ]] || err_exit "Expected 'xhellox', got ${s}."
[[ "${y1.myarray3[b].foo}" == "bar" ]] || err_exit "y1.myarray3[b].foo != bar"
[[ "${y2.myarray3[b].foo}" == "bar" ]] || err_exit "y2.myarray3[b].foo != bar"
[[ "$y1" != "" ]] || err_exit "y1 is empty"
[[ "$y2" != "" ]] || err_exit "y2 is empty"
(( ${#y1.myarray3[e].nested_cpv.myarray[@]} == 10 )) || err_exit "Expected 10 elements in y1.myarray3[e].nested_cpv, got ${#y1.myarray3[e].nested_cpv[@]}"
(( ${#y2.myarray3[e].nested_cpv.myarray[@]} == 10 )) || err_exit "Expected 10 elements in y2.myarray3[e].nested_cpv, got ${#y2.myarray3[e].nested_cpv[@]}"
(( isnan(y1.myarray3[a_nan].my_nan) ))   || err_exit "y1.myarray3[a_nan].my_nan not a NaN"
(( isnan(y2.myarray3[a_nan].my_nan) ))   || err_exit "y2.myarray3[a_nan].my_nan not a NaN"
(( signbit(y1.myarray3[a_nan].my_nan) )) || err_exit "y1.myarray3[a_nan].my_nan not negative"
(( signbit(y2.myarray3[a_nan].my_nan) )) || err_exit "y2.myarray3[a_nan].my_nan not negative"
count_brackets "$y1" || err_exit "y1: bracket open ${bracketstat.bopen} != bracket close ${bracketstat.bclose}"
count_brackets "$(print -v y1)" || err_exit "y1: bracket open ${bracketstat.bopen} != bracket close ${bracketstat.bclose}"
count_brackets "$(print -C y1)" || err_exit "y1: bracket open ${bracketstat.bopen} != bracket close ${bracketstat.bclose}"
count_brackets "$y2" || err_exit "y2: bracket open ${bracketstat.bopen} != bracket close ${bracketstat.bclose}"
count_brackets "$(print -v y2)" || err_exit "y2: bracket open ${bracketstat.bopen} != bracket close ${bracketstat.bclose}"
count_brackets "$(print -C y2)" || err_exit "y2: bracket open ${bracketstat.bopen} != bracket close ${bracketstat.bclose}"
[[ "$y1" == "$y2" ]] || err_exit "Expected $(printf "%q\n" "${y1}") == $(printf "%q\n" "${y2}")."
[[ "$x"  == "$y1" ]] || err_exit "Expected $(printf "%q\n" "${x}") == $(printf "%q\n" "${y}")."

# cleanup
unset x y1 y2 || err_exit "unset failed"
[[ "$x" == "" ]]  || err_exit "cleanup failed for x"
[[ "$y1" == "" ]] || err_exit "cleanup failed for y1"
[[ "$y2" == "" ]] || err_exit "cleanup failed for y2"


# Test 3: Test compound variable copy operator vs. "read -C"
compound x=(
	a=1 b=2
	typeset -a myarray=( 1 2 3 4 5 6 7 8 9 10 )
	typeset -A myarray2=( [a]=1 [b]=2 ["c d"]=3 [e]=4 ["f"]=5 [g]=6 [h]=7 [i]=8 [j]=9 [k]=10 )
	compound -A myarray3=(
		[a]=(
			float m1=0.5
			float m2=0.6
			foo="hello"
		)
		[b]=(
			foo="bar"
		)
		["c d"]=(
			integer at=90
		)
		[e]=(
			compound nested_cpv=(
				typeset -a myarray=( 1 2 3 4 5 6 7 8 9 10 )
				typeset str=$'a \'string'
			)
		)
		[f]=(
			typeset g="f"
		)
		[a_nan]=(
			float my_nan=-nan
		)
		[a_hexfloat]=(
		       typeset -X my_hexfloat=1.1
		)
	)
)

compound x_copy=x || err_exit "x_copy copy failed"
[[ "${x_copy}" != "" ]] || err_exit "x_copy should not be empty"
count_brackets "${x_copy}" || err_exit "x_copy: bracket open ${bracketstat.bopen} != bracket close ${bracketstat.bclose}"
count_brackets "$(print -v x_copy)" || err_exit "x_copy: bracket open ${bracketstat.bopen} != bracket close ${bracketstat.bclose}"
count_brackets "$(print -C x_copy)" || err_exit "x_copy: bracket open ${bracketstat.bopen} != bracket close ${bracketstat.bclose}"

compound nested_cpv_copy

nested_cpv_copy=x.myarray3[e].nested_cpv || err_exit "x.myarray3[e].nested_cpv copy failed"
(( ${#nested_cpv_copy.myarray[@]} == 10 )) || err_exit "Expected 10 elements in nested_cpv_copy.myarray, got ${#nested_cpv_copy.myarray[@]}"

# unset branch "x.myarray3[e].nested_cpv" of the variable tree "x" ...
unset x.myarray3[e].nested_cpv || err_exit "unset x.myarray3[e].nested_cpv failed"
[[ "${x.myarray3[e].nested_cpv}" == "" ]] || err_exit "x.myarray3[e].nested_cpv still has a value"

# ... and restore it from the saved copy
printf "%B\n" nested_cpv_copy | cpvcat1 | cpvcat2 | cpvcat3 | cpvcat4 | read -C x.myarray3[e].nested_cpv || err_exit "read failed"

# compare copy of the original tree and the modified one
[[ "${x}" == "${x_copy}" ]] || err_exit "x != x_copy"
count_brackets "${x}" || err_exit "x: bracket open ${bracketstat.bopen} != bracket close ${bracketstat.bclose}"
count_brackets "$(print -v x)" || err_exit "x: bracket open ${bracketstat.bopen} != bracket close ${bracketstat.bclose}"
count_brackets "$(print -C x)" || err_exit "x: bracket open ${bracketstat.bopen} != bracket close ${bracketstat.bclose}"
(( ${#x.myarray3[e].nested_cpv.myarray[@]} == 10 )) || err_exit "Expected 10 elements in x.myarray3[e].nested_cpv, got ${#x.myarray3[e].nested_cpv[@]}"
(( isnan(x.myarray3[a_nan].my_nan) ))   || err_exit "x.myarray3[a_nan].my_nan not a NaN"
(( signbit(x.myarray3[a_nan].my_nan) )) || err_exit "x.myarray3[a_nan].my_nan not negative"

# cleanup
unset x x_copy nested_cpv_copy || err_exit "unset failed"


# Test 4: Test "read -C" failure for missing bracket at the end
typeset s
s=$($SHELL -c 'compound myvar ; print "( unfinished=1" | read -C myvar 2>/dev/null || print "error $?"') || err_exit "shell failed"
[[ "$s" == "error 3" ]] || err_exit "compound_read: expected error 3, got ${s}"


# Test 5: Test "read -C" failure for missing bracket at the beginning
typeset s
s=$($SHELL -c 'compound myvar ; print "  unfinished=1 )" | read -C myvar 2>/dev/null || print "error $?"') || err_exit "shell failed"
[[ "$s" == "error 3" ]] || err_exit "compound_read: expected error 3, got ${s}"


# tests done
exit $((Errors))
#
# 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) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
#

#
# This test checks whether the issue described in CR #6687139
# ("command substitution, exec, and stdout redirection cause
# allocation loop") has been fixed:
# -- snip --
# The following one-liner (including back ticks) causes ksh93 to spin
# out of control consuming all memory at a *very* rapid pace:
#
#    `exec program > file`
#
#  If "file" is a real file (as opposed to /dev/null), the file will
#  also grow without bound.  "program" need not exist, i.e.
#
#    `exec > file`
#
#  has the same result.  Using $() instead of `` also has the same
#  effect.
#
#  This works fine under all other bourne-compatible shells.
# -- snip --
#

# test setup
function err_exit
{
	print -u2 -n "\t"
	print -u2 -r ${Command}[$1]: "${@:2}"
	(( Errors < 127 && Errors++ ))
}
alias err_exit='err_exit $LINENO'

set -o nounset
Command=${0##*/}
integer Errors=0

function isvalidpid
{
	kill -0 ${1} 2>/dev/null && return 0
	return 1
}

integer childpid
typeset testdir
integer childretval

testdir="/tmp/sun_solaris_cr_6687139_pid$$_${PPID}"
mkdir -p "${testdir}" || err_exit "Cannot create test dirctory"
cd "${testdir}" || { err_exit "Cannot cd to test dirctory" ; exit $Errors ; }

##############################################################################
##
## test variant 1a: Use command substitution $( ... )
##

# Run testcase with "nice" to make sure a "runaway" process can
# still be caught&&terminated by the current shell
nice -n 10 ${SHELL} -c 'touch z ; $(exec nosuchprogram_for_cr_6687139 > z) ; rm z' 2>/dev/null &
childpid=$!

sleep 5

if isvalidpid ${childpid} ; then
	# First _stop_, then log error since the child may eat up memory
	# VERY VERY quickly
	kill -STOP ${childpid}

	err_exit "Child still active after 5 seconds (hang ?)"

	# Get sample stack trace
	pstack ${childpid}
	kill -KILL ${childpid}
fi

# collect child's return status
wait ${childpid}
childretval=$?

(( childretval == 0 )) || err_exit "Child returned non-zero exit code ${childretval}."

[[ ! -f "z" ]] || { rm "z" ; err_exit "Child did not remove test file" ; }


##############################################################################
##
## test variant 1b: Same as test 1a but forces the shell to |fork()| for the
## subshell
##

# Run testcase with "nice" to make sure a "runaway" process can
# still be caught&&terminated by the current shell
nice -n 10 ${SHELL} -c 'touch z ; $(ulimit -c 0 ; exec nosuchprogram_for_cr_6687139 > z) ; rm z' 2>/dev/null &
childpid=$!

sleep 5

if isvalidpid ${childpid} ; then
	# First _stop_, then log error since the child may eat up memory
	# VERY VERY quickly
	kill -STOP ${childpid}

	err_exit "Child still active after 5 seconds (hang ?)"

	# Get sample stack trace
	pstack ${childpid}
	kill -KILL ${childpid}
fi

# collect child's return status
wait ${childpid}
childretval=$?

(( childretval == 0 )) || err_exit "Child returned non-zero exit code ${childretval}."

[[ ! -f "z" ]] || { rm "z" ; err_exit "Child did not remove test file" ; }


##############################################################################
##
## test variant 2a: Use plain subshell ( ... )
##

# Run testcase with "nice" to make sure a "runaway" process can
# still be caught&&terminated by the current shell
nice -n 10 ${SHELL} -c 'touch z ; (exec nosuchprogram_for_cr_6687139 > z) ; rm z' 2>/dev/null &
childpid=$!

sleep 5

if isvalidpid ${childpid} ; then
	# First _stop_, then log error since the child may eat up memory
	# VERY VERY quickly
	kill -STOP ${childpid}

	err_exit "Child still active after 5 seconds (hang ?)"

	# Get sample stack trace
	pstack ${childpid}
	kill -KILL ${childpid}
fi

# collect child's return status
wait ${childpid}
childretval=$?

(( childretval == 0 )) || err_exit "Child returned non-zero exit code ${childretval}."

[[ ! -f "z" ]] || { rm "z" ; err_exit "Child did not remove test file" ; }


##############################################################################
##
## test variant 2b: Same as test 2a but forces the shell to |fork()| for the
## subshell
##

# Run testcase with "nice" to make sure a "runaway" process can
# still be caught&&terminated by the current shell
nice -n 10 ${SHELL} -c 'touch z ; (ulimit -c 0 ; exec nosuchprogram_for_cr_6687139 > z) ; rm z' 2>/dev/null &
childpid=$!

sleep 5

if isvalidpid ${childpid} ; then
	# First _stop_, then log error since the child may eat up memory
	# VERY VERY quickly
	kill -STOP ${childpid}

	err_exit "Child still active after 5 seconds (hang ?)"

	# Get sample stack trace
	pstack ${childpid}
	kill -KILL ${childpid}
fi

# collect child's return status
wait ${childpid}
childretval=$?

(( childretval == 0 )) || err_exit "Child returned non-zero exit code ${childretval}."

[[ ! -f "z" ]] || { rm "z" ; err_exit "Child did not remove test file" ; }

# tests done, remove temporary test subdir
cd /tmp
rmdir "${testdir}" || err_exit "Could not remove temporary test directory ${testdir}"


# tests done
exit $((Errors))
#
# 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) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
#

#
# Test whether CR #6713682 has been fixed.
#
# Creating a compound variable in s subshell "bleeds through" to the calling subshell in some conditions.
# Example:
# -- snip --
# $ ksh93 -c 'unset l ; ( l=( a=1 b="BE" ) ; print "$l" ) ; print $l'
# (
#         a=1
#         b=BE
# )
# ( )
# -- snip --
# The first bracket pair is Ok since it's coming from $ print "$l" # , however the 2nd pair comes from the print $l _outside_ the subshell where the variable "l" should no longer exist.
#
# Workaround:
# Force ksh93 to call |fork()| for the matching subshell using $ ulimit -c #, e.g. ...
# -- snip --
# $ ksh93 -c 'unset l ; ( ulimit -c 0 ; l=( a=1 b="BE" ) ; print "$l" ) ; print $l'
# (
#         a=1
#         b=BE
# )
# -- snip --
# ... provides the correct output.
#

# test setup
function err_exit
{
	print -u2 -n "\t"
	print -u2 -r ${Command}[$1]: "${@:2}"
	(( Errors < 127 && Errors++ ))
}
alias err_exit='err_exit $LINENO'

set -o nounset
Command=${0##*/}
integer Errors=0


typeset var1 var2

# use unset, l=() compound syntax and print
var1="$(${SHELL} -c 'unset l ; (               l=( a=1 b="BE" ) ; print "$l" ) ; print $l')" || err_exit "Non-zero exit code."
var2="$(${SHELL} -c 'unset l ; ( ulimit -c 0 ; l=( a=1 b="BE" ) ; print "$l" ) ; print $l')" || err_exit "Non-zero exit code."
[[ "${var1}" == "${var2}" ]] || err_exit "Non-fork()'ed subshell output differes from fork()'ed subshell output (with unset)."

# do not use unset, l=() compound syntax and print
var1="$(${SHELL} -c '(               l=( a=1 b="BE" ) ; print "$l" ) ; print $l')" || err_exit "Non-zero exit code."
var2="$(${SHELL} -c '( ulimit -c 0 ; l=( a=1 b="BE" ) ; print "$l" ) ; print $l')" || err_exit "Non-zero exit code."
[[ "${var1}" == "${var2}" ]] || err_exit "Non-fork()'ed subshell output differes from fork()'ed subshell output (without unset)."

# use unset, typeset -C compound syntax and print
var1="$(${SHELL} -c 'unset l ; (               compound l ; l.a=1 ; l.b="BE" ; print "$l" ) ; print $l')" || err_exit "Non-zero exit code."
var2="$(${SHELL} -c 'unset l ; ( ulimit -c 0 ; compound l ; l.a=1 ; l.b="BE" ; print "$l" ) ; print $l')" || err_exit "Non-zero exit code."
[[ "${var1}" == "${var2}" ]] || err_exit "Non-fork()'ed subshell output differes from fork()'ed subshell output (with unset)."

# do not use unset, typeset -C compound syntax and print
var1="$(${SHELL} -c '(  	     compound l ; l.a=1 ; l.b="BE" ; print "$l" ) ; print $l')" || err_exit "Non-zero exit code."
var2="$(${SHELL} -c '( ulimit -c 0 ; compound l ; l.a=1 ; l.b="BE" ; print "$l" ) ; print $l')" || err_exit "Non-zero exit code."
[[ "${var1}" == "${var2}" ]] || err_exit "Non-fork()'ed subshell output differes from fork()'ed subshell output (with unset)."

# use unset, l=() compound syntax and printf "%B\n"
var1="$(${SHELL} -c 'unset l ; (               l=( a=1 b="BE" ) ; printf "%B\n" l ) ; printf "%B\n" l')" || err_exit "Non-zero exit code."
var2="$(${SHELL} -c 'unset l ; ( ulimit -c 0 ; l=( a=1 b="BE" ) ; printf "%B\n" l ) ; printf "%B\n" l')" || err_exit "Non-zero exit code."
[[ "${var1}" == "${var2}" ]] || err_exit "Non-fork()'ed subshell output differes from fork()'ed subshell output (with unset)."

# do not use unset, l=() compound syntax and printf "%B\n"
var1="$(${SHELL} -c '(               l=( a=1 b="BE" ) ; printf "%B\n" l) ; printf "%B\n" l')" || err_exit "Non-zero exit code."
var2="$(${SHELL} -c '( ulimit -c 0 ; l=( a=1 b="BE" ) ; printf "%B\n" l) ; printf "%B\n" l')" || err_exit "Non-zero exit code."
[[ "${var1}" == "${var2}" ]] || err_exit "Non-fork()'ed subshell output differes from fork()'ed subshell output (without unset)."

# use unset, typeset -C compound syntax and printf "%B\n"
var1="$(${SHELL} -c 'unset l ; (               compound l ; l.a=1 ; l.b="BE" ; printf "%B\n" l) ; printf "%B\n" l')" || err_exit "Non-zero exit code."
var2="$(${SHELL} -c 'unset l ; ( ulimit -c 0 ; compound l ; l.a=1 ; l.b="BE" ; printf "%B\n" l) ; printf "%B\n" l')" || err_exit "Non-zero exit code."
[[ "${var1}" == "${var2}" ]] || err_exit "Non-fork()'ed subshell output differes from fork()'ed subshell output (with unset)."

# do not use unset, typeset -C compound syntax and printf "%B\n"
var1="$(${SHELL} -c '(  	     compound l ; l.a=1 ; l.b="BE" ; printf "%B\n" l) ; printf "%B\n" l')" || err_exit "Non-zero exit code."
var2="$(${SHELL} -c '( ulimit -c 0 ; compound l ; l.a=1 ; l.b="BE" ; printf "%B\n" l) ; printf "%B\n" l')" || err_exit "Non-zero exit code."
[[ "${var1}" == "${var2}" ]] || err_exit "Non-fork()'ed subshell output differes from fork()'ed subshell output (with unset)."


# tests done
exit $((Errors))
#
# 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) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
#

#
# This test checks whether ksh93 (like ksh88) generates calls a
# CHLD/SIGCHLD trap for background jobs and _not_ for foreground jobs.
#
# This was reported as CR #6722134 ("*ksh93* (20080624_snapshot)
# doesn't execute CHLD trap"):
# -- snip --
# With "set -o monitor" on and "set -o notify" off, ksh88 executes the CHLD
# trap while waiting for interactive input when a background job completes.
# ksh93 appears not to execute the CHLD trap when a background job terminates.
# Probably related:  I noticed that with no CHLD trap set, but -o monitor and
# -o notify set, there should be a similar asynchronous job completion notice.
# It works in ksh88 but not in this ksh93 build.
# -- snip --
#

# test setup
function err_exit
{
	print -u2 -n "\t"
	print -u2 -r ${Command}[$1]: "${@:2}"
	(( Errors < 127 && Errors++ ))
}
alias err_exit='err_exit $LINENO'

set -o nounset
Command=${0##*/}
integer Errors=0


##
## test one:
##
s="$($SHELL -c '
set -o errexit
integer i

trap "print got_child" SIGCHLD

sleep 5 &
sleep 7 &
for ((i=0 ; i < 15 ; i++)) ; do
      print $i
      sleep 1

      # external, non-background command for which a SIGCHLD should
      # _not_ be fired
      /bin/true >/dev/null
done
print "loop finished"
wait
print "done"
' 2>&1 )" || err_exit "test loop failed."

[[ "$s" == ~(Er)$'14\nloop finished\ndone' ]] || err_exit "Expected '14\nloop finished\ndone' at the end of the output, got ${s}."
[[ "$s" == ~(El)$'0\n1\n2' ]] || err_exit "Expected '0\n1\n2' as at the beginning of the output, got ${s}."

integer count
(( count=$(fgrep "got_child" <<< "$s" | wc -l) )) || err_exit "counting failed."
(( count == 2 )) || err_exit "Expected count==2, got count==${count}."


##
## test two:
## (same as test "one" except that this test has one more "sleep" child)
##
s="$($SHELL -c '
set -o errexit
integer i

trap "print got_child" SIGCHLD

sleep 5 &
sleep 7 &
sleep 9 &
for ((i=0 ; i < 15 ; i++)) ; do
      print $i
      sleep 1

      # external, non-background command for which a SIGCHLD should
      # _not_ be fired
      /bin/true >/dev/null
done
print "loop finished"
wait
print "done"
' 2>&1 )" || err_exit "test loop failed."

[[ "$s" == ~(Er)$'14\nloop finished\ndone' ]] || err_exit "Expected '14\nloop finished\ndone' at the end of the output, got ${s}."
[[ "$s" == ~(El)$'0\n1\n2' ]] || err_exit "Expected '0\n1\n2' as at the beginning of the output, got ${s}."

(( count=$(fgrep "got_child" <<< "$s" | wc -l) )) || err_exit "counting failed."
(( count == 3 )) || err_exit "Expected count==3, got count==${count}."


# tests done
exit $((Errors))
#
# 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) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
#

#
# Test whether CR #6753538 ("umask modification leaks out of a ksh93
# subshell") has been fixed.
#
# Quote from CR #6753538:
# -- snip --
# I discovered that Solaris 11's /bin/sh exhibits the following
# surprising behavior:
#
#    $ /bin/sh -c 'umask 22; (umask 0); umask'
#    0000
#
# All other shells I tried print 22.
# -- snip --


# test setup
function err_exit
{
	print -u2 -n "\t"
	print -u2 -r ${Command}[$1]: "${@:2}"
	(( Errors < 127 && Errors++ ))
}
alias err_exit='err_exit $LINENO'

set -o nounset
Command=${0##*/}
integer Errors=0


#
# test set 1: Simple umask in subshell
#
x=$(${SHELL} -c 'umask 22; (umask  0); umask')
[[ "$x" == "0022" ]] || err_exit "expected umask 0022, got $x"

x=$(${SHELL} -c 'umask 20; (umask  0); umask')
[[ "$x" == "0020" ]] || err_exit "expected umask 0020, got $x"

x=$(${SHELL} -c 'umask  0; (umask 22); umask')
[[ "$x" == "0000" ]] || err_exit "expected umask 0000, got $x"


#
# test set 2: Simple umask in two subshells
#
x=$(${SHELL} -c 'umask 22; ( (umask 10); umask  0); umask')
[[ "$x" == "0022" ]] || err_exit "expected umask 0022, got $x"

x=$(${SHELL} -c 'umask 20; ( (umask 10); umask 0); umask')
[[ "$x" == "0020" ]] || err_exit "expected umas k 0020, got $x"

x=$(${SHELL} -c 'umask  0; ( (umask 10); umask 22); umask')
[[ "$x" == "0000" ]] || err_exit "expected umask 0000, got $x"


#
# test set 3: Compare normal subshell vs. subshell in seperate process
# ($ ulimit -c 0 # forced the subshell to |fork()|
#
x=$(${SHELL} -c 'umask 22; (              umask  0); umask') || err_exit "shell failed."
y=$(${SHELL} -c 'umask 22; (ulimit -c 0 ; umask  0); umask') || err_exit "shell failed."
[[ "$x" == "$y" ]] || err_exit "$x != $y"

x=$(${SHELL} -c 'umask 20; (              umask  0); umask') || err_exit "shell failed."
y=$(${SHELL} -c 'umask 20; (ulimit -c 0 ; umask  0); umask') || err_exit "shell failed."
[[ "$x" == "$y" ]] || err_exit "$x != $y"

x=$(${SHELL} -c 'umask  0; (              umask 20); umask') || err_exit "shell failed."
y=$(${SHELL} -c 'umask  0; (ulimit -c 0 ; umask 20); umask') || err_exit "shell failed."
[[ "$x" == "$y" ]] || err_exit "$x != $y"


# tests done
exit $((Errors))
#
# 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) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
#

#
# Test whether CR #6754020 ("ksh93 does weird '[' expansion") has
# been fixed.
#
# Quote from CR #6754020:
# ---- snip ----
# The problem is that subprocess uses /bin/sh as the shell when it
# spins off the process. As Brad demonstrated:
# /bin/sh -c 'echo F[[O]'
# F[[O][
#
# In short, this bug only appears when run through the test suite,
# or by people  running /bin/sh who don't understand how their shell
# treats special characters.
# -- snip --
#
# In this case ksh93 has a bug which causes "F[[O]" to be expanded
# in a wrong way.
# ---- snip ----


# test setup
function err_exit
{
	print -u2 -n "\t"
	print -u2 -r ${Command}[$1]: "${@:2}"
	(( Errors < 127 && Errors++ ))
}
alias err_exit='err_exit $LINENO'

set -o nounset
Command=${0##*/}
integer Errors=0


typeset s

# test using "echo"
s="$(${SHELL} -c 'echo F[[O]')"
[[ "$s" == 'F[[O]' ]] || err_exit "Expected 'F[[O]', got $s"

s="$(${SHELL} -c 'echo F[[[O]]')"
[[ "$s" == 'F[[[O]]' ]] || err_exit "Expected 'F[[[O]]', got $s"


# test using "print"
s="$(${SHELL} -c 'print F[[O]')"
[[ "$s" == 'F[[O]' ]] || err_exit "Expected 'F[[O]', got $s"

s="$(${SHELL} -c 'print F[[[O]]')"
[[ "$s" == 'F[[[O]]' ]] || err_exit "Expected 'F[[[O]]', got $s"


# tests done
exit $((Errors))
#
# 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) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
#

#
# Test whether CR #6763594 ('ksh93 executes command after "command"
# builtin twice on failure') has been fixed.
#
# Quote from CR #6763594:
# ---- snip ----
# ksh93 has a bug which causes shell to execute the command after the
# "command" builtin to be executed twice if "command" fails:
# -- snip --
# $ ksh93 -x -c 'print "true" >myfoo ; chmod a+x,a-r myfoo ; command ./myfoo ;
# print $?'
# + print true
# + 1> myfoo
# + chmod a+x,a-r myfoo
# + command ./myfoo
# ksh93[1]: ./myfoo: ./myfoo: cannot open [Permission denied]
# + print 1
# 1
# + print 0
# 0
# -- snip --
# The "print" command at the end is executed twice in this case since
# the shell jumps to the wrong position in the execution sequence.
#
# The correct output should be:
# -- snip --
# $ ksh93 -x -c 'print "true" >myfoo ; chmod a+x,a-r myfoo ; command ./myfoo ;
# print $?'
# + print true
# + 1> myfoo
# + chmod a+x,a-r myfoo
# + command ./myfoo
# ksh93[1]: ./myfoo: ./myfoo: cannot open [Permission denied]
# + print 1
# 1
# -- snip --
# ---- snip ----


# test setup
function err_exit
{
	print -u2 -n "\t"
	print -u2 -r ${Command}[$1]: "${@:2}"
	(( Errors < 127 && Errors++ ))
}
alias err_exit='err_exit $LINENO'

set -o nounset
Command=${0##*/}
integer Errors=0


typeset testtmpdir=/tmp/ksh93_test_cr_6763594_${PPID}_$$
mkdir "${testtmpdir}" || { err_exit "Could not create temporary directory ${testtmpdir}." ; exit ${Errors} ; }

cd "${testtmpdir}" || { err_exit "Cannot cd to temporary directory ${testtmpdir}." ; exit ${Errors} ; }

typeset s

${SHELL} -c 'print "true" >myfoo ; chmod a+x,a-r myfoo ; command ./myfoo ; print $?' 1>out_stdout 2>out_stderr
(( $? == 0 )) || err_exit "Return code $?, expected 0"

s=$( < out_stdout ) ; [[ "$s" == '126' ]] || err_exit "Expected '126', got $(printf "%q\n" "$s")."
s=$( < out_stderr ) ; [[ "$s" == ~(Elr)(.*:\ \./myfoo:\ \./myfoo:\ .*\[.*\]) ]] || err_exit "Output $(printf "%q\n" "$s") does not match pattern '~(Elr)(.*:\ \./myfoo:\ \./myfoo:\ .*\[.*\])'."

rm "myfoo" "out_stdout" "out_stderr" || err_exit "rm failed."
cd ..
rmdir "${testtmpdir}" || err_exit "Failed to remove temporary directory ${testtmpdir}."


# tests done
exit $((Errors))
#
# 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) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
#

#
# Test whether CR #6766246 ("bug in pattern matching") has been fixed.
#
# Quote from CR #6766246:
# ---- snip ----
# The bootstrap script of pkgsrc contains this code
# checkarg_sane_absolute_path() {
#   case "$1" in
#     "") ;; # the default value will be used.
#     *[!-A-Za-z0-9_./]*)
#       die "ERROR: Invalid characters in path $1 (from $2)." ;;
#     /*) ;;
#     *) die "ERROR: The argument to $2 must be an absolute path." ;;
#   esac
# }
# It turns out, the leading "!" in the pattern is not interpreted
# as negation, and the first "-" not as a literal. Instead the
# character range  "! to A" is constructed. Paths containing "%"
# or "@" are accepted, but paths containing "-" are rejected.
# Note that this interpretation makes the whole pattern
# syntactically wrong, which isn't noticed either.
#
# Test case:
# -- snip --
# !/bin/sh
# case "$1" in
# *[!-A-Za-z0-9_./]*)
#         echo invalid characters used in $1
#         ;;
# *)
#         echo only valid characters used in $1
#         ;;
# esac
# -- snip --
# Expected Result:
#    strings containing a "-" should be accepted, strings containing
#    a "@" should be rejected
# Actual Result:
#    strings containing a "-" are rejected, strings containing a
#    "@" are accepted
# Workaround
#    The pattern "*[!A-Za-z0-9_./-]*" (i.e. shifting the dash to
#    the end) works as expected.
# ---- snip ----


# test setup
function err_exit
{
	print -u2 -n "\t"
	print -u2 -r ${Command}[$1]: "${@:2}"
	(( Errors < 127 && Errors++ ))
}
alias err_exit='err_exit $LINENO'

set -o nounset
Command=${0##*/}
integer Errors=0


## test 1 (based on the bug report):

function do_match
{
	case "$1" in
		*[!-A-Za-z0-9_./]*)
			print "match"
			;;
		*)
			print "nomatch"
			;;
	esac
	return 0
}

typeset pat

pat="foo-bar" ; [[ "$(do_match "${pat}")" == "nomatch" ]] || err_exit "${pat} matched."
pat="foo+bar" ; [[ "$(do_match "${pat}")" == "match"   ]] || err_exit "${pat} not matched."
pat="foo/bar" ; [[ "$(do_match "${pat}")" == "nomatch" ]] || err_exit "${pat} matched."
pat="foo_bar" ; [[ "$(do_match "${pat}")" == "nomatch" ]] || err_exit "${pat} matched."
pat="foo@bar" ; [[ "$(do_match "${pat}")" == "match"   ]] || err_exit "${pat} not matched."
pat="foobar-" ; [[ "$(do_match "${pat}")" == "nomatch" ]] || err_exit "${pat} matched."
pat="foobar+" ; [[ "$(do_match "${pat}")" == "match"   ]] || err_exit "${pat} not matched."
pat="foobar/" ; [[ "$(do_match "${pat}")" == "nomatch" ]] || err_exit "${pat} matched."
pat="foobar_" ; [[ "$(do_match "${pat}")" == "nomatch" ]] || err_exit "${pat} matched."
pat="foobar@" ; [[ "$(do_match "${pat}")" == "match"   ]] || err_exit "${pat} not matched."
pat="-foobar" ; [[ "$(do_match "${pat}")" == "nomatch" ]] || err_exit "${pat} matched."
pat="+foobar" ; [[ "$(do_match "${pat}")" == "match"   ]] || err_exit "${pat} not matched."
pat="/foobar" ; [[ "$(do_match "${pat}")" == "nomatch" ]] || err_exit "${pat} matched."
pat="_foobar" ; [[ "$(do_match "${pat}")" == "nomatch" ]] || err_exit "${pat} matched."
pat="@foobar" ; [[ "$(do_match "${pat}")" == "match"   ]] || err_exit "${pat} not matched."


## test 2 (gsf's test chain):

# Make sure LC_COLLATE has a value
if [[ ! -v LC_COLLATE ]] ; then
	if [[ -v LANG && ! -v LC_ALL ]]; then
		LC_COLLATE="${LANG}"
	fi
fi

if [[ -v LC_ALL ]] ; then
	LC_COLLATE="${LC_ALL}"
fi

[[ -v LC_COLLATE ]] || LC_COLLATE=C

set -- \
        'A'   0 1 1   0 1 1      1 0 0   1 0 0   \
        'Z'   0 1 1   0 1 1      1 0 0   1 0 0   \
        '/'   0 0 0   0 0 0      1 1 1   1 1 1   \
        '.'   0 0 0   0 0 0      1 1 1   1 1 1   \
        '_'   0 0 0   0 0 0      1 1 1   1 1 1   \
        '-'   1 1 1   1 1 1      0 0 0   0 0 0   \
        '%'   0 0 0   0 0 0      1 1 1   1 1 1   \
        '@'   0 0 0   0 0 0      1 1 1   1 1 1   \
        '!'   0 0 0   0 0 0      1 1 1   1 1 1   \
        '^'   0 0 0   0 0 0      1 1 1   1 1 1   \
        # retain this line #
while (( $# >= 13 )) ; do
	c=$1
	shift
	for p in \
		'[![.-.]]' \
		'[![.-.][:upper:]]' \
		'[![.-.]A-Z]' \
		'[!-]' \
		'[!-[:upper:]]' \
		'[!-A-Z]' \
		'[[.-.]]' \
		'[[.-.][:upper:]]' \
		'[[.-.]A-Z]' \
		'[-]' \
		'[-[:upper:]]' \
		'[-A-Z]' \
		# retain this line #
	do      e=$1
		shift
		[[ $c == $p ]]
		g=$?
		[[ $g == $e ]] || err_exit "[[ '$c' == $p ]] for LC_COLLATE=$l failed -- expected $e, got $g"
	done
done


# tests done
exit $((Errors))
#
# 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) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
#

#
# This test checks whether ksh93 supports more than 256 recursive
# function+command substitution calls.
#
# This was reported as CR #6769332 ('Recursive function+command
# substitutions terminate shell after 257 iterations'):
# ------------ snip ------------
# Recursive function+command substitutions
# (e.g. func1() { x=$( func2 ) ; } ; x=$( func1 ) ) terminate the
# ksh93 shell after 257 iterations with a exit code of "0" (it
# seems the shell just "quits" after the last "return 0" statement
# in the function).
# Running the attached testcase terminates the shell after 257
# iterations (g=257 in the script) while 256 iterations (replace
# "257" with "256" in the script) just works fine.
# The same testcase works Ok in ksh88 (=/usr/bin/ksh in
# Solaris 10U5)
#
# Expected Result
#    The script should output "done" and return the exit code 0.
#
# Actual Result
#    No messsge. Exit code "0".
#
# Error Message(s)
#    None (exit code is "0").
#
# Test Case
#    f1()
# {
#         h=$1
#         (( h=h-1 ))
#         (( h <= 0 )) && return 0
#         x=$(f1 "$h" "$l" "$g" d e "$l") || print -u2 "$g/$h: fail"
#         return 0
# }
# l=""
# g=257
# i=0
# while (( i < $g )) ; do
#         l="${l}x"
#         (( i=i+1 ))
# done
# f1 "$g" "$l" "$g" d e "$l" || print -u2 "$g: fail0"
# print "done"
# exit 0
#
# Workaround
#    -
# ------------ snip ------------
#

# test setup
function err_exit
{
	print -u2 -n "\t"
	print -u2 -r ${Command}[$1]: "${@:2}"
	(( Errors < 127 && Errors++ ))
}
alias err_exit='err_exit $LINENO'

set -o nounset
Command=${0##*/}
integer Errors=0

#
# test1: Testcase from CR #6769332
#
(
cat <<EOF
# make sure we have enougth stack (needed for 64bit SPARC and SystemZ)
ulimit -s 65536

f1()
{
        h=\$1
        (( h=h-1 ))
        (( h <= 0 )) && return 0
        x=\$(f1 "\$h" "\$l" "\$g" d e "\$l") || print -u2 "\$g/\$h: fail"
        return 0
}
l=""
g=257
i=0
while (( i < \$g )) ; do
        l="\${l}x"
        (( i=i+1 ))
done
f1 "\$g" "\$l" "\$g" d e "\$l" || print -u2 "\$g: fail0"
print "done"
EOF
) | out="$( ${SHELL} 2>&1 ; )" || err_exit "Shell returned non-zero exit code $?."

[[ "${out}" == "done" ]] || err_exit "Output expected to be 'done', got '${out}'."


# tests done
exit $((Errors))
#
# 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) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
#

#
# This test checks whether the arithmetric function "iszero" is available.
#
# This was reported as CR #6777491 ("*ksh93* lacks arithmetric function
# iszero()"):
# ------------ snip ------------
# ksh93 lacks arithmetric function "iszero()" which limits the ability
# to classify floating-point values or even correctly match against
# zero (since IEEE754-1985/2008 floating-point math differs between
# positive and negaive zero values).
# Frequency
#    Always
# Regression
#    No
# Steps to Reproduce
#    $ ksh93 -c '(( iszero(0) )) && print "0 is a zero"'
# Expected Result
#    Output to stdout:
# -- snip --
# 0 is a zero
# -- snip --
# Actual Result
#    ksh93 exists with:
# -- snip --
# ksh93: iszero(0) : unknown function
# -- snip --
# Error Message(s)
#    ksh93: iszero(0) : unknown function
# Test Case
#    ksh93 -c '(( iszero(0) )) && print "0 is a zero"'
# ------------ snip ------------
#

# test setup
function err_exit
{
	print -u2 -n "\t"
	print -u2 -r ${Command}[$1]: "${@:2}"
	(( Errors < 127 && Errors++ ))
}
alias err_exit='err_exit $LINENO'

set -o nounset
Command=${0##*/}
integer Errors=0

typeset str
integer i

typeset -a tests=(
	'(( iszero(0)   )) && print "OK"'
	'(( iszero(0.)  )) && print "OK"'
	'(( iszero(-0)  )) && print "OK"'
	'(( iszero(-0.) )) && print "OK"'
	'float n=0.  ; (( iszero(n) )) && print "OK"'
	'float n=+0. ; (( iszero(n) )) && print "OK"'
	'float n=-0. ; (( iszero(n) )) && print "OK"'
	'float n=1.  ; (( iszero(n) )) || print "OK"'
	'float n=1.  ; (( iszero(n-1.) )) && print "OK"'
	'float n=-1. ; (( iszero(n+1.) )) && print "OK"'
)

for (( i=0 ; i < ${#tests[@]} ; i++ )) ; do
	str="$( $SHELL -o errexit -c "${tests[i]}" 2>&1 )" || err_exit "test $i: returned non-zero exit code $?"
	[[ "${str}" == "OK" ]] || err_exit "test $i: expected 'OK', got '${str}'"
done

# tests done
exit $((Errors))
#
# 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) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
#

#
# This test checks whether ksh93 supports traps for the SIGTHAW
# signal.
#
# This was reported as CR #6778077 ("*ksh93* does not understand "THAW"
# as a signal for use with trap"):
# -- snip --
# While ksh93 understand THAW in the list of signals for kill it does
# not understand it for "trap'
#
# : pod5.eu TS 6 $; kill -l | egrep '(THAW|FREEZE)'
# FREEZE
# THAW
# : pod5.eu TS 7 $; trap "echo THAW" THAW
# ksh93: trap: THAW: bad trap
# : pod5.eu TS 8 $;
#
# Using the signal number (35) works around this.
# -- snip --
#

# test setup
function err_exit
{
	print -u2 -n "\t"
	print -u2 -r ${Command}[$1]: "${@:2}"
	(( Errors < 127 && Errors++ ))
}
alias err_exit='err_exit $LINENO'

set -o nounset
Command=${0##*/}
integer Errors=0


## test one: Check whether the shell supports SIGTHAW as trap
${SHELL} -o errexit -c 'trap "true" SIGTHAW ; true' || err_exit "SIGTHAW not supported."
${SHELL} -o errexit -c 'trap "true" THAW ; true'    || err_exit "THAW not supported."
${SHELL} -o errexit -c 'trap "true" 35 ; true'      || err_exit "signal 35 not supported."


## test two: Check whether the shell supports SIGFREEZE as trap
## (we check this since it is SIGTHAW's counterpart)
${SHELL} -o errexit -c 'trap "true" SIGFREEZE ; true' || err_exit "SIGFREEZE not supported."
${SHELL} -o errexit -c 'trap "true" FREEZE ; true'    || err_exit "FREEZE not supported."
${SHELL} -o errexit -c 'trap "true" 34 ; true'        || err_exit "signal 34 not supported."


## test three: Check all other signals listed by "kill -l"
kill -l | while read i ; do
	str="$( ${SHELL} -c "trap true $i ; print 'ok'" 2>&1 )" || err_exit "shell returned code $? for trap $i"
	[[ "${str}" == "ok" ]] || err_exit "expected 'ok', got $str"
done


# tests done
exit $((Errors))
#
# 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) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
#

#
# This test checks whether arithmetric math correctly supports
# negative zero values
#
# This was reported as CR #6789247 ("libast/ksh93 1-digit hexfloat base conversion rounds incorrectly"):
# ---- snip ----
# Description
#   [The same issue was described in http://mail.opensolaris.org/pipermail/ksh93-integration-discuss/2008-December/006737.html]
#   This is basically a spin-off of http://bugs.opensolaris.org/view_bug.do?bug_id=6773712 ("1-digit hex fp
#   base conversion of long double rounds incorrectly").
#   The bug description for Solaris libc says this:
#   > The first line of output from this program is correct.  The second line
#   > is not.
#   >
#   > leviathan% cat a.c
#   > #include <stdio.h>
#   >
#   > int main()
#   > {
#   >     printf("%.0a\n", 1.5);
#   >     printf("%.0La\n", 1.5L);
#   >     return 0;
#   > }
#   > leviathan% cc -o a a.c
#   > leviathan% a
#   > 0x1p+1
#   > 0x1p+0
#   > leviathan%
#   If I compile the testcase with libast on Solaris 11/B84 SPARC (which
#   matches ast-open.2008-11-04) I get this:
#   -- snip --
#   $ cc -xc99=%all -I/usr/include/ast -last a.c -o a &&
#   ./a
#   0x1p+00
#   0x1p+00
#   -- snip --
#   ... which seems to be incorrect per the bugs comment above and should
#   be:
#   -- snip --
#   0x1p+1
#   0x1p+1
#   -- snip --
#   ksh93 has the same problem:
#   $ ksh93 -c 'float r=1.5 ; printf "%.0a\n" r'
#   0x1p+00
# Steps to Reproduce
#    Compile and run testcase like this:
#    -- snip --
#    $ cc -xc99=%all -I/usr/include/ast -last a.c -o a &&
#    ./a
#    -- snip --
# Expected Result
#    0x1p+1
#    0x1p+1
# Actual Result
#    0x1p+00
#    0x1p+00
# ---- snip ----
#

# test setup
function err_exit
{
	print -u2 -n "\t"
	print -u2 -r ${Command}[$1]: "${@:2}"
	(( Errors < 127 && Errors++ ))
}
alias err_exit='err_exit $LINENO'

set -o nounset
Command=${0##*/}
integer Errors=0


float r
float result
typeset str

# Test #001/a - check whether the result of a rounded 1.5 is 2.0
r=1.5
result=$(printf "%.0a\n" r) || err_exit "printf returned non-zero exit code"
(( result == 2.0 )) || err_exit "result expected to be 2.0, got ${result}"


# Test #001/b - same as test #001/a but uses "%.0A\n" instead of "%.0a\n"
r=1.5
result=$(printf "%.0A\n" r) || err_exit "printf returned non-zero exit code"
(( result == 2.0 )) || err_exit "result expected to be 2.0, got ${result}"


# Test #002/a - check whether the hexfloat string value matches the expected pattern
r=1.5
str=$(printf "%.0a\n" r) || err_exit "printf returned non-zero exit code"
[[ "${str}" == ~(Glri)0x0*1p\+0*1 ]] || err_exit "str expected to match ~(Glri)0x0*1p\+0*1, got |${str}|"


# Test #002/b - same as test #002/a but uses "%.0A\n" instead of "%.0a\n"
r=1.5
str=$(printf "%.0A\n" r) || err_exit "printf returned non-zero exit code"
[[ "${str}" == ~(Glri)0x0*1p\+0*1 ]] || err_exit "str expected to match ~(Glri)0x0*1p\+0*1, got |${str}|"


# tests done
exit $((Errors))
#
# 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) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
#

#
# Test whether CR #6800929 ("snv_106 ksh93 update breaks Install(1M)") has been fixed.
#
# Quote from CR #6800929:
# ---- snip ----
# so i just upgraded this morning from snv_105 to snv_106.  now
# Install(1M) is hanging whenever i run it.  i'm running it as follows:
#         Install -o debug -k i86xpv -T domu-219:/tmp
#
# and here's where it's hung:
# ---8<---
#  Edward Pilatowicz <edward.pilatowicz@sun.com>
# $ pstack 204600
# 204600: /bin/ksh /opt/onbld/bin/Install -o debug -k i86xpv -T domu-219:/tmp
#  fffffd7fff2e3d1a write    (1, 4154c0, 64)
#  fffffd7ffefdafc8 sfwr () + 2d0
#  fffffd7ffefc0f6f _sfflsbuf () + 217
#  fffffd7ffefcb9f7 sfsync () + 17f
#  fffffd7ffefc5c58 _sfphead () + 188
#  fffffd7ffefc5ef5 _sfpmove () + 55
#  fffffd7ffefc2595 _sfmode () + 22d
#  fffffd7ffefc5fb1 sfpool () + 99
#  fffffd7fff15eb8e sh_exec () + 2f56
#  fffffd7fff15f78c sh_exec () + 3b54
#  fffffd7fff15d9c8 sh_exec () + 1d90
#  fffffd7fff15788e sh_subshell () + 646
#  fffffd7fff134562 comsubst () + 8a2
#  fffffd7fff12f61f copyto () + bcf
#  fffffd7fff12df79 sh_macexpand () + 1f1
#  fffffd7fff1129f5 arg_expand () + a5
#  fffffd7fff112812 sh_argbuild () + 9a
#  fffffd7fff15dbe2 sh_exec () + 1faa
#  fffffd7fff15d854 sh_exec () + 1c1c
#  fffffd7fff0f22ef b_dot_cmd () + 507
#  fffffd7fff161559 sh_funct () + 199
#  fffffd7fff15ef35 sh_exec () + 32fd
#  fffffd7fff136e86 exfile () + 786
#  fffffd7fff136676 sh_main () + 7fe
#  0000000000400e72 main () + 52
#  0000000000400ccc ????
# ---8<---
#
# there is only one place where Install(1M) invokes "uniq":
#         set -- `grep "^CONF" $modlist | sort | uniq`;
#
# as it turns out, i can easily reproduce this problem as follows:
# ---8<---
# $ ksh93
# $ set -- `cat /etc/termcap | sort | uniq`
# <hang>
# ---8<---
# ---- snip ----


# test setup
function err_exit
{
	print -u2 -n "\t"
	print -u2 -r ${Command}[$1]: "${@:2}"
	(( Errors < 127 && Errors++ ))
}
alias err_exit='err_exit $LINENO'

set -o nounset
Command=${0##*/}
integer Errors=0

# common functions/variables
function isvalidpid
{
	kill -0 ${1} 2>/dev/null && return 0
	return 1
}
integer testfilesize i maxwait
typeset tmpfile
integer testid


# test 1: run loop and check various temp filesizes
tmpfile="$(mktemp -t "sun_solaris_cr_6800929_large_command_substitution_hang.${PPID}.$$.XXXXXX")" || err_exit "Cannot create temporary file."

compound -a testcases=(
	# test 1a: Run test child for $(...)
	# (note the pipe chain has to end in a builtin command, an external command may not trigger the bug)
	( name="test1a" cmd="builtin cat ; print -- \"\$(cat \"${tmpfile}\" | cat)\" ; true" )
	# test 1b: Same as test1a but uses ${... ; } instead if $(...)
	( name="test1b" cmd="builtin cat ; print -- \"\${ cat \"${tmpfile}\" | cat ; }\" ; true" )
	# test 1c: Same as test1a but does not use a pipe
	( name="test1c" cmd="builtin cat ; print -- \"\$(cat \"${tmpfile}\" ; true)\" ; true" )
	# test 1d: Same as test1a but does not use a pipe
	( name="test1d" cmd="builtin cat ; print -- \"\${ cat \"${tmpfile}\" ; true ; }\" ; true" )

	# test 1e: Same as test1a but uses an external "cat" command
	( name="test1e" cmd="builtin -d cat /bin/cat ; print -- \"\$(cat \"${tmpfile}\" | cat)\" ; true" )
	# test 1f: Same as test1a but uses an external "cat" command
	( name="test1f" cmd="builtin -d cat /bin/cat ; print -- \"\${ cat \"${tmpfile}\" | cat ; }\" ; true" )
	# test 1g: Same as test1a but uses an external "cat" command
	( name="test1g" cmd="builtin -d cat /bin/cat ; print -- \"\$(cat \"${tmpfile}\" ; true)\" ; true" )
	# test 1h: Same as test1a but uses an external "cat" command
	( name="test1h" cmd="builtin -d cat /bin/cat ; print -- \"\${ cat \"${tmpfile}\" ; true ; }\" ; true" )
)

for (( testfilesize=1*1024 ; testfilesize <= 1024*1024 ; testfilesize*=2 )) ; do
	# Create temp file
	{
		for (( i=0 ; i < testfilesize ; i+=64 )) ; do
			print "0123456789abcdef01234567890ABCDEF0123456789abcdef01234567890ABCDE"
		done
	} >"${tmpfile}"

	# wait up to log2(i) seconds for the child to terminate
	# (this is 10 seconds for 1KB and 19 seconds for 512KB)
	(( maxwait=log2(testfilesize) ))

	for testid in "${!testcases[@]}" ; do
		nameref currtst=testcases[testid]
		${SHELL} -o errexit -c "${currtst.cmd}" >"${tmpfile}.out" &
		(( childpid=$! ))

		for (( i=0 ; i < maxwait ; i++ )) ; do
			isvalidpid ${childpid} || break
			sleep 0.25
		done

		if isvalidpid ${childpid} ; then
			err_exit "${currtst.name}: child (pid=${childpid}) still busy, filesize=${testfilesize}."
			kill -KILL ${childpid} 2>/dev/null
		fi
		wait || err_exit "${currtst.name}: Child returned non-zero exit code." # wait for child (and/or avoid zombies/slime)

		# compare input/output
		cmp -s "${tmpfile}" "${tmpfile}.out" || err_exit "${currtst.name}: ${tmpfile} and ${tmpfile}.out differ, filesize=${testfilesize}."
		rm "${tmpfile}.out"
	done

	# Cleanup
	rm "${tmpfile}"
done


# test 2a: Edward Pilatowicz <edward.pilatowicz@sun.com>'s Solaris-specific testcase
${SHELL} -o errexit -c 'builtin uniq ; set -- `cat /etc/termcap | sort | uniq` ; true' >/dev/null &
(( childpid=$! ))
sleep 5
if isvalidpid ${childpid} ; then
	err_exit "test2a: child (pid=${childpid}) still busy."
	kill -KILL ${childpid} 2>/dev/null
fi
wait || err_exit "test2a: Child returned non-zero exit code." # wait for child (and/or avoid zombies/slime)


# test 2b: Same as test 2a but uses ${... ; } instead of $(...)
${SHELL} -o errexit -c 'builtin uniq ; set -- ${ cat /etc/termcap | sort | uniq ; } ; true' >/dev/null &
(( childpid=$! ))
sleep 5
if isvalidpid ${childpid} ; then
	err_exit "test2b: child (pid=${childpid}) still busy."
	kill -KILL ${childpid} 2>/dev/null
fi
wait || err_exit "test2b: Child returned non-zero exit code." # wait for child (and/or avoid zombies/slime)


# test 2c: Same as test 2a but makes sure that "uniq" is not a builtin
${SHELL} -o errexit -c 'builtin -d uniq /bin/uniq ; set -- `cat /etc/termcap | sort | uniq` ; true' >/dev/null &
(( childpid=$! ))
sleep 5
if isvalidpid ${childpid} ; then
	err_exit "test2c: child (pid=${childpid}) still busy."
	kill -KILL ${childpid} 2>/dev/null
fi
wait || err_exit "test2c: Child returned non-zero exit code." # wait for child (and/or avoid zombies/slime)


# test 2d: Same as test 2c but uses ${... ; } instead of $(...)
${SHELL} -o errexit -c 'builtin -d uniq /bin/uniq ; set -- ${ cat /etc/termcap | sort | uniq ; } ; true' >/dev/null &
(( childpid=$! ))
sleep 5
if isvalidpid ${childpid} ; then
	err_exit "test2d: child (pid=${childpid}) still busy."
	kill -KILL ${childpid} 2>/dev/null
fi
wait || err_exit "test2d: Child returned non-zero exit code." # wait for child (and/or avoid zombies/slime)


# tests done
exit $((Errors))
#
# 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) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
#

#
# This test checks whether "typeset -m" correctly moves local variables
# into a global variable tree.
#
# This was reported as CR #6805792 ("XXXX"):
# -------- snip --------
# The following attempt to move a local node into an associative array
# fails like this:
# -- snip --
# typeset -C tree
# function f1
# {
#        nameref tr=$1
#
#        typeset -A tr.subtree
#
#        typeset -C node
#
#        node.one="hello"
#        node.two="world"
#
#        # move local note into the array
#        typeset -m tr.subtree["a_node"]=node
#
#        return 0
# }
# f1 tree
# printf "%B\n" tree
# print "ok"
# exit 0
# -- snip --
# The output looks like this:
# -- snip --
# $ ksh93
# varmovetest1.sh
# (
# (
# )
# ok
# -- snip --
# ... but AFAIK it should print:
# -- snip --
# (
#        typeset -A subtree=(
#                [a_node]=(
#                        one=hello
#                        two=world
#                )
#        )
# )
# ok
# -- snip --
# -------- snip --------
#

# test setup
function err_exit
{
	print -u2 -n "\t"
	print -u2 -r ${Command}[$1]: "${@:2}"
	(( Errors < 127 && Errors++ ))
}
alias err_exit='err_exit $LINENO'

set -o nounset
Command=${0##*/}
integer Errors=0


## test start
compound tree1 tree2

# add node to tree which uses "typeset -m" to move a local variable
# into tree1.subtree["a_node"]
function f1
{
	nameref tr=$1

	typeset -A tr.subtree

	compound node

	node.one="dummy1"
	node.two="dummy2"

	# We use the nameref's here since ast-ksh,2008-12-12 crashes
	# when this function returns because "nodeone" and "nodetwo"
	# still reference "node" which was renamed.
	# (note that "f1" must be first function and the first being
	# called, otherwise the crash will not occur)
	nameref nodeone=node.one
	nameref nodetwo=node.two
	nodeone="hello"
	nodetwo="world"

	# move local note into the array
	typeset -m tr.subtree["a_node"]=node

	return 0
}

# Alternative version which uses "nameref" instead of "typeset -m"
function f2
{
	nameref tr=$1

	typeset -A tr.subtree

	nameref node=tr.subtree["a_node"]

	node.one="hello"
	node.two="world"

	return 0
}

f1 tree1
f2 tree2

[[ "${tree1.subtree["a_node"].one}" == "hello" ]] || err_exit "Expected tree1.subtree[\"a_node\"].one == 'hello', got ${tree1.subtree["a_node"].one}"
[[ "${tree1.subtree["a_node"].two}" == "world" ]] || err_exit "Expected tree1.subtree[\"a_node\"].two == 'world', got ${tree1.subtree["a_node"].two}"
[[ "${tree1}" == "${tree2}" ]] || err_exit "tree1 and tree2 differ:"$'\n'"$(diff -u <( printf '%B\n' tree1 ) <( printf '%B\n' tree2 ) )"


# tests done
exit $((Errors))
#
# 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) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
#

#
# This test checks whether arithmetric operator '<character>
# is working
#
# This was reported as CR #6805794 ('[ku1] printf returns "invalid character constant" for $ printf "%d\n" "'<euro>"'):
# ------------ snip ------------
# There seems be a bug in how ast-ksh.2008-11-04's "printf" builtin
# handles multibyte characters. For example if I try this in the
# en_US.UTF-8 locale ("<euro>" needs to be replace with the EURO symbol):
# -- snip --
# $ printf "%d\n" "'<euro>"
# -ksh93: printf: warning: ': invalid character constant
# 226
# -- snip --
# AFAIK the correct behaviour was to return the numeric value of the
# <euro> symbol in this case (hexadecimal "20ac", decimal 8364), e.g.
# -- snip --
# $ printf "%d\n"
# "'<euro>"
# 8364
# -- snip --
# Frequency
#    Always
# Regression
#    No
# Steps to Reproduce
#    Enter this in an interractive shell:
# $ printf "%d\n" "'<euro>"
# Expected Result
#    -- snip --
# $ printf "%d\n"
# "'<euro>"
# 8364
# -- snip --
# Actual Result
#    -- snip --
# $ printf "%d\n" "'<euro>"
# -ksh93: printf: warning: ': invalid character constant
# 226
# -- snip --
# Error Message(s)
#    printf: warning: ': invalid character constant
# Test Case
#    printf "%d\n" "'<euro>"
# Workaround
#    None.
# ------------ snip ------------
#

# test setup
function err_exit
{
	print -u2 -n "\t"
	print -u2 -r ${Command}[$1]: "${@:2}"
	(( Errors < 127 && Errors++ ))
}
alias err_exit='err_exit $LINENO'

set -o nounset
Command=${0##*/}
integer Errors=0


# declare variables
typeset str

# test whether the locale uses an UTF-8 (-like) encoding and override it on demand
[[ "$(printf "\u[20ac]")" == $'\342\202\254' ]] || LC_ALL=en_US.UTF-8
if [[ "$(printf "\u[20ac]")" != $'\342\202\254' ]] ; then
	err_exit "Local overrride failed."
	exit $((Errors))
fi

# run test
str=$(print $'printf "%d\\\\n" "\'\342\202\254"' | source /dev/stdin)
[[ "${str}" == "8364" ]] || err_exit "expected 8364, got ${str}"


# tests done
exit $((Errors))
#
# 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) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
#

#
# This test checks whether arithmetric math correctly supports
# negative zero values
#
# This was reported as CR #6805795 ("[ku1] ksh93 does not differ between -0 and +0"):
# ------------ snip ------------
#  Original bug report was:
# ------ snip ------
# Is there a reason why ksh93 does not display the negative sign for the
# value zero ? For example if I have use the C99 function "copysign"
# (copies absolute value of operant a and sign of operant b) I get this
# for { a=5, b=-0 }:
# -- snip --
# $ ksh93 -c 'float x; (( x=copysign(5, -0) )) ; printf "%f\n"
# x'
# -5.000000
# -- snip --
# Now if I swap operands a and b I get this result:
# -- snip --
# $ ksh93 -c 'float x; (( x=copysign(0, -5) )) ; printf "%f\n" x'
# 0.000000
# -- snip --
# AFAIK this result should be "-0.000000" ... or not ?
# BTW: Parsing of "-0" doesn't seem to work either, e.g.
# -- snip --
# $ ksh93 -c 'float x a=-1 b=-0; (( x=copysign(a, b) )) ; printf "%f\n"
# x'
# 1.000000
# -- snip --
# ... while AFAIK it should be "-1.000000" since the 2nd operand of
# "copysign" defines the sign of the result.
# ------ snip ------
# ------------ snip ------------
#

# test setup
function err_exit
{
	print -u2 -n "\t"
	print -u2 -r ${Command}[$1]: "${@:2}"
	(( Errors < 127 && Errors++ ))
}
alias err_exit='err_exit $LINENO'

set -o nounset
Command=${0##*/}
integer Errors=0

typeset str

# test 1: test "copysign()" using constant values
str=$(
	set -o errexit

	print -- $(( copysign(0, -5) ))
	) || err_exit "test failed."
[[ "${str}" == "-0" ]] || err_exit "Expected copysign(0, -5) == -0, got ${str}"


# test 2: Same as test 1 but using variables for the values
str=$(
	set -o errexit

	float a
	float b
	float c

	a=0.
	b=-5.

	(( c=copysign(a, b) ))

	print -- "$c"
	) || err_exit "test failed."
[[ "${str}" == "-0" ]] || err_exit "Expected c == -0, got ${str}"


# test 3: test "signbit()"
str=$(
	set -o errexit

	float a

	a=-0.

	print -- $(( signbit(a) ))
	) || err_exit "test failed."
[[ "${str}" == "1" ]] || err_exit "Expected signbit(a, b) == 1, got ${str}"


# test 4: test "signbit()"
str=$(
	set -o errexit

	float a
	float c

	a=-0.

	(( c=signbit(a) ))

	print -- "$c"
	) || err_exit "test failed."
[[ "${str}" == "1" ]] || err_exit "Expected c == 1, got ${str}"


# test 5: test whether "typeset -X" (C99 "hexfloat") correctly recognizes
# negative zero assigned from a "float"
str=$(
	set -o errexit

	float a      # float
	typeset -X c # hexfloat

	a=-0.

	# copy value from "float" to "hexfloat"
	(( c=a ))

	print -- "$c"
	) || err_exit "test failed."
[[ "${str}" == -0x* ]] || err_exit "Expected c == -0x*, got ${str}"


# test 6: Reverse of test 5: Test whether "float" correctly recognizes
# a C99 "hexfloat" value
str=$(
	set -o errexit

	typeset -X a # hexfloat
	float c      # float

	a=-0x0.0000000000000000000000000000p+00

	# copy value from "hexfloat" to "float"
	(( c=a ))

	print -- "$c"
	) || err_exit "test failed."
[[ "${str}" == "-0" ]] || err_exit "Expected c == -0, got ${str}"


# tests done
exit $((Errors))
#
# 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) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
#

#
# This test checks whether ksh93 does unneccesaty |libc::getpwnam()|
# calls for "~(modifer)pattern"-style shell patterns
#
# This was reported as CR #6807179 ("ksh93 does unneccesary |libc::getpwnam()| lookups for ~(modifier) pattern patterns"):
# ------------ snip ------------
# ksh93 does unneccesary |libc::getpwnam()| lookups for
# ~(modifer)pattern patterns, e.g. [[ $foo == ~(E)hello.*world ]].
# The problem is that the shell ~(modifer)pattern is an extended
# pattern syntax which allows to specify a "modifer" to change
# the behaviour for "pattern". However the '~' at the beginning
# of this string is causing a tilde expansion (or better: It's
# filling an internal buffer as preparation for tilde expansion
# and this code calls |libc::getpwnam()|) which shouldn't be
# done in this case.
# [1]=For example the "modifer" allows to specifcy "perl",
# "fgrep", "grep", "egrep", "POSIX shell", "korn shell" and
# other types of pattern matching systems (or select stuff
# like archors, case-insensitive matching etc. etc.).
# ------------ snip ------------
#

# test setup
function err_exit
{
	print -u2 -n "\t"
	print -u2 -r ${Command}[$1]: "${@:2}"
	(( Errors < 127 && Errors++ ))
}
alias err_exit='err_exit $LINENO'

set -o nounset
Command=${0##*/}
integer Errors=0

typeset tmpfile

tmpfile="$(mktemp -t "sun_solaris_cr_6807179_shellpattern_uses_getpwnam.${PPID}.$$.XXXXXX")" || err_exit "Cannot create temporary file."
rm -f "${tmpfile}"


# test 1: Check if the shell uses |libc::getpwnam()| for pattern "~(Elr)wo.*ld"
truss -u :: -o "${tmpfile}" ${SHELL} -c '[[ ${hello} == ~(Elr)wo.*ld ]] ; true' || err_exit "truss returned failure=$?"
[[ "$( < "${tmpfile}")" != *getpwnam* ]] || err_exit "truss log reports the use of getpwnam() for pattern ~(Elr)wo.*ld"
rm "${tmpfile}" || err_exit "rm ${tmpfile} failed."


# test 2: Check if the shell uses |libc::getpwnam()| for pattern "~(Si)wo*ld"
truss -u :: -o "${tmpfile}" ${SHELL} -c '[[ ${hello} == ~(Si)wo*ld ]] ; true' || err_exit "truss returned failure=$?"
[[ "$( < "${tmpfile}")" != *getpwnam* ]] || err_exit "truss log reports the use of getpwnam() for pattern ~(Si)wo*ld"
rm "${tmpfile}" || err_exit "rm ${tmpfile} failed."


# test 3: Same as test 1 but uses ~root/ as pattern which will force the use of |libc::getpwnam()|
getent passwd root >/dev/null || err_exit "getent passwd root failed" # safeguard to make sure we get a warning if user root is missing

truss -u :: -o "${tmpfile}" ${SHELL} -c '[[ ${hello} == ~root/ ]] ; true' || err_exit "truss returned failure=$?"
[[ "$( < "${tmpfile}" )" == *getpwnam* ]] || err_exit "truss log reports the use of getpwnam() for pattern ~root/"
rm "${tmpfile}" || err_exit "rm ${tmpfile} failed."


# tests done
exit $((Errors))
#
# 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) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
#

#
# This test checks whether ksh93's builtin "cat" command properly
# supports the "-n" option.
#
# This was reported as CR #6835835 ('ksh93 "cat" builtin does not handle "-n" correctly'):
# ------------ snip ------------
# [Originally reported in
# http://mail.opensolaris.org/pipermail/ksh93-integration-discuss/2009-February/007050.html
# by Casper Dik]
# -- snip --
# I just noticed this in ksh93:
#  ksh93 -c 'yes "" | head -5|cat -n'
#     1
#     2
#     3
#     4
# (I used this for older shells when I want to a list of all integers from 1
# to a particular number)
# -- snip --
# Frequency
#   Always
# Regression
#   No
# Steps to Reproduce
#   Execute $ ksh93 -c 'yes "" | head -5|cat -n' #
# Expected Result
#     1
#     2
#     3
#     4
#     5
# Actual Result
#
#
#     1
#     2
#
#     3
#
#     4
# Error Message(s)
#   None.
# Test Case
#   See description.
# Workaround
#   Disable ksh93's builtin "cat" command either via using an absolute path
#   to the "cat" command (POSIX-style workaround) or using ksh93's
#   "builtin" command to remove "cat" from the list of builtin
#   commands (e.g. $ builtin -d /bin/cat /bin/cat #).
# ------------ snip ------------
#

# test setup
function err_exit
{
	print -u2 -n "\t"
	print -u2 -r ${Command}[$1]: "${@:2}"
	(( Errors < 127 && Errors++ ))
}
alias err_exit='err_exit $LINENO'

set -o nounset
Command=${0##*/}
integer Errors=0

#
# test 1: Compare output of various "cat -n" combinations
#
integer i
typeset expected_output
typeset out

expected_output=$( ${SHELL} -c 'for ((i=1 ; i <= 12 ; i++ )) ; do printf "%6d\t\n" i ; done' )

compound -a testcases=(
	# note: we have to add an extra /bin/cat at the end of the pipe to make
	# sure the "cat" builtin uses the correct buffering mode to trigger
	# the error and a "true" to make sure the "cat" command isn't the last command
	# of the shell
	( name="test1a" cmd='integer i ; builtin cat ; for ((i=1 ; i <= 12 ; i++ )) ; do print ; done | cat -n          | /bin/cat ; true' )
	# same as "test1a" but uses external "cat" command
	( name="test1b" cmd='integer i ;               for ((i=1 ; i <= 12 ; i++ )) ; do print ; done | /bin/cat -n | /bin/cat ; true' )

	# same as "test1a" but without the last /bin/cat in the pipe
	( name="test1c" cmd='integer i ; builtin cat ; for ((i=1 ; i <= 12 ; i++ )) ; do print ; done | cat -n ; true' )
	# same as "test1b" but without the last /bin/cat in the pipe
	( name="test1d" cmd='integer i ;               for ((i=1 ; i <= 12 ; i++ )) ; do print ; done | /bin/cat -n ; true' )
)

for testid in "${!testcases[@]}" ; do
	nameref tc=testcases[${testid}]

	out="$( ${SHELL} -o errexit -c "${tc.cmd}" )" || err_exit "${tc.name}: Shell failed"
	[[ "${expected_output}" == "${out}" ]] || err_exit "${tc.name}: Builtin output does not match expected output"

	out="$( ${SHELL} +o errexit -c "${tc.cmd}" )" || err_exit "${tc.name}: Shell failed"
	[[ "${expected_output}" == "${out}" ]] || err_exit "${tc.name}: Builtin output does not match expected output"
done


#
# test 2: Casper Dik's original testcase
# from http://mail.opensolaris.org/pipermail/ksh93-integration-discuss/2009-February/007050.html
#

cmp -s \
	<( ${SHELL} -c 'yes "" | head -5 | cat -n' ) \
	<( for ((i=1 ; i <= 5 ; i++ )) ; do printf "%6d\t\n" i ; done ) \
	|| err_exit 'yes "" | head -5 | cat -n does not match expected output.'


# tests done
exit $((Errors))
#
# 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) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
#

#
# This test checks whether ksh93 does not execute builtin command
# "foo" when referencing variable "foo" when the variable is not
# set (this applies to all builtin commands not bound to a
# specific PATH element, e.g. "test", "sleep", "print" etc.).
#
# This was reported as CR #6848486 ('"echo ${test}" with test
# undefined crashes the shell')
# ------------ snip ------------
# This is an odd one:
#
# $ ksh93 --version
#   version         sh (AT&T Research) 93t 2008-11-04
# $ ksh93
# jl138328@gir:~$ echo $test
#
# jl138328@gir:~$ echo ${test}
# Segmentation Fault (core dumped)
# ------------ snip ------------
#
# The bug originates from the ksh93 "type system" which allows
# an application to define it's own types in ksh93. In such cases
# the output of function "mytype.len" is used when type "mytype"
# has no member variable "len" (note it requires the use of
# ${foo} since the use of $foo does not allow "foo" to contain
# a dot in the variable name).
# The implementation in ast-ksh.2009-11-04 however does this
# for _all_ types of variables and not only for those which
# are a member of an application-defined type, therefore
# causing this bug.
#

# test setup
function err_exit
{
	print -u2 -n "\t"
	print -u2 -r ${Command}[$1]: "${@:2}"
	(( Errors < 127 && Errors++ ))
}
alias err_exit='err_exit $LINENO'

set -o nounset
Command=${0##*/}
integer Errors=0


# Test 1: Test whether the shell crashes when looking for an empty
# "shell" variable.
# (note: return code 78 was just picked randomly)
$SHELL -c 'unset test ; print ${test} ; exit 78' >/dev/null 2>&1
(( $? == 78 )) || err_exit "expected return code is 78, got $?"


# Test 2: Test whether the shell can reach a point (which prints
# "#mark") after the use of ${test} in the script.
out=$($SHELL -o errexit -c 'unset test ; print ${test} ; print "#mark"' 2>&1 ) || err_exit "Shell returned error code $?, expected 0."
[[ "$out" == $'\n#mark' ]] || err_exit "Expected output \$'\n#mark', got '${out}'"


# Test 3: Check whether the use of ${sleep} returns nothing
# (ast-ksh.2008-11-04 will return the usage string of the sleep
# builtin)
out=$($SHELL -o errexit -c 'print ${sleep} ; print "#mark"' 2>&1 ) || err_exit "Shell returned error code $?, expected 0."
[[ "$out" == $'\n#mark' ]] || err_exit "Expected output \$'\n#mark', got '${out}'"


# tests done
exit $((Errors))
#
# 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) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
#

#
# This test checks whether arithmetric math correctly
# converts a IEEE 754-2008 floating-point value to the C99 hexfloat format
# and back _without_ using digits.
#
# This was reported as CR #6855875 ("typeset -X x ; print $x # does not
# print sufficient digits to restore value"):
# ------------ snip ------------
# $ typeset -X varname # was added to ksh93 to get a reliable way
# (using the C99 "hexfloat" format (see printf(3c)'s "%a" format)) to
# serialise a IEEE754-2008 floating-point value to a string and later feed
# it back into a application _without_ loosing any precision (normal
# base10 floating-point values (e.g. used by $ typeset -E/-F-G #) cause
# rounding errors since IEEE754-2008 |long double| uses base2).
# However $ typeset -l -X x ; ... ; print $x # currently does not print
# sufficient number of digits to restore the full |long double| value as
# expected, instead some digits are missing, resulting in an unwanted
# rounding.
# Example:
# -- snip --
# $ ksh93 -c 'typeset -l -X y y_ascii; (( y=sin(90) )) ; y_ascii=$y ; (( y
# == y_ascii )) || print "no match,\n\t$(printf "%a\n" y)\n!=\n\t$(printf
# "%a\n" y_ascii)"'
# no match,
#         0x1.c9b9ee41cb8665c7890a136ace6bp-01
# !=
#         0x1.c9b9ee41cc000000000000000000p-01
# -- snip --
# Frequency
#    Always
# Regression
#    No
# Steps to Reproduce
#    [See description]
# Expected Result
#    [See description]
# Actual Result
#    [See description]
# Error Message(s)
#    -
# Test Case
#    typeset -l -X y y_ascii
# (( y=sin(90) ))
# y_ascii=$y # convert y to string and store it in "y_ascii"
# if (( y == y_ascii )) ; then
#     print "no match,\n\t$(printf "%a\n" y)\n!=\n\t$(printf "%a\n"
# y_ascii)"
# fi
# Workaround
#    1. Manually increase the number of digits via typeset
# -X<numdigits>
#     OR
# 2. Use $ printf "%a" varname #
# ------------ snip ------------
#

# test setup
function err_exit
{
	print -u2 -n "\t"
	print -u2 -r ${Command}[$1]: "${@:2}"
	(( Errors < 127 && Errors++ ))
}
alias err_exit='err_exit $LINENO'

set -o nounset
Command=${0##*/}
integer Errors=0


# declare variables
typeset		str
integer		i
float		x
float -a	test_values

typeset -l -X	y # hexfloat
typeset -l -E	y_restored1
typeset -l -F	y_restored2
typeset -l -X	y_restored3


# create array of test values
for (( x=-181. ; x < 361. ; x+=.1 )) ; do
	test_values+=( x )
done
test_values+=( 0 -0 +0 ) # (nan -nan inf -inf) are excluded since nan!=nan is always "true"


# run the tests
for (( i=0 ; i < ${#test_values[@]} ; i++ )) ; do
	(( y=sin(test_values[i]) ))

	# convert floating-point value to string (using the hexfloat format) and store it in "str"
	str="${y}"

	# convert it back (via string assignment)
	y_restored1="${str}"
	y_restored2="${str}"
	y_restored3="${str}"
	(( y == y_restored1 )) || err_exit "no match,"$'\n\t'"$(printf "%a\n" y)"$'\n'"!="$'\n\t'"$(printf "%a\n" y_restored1)"
	(( y == y_restored2 )) || err_exit "no match,"$'\n\t'"$(printf "%a\n" y)"$'\n'"!="$'\n\t'"$(printf "%a\n" y_restored2)"
	(( y == y_restored3 )) || err_exit "no match,"$'\n\t'"$(printf "%a\n" y)"$'\n'"!="$'\n\t'"$(printf "%a\n" y_restored3)"

	# convert it back (using arithmetric expression)
	(( y_restored1=str ))
	(( y_restored2=str ))
	(( y_restored3=str ))
	(( y == y_restored1 )) || err_exit "no match,"$'\n\t'"$(printf "%a\n" y)"$'\n'"!="$'\n\t'"$(printf "%a\n" y_restored1)"
	(( y == y_restored2 )) || err_exit "no match,"$'\n\t'"$(printf "%a\n" y)"$'\n'"!="$'\n\t'"$(printf "%a\n" y_restored2)"
	(( y == y_restored3 )) || err_exit "no match,"$'\n\t'"$(printf "%a\n" y)"$'\n'"!="$'\n\t'"$(printf "%a\n" y_restored3)"

	# we exit if we get more than 8 errors (126 would be the maximum)
	(( Errors > 8 )) && exit $((Errors))
done


# tests done
exit $((Errors))
#
# 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) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
#

#
# This test checks whether the Solaris kernel can directly execute compiled
# shell code.
#
# This was reported as CR #6862121 ("shbinexec kernel module defunct"):
# ------------ snip ------------
# [Originally reported by Sun Japan]
# The new shbinexec kernel module added in B106 is defunct, originally
# caused by my mismerge of the original development tree and later
# because the matching test module didn't test it correctly (April
# quickly discovered the problem but the issue drowned in the cleanup
# putbacks ).
# Frequency
#    Always
# Regression
#    No
# Steps to Reproduce
#    $ cat test1.sh
# print hello
# printf "args=%s\n" "$@"
# $ shcomp test1.sh test1
# # note: this MUST be bash since ksh93 has special support for compiled shell
# # scripts which causes the kernel module to be bypassed (that's why the tes
# # never worked)
# $ bash -c './test1 "a b" "c" "d"'
# Expected Result
#    hello
# args=a a1
# args=b
# args=c
# Actual Result
#    ./test1: line 1: a: not found
# Error Message(s)
#    ./test1: line 1: a: not found
# Test Case
#    See above.
# ------------ snip ------------
#

# test setup
function err_exit
{
	print -u2 -n "\t"
	print -u2 -r ${Command}[$1]: "${@:2}"
	(( Errors < 127 && Errors++ ))
}
alias err_exit='err_exit $LINENO'

set -o nounset
Command=${0##*/}
integer Errors=0

typeset ocwd
typeset tmpdir
typeset out

# create temporary test directory
ocwd="$PWD"
tmpdir="$(mktemp -t -d "test_sun_solaris_cr_6862121_shbinexec_kernel_module_defunct.XXXXXXXX")" || err_exit "Cannot create temporary directory"

cd "${tmpdir}" || { err_exit "cd ${tmpdir} failed." ; exit $((Errors)) ; }


# run tests
{
cat <<EOF
	print hello
	printf "args=%s\n" "\$@"
EOF
} >script1.sh

# Compile script (note we use the platform's /usr/bin/shcomp, _not_ ${SHCOMP})
/usr/bin/shcomp "script1.sh" "script1" || err_exit "shcomp failed with error=$?"

[[ -x "./script1" ]] || err_exit "Script script1 not executable"
out="$(/usr/bin/bash -c './script1 a b "c d"' 2>&1 )" || err_exit "Compiled script failed to execute, error=$?"
[[ "${out}" == $'hello\nargs=a\nargs=b\nargs=c d' ]] || err_exit "Expected xxx, got $(printf "%q\n" "$out")"

# cleanup
rm "script1" "script1.sh"
cd "${ocwd}"
rmdir "${tmpdir}" || err_exit "Cannot remove temporary directory ${tmpdir}".

# tests done
exit $((Errors))
#
# 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) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
#

#
# This test checks whether a background process called in a subshell can
# cause it to wait for the child process instead of exiting.
#
# This was reported as CR #6881017 ("Subshell doesn't exit, holds pipe
# open preventing callers from exiting"):
# ------------ snip ------------
# The following scenario hangs with snv_122, 100% reproducible:
#
# Create a script hangit:
# -----
# #!/bin/ksh
# ( sleep 100000 </dev/null >/dev/null 2>&1 & )
# exit 0
# -----
#
# Run the following command:
# hangit | tee -a /tmp/log
#
# The hang can be eliminated either by removing the "exit 0" line (?!?), or by
# redirecting the subshell output to /dev/null.
#
# This is pretty nasty. I've whittled it down to this simple case but am seeing
# it in a much more subtle and complex environment where there are several
# intermediate calling scripts which have exited and eventually the parent pipes
# the output and hangs on the open pipe. It was hard to track down.
# ------------ snip ------------
#

# test setup
function err_exit
{
	print -u2 -n "\t"
	print -u2 -r ${Command}[$1]: "${@:2}"
	(( Errors < 127 && Errors++ ))
}
alias err_exit='err_exit $LINENO'

set -o nounset
Command=${0##*/}
integer Errors=0

float tstart tstop tdiff

# run test with 10 second timeout
(( tstart=SECONDS ))
$SHELL -c '( sleep 10 </dev/null >/dev/null 2>&1 & ) ; exit 0' | cat >/dev/null
(( tstop=SECONDS ))

# we remove two seconds below to make sure we don't run into issues
# with smaller xntpd adjustments
(( tdiff=tstop-tstart ))
(( tdiff < (10.-2.) )) || err_exit "test run needed ${tdiff} seconds to complete (instead of < 8.)"

# tests done
exit $((Errors))
#
# 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) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
#

#
# This test checks whether the return code of a child process
# is reported properly.
#
# This was reported as CR #6887363 ("Korn shell 93 sometimes
# mishandles return value of its child process"):
# ------------ snip ------------
# Following construction sometimes ends with wrong return value.
#
#      56 	 echo $op | grep rand 2>&1 >/dev/null
#      57 	 if [ $? = 0 ]; then
#      58 		randseq="rand${SEED}"
#      59 	 else
#      60 		randseq="seq"
#      61 	 fi
#
# Sometimes, the given result is "rand..." even when there is
# no "rand" word in $op. This can be demonstrated with
# TSufs/SnapShots/Func test case which excercises shown code
# quite often.
#
# As it happens only sometimes, I suppose there is an
# race-condition in handling return value from a child process.
# ------------ snip ------------
#

# test setup
function err_exit
{
	print -u2 -n "\t"
	print -u2 -r ${Command}[$1]: "${@:2}"
	(( Errors < 127 && Errors++ ))
}
alias err_exit='err_exit $LINENO'

set -o nounset
Command=${0##*/}
integer Errors=0

typeset ocwd
typeset tmpdir
typeset out

# create temporary test directory
ocwd="$PWD"
tmpdir="$(mktemp -t -d "test_sun_solaris_cr_6887363_shell_sometimes_mishandles_return_value_of_its_child_process.XXXXXXXX")" || err_exit "Cannot create temporary directory"

cd "${tmpdir}" || { err_exit "cd ${tmpdir} failed." ; exit $((Errors)) ; }


# run tests

# print test case from bug that ksh93 can read this script via stdin
function cat_test
{
cat <<EOF
#!/bin/sh
#
# Test derived from Sun's SnapShots Functional Suite
#

export PATH=/usr/xpg6/bin:/usr/xpg4/bin:/bin:/usr/bin

# WARNING: make sure "expr" and "grep" are _external_ commands in this test

# start test
_pcnt=0

PASS(){
	_pcnt=\`/bin/expr \$_pcnt + 1\`
	true
}

doblockstamper() {
	output=\`/bin/sleep .01\`
	_status=\$?

	PASS "Here I am"
}

lotsaFiles() {
	OPS="read-seq read-rand syncread-seq syncread-seq"
	echo \$OPS
	for op in \$OPS; do
	 echo \$op
	 echo \$op | /bin/grep rand 2>&1 >/dev/null
	 status=\$?
	 if [ \$status = 0 ]; then
		randseq="rand"
		phrase="read-rand"
	 else
		randseq="seq"
		phrase="read-seq"
	 fi
	 retcode=\$status

	 echo \$op | /bin/grep sync 2>&1 >/dev/null
	 status=\$?
	 if [ \$status = 0 ]; then
		syncasync="sync"
		phrase="sync\$phrase"
	 else
		syncasync="async"
	 fi
	 retcode=\${status}-\${retcode}

	if [ "\$op" != "\$phrase" ]; then
		echo "Bad mode: \$op != \$phrase (\$retcode)"
		exit 2
	fi

	 for sz in 1 2 3 4; do
	   for type in 1 2 3 4; do
		PASS "Something"
		doblockstamper &
	   done
	   wait # Let a few finish
	 done
	done

	wait    # Make sure everyone got done

	PASS "lotsafiles \$1 \$fill"
}

cycle=0
while [ cycle -lt 24 ]; do
	cycle=\`/bin/expr \$cycle + 1\`

	lotsaFiles write
	lotsaFiles write
	lotsaFiles write

	lotsaFiles read
	lotsaFiles read
	lotsaFiles read

	PASS "Cycle"
done
exit 0
EOF
}

# FIXME: we reset the VMALLOC_OPTIONS (and the depreciated VMDEBUG (for now)) variable for the run to avoid
# that the test may run for hours. This may require re-investigation why this happens.
out="$(unset VMALLOC_OPTIONS VMDEBUG ; cat_test | ${SHELL} 2>&1)" || err_exit "Unexpected exit code $?"
[[ "${out}" != "" ]] || err_exit "No output from test"

# filter output and check it
out2="$(/bin/egrep -v '^((read-seq|read-rand|syncread-seq|syncread-seq)[[:space:][:blank:]]*)*$' <<<"${out}")"
[[ "${out2}" == "" ]] || err_exit "Unexpected output '${out2}'"


cd "${ocwd}"
rmdir "${tmpdir}" || err_exit "Cannot remove temporary directory ${tmpdir}".

# tests done
exit $((Errors))
#
# 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) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
#

#
# This test checks whether "wc" builtin counts the number of bytes
# and multibyte characters in different locales correctly.
#
# This was reported as CR #6904557 ("wc no longer counts number of
# bytes correctly"):
# ------------ snip ------------
# wc no longer count bytes.
#
# $ echo $LANG
# en_US.UTF-8
# $ ls -l mb.utf8
# -rw-r--r--   1 nakanon  staff          7 Nov  2 14:06 mb.utf8
# $ wc mb.utf8
#        1       1       4 mb.utf8
# $
#
# mb.utf8 is attached.
#
# Man page says:
#
#      If no option is  specified,  the  default  is  -lwc  (counts
#      lines, words, and bytes.)
#
# SUS says:
# http://www.opengroup.org/onlinepubs/000095399/utilities/wc.html
#
# By default, the standard output shall contain an entry for each
# input file of the form:
#
# "%d %d %d %s\n", <newlines>, <words>, <bytes>, <file>
#
# If the -m option is specified, the number of characters shall
# replace the <bytes> field in this format.
# ------------ snip ------------
#

# test setup
function err_exit
{
	print -u2 -n "\t"
	print -u2 -r ${Command}[$1]: "${@:2}"
	(( Errors < 127 && Errors++ ))
}
alias err_exit='err_exit $LINENO'

set -o nounset
Command=${0##*/}
integer Errors=0

typeset ocwd
typeset tmpdir
typeset out

# create temporary test directory
ocwd="$PWD"
tmpdir="$(mktemp -t -d "test_sun_solaris_cr_6904557_wc_no_longer_counts_number_of_bytes_correctly.XXXXXXXX")" || err_exit "Cannot create temporary directory"

cd "${tmpdir}" || { err_exit "cd ${tmpdir} failed." ; exit $((Errors)) ; }


# run tests

function test1
{
	typeset wc_cmd="$1"
	typeset testid
	typeset out
	typeset testname
	compound saved_locale

	# save locale information
	[[ -v LC_ALL	]] && saved_locale.LC_ALL="${LC_ALL}"
	[[ -v LC_CTYPE	]] && saved_locale.LC_CTYPE="${LC_CTYPE}"
	[[ -v LANG	]] && saved_locale.LANG="${LANG}"

	compound -r -a testcases=(
		(
			typeset name="unicode_plain"
			typeset locale="<unicode>"
			typeset input_format='\xc3\xa1\xc3\xa2\xc3\xa3\x0a'
			typeset output_pattern='~(Elr)[[:space:][:blank:]]*1[[:space:][:blank:]]*1[[:space:][:blank:]]*7'
			typeset -a wc_args=( )
		)
		(
			typeset name="unicode_clw"
			typeset locale="<unicode>"
			typeset input_format='\xc3\xa1\xc3\xa2\xc3\xa3\x0a'
			typeset output_pattern='~(Elr)[[:space:][:blank:]]*1[[:space:][:blank:]]*1[[:space:][:blank:]]*7'
			typeset -a wc_args=( "-c" "-l" "-w" )
		)
		(
			typeset name="unicode_widechars_lines_words"
			typeset locale="<unicode>"
			typeset input_format='\xc3\xa1\xc3\xa2\xc3\xa3\x0a'
			typeset output_pattern='~(Elr)[[:space:][:blank:]]*1[[:space:][:blank:]]*1[[:space:][:blank:]]*4'
			typeset -a wc_args=( "-C" "-l" "-w" )
		)
		(
			typeset name="ja_JP.eucJP_plain"
			typeset locale="ja_JP.eucJP"
			typeset input_format='\x74\x32\xa1\xf7\x66\x31\x0a'
			typeset output_pattern='~(Elr)[[:space:][:blank:]]*1[[:space:][:blank:]]*1[[:space:][:blank:]]*7'
			typeset -a wc_args=( )
		)
		(
			typeset name="ja_JP.eucJP_widechars_lines_words"
			typeset locale="ja_JP.eucJP"
			typeset input_format='\x74\x32\xa1\xf7\x66\x31\x0a'
			typeset output_pattern='~(Elr)[[:space:][:blank:]]*1[[:space:][:blank:]]*1[[:space:][:blank:]]*6'
			typeset -a wc_args=( "-C" "-l" "-w" )
		)
	)

	for testid in "${!testcases[@]}" ; do
        	nameref tc=testcases[${testid}]
		testname="${wc_cmd}/${tc.name}"

		if [[ "${tc.locale}" == "<unicode>" ]] ; then
			if [[ "$LC_ALL" != *.UTF-8 ]] ; then
				export LC_ALL='en_US.UTF-8'
			fi
		else
			export LC_ALL="${tc.locale}"
		fi

		out="$(printf "${tc.input_format}" | ${SHELL} -c "${wc_cmd} \"\$@\"" dummy "${tc.wc_args[@]}" 2>&1)" || err_exit "${testname}: Command returned exit code $?"
		[[ "${out}" == ${tc.output_pattern} ]] || err_exit "${testname}: Expected match for $(printf "%q\n" "${tc.output_pattern}"), got $(printf "%q\n" "${out}")"

		# restore locale settings
		[[ -v saved_locale.LC_ALL	]] && LC_ALL="${saved_locale.LC_ALL}" || unset LC_ALL
		[[ -v saved_locale.LC_CTYPE	]] && LC_CTYPE="${saved_locale.LC_CTYPE}" || unset LC_CTYPE
		[[ -v saved_locale.LANG		]] && LANG="${saved_locale.LANG}" || unset LANG
	done

	return 0
}

#for cmd in "wc" "/usr/bin/wc" ; do
for cmd in "wc" ; do
	test1 "${cmd}"
done


cd "${ocwd}"
rmdir "${tmpdir}" || err_exit "Cannot remove temporary directory ${tmpdir}".

# tests done
exit $((Errors))
#
# 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) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
#

#
# This test checks whether the AST "cut" utility's "-d" option
# works with multibyte characters
#
# This was reported as CR #6904575 ("cut -d with multibyte character no longer works"):
# ------------ snip ------------
# cut -d with multibyte char no longer work correctly.
#
# $ echo $LANG
# ja
# $ od -tx1 mb.eucjp
# 0000000 a4 a2 a4 a4 a4 a4 a4 a6 a4 a8 0a
# 0000013
# $ od -tx1 delim
# 0000000 a4 a4 0a
# 0000003
# $ wc -m mb.eucjp
#        6 mb.eucjp
#
# It has 5 characters (2byte each).
#
# $ /usr/bin/cut -d `cat delim` -f1 mb.eucjp | od -tx1
# 0000000 0a
# 0000001
#
# correct output is
#
# 0000000 a4 a2 0a
# 0000003
#
# files are attached.
# ------------ snip ------------
#

# test setup
function err_exit
{
	print -u2 -n "\t"
	print -u2 -r ${Command}[$1]: "${@:2}"
	(( Errors < 127 && Errors++ ))
}
alias err_exit='err_exit $LINENO'

set -o nounset
Command=${0##*/}
integer Errors=0

typeset ocwd
typeset tmpdir
typeset out

# create temporary test directory
ocwd="$PWD"
tmpdir="$(mktemp -t -d "test_sun_solaris_cr_6904575_cut_-d_with_multibyte_character_no_longer_works.XXXXXXXX")" || err_exit "Cannot create temporary directory"

cd "${tmpdir}" || { err_exit "cd ${tmpdir} failed." ; exit $((Errors)) ; }


# run tests


function test1
{
	typeset cut_cmd="$1"
	typeset testid
	typeset out
	typeset testname
	compound saved_locale

	# save locale information
	[[ -v LC_ALL	]] && saved_locale.LC_ALL="${LC_ALL}"
	[[ -v LC_CTYPE	]] && saved_locale.LC_CTYPE="${LC_CTYPE}"
	[[ -v LANG	]] && saved_locale.LANG="${LANG}"

	compound -r -a testcases=(
		(
			typeset name="ascii_plain"
			typeset locale="C"
			typeset input_format='abcdefg'
			typeset -a cut_args_format=( "-f1" "-d" "e" )
			typeset output_format='abcd'
		)
		(
			typeset name="unicode_plain"
			typeset locale="<unicode>"
			typeset input_format='abcd\u[20ac]fg'
			typeset -a cut_args_format=( '-f1' '-d' '\u[20ac]' )
			typeset output_format='abcd'
		)
		(
			typeset name="unicode_plain2"
			typeset locale="<unicode>"
			typeset input_format='abcd\u[20ac]fg'
			typeset -a cut_args_format=( '-f1' '-d' 'f' )
			typeset output_format='abcd\u[20ac]'
		)
	)

	for testid in "${!testcases[@]}" ; do
        	nameref tc=testcases[${testid}]
		testname="${cut_cmd}/${tc.name}"

		if [[ "${tc.locale}" == "<unicode>" ]] ; then
			if [[ ! -v LC_ALL || $LC_ALL != .*.UTF-8 ]]; then
				export LC_ALL='en_US.UTF-8'
			fi
		else
			export LC_ALL="${tc.locale}"
		fi

		# build "cut_args" array with multibyte characters in the current locale
		typeset -a cut_args
		integer arg_index
		for arg_index in "${!tc.cut_args_format[@]}" ; do
			cut_args+=( "$( printf -- "${tc.cut_args_format[arg_index]}" )" )
		done

		typeset output_format="$( printf -- "${tc.output_format}" )"

		#printf "args=|%q|\n" "${cut_args[@]}"

		out="$(printf "${tc.input_format}" | ${SHELL} -c "${cut_cmd} \"\$@\"" dummy "${cut_args[@]}" 2>&1)" || err_exit "${testname}: Command returned exit code $?"
		[[ "${out}" == ${output_format} ]] || err_exit "${testname}: Expected match for $(printf "%q\n" "${output_format}"), got $(printf "%q\n" "${out}")"

		# cleanup and restore locale settings
		unset cut_args arg_index
		[[ -v saved_locale.LC_ALL	]] && LC_ALL="${saved_locale.LC_ALL}" || unset LC_ALL
		[[ -v saved_locale.LC_CTYPE	]] && LC_CTYPE="${saved_locale.LC_CTYPE}" || unset LC_CTYPE
		[[ -v saved_locale.LANG		]] && LANG="${saved_locale.LANG}" || unset LANG
	done

	return 0
}


function test2
{
	typeset cutcmd=$1
	typeset testname="${cutcmd}"
	typeset out

	# create files
	printf "\xa4\xa2\xa4\xa4\xa4\xa4\xa4\xa6\xa4\xa8\x0a" >"mb.eucjp"
	printf "\xa4\xa4\x0a" >"delim"

	# run test
	out=$( LC_ALL=ja_JP.eucJP ${SHELL} -o pipefail -o errexit -c '$1 -d $(cat delim) -f1 "mb.eucjp" | od -tx1' dummy "${cutcmd}" 2>&1 ) || err_exit "${testname}: Test failed with exit code $?"
	[[ "${out}" == $'0000000 a4 a2 0a\n0000003' ]] || err_exit "${testname}: Expected \$'0000000 a4 a2 0a\n0000003', got $(printf "%q\n" "${out}")"

	# cleanup
	rm "mb.eucjp" "delim"

	return 0
}

#for cmd in "/usr/bin/cut" "cut" ; do
for cmd in "cut" ; do
	test1 "${cmd}"
	test2 "${cmd}"
done



cd "${ocwd}"
rmdir "${tmpdir}" || err_exit "Cannot remove temporary directory ${tmpdir}".

# tests done
exit $((Errors))
#
# 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) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
#

#
# This test checks whether the AST "join" utility works with
# multibyte characters as seperator.
#
# This was reported as CR #6904878 ("join -t no longer works with multibyte char separator"):
# ------------ snip ------------
# join doesn't handle multibyte separator correctly.
#
# $ echo $LANG
# ja
# $ od -tx1 input1
# 0000000 66 31 a1 f7 66 32 0a
# 0000007
# $ od -tx1 input2
# 0000000 74 32 a1 f7 66 31 0a
# 0000007
# # 0xa1 0xf7 in the file is multibyte character.
# $ od -tx1 delim
# 0000000 a1 f7 0a
# 0000003
#
# $ /usr/bin/join -j1 1 -j2 2 -o 1.1 -t `cat delim` input1 input2
# $
#
# It should output "f1".
#
# files are attached.
# ------------ snip ------------
#

# test setup
function err_exit
{
	print -u2 -n "\t"
	print -u2 -r ${Command}[$1]: "${@:2}"
	(( Errors < 127 && Errors++ ))
}
alias err_exit='err_exit $LINENO'

set -o nounset
Command=${0##*/}
integer Errors=0

typeset ocwd
typeset tmpdir
typeset out

# create temporary test directory
ocwd="$PWD"
tmpdir="$(mktemp -t -d "test_sun_solaris_cr_6904878_join_-t_no_longer_works_with_multibyte_char_separator.XXXXXXXX")" || err_exit "Cannot create temporary directory"

cd "${tmpdir}" || { err_exit "cd ${tmpdir} failed." ; exit $((Errors)) ; }


# run tests


function test1
{
	typeset join_cmd="$1"
	typeset testid
	typeset out
	typeset testname
	compound saved_locale

	# save locale information
	[[ -v LC_ALL	]] && saved_locale.LC_ALL="${LC_ALL}"
	[[ -v LC_CTYPE	]] && saved_locale.LC_CTYPE="${LC_CTYPE}"
	[[ -v LANG	]] && saved_locale.LANG="${LANG}"

	compound -r -a testcases=(
		(
			typeset name="ascii_simple"
			typeset locale="C"
			typeset input1_format="fish 81 91\n"
			typeset input2_format="fish B A\n"
			typeset -a join_args_format=( "input1" "input2" )
			typeset output_format="fish 81 91 B A"
		)
		(
			typeset name="ja_JP.eucJP_multibyte_delimiter"
			typeset locale="ja_JP.eucJP"
			typeset input1_format="\x66\x31\xa1\xf7\x66\x32\x0a"
			typeset input2_format="\x74\x32\xa1\xf7\x66\x31\x0a"
			typeset -a join_args_format=( "-j1" "1" "-j2" "2" "-o" "1.1" "-t" "\xa1\xf7" "input1" "input2" )
			typeset output_format="f1"
		)
	)

	for testid in "${!testcases[@]}" ; do
        	nameref tc=testcases[${testid}]
		testname="${join_cmd}/${tc.name}"

		if [[ "${tc.locale}" == "<unicode>" ]] ; then
			if [[ "$LC_ALL" != *.UTF-8 ]] ; then
				export LC_ALL='en_US.UTF-8'
			fi
		else
			export LC_ALL="${tc.locale}"
		fi

		# build "join_args" array with multibyte characters in the current locale
		typeset -a join_args
		integer arg_index
		for arg_index in "${!tc.join_args_format[@]}" ; do
			join_args+=( "$( printf -- "${tc.join_args_format[arg_index]}" )" )
		done

		typeset output_format="$( printf -- "${tc.output_format}" )"

		#printf "args=|%q|\n" "${join_args[@]}"

		printf "${tc.input1_format}" >"input1"
		printf "${tc.input2_format}" >"input2"

		out="$(${SHELL} -c "${join_cmd} \"\$@\"" dummy "${join_args[@]}" 2>&1)" || err_exit "${testname}: Command returned exit code $?"
		[[ "${out}" == ${output_format} ]] || err_exit "${testname}: Expected match for $(printf "%q\n" "${output_format}"), got $(printf "%q\n" "${out}")"

		rm "input1" "input2"

		# cleanup and restore locale settings
		unset join_args arg_index
		[[ -v saved_locale.LC_ALL	]] && LC_ALL="${saved_locale.LC_ALL}" || unset LC_ALL
		[[ -v saved_locale.LC_CTYPE	]] && LC_CTYPE="${saved_locale.LC_CTYPE}" || unset LC_CTYPE
		[[ -v saved_locale.LANG		]] && LANG="${saved_locale.LANG}" || unset LANG
	done

	return 0
}


function test2
{
	typeset joincmd=$1
	typeset testname="${joincmd}"
	typeset out

	# create files
	printf "\x66\x31\xa1\xf7\x66\x32\x0a" >"input1"
	printf "\x74\x32\xa1\xf7\x66\x31\x0a" >"input2"
	printf "\xa1\xf7\x0a" >"delim"

	# run test
	out=$( LC_ALL=ja_JP.eucJP ${SHELL} -o pipefail -o errexit -c '$1 -j1 1 -j2 2 -o 1.1 -t $(cat delim) input1 input2' dummy "${joincmd}" 2>&1 ) || err_exit "${testname}: Test failed with exit code $?"
	[[ "${out}" == 'f1' ]] || err_exit "${testname}: Expected 'f1', got $(printf "%q\n" "${out}")"

	# cleanup
	rm "input1" "input2" "delim"

	return 0
}

#for cmd in "/usr/bin/join" "join" ; do
for cmd in "join" ; do
	test1 "${cmd}"
	test2 "${cmd}"
done



cd "${ocwd}"
rmdir "${tmpdir}" || err_exit "Cannot remove temporary directory ${tmpdir}".

# tests done
exit $((Errors))
#
# 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) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
#

#
# This test checks whether the EXIT trap is called correctly in subshells
#
# This was reported as CR #6907460 ("EXIT trap handlers are sometimes executed twice"):
# ------------ snip ------------
# During SST testing of snv_128(RE) we found out that ksh93 executes EXIT
# trap handlers twice under some circumstances.
#
# Here is a test script:
# ---
# #!/bin/ksh93 -x
#
# function A
# {
#         set -x
#         trap "print TRAP A >>log" EXIT
#         print >&2
# }
#
# function B
# {
#         set -x
#         trap "print TRAP B >>log" EXIT
#         A
# }
#
# rm -f log
# x=$(B)
# ---
#
# It produces the following output on snv_128:
# ---
# + rm -f log
# + B
# + trap 'print TRAP B >>log' EXIT
# + A
# + trap 'print TRAP A >>log' EXIT
# + print
# + + print TRAP A
# 1>& 2
# + 1>> log
# + print TRAP B
#
# + 1>> log
# + print TRAP A
# + 1>> log
# + print TRAP B
# + 1>> log
# + x=''
# ---
#
# The log file then contains:
# TRAP A
# TRAP B
# TRAP A
# TRAP B
#
# However, the expected log would be:
# TRAP A
# TRAP B
#
# When the "x=$(B)" line is changed to "B", the log is correct:
# TRAP A
# TRAP B
# ------------ snip ------------
#

# test setup
function err_exit
{
	print -u2 -n "\t"
	print -u2 -r ${Command}[$1]: "${@:2}"
	(( Errors < 127 && Errors++ ))
}
alias err_exit='err_exit $LINENO'

set -o nounset
Command=${0##*/}
integer Errors=0

typeset ocwd
typeset tmpdir
typeset out

# create temporary test directory
ocwd="$PWD"
tmpdir="$(mktemp -t -d "test_sun_solaris_cr_6907460_EXIT_trap_handlers_are_sometimes_executed_twice.XXXXXXXX")" || err_exit "Cannot create temporary directory"

cd "${tmpdir}" || { err_exit "cd ${tmpdir} failed." ; exit $((Errors)) ; }


# run tests

# test 1: Run test with some variations
compound vari
typeset testname

for vari.shell_options in \
	"" \
	"-o xtrace" \
	"-o errexit" \
	"-o errexit -o xtrace" ; do
	for vari.xtrace1 in \
		"" \
		"set -x" ; do
		for vari.xtrace2 in \
			"" \
			"set -x" ; do
			for vari.func_A_end in \
				"" \
				"print >&2" \
				"return 0" \
				"print >&2 ; return 0" ; do
				for vari.subshell in \
					$'x=$(B)' \
					$'x=$( ( B ) )' \
					$'x=${ B ; }' \
					$'x=${ ( B ) ; }' \
					$'( x=$(B) )' \
					$'( x=$( ( B ) ) )' \
					$'( x=${ B ; } )' \
					$'( x=${ ( B ) ; } )' ; do
					testname="$( printf "test |%#B|\n" vari )"

cat >"testscript.sh" <<EOF
		function A
		{
			${vari.xtrace1}
			trap "print TRAP A >>log" EXIT
			${vari.func_A_end}
		}

		function B
		{
			${vari.xtrace2}
			trap "print TRAP B >>log" EXIT
			A
		}

		rm -f log
		${vari.subshell}
EOF
					${SHELL} ${vari.shell_options} "testscript.sh" >/dev/null 2>&1 || err_exit "${testname}: Unexpected error code $?"
					rm "testscript.sh"

					if [[ -f "log" ]] ; then
						out="$( < log )"
						rm "log"
					else
						err_exit "${testname}: File 'log' not found."
					fi
					[[ "${out}" == $'TRAP A\nTRAP B' ]] || err_exit "${testname}: Expected \$'TRAP A\nTRAP B', got $(printf "%q\n" "${out}")"
				done
			done
		done
	done
done



# test 2: This is the unmodified test from the bugster bug report
(
cat <<EOF
	function A
	{
       		set -x
        	trap "print TRAP A >>log" EXIT
        	print >&2
	}

	function B
	{
		set -x
		trap "print TRAP B >>log" EXIT
		A
	}

	rm -f log
	x=\$(B)
EOF
) | ${SHELL} >/dev/null 2>&1 || err_exit "Unexpected error code $?"

if [[ -f "log" ]] ; then
	out="$( < log )"
	rm "log"
else
	err_exit "File 'log' not found."
fi
[[ "${out}" == $'TRAP A\nTRAP B' ]] || err_exit "Expected \$'TRAP A\nTRAP B', got $(printf "%q\n" "${out}")"


cd "${ocwd}"
rmdir "${tmpdir}" || err_exit "Cannot remove temporary directory ${tmpdir}".

# tests done
exit $((Errors))
#
# 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.
#

#
# <short summary>
#
# This was reported as CR #xxxxxxxx ("<title>"):
# ------------ snip ------------
# <description>
# ------------ snip ------------
#

# test setup
function err_exit
{
	print -u2 -n "\t"
	print -u2 -r ${Command}[$1]: "${@:2}"
	(( Errors < 127 && Errors++ ))
}
alias err_exit='err_exit $LINENO'

set -o nounset
Command=${0##*/}
integer Errors=0

typeset ocwd
typeset tmpdir
typeset out

# create temporary test directory
ocwd="$PWD"
tmpdir="$(mktemp -t -d "test_<description>.XXXXXXXX")" || err_exit "Cannot create temporary directory"

cd "${tmpdir}" || { err_exit "cd ${tmpdir} failed." ; exit $((Errors)) ; }


# run tests


cd "${ocwd}"
rmdir "${tmpdir}" || err_exit "Cannot remove temporary directory ${tmpdir}".

# tests done
exit $((Errors))
#
# 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) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
#

#
# sun_solaris_getconf.sh - test the ksh93 getconf builtin for compatibility
# with /usr/bin/getconf
#

# test setup
function err_exit
{
	print -u2 -n "\t"
	print -u2 -r ${Command}[$1]: "${@:2}"
	(( Errors < 127 && Errors++ ))
}
alias err_exit='err_exit $LINENO'

set -o nounset
Command=${0##*/}
integer Errors=0


# setup
integer mismatch     # counts mismatches between builtin and external command
integer getconf_keys # counts tests (paranoid check to make sure the test loop works)
export PATH=/usr/bin:/bin

# prechecks
[[ ! -f "/bin/getconf" ]] && err_exit '/bin/getconf not found.'
[[ ! -x "/bin/getconf" ]] && err_exit '/bin/getconf not executable.'

# Define test functions and store them in a string for repeated usagae
# (we can't use "functions" (alias "typeset -f") since this does not
# work in compiled shell scripts)
typeset -r getconf_test_functions="$(
cat <<EOF
function err_exit
{
	print -u2 -n "\t"
	print -u2 -r \${Command}[\$1]: "\${@:2}"
	(( Errors++ ))
}
alias err_exit='err_exit \$LINENO'
Command=\${0##*/}
integer Errors=0
# compare builtin getconf output with /usr/bin/getconf
function compare_normal
{
    mismach=0 getconf_keys=0
    /usr/bin/getconf -a |
        while read i ; do
            (( getconf_keys++ ))
            t="\${i%:*}"

            a="\$(getconf          "\$t" 2>/dev/null)"
            b="\$(/usr/bin/getconf "\$t" 2>/dev/null)"

            if [[ "\$a" != "\$b" ]] ; then
                print -u2 "getconf/normal built mismatch: |\$t|:|\$a| != |\$b|"
                (( mismatch++ ))
            fi
        done
}

# compare builtin getconf output with /usr/bin/getconf while passing a path argument
function compare_path
{
    mismach=0 getconf_keys=0
    /usr/bin/getconf -a |
        while read i ; do
            (( getconf_keys++ ))
            t="\${i%:*}"

            a="\$(getconf          "\$t" "/tmp" 2>/dev/null)"
            b="\$(/usr/bin/getconf "\$t" "/tmp" 2>/dev/null)"

            if [[ "\$a" != "\$b" ]] ; then
                print -u2 "getconf/path built mismatch: |\$t|:|\$a| != |\$b|"
                (( mismatch++ ))
            fi
        done
}
EOF
)"

print -r -- "$getconf_test_functions" | source /dev/stdin

# future versions of this test should test the following ${PATH}s, too:
# "/usr/xpg6/bin:/usr/xpg4/bin:/bin:/usr/bin" \
#"/usr/xpg4/bin:/bin:/usr/bin" \
for i in \
    "/usr/bin:/bin" \
    "/bin:/usr/bin"
do
    export PATH="${i}"

    ## test whether the getconf builtin is available
    if [[ "$(builtin | fgrep "/bin/getconf")" == "" ]] ; then
        err_exit '/bin/getconf not found in the list of builtins.'
    fi


    ## compare "getconf -a" output
    if [[ "$(getconf -a)" != "$(/usr/bin/getconf -a)" ]] ; then
        err_exit 'getconf -a output mismatch.'
    fi


    ## check for a key which is only supported by the AST builtin version of getconf:
    if [[ "$(getconf LIBPREFIX)" != "lib" ]] ; then
        err_exit 'getconf LIBPREFIX did not return "lib".'
    fi


    ## run normal test
    compare_normal
    (( getconf_keys == 0 )) && err_exit "getconf/normal not working (PATH=${PATH})."
    (( mismatch     >  0 )) && err_exit "getconf/normal test found ${mismatch} differences (PATH=${PATH})."

    # run the same test in a seperate shell
    # (we explicitly test this because ast-ksh.2007-01-11 picks up /usr/xpg6/bin/getconf
    # if /usr/xpg6/bin/ comes in ${PATH} before /usr/bin (this happens only of ${PATH}
    # contains /usr/xpg6/bin before ksh93 is started)).
    ${SHELL} -c "integer mismatch ; \
        integer getconf_keys ; \
        ${getconf_test_functions} ; \
        compare_normal ;
        (( getconf_keys == 0 )) && err_exit \"getconf/normal not working (PATH=\${PATH}).\" ; \
        (( mismatch      > 0 )) && err_exit \"getconf/normal test found \${mismatch} differences (PATH=\${PATH}).\" ; \
        exit $((Errors))"
    (( Errors+=$? ))


    ## run test with path argument
    compare_path
    (( getconf_keys == 0 )) && err_exit "getconf/path not working."
    (( mismatch      > 0 )) && err_exit "getconf/path test found ${mismatch} differences."

    # run the same test in a seperate shell
    # (see comment above)
    ${SHELL} -c "integer mismatch ; \
        integer getconf_keys ; \
        ${getconf_test_functions} ; \
        compare_path ;
        (( getconf_keys == 0 )) && err_exit \"getconf/normal not working (PATH=\${PATH}).\" ; \
        (( mismatch      > 0 )) && err_exit \"getconf/normal test found \${mismatch} differences (PATH=\${PATH}).\" ; \
        exit $((Errors))"
    (( Errors+=$? ))
done


# tests done
exit $((Errors))
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License (the "License").
# You may not use this file except in compliance with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#

#
# Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#

#
# name reference test #001
#

# test setup
function err_exit
{
	print -u2 -n "\t"
	print -u2 -r ${Command}[$1]: "${@:2}"
	(( Errors++ ))
}
alias err_exit='err_exit $LINENO'

set -o nounset
Command=${0##*/}
integer Errors=0


function function2
{
	nameref v=$1

	v.x=19
	v.y=20
}

function function1
{
	typeset compound_var=()

	function2 compound_var

	printf "x=%d, y=%d\n" compound_var.x compound_var.y
}

x="$(function1)"

[[ "$x" != 'x=19, y=20' ]] && err_exit "expected 'x=19, y=20', got '${x}'"


# tests done
exit $((Errors))
#
# 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.
#

#
# This test module contains misc l10n tests
#
#

# test setup
function err_exit
{
	print -u2 -n "\t"
	print -u2 -r ${Command}[$1]: "${@:2}"
	(( Errors < 127 && Errors++ ))
}
alias err_exit='err_exit $LINENO'

set -o nounset
Command=${0##*/}
integer Errors=0

typeset ocwd
typeset tmpdir

# create temporary test directory
ocwd="$PWD"
tmpdir="$(mktemp -t -d "test_sun_solaris_locale_misc.XXXXXXXX")" || err_exit "Cannot create temporary directory"

cd "${tmpdir}" || { err_exit "cd ${tmpdir} failed." ; exit $((Errors)) ; }

#
# utility functions
#

function string_has_multibyte_characters
{
	typeset str="$1"
	integer bytecount
	integer mbcharactercount

	(( mbcharactercount=$(LC_ALL="en_US.UTF-8" wc -C <<<"${str}") ))
	(( bytecount=$(wc -c <<<"${str}") ))

	(( bytecount != mbcharactercount )) && return 0
	return 1
}

#
# test functions
#

# test whether LC_ALL correctly overrides LC_MESSAGES in the choice of the system message
# catalog
# 1. This test assumes that the machine has ko_KR.UTF-8 + matching message catalogs installed
# 2. We run this test in a |fork()|'ed subshell to isolate it from the other tests
function test_lc_all_override1
{
	typeset out

	(
		ulimit -c 0 # force ksh93 to |fork()| for this subshell

		unset ${!LC_*} LANG
		#export LANG=en_US.UTF-8
		export LC_ALL="en_US.UTF-8"

		integer ch_val
		integer korean_count=0
		${SHELL} -c 'LC_MESSAGES=C ${SHELL} -c "cd no_dir_llkk ; export LC_ALL="ko_KR.UTF-8" ; cd "no_dir_ooo" ; true"' >"out" 2>&1  || err_exit "Test shell failed with non-zero exit code $?"

		while read -N1 c ; do
			(( ch_val='${c} ))

			(( ch_val >= 0xac00 && ch_val <= 0xdfff )) && (( korean_count++ ))
		done <"out"

		# Solaris 11/B110 returns 13 characters for this test
		(( korean_count >= 10 )) || err_exit "Expected at least 10 korean characters, got ${korean_count}"

		rm "out"

		exit $((Errors))
	)
	(( Errors += $? ))
	return 0
}

# test whether the shell internally selects the correct message catalogs
# when the value of LC_* or LANG is restored to a "previous" value (e.g.
# subshell, function) or gets "reset" (e.g. unset)
function test_lc_l10n_scope1
{
	compound -r -a testgroups=(
		(
			name="subshell"
			typeset -a tests=(
				'LC_ALL="C" ;		cd "nosuchdir2" ; (LC_ALL="ja_JP.UTF-8" ;	cd "nosuchdir2") ; cd "nosuchdir2" ; true'
				'LC_MESSAGES="C" ;	cd "nosuchdir2" ; (LC_MESSAGES="ja_JP.UTF-8" ;	cd "nosuchdir2") ; cd "nosuchdir2" ; true'
				'LANG="C" ;		cd "nosuchdir2" ; (LANG="ja_JP.UTF-8" ;		cd "nosuchdir2") ; cd "nosuchdir2" ; true'
			)
		)
		(
			name="unset"
			typeset -a tests=(
				'LC_ALL="C" ;		cd "nosuchdir2" ; LC_ALL="ja_JP.UTF-8" ;	cd "nosuchdir2" ; unset LC_ALL ;	cd "nosuchdir2" ; true'
				'LC_MESSAGES="C" ;	cd "nosuchdir2" ; LC_MESSAGES="ja_JP.UTF-8" ;	cd "nosuchdir2" ; unset LC_MESSAGES ;	cd "nosuchdir2" ; true'
				'LANG="C" ;		cd "nosuchdir2" ; LANG="ja_JP.UTF-8" ;		cd "nosuchdir2" ; unset LANG ;		cd "nosuchdir2" ; true'
			)
		)
		(
			name="empty LC_xxx"
			typeset -a tests=(
				'LC_ALL="C" ;		cd "nosuchdir2" ; LC_ALL="ja_JP.UTF-8" ;	cd "nosuchdir2" ; LC_ALL="" ;		cd "nosuchdir2" ; true'
				'LC_MESSAGES="C" ;	cd "nosuchdir2" ; LC_MESSAGES="ja_JP.UTF-8" ;	cd "nosuchdir2" ; LC_MESSAGES="" ;	cd "nosuchdir2" ; true'
				'LANG="C" ;		cd "nosuchdir2" ; LANG="ja_JP.UTF-8" ;		cd "nosuchdir2" ; LANG="" ;		cd "nosuchdir2" ; true'
			)
		)
		(
			name="function"
			typeset -a tests=(
				'LC_ALL="C" ;		cd "nosuchdir2" ; function x { typeset LC_ALL="ja_JP.UTF-8" ;		cd "nosuchdir2" ; } ; x ; cd "nosuchdir2" ; true'
				'LC_MESSAGES="C" ;	cd "nosuchdir2" ; function x { typeset LC_MESSAGES="ja_JP.UTF-8" ;	cd "nosuchdir2" ; } ; x ; cd "nosuchdir2" ; true'
				'LANG="C" ;		cd "nosuchdir2" ; function x { typeset LANG="ja_JP.UTF-8" ;		cd "nosuchdir2" ; } ; x ; cd "nosuchdir2" ; true'
			)
		)
	)


	typeset tgi ti out2

	for tgi in "${!testgroups[@]}" ; do
		nameref tg=testgroups[${tgi}]

		for ti in "${!tg.tests[@]}" ; do
			nameref ts=tg.tests[${ti}]

			${SHELL} -c "unset LANG \${!LC_*} ; ${SHELL} -c \"${ts}\"" >out 2>&1 || err_exit "test returned non-zero exit code $?"
			out2="${
				while read -r line ; do
					string_has_multibyte_characters "${line}" && print -n "A" || print -n "_"
				done <"out"
				print ""
			}"
			if [[ "${out2}" != '_A_' ]] ; then
				err_exit "test '${tg.name}'/'$ts' failed: Expected '_A_', got '${out2}'"
				#cat out
			fi
		done
	done

	rm "out"

	return 0
}


# run tests
test_lc_all_override1
test_lc_l10n_scope1


cd "${ocwd}"
rmdir "${tmpdir}" || err_exit "Cannot remove temporary directory ${tmpdir}".

# tests done
exit $((Errors))
#
# 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) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
#

function err_exit2
{
	print -u2 -n "\t"
	print -u2 -r ${Command}[$1]: "${@:2}"
	(( Errors < 127 && Errors++ ))
}

function testfunc
{
	integer line_number=$1
	typeset cmd="$2"
	typeset expected_output="$3"
	typeset output

	output="$($SHELL -c "${cmd}" 2>&1 )"

	[[ "${output}" != "${expected_output}" ]] && err_exit2 ${line_number} "${output} != ${expected_output}"
}
alias testfunc='testfunc $LINENO'
alias err_exit='err_exit2 $LINENO'

set -o nounset
Command=${0##*/}
integer Errors=0


# string
testfunc '(function l { typeset -S x ;     x+="#" ; $1 && print "$x" ; } ; l false ; l false   ; l true)'  "###"
testfunc 'function  l { typeset -S x=">" ; x+="#" ; $1 && print "$x" ; } ; l false ; l false   ; l true'   ">###"
testfunc 'function  l { typeset -S x=">" ; x+="#" ; $1 && print "$x" ; } ; l false ; (l false) ; l true'   ">##"
testfunc 'function  l { typeset -S x=">" ; x+="#" ; $1 && print "$x" ; } ; l false; ( ulimit -c 0 ; l false) ; l true' ">##"

# integer
testfunc '(function l { typeset -S -i x ;  x+=1 ;   $1 && print "$x" ; } ; l false ; l false   ; l true )' "3"
testfunc '(function l { typeset -S -i x ;  x+=1 ;   $1 && print "$x" ; } ; l false ; (l false) ; l true )' "2"

# float
testfunc '(function l { float -S x=0.5 ;  (( x+=.5 )) ;   $1 && print "$x" ; } ; l false ; l false   ; l true )' "2"
testfunc '(function l { float -S x=0.5 ;  (( x+=.5 )) ;   $1 && print "$x" ; } ; l false ; (l false) ; l true )' "1.5"

# compound variable
[[ "${
	function l
	{
		typeset -S s=( a=0 b=0 )

		(( s.a++, s.b++ ))

		$1 && printf 'a=%d, b=%d\n' s.a s.b
	}
	l false ; l false ; l true
}" != "a=3, b=3" ]] && err_exit "static compound var failed"


# array variable
[[ "$(
	function ar
	{
		typeset -a -S s=( "hello" )

		s+=( "an element" )

		$1 && { printf '%s' "${s[@]}" ; printf '\n' ; }
	}
	ar false ; ar false ; ar true
)" != "helloan elementan elementan element" ]] && err_exit "static array var failed"


# Test visibilty of "global" vs. "static" variables. if we have a "static" variable in a
# function and "unset" it we should see a global variable with the same
# name, right ?
integer hx=5
function test_hx_scope
{
	integer -S hx=9
	$2 && unset hx
	$1 && printf "hx=%d\n" hx
}
test_hx_scope false false
test_hx_scope false false
# first test the "unset" call in a $(...) subshell...
[[ "$( test_hx_scope true true  )" != "hx=5" ]] && err_exit "can't see global variable hx after unsetting static variable hx"
# ... end then test whether the value has changed.
[[ "${ test_hx_scope true false }" != "hx=9" ]] && err_exit "hx variable somehow changed"


# tests done
exit $((Errors))
#
# 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) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
#

#
# variable tree test #001
# Propose of this test is whether ksh93 crashes or not - ast-ksh.2008-05-14
# crashes like this when running this test:
#
# program terminated by signal ILL (illegal opcode)
# 0xffffffffffffffff:     <bad address 0xffffffffffffffff>
# Current function is nv_diropen
#   123                   dp->hp = (Namval_t*)dtprev(dp->root,&fake);
# (dbx) where
#   [1] 0x100381e80(0x100381e80, 0xffffffff7fffe690, 0x10, 0x61, 0x0, 0x100381ec9), at 0x100381e80
# =>[2] nv_diropen(np = (nil), name = 0x100381ebc "mysrcdata"), line 123 in "nvtree.c"
#   [3] walk_tree(np = 0x1003809e0, dlete = 524289), line 743 in "nvtree.c"
#   [4] put_tree(np = 0x1003809e0, val = (nil), flags = 524289, fp = 0x100381db0), line 814 in "nvtree.c"
#   [5] nv_putv(np = 0x1003809e0, value = (nil), flags = 524289, nfp = 0x100381db0), line 141 in "nvdisc.c"
#   [6] _nv_unset(np = 0x1003809e0, flags = 524289), line 1976 in "name.c"
#   [7] table_unset(shp = 0x10033e900, root = 0x100380900, flags = 524289, oroot = 0x100360980), line 1902 in "name.c"
#   [8] sh_unscope(shp = 0x10033e900), line 2711 in "name.c"
#   [9] sh_funscope(argn = 1, argv = 0x10035e680, fun = (nil), arg = 0xffffffff7ffff118, execflg = 4), line 2470 in "xec.c"
#   [10] sh_funct(np = 0x100380860, argn = 1, argv = 0x10035e680, envlist = (nil), execflg = 4), line 2528 in "xec.c"
#   [11] sh_exec(t = 0x10035e620, flags = 4), line 1032 in "xec.c"
#   [12] exfile(shp = 0x10033e900, iop = 0x100379a20, fno = 10), line 589 in "main.c"
#   [13] sh_main(ac = 2, av = 0xffffffff7ffffa08, userinit = (nil)), line 364 in "main.c"
#   [14] main(argc = 2, argv = 0xffffffff7ffffa08), line 46 in "pmain.c"
#

# test setup
function err_exit
{
	print -u2 -n "\t"
	print -u2 -r ${Command}[$1]: "${@:2}"
	(( Errors < 127 && Errors++ ))
}
alias err_exit='err_exit $LINENO'

# the test cannot use "nounset"
Command=${0##*/}
integer Errors=0


function build_tree
{
#set -o errexit -o xtrace
	typeset index
	typeset s
	typeset i
	typeset dummy
	typeset a b c d e f

	nameref dest_tree="$1" # destination tree
	nameref srcdata="$2"   # source data
	typeset tree_mode="$3" # mode to define the type of leads

	typeset -A dest_tree.l1

	for index in "${!srcdata.hashnodes[@]}" ; do
		nameref node=srcdata.hashnodes["${index}"]

		for i in "${node.xlfd[@]}" ; do
			IFS='-' read dummy a b c d e f <<<"$i"

			if [[ "$a" == "" ]] ; then
				a="$dummy"
			fi

			[[ "$a" == "" ]] && a='-'
			[[ "$b" == "" ]] && b='-'
			[[ "$c" == "" ]] && c='-'

			if [[ "${dest_tree.l1["$a"]}" == "" ]] ; then
			#if ! (unset dest_tree.l1["$a"]) ; then
				typeset -A dest_tree.l1["$a"].l2
			fi

			if [[ "${dest_tree.l1["$a"].l2["$b"]}" == "" ]] ; then
			#if ! (unset dest_tree.l1["$a"].l2["$b"]) ; then
				typeset -A dest_tree.l1["$a"].l2["$b"].l3
			fi

			if [[ "${!dest_tree.l1["$a"].l2["$b"].l3["$c"].entries[*]}" == "" ]] ; then
				typeset -A dest_tree.l1["$a"].l2["$b"].l3["$c"].entries
			fi

			#dest_tree.l1["$a"].l2["$b"].l3["$c"].entries+=( "$index" )
			typeset new_index
			if [[ "${tree_mode}" == "leaf_name" ]] ; then
				new_index=$(( ${#dest_tree.l1["$a"].l2["$b"].l3["$c"].entries[@]}+1 ))
			else
				new_index="${node.name}"

				# skip if the leaf node already exists
				if [[ "${dest_tree.l1["$a"].l2["$b"].l3["$c"].entries[${new_index}]}" != "" ]] ; then
					continue
				fi
			fi

			add_tree_leaf dest_tree.l1["$a"].l2["$b"].l3["$c"].entries[${new_index}] "${index}" "${tree_mode}"
		done
	done

	return 0
}

function add_tree_leaf
{
	nameref tree_leafnode="$1"
	nameref data_node=srcdata.hashnodes["$2"]
	typeset add_mode="$3"

	case "${add_mode}" in
		"leaf_name")
			tree_leafnode="${data_node.name}"
			return 0
			;;
		"leaf_compound")
			tree_leafnode=(
				typeset name="${data_node.name}"
				typeset -a filenames=( "${data_node.filenames[@]}" )
				typeset -a comments=( "${data_node.comments[@]}" )
				typeset -a xlfd=( "${data_node.xlfd[@]}" )
			)
			return 0
			;;
		*)
			print -u2 -f "ERROR: Unknown mode %s in add_tree_leaf\n" "${add_mode}"
			return 1
			;;
	esac

	# not reached
	return 1
}

function main
{
	typeset mysrcdata=(
		typeset -A hashnodes=(
			[abcd]=(
				name='abcd'
				typeset -a xlfd=(
					'-urw-itc zapfchancery-medium-i-normal--0-0-0-0-p-0-iso8859-1'
					'-urw-itc zapfdingbats-medium-r-normal--0-0-0-0-p-0-adobe-fontspecific'
					'-urw-itc zapfdingbats-medium-r-normal--0-0-0-0-p-0-sun-fontspecific'
				)
				typeset -a comments=(
					'comment 1'
					'comment 2'
					'comment 3'
				)
				typeset -a filenames=(
					'/home/foo/abcd_1'
					'/home/foo/abcd_2'
					'/home/foo/abcd_3'
				)
			)
		)
	)

	mytree=()
	build_tree mytree mysrcdata leaf_compound
#	(( $(print -r -- "$mytree" | wc -l) > 10 )) || err_exit "Compound tree too small."
}

main

# tests done
exit $((Errors))
#
# 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) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
#

#
# variable tree test #002
# Propose of this test is whether ksh93 handles global variable trees
# and function-local variable trees the same way, including "nameref"
# and "unset" handling.
#

# test setup
function err_exit
{
	print -u2 -n "\t"
	print -u2 -r ${Command}[$1]: "${@:2}"
	(( Errors < 127 && Errors++ ))
}
alias err_exit='err_exit $LINENO'

# the test cannot use "nounset"
Command=${0##*/}
integer Errors=0

# "built_tree1" and "built_tree2" are identical except the way how they test
# whether a variable exists:
# - "built_tree1" uses "${varname}" != "", e.g. looking whether the variable
#    as non-zero length content
# - "built_tree2" uses "! ([[ -v varname ]] ; res=$? ; unset varname ; exit $res)", e.g. "unset" in a subshell.
function build_tree1
{
#set -o errexit -o xtrace
	typeset index
	typeset s
	typeset i
	typeset dummy
	typeset a b c d e f

	nameref dest_tree="$1" # destination tree
	nameref srcdata="$2"   # source data
	typeset tree_mode="$3" # mode to define the type of leads

	typeset -A dest_tree.l1

	for index in "${!srcdata.hashnodes[@]}" ; do
		nameref node=srcdata.hashnodes["${index}"]

		for i in "${node.xlfd[@]}" ; do
			IFS='-' read dummy a b c d e f <<<"$i"

			if [[ "$a" == "" ]] ; then
				a="$dummy"
			fi

			[[ "$a" == "" ]] && a='-'
			[[ "$b" == "" ]] && b='-'
			[[ "$c" == "" ]] && c='-'

			if [[ "${dest_tree.l1["$a"]}" == "" ]] ; then
			#if ! (unset dest_tree.l1["$a"]) ; then
				typeset -A dest_tree.l1["$a"].l2
			fi

			if [[ "${dest_tree.l1["$a"].l2["$b"]}" == "" ]] ; then
			#if ! (unset dest_tree.l1["$a"].l2["$b"]) ; then
				typeset -A dest_tree.l1["$a"].l2["$b"].l3
			fi

			if [[ "${!dest_tree.l1["$a"].l2["$b"].l3["$c"].entries[*]}" == "" ]] ; then
				typeset -A dest_tree.l1["$a"].l2["$b"].l3["$c"].entries
			fi

			typeset new_index
			if [[ "${tree_mode}" == "leaf_name" ]] ; then
				new_index=$(( ${#dest_tree.l1["$a"].l2["$b"].l3["$c"].entries[@]}+1 ))
			else
				new_index="${node.name}"

				# skip if the leaf node already exists
				if [[ "${dest_tree.l1["$a"].l2["$b"].l3["$c"].entries[${new_index}]}" != "" ]] ; then
					continue
				fi
			fi

			add_tree_leaf dest_tree.l1["$a"].l2["$b"].l3["$c"].entries[${new_index}] "${index}" "${tree_mode}"
		done
	done

	return 0
}

# "built_tree1" and "built_tree2" are identical except the way how they test
# whether a variable exists:
# - "built_tree1" uses "${varname}" != "", e.g. looking whether the variable
#    as non-zero length content
# - "built_tree2" uses "! ([[ -v varname ]] ; res=$? ; unset varname ; exit $res)", e.g. "unset" in a subshell.
function build_tree2
{
#set -o errexit -o xtrace
	typeset index
	typeset s
	typeset i
	typeset dummy
	typeset a b c d e f

	nameref dest_tree="$1" # destination tree
	nameref srcdata="$2"   # source data
	typeset tree_mode="$3" # mode to define the type of leads

	typeset -A dest_tree.l1

	for index in "${!srcdata.hashnodes[@]}" ; do
		nameref node=srcdata.hashnodes["${index}"]

		for i in "${node.xlfd[@]}" ; do
			IFS='-' read dummy a b c d e f <<<"$i"

			if [[ "$a" == "" ]] ; then
				a="$dummy"
			fi

			[[ "$a" == "" ]] && a='-'
			[[ "$b" == "" ]] && b='-'
			[[ "$c" == "" ]] && c='-'

			#if [[ "${dest_tree.l1["$a"]}" == "" ]] ; then
			if ! ([[ -v dest_tree.l1["$a"] ]] ; res=$? ; unset dest_tree.l1["$a"] ; exit $res) ; then
				typeset -A dest_tree.l1["$a"].l2
			fi

			#if [[ "${dest_tree.l1["$a"].l2["$b"]}" == "" ]] ; then
			if ! ([[ -v dest_tree.l1["$a"].l2["$b"] ]] ; res=$? ; unset dest_tree.l1["$a"].l2["$b"] ; exit $res) ; then
				typeset -A dest_tree.l1["$a"].l2["$b"].l3
			fi

			if [[ "${!dest_tree.l1["$a"].l2["$b"].l3["$c"].entries[*]}" == "" ]] ; then
				typeset -A dest_tree.l1["$a"].l2["$b"].l3["$c"].entries
			fi

			typeset new_index
			if [[ "${tree_mode}" == "leaf_name" ]] ; then
				new_index=$(( ${#dest_tree.l1["$a"].l2["$b"].l3["$c"].entries[@]}+1 ))
			else
				new_index="${node.name}"

				# skip if the leaf node already exists
				if [[ "${dest_tree.l1["$a"].l2["$b"].l3["$c"].entries[${new_index}]}" != "" ]] ; then
					continue
				fi
			fi

			add_tree_leaf dest_tree.l1["$a"].l2["$b"].l3["$c"].entries[${new_index}] "${index}" "${tree_mode}"
		done
	done

	return 0
}


function add_tree_leaf
{
	nameref tree_leafnode="$1"
	nameref data_node=srcdata.hashnodes["$2"]
	typeset add_mode="$3"

	case "${add_mode}" in
		"leaf_name")
			tree_leafnode="${data_node.name}"
			return 0
			;;
		"leaf_compound")
			tree_leafnode=(
				typeset name="${data_node.name}"
				typeset -a filenames=( "${data_node.filenames[@]}" )
				typeset -a comments=( "${data_node.comments[@]}" )
				typeset -a xlfd=( "${data_node.xlfd[@]}" )
			)
			return 0
			;;
		*)
			print -u2 -f "ERROR: Unknown mode %s in add_tree_leaf\n" "${add_mode}"
			return 1
			;;
	esac

	# not reached
	return 1
}

# "mysrcdata_local" and "mysrcdata_global" must be identical
typeset mysrcdata_global=(
	typeset -A hashnodes=(
		[abcd]=(
			name='abcd'
			typeset -a xlfd=(
				'-urw-itc zapfchancery-medium-i-normal--0-0-0-0-p-0-iso8859-1'
				'-urw-itc zapfdingbats-medium-r-normal--0-0-0-0-p-0-adobe-fontspecific'
				'-urw-itc zapfdingbats-medium-r-normal--0-0-0-0-p-0-sun-fontspecific'
			)
			typeset -a comments=(
				'comment 1'
				'comment 2'
				'comment 3'
			)
			typeset -a filenames=(
				'/home/foo/abcd_1'
				'/home/foo/abcd_2'
				'/home/foo/abcd_3'
			)
		)
	)
)

mytree_global1=()
mytree_global2=()

function main
{
	# "mysrcdata_local" and "mysrcdata_global" must be identical
	typeset mysrcdata_local=(
		typeset -A hashnodes=(
			[abcd]=(
				name='abcd'
				typeset -a xlfd=(
					'-urw-itc zapfchancery-medium-i-normal--0-0-0-0-p-0-iso8859-1'
					'-urw-itc zapfdingbats-medium-r-normal--0-0-0-0-p-0-adobe-fontspecific'
					'-urw-itc zapfdingbats-medium-r-normal--0-0-0-0-p-0-sun-fontspecific'
				)
				typeset -a comments=(
					'comment 1'
					'comment 2'
					'comment 3'
				)
				typeset -a filenames=(
					'/home/foo/abcd_1'
					'/home/foo/abcd_2'
					'/home/foo/abcd_3'
				)
			)
		)
	)

	#### Build tree using global tree variables
	build_tree1 mytree_global1 mysrcdata_global leaf_compound || \
		err_exit 'build_tree1 mytree_global1 mysrcdata_global leaf_compound returned an error'
	(( $(print -r -- "${mytree_global1}" | wc -l) > 10 )) || err_exit "Compound tree 'mytree_global1' too small."

	build_tree2 mytree_global2 mysrcdata_global leaf_compound || \
		err_exit 'build_tree2 mytree_global2 mysrcdata_global leaf_compound returned an error'
	(( $(print -r -- "${mytree_global2}" | wc -l) > 10 )) || err_exit "Compound tree 'mytree_global2' too small."


	#### build tree using local tree variables
	mytree_local1=()
	mytree_local2=()

	build_tree1 mytree_local1 mysrcdata_local leaf_compound || \
		err_exit 'build_tree1 mytree_local1 mysrcdata_local leaf_compound returned an error'
	(( $(print -r -- "${mytree_local1}" | wc -l) > 10 )) || err_exit "Compound tree 'mytree_local1' too small."

	build_tree2 mytree_local2 mysrcdata_local leaf_compound || \
		err_exit 'build_tree2 mytree_local2 mysrcdata_local leaf_compound returned an error'
	(( $(print -r -- "${mytree_local2}" | wc -l) > 10 )) || err_exit "Compound tree 'mytree_local2' too small."


	#### Compare treess
	if [[ "${mytree_global1}" != "${mytree_local1}" ]] ; then
		err_exit "Compound trees 'mytree_global1' and 'mytree_local1' not identical"
		diff -u <( printf "%s\n" "${mytree_global1}" ) <( printf "%s\n" "${mytree_local1}" )
	fi

	if [[ "${mytree_global1}" != "${mytree_global2}" ]] ; then
		err_exit "Compound trees 'mytree_global1' and 'mytree_global2' not identical"
		diff -u <( printf "%s\n" "${mytree_global1}" ) <( printf "%s\n" "${mytree_global2}" )
	fi

	if [[ "${mytree_local1}" != "${mytree_local2}" ]] ; then
		err_exit "Compound trees 'mytree_local1' and 'mytree_local2' not identical"
		diff -u <( printf "%s\n" "${mytree_local1}" ) <( printf "%s\n" "${mytree_local2}" )
	fi


	#### test "unset" in a subshell
	(  [[ -v 'mytree_global1.l1[urw].l2[itc zapfdingbats]' ]] ; res=$? ; unset 'mytree_global1.l1[urw].l2[itc zapfdingbats]' ; exit $res ) || \
		err_exit "Try 1: Variable 'mytree_global1.l1[urw].l2[itc zapfdingbats]' not found."
	(  [[ -v 'mytree_global1.l1[urw].l2[itc zapfdingbats]' ]] ; res=$? ; unset 'mytree_global1.l1[urw].l2[itc zapfdingbats]' ; exit $res ) || \
		err_exit "Try 2: Variable 'mytree_global1.l1[urw].l2[itc zapfdingbats]' not found."

	# remove parent node (array element) and then check whether the child is gone, too:
	(
		set -o errexit
		unset 'mytree_global1.l1[urw].l2[itc zapfdingbats]'
		! [[ -v 'mytree_global1.l1[urw].l2[itc zapfdingbats].l3[medium].entries[abcd].filenames[0]' ]]
	) || err_exit "Global: Parent node removed (array element), child still exists"
	(
		set -o errexit
		unset 'mytree_local1.l1[urw].l2[itc zapfdingbats]'
		! [[ -v 'mytree_local1.l1[urw].l2[itc zapfdingbats].l3[medium].entries[abcd].filenames[0]' ]]
	) || err_exit "Local: Parent node removed (array element), child still exists"

	# remove parent node  (array variable) and then check whether the child is gone, too:
	(
		set -o errexit
		unset 'mytree_local1.l1[urw].l2'
		! [[ -v 'mytree_local1.l1[urw].l2[itc zapfdingbats].l3[medium].entries[abcd].filenames[0]' ]]
	) || err_exit "Global: Parent node removed (array variable), child still exists"
	(
		set -o errexit
		unset 'mytree_local1.l1[urw].l2'
		! [[ -v 'mytree_local1.l1[urw].l2[itc zapfdingbats].l3[medium].entries[abcd].filenames[0]' ]]
	) || err_exit "Local: Parent node removed (array variable), child still exists"


	#### test "unset" and compare trees
	[[ -v 'mytree_global1.l1[urw].l2[itc zapfdingbats].l3[medium].entries[abcd].filenames[0]' ]] ; res=$?
	unset 'mytree_global1.l1[urw].l2[itc zapfdingbats].l3[medium].entries[abcd].filenames[0]'
	(( res == 0 ))  ||
		err_exit "Variable 'mytree_global1.l1[urw].l2[itc zapfdingbats].l3[medium].entries[abcd].filenames[0]' not found."

	[[ "${mytree_global1}" != "${mytree_local1}" ]] || err_exit "mytree_global1 and mytree_local1 should differ"

	[[ -v 'mytree_local1.l1[urw].l2[itc zapfdingbats].l3[medium].entries[abcd].filenames[0]' ]] ; res=$?
	unset 'mytree_local1.l1[urw].l2[itc zapfdingbats].l3[medium].entries[abcd].filenames[0]'
	(( res == 0 ))  ||
		err_exit "Variable 'mytree_local1.l1[urw].l2[itc zapfdingbats].l3[medium].entries[abcd].filenames[0]' not found."

	# Compare trees (after "unset")
	if [[ "${mytree_global1}" != "${mytree_local1}" ]] ; then
		err_exit "Compound trees 'mytree_local1' and 'mytree_global1' not identical after unset"
		diff -u <( printf "%s\n" "${mytree_global1}" ) <( printf "%s\n" "${mytree_local1}" )
	fi
}

main

# tests done
exit $((Errors))
#
# 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) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
#

#
# variable tree test #003
# Propose of this test is whether ksh93 handles global variable trees
# and function-local variable trees the same way, including "nameref"
# and "unset" handling.
#

# test setup
function err_exit
{
	print -u2 -n "\t"
	print -u2 -r ${Command}[$1]: "${@:2}"
	(( Errors < 127 && Errors++ ))
}
alias err_exit='err_exit $LINENO'

# the test cannot use "nounset"
Command=${0##*/}
integer Errors=0

function example_tree
{
cat <<EOF
(
	typeset -A l1=(
		[adobe]=(
			typeset -A l2=(
				[avantgarde]=(
					typeset -A l3=(
						[demi]=(
							typeset -A entries=(
								[182c069a485316b1bc7ae001c04c7835]=(
									typeset -a comments=(
										FONT
										-adobe-avantgarde-demi-r-normal--199-120-1200-1200-p-1130-iso8859-1
										COPYRIGHT
										'Copyright Notice not available'
										RAW_PIXELSIZE
										RAW_POINTSIZE
										--
										section
										diaeresis
										copyright
										ordfeminine
										guillemotleft
									)
									typeset -a filenames=(
										X11Rx/R6.4/xc/programs/Xserver/XpConfig/C/print/models/SPSPARC2/fonts/AvantGarde-Demi.pmf
									)
									md5sum=182c069a485316b1bc7ae001c04c7835
									typeset -a xlfd=(
										-adobe-avantgarde-demi-r-normal--199-120-1200-1200-p-1130-iso8859-1
									)
								)
								[7db15b51965d8fe1f1c55fcb101d7616]=(
									typeset -a comments=(
										FONT
										-adobe-avantgarde-demi-i-normal--199-120-1200-1200-p-1130-iso8859-1
										COPYRIGHT
										'Copyright Notice not available'
										RAW_PIXELSIZE
										RAW_POINTSIZE
										--
										section
										diaeresis
										copyright
										ordfeminine
										guillemotleft
									)
									typeset -a filenames=(
										X11Rx/R6.4/xc/programs/Xserver/XpConfig/C/print/models/SPSPARC2/fonts/AvantGarde-DemiOblique.pmf
									)
									md5sum=7db15b51965d8fe1f1c55fcb101d7616
									typeset -a xlfd=(
										-adobe-avantgarde-demi-i-normal--199-120-1200-1200-p-1130-iso8859-1
									)
								)
								[a37e4a4a5035abf6f294d830fbd9e775]=(
									typeset -a comments=(
										FONT
										-adobe-avantgarde-demi-r-normal--422-120-2540-2540-p-2395-iso8859-1
										COPYRIGHT
										'Copyright (c) 1985, 1987, 1989, 1990, 1991 Adobe Systems Incorporated.  All Rights Reserved.ITC Avant Garde Gothic is a registered trademark of International Typeface Corporation.'
										RAW_PIXELSIZE
										RAW_POINTSIZE
										--
										section
										diaeresis
										copyright
										ordfeminine
										guillemotleft
									)
									typeset -a filenames=(
										fox-gate/XW_NV/open-src/tarballs/xorg-server-1.3.0.0/hw/xprint/config/C/print/models/PSdefault/fonts/AvantGarde-Demi.pmf
									)
									md5sum=a37e4a4a5035abf6f294d830fbd9e775
									typeset -a xlfd=(
										-adobe-avantgarde-demi-r-normal--422-120-2540-2540-p-2395-iso8859-1
									)
								)
								[da3d6d94fcf759b95c7f829ce5619374]=(
									typeset -a comments=(
										FONT
										-adobe-avantgarde-demi-i-normal--422-120-2540-2540-p-2395-iso8859-1
										COPYRIGHT
										'Copyright (c) 1985, 1987, 1989, 1990, 1991 Adobe Systems Incorporated.  All Rights Reserved.ITC Avant Garde Gothic is a registered trademark of International Typeface Corporation.'
										RAW_PIXELSIZE
										RAW_POINTSIZE
										--
										section
										diaeresis
										copyright
										ordfeminine
										guillemotleft
									)
									typeset -a filenames=(
										fox-gate/XW_NV/open-src/tarballs/xorg-server-1.3.0.0/hw/xprint/config/C/print/models/PSdefault/fonts/AvantGarde-DemiOblique.pmf
									)
									md5sum=da3d6d94fcf759b95c7f829ce5619374
									typeset -a xlfd=(
										-adobe-avantgarde-demi-i-normal--422-120-2540-2540-p-2395-iso8859-1
									)
								)
							)
						)
					)
				)
			)
		)
	)
)
EOF
}

function main
{
	set -o errexit

	typeset xlfd_tree=()
	typeset -A xlfd_tree.l1

	eval "xlfd_tree=$( example_tree )"

	typeset i j k l fn

        # filter chain begin
        for i in "${!xlfd_tree.l1[@]}" ; do
              for j in "${!xlfd_tree.l1["$i"].l2[@]}" ; do
        	     for k in "${!xlfd_tree.l1["$i"].l2["$j"].l3[@]}" ; do
        		     nameref vndnode=xlfd_tree.l1["$i"].l2["$j"].l3["$k"]

        		     for l in "${!vndnode.entries[@]}" ; do
        			     nameref node=vndnode.entries["$l"]

        			     for fn in "${node.filenames[@]}" ; do
        				     if [[ "${fn}" != ~(E)x-re_gate_XW_NV_MWS ]] ; then
        					     unset "${!node}"
        					     break
        				     fi
        			     done
        		     done
        	     done
              done
	done

	# filter chain end

	return 0
}

main || ((Errors++))

# tests done
exit $((Errors))
#
# 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) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
# Copyright 2021 OmniOS Community Edition (OmniOSce) Association.
#

#
# MAPFILE HEADER START
#
# WARNING:  STOP NOW.  DO NOT MODIFY THIS FILE.
# Object versioning must comply with the rules detailed in
#
#	usr/src/lib/README.mapfiles
#
# You should not be making modifications here until you've read the most current
# copy of that file. If you need help, contact a gatekeeper for guidance.
#
# MAPFILE HEADER END
#

$mapfile_version 2

SYMBOL_VERSION SUNWprivate_1.1 {
    global:
	plugin_version;

	sh_access;
	sh_addbuiltin;
	sh_bltin_tree;
	sh_close;
	sh_delay;
	sh_dup;
	sh_eval;
	sh_exec;
	sh_exit;
	sh_fcntl;
	sh_fmtq;
	sh_fmtqf;
	sh_fun;
	sh_funscope;
	sh_getinterp;
	sh_getscope;
	sh_init;
	sh_iogetiop;
	sh_isoption;
	sh_main;
	sh_menu;
	sh_offoption;
	sh_onoption;
	sh_open;
	sh_parse;
	sh_pathopen;
	sh_pipe;
	sh_read;
	sh_reinit;
	sh_seek;
	sh_setscope;
	sh_sigcheck;
	sh_strnum;
	sh_subfork;
	sh_tdump;
	sh_trap;
	sh_waitnotify;
	sh_waitsafe;
	sh_write;

	nv_adddisc;
	nv_aindex;
	nv_associative;
	nv_clone;
	nv_close;
	nv_context;
	nv_create;
	nv_dict;
	nv_disc;
	nv_discfun;
	nv_getn;
	nv_getnum;
	nv_getsub;
	nv_getv;
	nv_getval;
	nv_hasdisc;
	nv_isnull;
	nv_lastdict;
	nv_name;
	nv_newattr;
	nv_nextsub;
	nv_open;
	nv_opensub;
	nv_putsub;
	nv_putv;
	nv_putval;
	nv_scan;
	nv_search;
	nv_setarray;
	nv_setdisc;
	nv_setref;
	nv_setsize;
	nv_settype;
	nv_setvec;
	nv_setvtree;
	nv_unset;

	# semi-private, needed for shcomp
$if _ELF64
	$if _x86
	sh	{ ASSERT = { TYPE = OBJECT; SIZE = 1888; }; };
	$elif _sparc
	sh	{ ASSERT = { TYPE = OBJECT; SIZE = 1920; }; };
	$else
	$error Unknown architecture
	$endif
$elif _ELF32
	$if _x86
	sh	{ ASSERT = { TYPE = OBJECT; SIZE = 1216; }; };
	$elif _sparc
	sh	{ ASSERT = { TYPE = OBJECT; SIZE = 1224; }; };
	$else
	$error Unknown architecture
	$endif
$else
$error unknown ELFCLASS
$endif
	e_dict	{ ASSERT = { TYPE = OBJECT; SIZE = 9; }; };

    local:
	*;
};

# Builtin shell commands
# (see libshell/common/include/builtins.h)
# Note: We have to export all the |b_*()| symbols that the "builtin" command
# can load builtins which are not enabled by the default OS/Net configuration.
SYMBOL_VERSION SUNWprivate_1.1 {
    global:
	B_echo;
	B_login;
	b_alarm;
	b_alias;
	b_bg;
	b_break;
	b_builtin;
	b_cd;
	b_close;
	b_command;
	b_dot_cmd;
	b_dup;
	b_eval;
	b_exec;
	b_false;
	b_getopts;
	b_hist;
	b_jobs;
	b_kill;
	b_let;
	b_open;
	b_poll;
	b_print;
	b_printf;
	b_pwd;
	b_read;
	b_readonly;
	b_return;
	b_rewind;
	b_set;
	b_shift;
	b_sleep;
	b_stat;
	b_test;
	b_tmpfile;
	b_trap;
	b_true;
	b_typeset;
	b_ulimit;
	b_umask;
	b_unalias;
	b_unset;
	b_vpath;
	b_wait;
	b_whence;
    local:
	*;
};