File: debian-changes

package info (click to toggle)
mksh 59c-43
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 4,688 kB
  • sloc: ansic: 58,251; sh: 6,114; perl: 2,155; makefile: 127
file content (33468 lines) | stat: -rw-r--r-- 956,544 bytes parent folder | download | duplicates (2)
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
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557
16558
16559
16560
16561
16562
16563
16564
16565
16566
16567
16568
16569
16570
16571
16572
16573
16574
16575
16576
16577
16578
16579
16580
16581
16582
16583
16584
16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620
16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
16638
16639
16640
16641
16642
16643
16644
16645
16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
16689
16690
16691
16692
16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735
16736
16737
16738
16739
16740
16741
16742
16743
16744
16745
16746
16747
16748
16749
16750
16751
16752
16753
16754
16755
16756
16757
16758
16759
16760
16761
16762
16763
16764
16765
16766
16767
16768
16769
16770
16771
16772
16773
16774
16775
16776
16777
16778
16779
16780
16781
16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
16802
16803
16804
16805
16806
16807
16808
16809
16810
16811
16812
16813
16814
16815
16816
16817
16818
16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832
16833
16834
16835
16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851
16852
16853
16854
16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871
16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882
16883
16884
16885
16886
16887
16888
16889
16890
16891
16892
16893
16894
16895
16896
16897
16898
16899
16900
16901
16902
16903
16904
16905
16906
16907
16908
16909
16910
16911
16912
16913
16914
16915
16916
16917
16918
16919
16920
16921
16922
16923
16924
16925
16926
16927
16928
16929
16930
16931
16932
16933
16934
16935
16936
16937
16938
16939
16940
16941
16942
16943
16944
16945
16946
16947
16948
16949
16950
16951
16952
16953
16954
16955
16956
16957
16958
16959
16960
16961
16962
16963
16964
16965
16966
16967
16968
16969
16970
16971
16972
16973
16974
16975
16976
16977
16978
16979
16980
16981
16982
16983
16984
16985
16986
16987
16988
16989
16990
16991
16992
16993
16994
16995
16996
16997
16998
16999
17000
17001
17002
17003
17004
17005
17006
17007
17008
17009
17010
17011
17012
17013
17014
17015
17016
17017
17018
17019
17020
17021
17022
17023
17024
17025
17026
17027
17028
17029
17030
17031
17032
17033
17034
17035
17036
17037
17038
17039
17040
17041
17042
17043
17044
17045
17046
17047
17048
17049
17050
17051
17052
17053
17054
17055
17056
17057
17058
17059
17060
17061
17062
17063
17064
17065
17066
17067
17068
17069
17070
17071
17072
17073
17074
17075
17076
17077
17078
17079
17080
17081
17082
17083
17084
17085
17086
17087
17088
17089
17090
17091
17092
17093
17094
17095
17096
17097
17098
17099
17100
17101
17102
17103
17104
17105
17106
17107
17108
17109
17110
17111
17112
17113
17114
17115
17116
17117
17118
17119
17120
17121
17122
17123
17124
17125
17126
17127
17128
17129
17130
17131
17132
17133
17134
17135
17136
17137
17138
17139
17140
17141
17142
17143
17144
17145
17146
17147
17148
17149
17150
17151
17152
17153
17154
17155
17156
17157
17158
17159
17160
17161
17162
17163
17164
17165
17166
17167
17168
17169
17170
17171
17172
17173
17174
17175
17176
17177
17178
17179
17180
17181
17182
17183
17184
17185
17186
17187
17188
17189
17190
17191
17192
17193
17194
17195
17196
17197
17198
17199
17200
17201
17202
17203
17204
17205
17206
17207
17208
17209
17210
17211
17212
17213
17214
17215
17216
17217
17218
17219
17220
17221
17222
17223
17224
17225
17226
17227
17228
17229
17230
17231
17232
17233
17234
17235
17236
17237
17238
17239
17240
17241
17242
17243
17244
17245
17246
17247
17248
17249
17250
17251
17252
17253
17254
17255
17256
17257
17258
17259
17260
17261
17262
17263
17264
17265
17266
17267
17268
17269
17270
17271
17272
17273
17274
17275
17276
17277
17278
17279
17280
17281
17282
17283
17284
17285
17286
17287
17288
17289
17290
17291
17292
17293
17294
17295
17296
17297
17298
17299
17300
17301
17302
17303
17304
17305
17306
17307
17308
17309
17310
17311
17312
17313
17314
17315
17316
17317
17318
17319
17320
17321
17322
17323
17324
17325
17326
17327
17328
17329
17330
17331
17332
17333
17334
17335
17336
17337
17338
17339
17340
17341
17342
17343
17344
17345
17346
17347
17348
17349
17350
17351
17352
17353
17354
17355
17356
17357
17358
17359
17360
17361
17362
17363
17364
17365
17366
17367
17368
17369
17370
17371
17372
17373
17374
17375
17376
17377
17378
17379
17380
17381
17382
17383
17384
17385
17386
17387
17388
17389
17390
17391
17392
17393
17394
17395
17396
17397
17398
17399
17400
17401
17402
17403
17404
17405
17406
17407
17408
17409
17410
17411
17412
17413
17414
17415
17416
17417
17418
17419
17420
17421
17422
17423
17424
17425
17426
17427
17428
17429
17430
17431
17432
17433
17434
17435
17436
17437
17438
17439
17440
17441
17442
17443
17444
17445
17446
17447
17448
17449
17450
17451
17452
17453
17454
17455
17456
17457
17458
17459
17460
17461
17462
17463
17464
17465
17466
17467
17468
17469
17470
17471
17472
17473
17474
17475
17476
17477
17478
17479
17480
17481
17482
17483
17484
17485
17486
17487
17488
17489
17490
17491
17492
17493
17494
17495
17496
17497
17498
17499
17500
17501
17502
17503
17504
17505
17506
17507
17508
17509
17510
17511
17512
17513
17514
17515
17516
17517
17518
17519
17520
17521
17522
17523
17524
17525
17526
17527
17528
17529
17530
17531
17532
17533
17534
17535
17536
17537
17538
17539
17540
17541
17542
17543
17544
17545
17546
17547
17548
17549
17550
17551
17552
17553
17554
17555
17556
17557
17558
17559
17560
17561
17562
17563
17564
17565
17566
17567
17568
17569
17570
17571
17572
17573
17574
17575
17576
17577
17578
17579
17580
17581
17582
17583
17584
17585
17586
17587
17588
17589
17590
17591
17592
17593
17594
17595
17596
17597
17598
17599
17600
17601
17602
17603
17604
17605
17606
17607
17608
17609
17610
17611
17612
17613
17614
17615
17616
17617
17618
17619
17620
17621
17622
17623
17624
17625
17626
17627
17628
17629
17630
17631
17632
17633
17634
17635
17636
17637
17638
17639
17640
17641
17642
17643
17644
17645
17646
17647
17648
17649
17650
17651
17652
17653
17654
17655
17656
17657
17658
17659
17660
17661
17662
17663
17664
17665
17666
17667
17668
17669
17670
17671
17672
17673
17674
17675
17676
17677
17678
17679
17680
17681
17682
17683
17684
17685
17686
17687
17688
17689
17690
17691
17692
17693
17694
17695
17696
17697
17698
17699
17700
17701
17702
17703
17704
17705
17706
17707
17708
17709
17710
17711
17712
17713
17714
17715
17716
17717
17718
17719
17720
17721
17722
17723
17724
17725
17726
17727
17728
17729
17730
17731
17732
17733
17734
17735
17736
17737
17738
17739
17740
17741
17742
17743
17744
17745
17746
17747
17748
17749
17750
17751
17752
17753
17754
17755
17756
17757
17758
17759
17760
17761
17762
17763
17764
17765
17766
17767
17768
17769
17770
17771
17772
17773
17774
17775
17776
17777
17778
17779
17780
17781
17782
17783
17784
17785
17786
17787
17788
17789
17790
17791
17792
17793
17794
17795
17796
17797
17798
17799
17800
17801
17802
17803
17804
17805
17806
17807
17808
17809
17810
17811
17812
17813
17814
17815
17816
17817
17818
17819
17820
17821
17822
17823
17824
17825
17826
17827
17828
17829
17830
17831
17832
17833
17834
17835
17836
17837
17838
17839
17840
17841
17842
17843
17844
17845
17846
17847
17848
17849
17850
17851
17852
17853
17854
17855
17856
17857
17858
17859
17860
17861
17862
17863
17864
17865
17866
17867
17868
17869
17870
17871
17872
17873
17874
17875
17876
17877
17878
17879
17880
17881
17882
17883
17884
17885
17886
17887
17888
17889
17890
17891
17892
17893
17894
17895
17896
17897
17898
17899
17900
17901
17902
17903
17904
17905
17906
17907
17908
17909
17910
17911
17912
17913
17914
17915
17916
17917
17918
17919
17920
17921
17922
17923
17924
17925
17926
17927
17928
17929
17930
17931
17932
17933
17934
17935
17936
17937
17938
17939
17940
17941
17942
17943
17944
17945
17946
17947
17948
17949
17950
17951
17952
17953
17954
17955
17956
17957
17958
17959
17960
17961
17962
17963
17964
17965
17966
17967
17968
17969
17970
17971
17972
17973
17974
17975
17976
17977
17978
17979
17980
17981
17982
17983
17984
17985
17986
17987
17988
17989
17990
17991
17992
17993
17994
17995
17996
17997
17998
17999
18000
18001
18002
18003
18004
18005
18006
18007
18008
18009
18010
18011
18012
18013
18014
18015
18016
18017
18018
18019
18020
18021
18022
18023
18024
18025
18026
18027
18028
18029
18030
18031
18032
18033
18034
18035
18036
18037
18038
18039
18040
18041
18042
18043
18044
18045
18046
18047
18048
18049
18050
18051
18052
18053
18054
18055
18056
18057
18058
18059
18060
18061
18062
18063
18064
18065
18066
18067
18068
18069
18070
18071
18072
18073
18074
18075
18076
18077
18078
18079
18080
18081
18082
18083
18084
18085
18086
18087
18088
18089
18090
18091
18092
18093
18094
18095
18096
18097
18098
18099
18100
18101
18102
18103
18104
18105
18106
18107
18108
18109
18110
18111
18112
18113
18114
18115
18116
18117
18118
18119
18120
18121
18122
18123
18124
18125
18126
18127
18128
18129
18130
18131
18132
18133
18134
18135
18136
18137
18138
18139
18140
18141
18142
18143
18144
18145
18146
18147
18148
18149
18150
18151
18152
18153
18154
18155
18156
18157
18158
18159
18160
18161
18162
18163
18164
18165
18166
18167
18168
18169
18170
18171
18172
18173
18174
18175
18176
18177
18178
18179
18180
18181
18182
18183
18184
18185
18186
18187
18188
18189
18190
18191
18192
18193
18194
18195
18196
18197
18198
18199
18200
18201
18202
18203
18204
18205
18206
18207
18208
18209
18210
18211
18212
18213
18214
18215
18216
18217
18218
18219
18220
18221
18222
18223
18224
18225
18226
18227
18228
18229
18230
18231
18232
18233
18234
18235
18236
18237
18238
18239
18240
18241
18242
18243
18244
18245
18246
18247
18248
18249
18250
18251
18252
18253
18254
18255
18256
18257
18258
18259
18260
18261
18262
18263
18264
18265
18266
18267
18268
18269
18270
18271
18272
18273
18274
18275
18276
18277
18278
18279
18280
18281
18282
18283
18284
18285
18286
18287
18288
18289
18290
18291
18292
18293
18294
18295
18296
18297
18298
18299
18300
18301
18302
18303
18304
18305
18306
18307
18308
18309
18310
18311
18312
18313
18314
18315
18316
18317
18318
18319
18320
18321
18322
18323
18324
18325
18326
18327
18328
18329
18330
18331
18332
18333
18334
18335
18336
18337
18338
18339
18340
18341
18342
18343
18344
18345
18346
18347
18348
18349
18350
18351
18352
18353
18354
18355
18356
18357
18358
18359
18360
18361
18362
18363
18364
18365
18366
18367
18368
18369
18370
18371
18372
18373
18374
18375
18376
18377
18378
18379
18380
18381
18382
18383
18384
18385
18386
18387
18388
18389
18390
18391
18392
18393
18394
18395
18396
18397
18398
18399
18400
18401
18402
18403
18404
18405
18406
18407
18408
18409
18410
18411
18412
18413
18414
18415
18416
18417
18418
18419
18420
18421
18422
18423
18424
18425
18426
18427
18428
18429
18430
18431
18432
18433
18434
18435
18436
18437
18438
18439
18440
18441
18442
18443
18444
18445
18446
18447
18448
18449
18450
18451
18452
18453
18454
18455
18456
18457
18458
18459
18460
18461
18462
18463
18464
18465
18466
18467
18468
18469
18470
18471
18472
18473
18474
18475
18476
18477
18478
18479
18480
18481
18482
18483
18484
18485
18486
18487
18488
18489
18490
18491
18492
18493
18494
18495
18496
18497
18498
18499
18500
18501
18502
18503
18504
18505
18506
18507
18508
18509
18510
18511
18512
18513
18514
18515
18516
18517
18518
18519
18520
18521
18522
18523
18524
18525
18526
18527
18528
18529
18530
18531
18532
18533
18534
18535
18536
18537
18538
18539
18540
18541
18542
18543
18544
18545
18546
18547
18548
18549
18550
18551
18552
18553
18554
18555
18556
18557
18558
18559
18560
18561
18562
18563
18564
18565
18566
18567
18568
18569
18570
18571
18572
18573
18574
18575
18576
18577
18578
18579
18580
18581
18582
18583
18584
18585
18586
18587
18588
18589
18590
18591
18592
18593
18594
18595
18596
18597
18598
18599
18600
18601
18602
18603
18604
18605
18606
18607
18608
18609
18610
18611
18612
18613
18614
18615
18616
18617
18618
18619
18620
18621
18622
18623
18624
18625
18626
18627
18628
18629
18630
18631
18632
18633
18634
18635
18636
18637
18638
18639
18640
18641
18642
18643
18644
18645
18646
18647
18648
18649
18650
18651
18652
18653
18654
18655
18656
18657
18658
18659
18660
18661
18662
18663
18664
18665
18666
18667
18668
18669
18670
18671
18672
18673
18674
18675
18676
18677
18678
18679
18680
18681
18682
18683
18684
18685
18686
18687
18688
18689
18690
18691
18692
18693
18694
18695
18696
18697
18698
18699
18700
18701
18702
18703
18704
18705
18706
18707
18708
18709
18710
18711
18712
18713
18714
18715
18716
18717
18718
18719
18720
18721
18722
18723
18724
18725
18726
18727
18728
18729
18730
18731
18732
18733
18734
18735
18736
18737
18738
18739
18740
18741
18742
18743
18744
18745
18746
18747
18748
18749
18750
18751
18752
18753
18754
18755
18756
18757
18758
18759
18760
18761
18762
18763
18764
18765
18766
18767
18768
18769
18770
18771
18772
18773
18774
18775
18776
18777
18778
18779
18780
18781
18782
18783
18784
18785
18786
18787
18788
18789
18790
18791
18792
18793
18794
18795
18796
18797
18798
18799
18800
18801
18802
18803
18804
18805
18806
18807
18808
18809
18810
18811
18812
18813
18814
18815
18816
18817
18818
18819
18820
18821
18822
18823
18824
18825
18826
18827
18828
18829
18830
18831
18832
18833
18834
18835
18836
18837
18838
18839
18840
18841
18842
18843
18844
18845
18846
18847
18848
18849
18850
18851
18852
18853
18854
18855
18856
18857
18858
18859
18860
18861
18862
18863
18864
18865
18866
18867
18868
18869
18870
18871
18872
18873
18874
18875
18876
18877
18878
18879
18880
18881
18882
18883
18884
18885
18886
18887
18888
18889
18890
18891
18892
18893
18894
18895
18896
18897
18898
18899
18900
18901
18902
18903
18904
18905
18906
18907
18908
18909
18910
18911
18912
18913
18914
18915
18916
18917
18918
18919
18920
18921
18922
18923
18924
18925
18926
18927
18928
18929
18930
18931
18932
18933
18934
18935
18936
18937
18938
18939
18940
18941
18942
18943
18944
18945
18946
18947
18948
18949
18950
18951
18952
18953
18954
18955
18956
18957
18958
18959
18960
18961
18962
18963
18964
18965
18966
18967
18968
18969
18970
18971
18972
18973
18974
18975
18976
18977
18978
18979
18980
18981
18982
18983
18984
18985
18986
18987
18988
18989
18990
18991
18992
18993
18994
18995
18996
18997
18998
18999
19000
19001
19002
19003
19004
19005
19006
19007
19008
19009
19010
19011
19012
19013
19014
19015
19016
19017
19018
19019
19020
19021
19022
19023
19024
19025
19026
19027
19028
19029
19030
19031
19032
19033
19034
19035
19036
19037
19038
19039
19040
19041
19042
19043
19044
19045
19046
19047
19048
19049
19050
19051
19052
19053
19054
19055
19056
19057
19058
19059
19060
19061
19062
19063
19064
19065
19066
19067
19068
19069
19070
19071
19072
19073
19074
19075
19076
19077
19078
19079
19080
19081
19082
19083
19084
19085
19086
19087
19088
19089
19090
19091
19092
19093
19094
19095
19096
19097
19098
19099
19100
19101
19102
19103
19104
19105
19106
19107
19108
19109
19110
19111
19112
19113
19114
19115
19116
19117
19118
19119
19120
19121
19122
19123
19124
19125
19126
19127
19128
19129
19130
19131
19132
19133
19134
19135
19136
19137
19138
19139
19140
19141
19142
19143
19144
19145
19146
19147
19148
19149
19150
19151
19152
19153
19154
19155
19156
19157
19158
19159
19160
19161
19162
19163
19164
19165
19166
19167
19168
19169
19170
19171
19172
19173
19174
19175
19176
19177
19178
19179
19180
19181
19182
19183
19184
19185
19186
19187
19188
19189
19190
19191
19192
19193
19194
19195
19196
19197
19198
19199
19200
19201
19202
19203
19204
19205
19206
19207
19208
19209
19210
19211
19212
19213
19214
19215
19216
19217
19218
19219
19220
19221
19222
19223
19224
19225
19226
19227
19228
19229
19230
19231
19232
19233
19234
19235
19236
19237
19238
19239
19240
19241
19242
19243
19244
19245
19246
19247
19248
19249
19250
19251
19252
19253
19254
19255
19256
19257
19258
19259
19260
19261
19262
19263
19264
19265
19266
19267
19268
19269
19270
19271
19272
19273
19274
19275
19276
19277
19278
19279
19280
19281
19282
19283
19284
19285
19286
19287
19288
19289
19290
19291
19292
19293
19294
19295
19296
19297
19298
19299
19300
19301
19302
19303
19304
19305
19306
19307
19308
19309
19310
19311
19312
19313
19314
19315
19316
19317
19318
19319
19320
19321
19322
19323
19324
19325
19326
19327
19328
19329
19330
19331
19332
19333
19334
19335
19336
19337
19338
19339
19340
19341
19342
19343
19344
19345
19346
19347
19348
19349
19350
19351
19352
19353
19354
19355
19356
19357
19358
19359
19360
19361
19362
19363
19364
19365
19366
19367
19368
19369
19370
19371
19372
19373
19374
19375
19376
19377
19378
19379
19380
19381
19382
19383
19384
19385
19386
19387
19388
19389
19390
19391
19392
19393
19394
19395
19396
19397
19398
19399
19400
19401
19402
19403
19404
19405
19406
19407
19408
19409
19410
19411
19412
19413
19414
19415
19416
19417
19418
19419
19420
19421
19422
19423
19424
19425
19426
19427
19428
19429
19430
19431
19432
19433
19434
19435
19436
19437
19438
19439
19440
19441
19442
19443
19444
19445
19446
19447
19448
19449
19450
19451
19452
19453
19454
19455
19456
19457
19458
19459
19460
19461
19462
19463
19464
19465
19466
19467
19468
19469
19470
19471
19472
19473
19474
19475
19476
19477
19478
19479
19480
19481
19482
19483
19484
19485
19486
19487
19488
19489
19490
19491
19492
19493
19494
19495
19496
19497
19498
19499
19500
19501
19502
19503
19504
19505
19506
19507
19508
19509
19510
19511
19512
19513
19514
19515
19516
19517
19518
19519
19520
19521
19522
19523
19524
19525
19526
19527
19528
19529
19530
19531
19532
19533
19534
19535
19536
19537
19538
19539
19540
19541
19542
19543
19544
19545
19546
19547
19548
19549
19550
19551
19552
19553
19554
19555
19556
19557
19558
19559
19560
19561
19562
19563
19564
19565
19566
19567
19568
19569
19570
19571
19572
19573
19574
19575
19576
19577
19578
19579
19580
19581
19582
19583
19584
19585
19586
19587
19588
19589
19590
19591
19592
19593
19594
19595
19596
19597
19598
19599
19600
19601
19602
19603
19604
19605
19606
19607
19608
19609
19610
19611
19612
19613
19614
19615
19616
19617
19618
19619
19620
19621
19622
19623
19624
19625
19626
19627
19628
19629
19630
19631
19632
19633
19634
19635
19636
19637
19638
19639
19640
19641
19642
19643
19644
19645
19646
19647
19648
19649
19650
19651
19652
19653
19654
19655
19656
19657
19658
19659
19660
19661
19662
19663
19664
19665
19666
19667
19668
19669
19670
19671
19672
19673
19674
19675
19676
19677
19678
19679
19680
19681
19682
19683
19684
19685
19686
19687
19688
19689
19690
19691
19692
19693
19694
19695
19696
19697
19698
19699
19700
19701
19702
19703
19704
19705
19706
19707
19708
19709
19710
19711
19712
19713
19714
19715
19716
19717
19718
19719
19720
19721
19722
19723
19724
19725
19726
19727
19728
19729
19730
19731
19732
19733
19734
19735
19736
19737
19738
19739
19740
19741
19742
19743
19744
19745
19746
19747
19748
19749
19750
19751
19752
19753
19754
19755
19756
19757
19758
19759
19760
19761
19762
19763
19764
19765
19766
19767
19768
19769
19770
19771
19772
19773
19774
19775
19776
19777
19778
19779
19780
19781
19782
19783
19784
19785
19786
19787
19788
19789
19790
19791
19792
19793
19794
19795
19796
19797
19798
19799
19800
19801
19802
19803
19804
19805
19806
19807
19808
19809
19810
19811
19812
19813
19814
19815
19816
19817
19818
19819
19820
19821
19822
19823
19824
19825
19826
19827
19828
19829
19830
19831
19832
19833
19834
19835
19836
19837
19838
19839
19840
19841
19842
19843
19844
19845
19846
19847
19848
19849
19850
19851
19852
19853
19854
19855
19856
19857
19858
19859
19860
19861
19862
19863
19864
19865
19866
19867
19868
19869
19870
19871
19872
19873
19874
19875
19876
19877
19878
19879
19880
19881
19882
19883
19884
19885
19886
19887
19888
19889
19890
19891
19892
19893
19894
19895
19896
19897
19898
19899
19900
19901
19902
19903
19904
19905
19906
19907
19908
19909
19910
19911
19912
19913
19914
19915
19916
19917
19918
19919
19920
19921
19922
19923
19924
19925
19926
19927
19928
19929
19930
19931
19932
19933
19934
19935
19936
19937
19938
19939
19940
19941
19942
19943
19944
19945
19946
19947
19948
19949
19950
19951
19952
19953
19954
19955
19956
19957
19958
19959
19960
19961
19962
19963
19964
19965
19966
19967
19968
19969
19970
19971
19972
19973
19974
19975
19976
19977
19978
19979
19980
19981
19982
19983
19984
19985
19986
19987
19988
19989
19990
19991
19992
19993
19994
19995
19996
19997
19998
19999
20000
20001
20002
20003
20004
20005
20006
20007
20008
20009
20010
20011
20012
20013
20014
20015
20016
20017
20018
20019
20020
20021
20022
20023
20024
20025
20026
20027
20028
20029
20030
20031
20032
20033
20034
20035
20036
20037
20038
20039
20040
20041
20042
20043
20044
20045
20046
20047
20048
20049
20050
20051
20052
20053
20054
20055
20056
20057
20058
20059
20060
20061
20062
20063
20064
20065
20066
20067
20068
20069
20070
20071
20072
20073
20074
20075
20076
20077
20078
20079
20080
20081
20082
20083
20084
20085
20086
20087
20088
20089
20090
20091
20092
20093
20094
20095
20096
20097
20098
20099
20100
20101
20102
20103
20104
20105
20106
20107
20108
20109
20110
20111
20112
20113
20114
20115
20116
20117
20118
20119
20120
20121
20122
20123
20124
20125
20126
20127
20128
20129
20130
20131
20132
20133
20134
20135
20136
20137
20138
20139
20140
20141
20142
20143
20144
20145
20146
20147
20148
20149
20150
20151
20152
20153
20154
20155
20156
20157
20158
20159
20160
20161
20162
20163
20164
20165
20166
20167
20168
20169
20170
20171
20172
20173
20174
20175
20176
20177
20178
20179
20180
20181
20182
20183
20184
20185
20186
20187
20188
20189
20190
20191
20192
20193
20194
20195
20196
20197
20198
20199
20200
20201
20202
20203
20204
20205
20206
20207
20208
20209
20210
20211
20212
20213
20214
20215
20216
20217
20218
20219
20220
20221
20222
20223
20224
20225
20226
20227
20228
20229
20230
20231
20232
20233
20234
20235
20236
20237
20238
20239
20240
20241
20242
20243
20244
20245
20246
20247
20248
20249
20250
20251
20252
20253
20254
20255
20256
20257
20258
20259
20260
20261
20262
20263
20264
20265
20266
20267
20268
20269
20270
20271
20272
20273
20274
20275
20276
20277
20278
20279
20280
20281
20282
20283
20284
20285
20286
20287
20288
20289
20290
20291
20292
20293
20294
20295
20296
20297
20298
20299
20300
20301
20302
20303
20304
20305
20306
20307
20308
20309
20310
20311
20312
20313
20314
20315
20316
20317
20318
20319
20320
20321
20322
20323
20324
20325
20326
20327
20328
20329
20330
20331
20332
20333
20334
20335
20336
20337
20338
20339
20340
20341
20342
20343
20344
20345
20346
20347
20348
20349
20350
20351
20352
20353
20354
20355
20356
20357
20358
20359
20360
20361
20362
20363
20364
20365
20366
20367
20368
20369
20370
20371
20372
20373
20374
20375
20376
20377
20378
20379
20380
20381
20382
20383
20384
20385
20386
20387
20388
20389
20390
20391
20392
20393
20394
20395
20396
20397
20398
20399
20400
20401
20402
20403
20404
20405
20406
20407
20408
20409
20410
20411
20412
20413
20414
20415
20416
20417
20418
20419
20420
20421
20422
20423
20424
20425
20426
20427
20428
20429
20430
20431
20432
20433
20434
20435
20436
20437
20438
20439
20440
20441
20442
20443
20444
20445
20446
20447
20448
20449
20450
20451
20452
20453
20454
20455
20456
20457
20458
20459
20460
20461
20462
20463
20464
20465
20466
20467
20468
20469
20470
20471
20472
20473
20474
20475
20476
20477
20478
20479
20480
20481
20482
20483
20484
20485
20486
20487
20488
20489
20490
20491
20492
20493
20494
20495
20496
20497
20498
20499
20500
20501
20502
20503
20504
20505
20506
20507
20508
20509
20510
20511
20512
20513
20514
20515
20516
20517
20518
20519
20520
20521
20522
20523
20524
20525
20526
20527
20528
20529
20530
20531
20532
20533
20534
20535
20536
20537
20538
20539
20540
20541
20542
20543
20544
20545
20546
20547
20548
20549
20550
20551
20552
20553
20554
20555
20556
20557
20558
20559
20560
20561
20562
20563
20564
20565
20566
20567
20568
20569
20570
20571
20572
20573
20574
20575
20576
20577
20578
20579
20580
20581
20582
20583
20584
20585
20586
20587
20588
20589
20590
20591
20592
20593
20594
20595
20596
20597
20598
20599
20600
20601
20602
20603
20604
20605
20606
20607
20608
20609
20610
20611
20612
20613
20614
20615
20616
20617
20618
20619
20620
20621
20622
20623
20624
20625
20626
20627
20628
20629
20630
20631
20632
20633
20634
20635
20636
20637
20638
20639
20640
20641
20642
20643
20644
20645
20646
20647
20648
20649
20650
20651
20652
20653
20654
20655
20656
20657
20658
20659
20660
20661
20662
20663
20664
20665
20666
20667
20668
20669
20670
20671
20672
20673
20674
20675
20676
20677
20678
20679
20680
20681
20682
20683
20684
20685
20686
20687
20688
20689
20690
20691
20692
20693
20694
20695
20696
20697
20698
20699
20700
20701
20702
20703
20704
20705
20706
20707
20708
20709
20710
20711
20712
20713
20714
20715
20716
20717
20718
20719
20720
20721
20722
20723
20724
20725
20726
20727
20728
20729
20730
20731
20732
20733
20734
20735
20736
20737
20738
20739
20740
20741
20742
20743
20744
20745
20746
20747
20748
20749
20750
20751
20752
20753
20754
20755
20756
20757
20758
20759
20760
20761
20762
20763
20764
20765
20766
20767
20768
20769
20770
20771
20772
20773
20774
20775
20776
20777
20778
20779
20780
20781
20782
20783
20784
20785
20786
20787
20788
20789
20790
20791
20792
20793
20794
20795
20796
20797
20798
20799
20800
20801
20802
20803
20804
20805
20806
20807
20808
20809
20810
20811
20812
20813
20814
20815
20816
20817
20818
20819
20820
20821
20822
20823
20824
20825
20826
20827
20828
20829
20830
20831
20832
20833
20834
20835
20836
20837
20838
20839
20840
20841
20842
20843
20844
20845
20846
20847
20848
20849
20850
20851
20852
20853
20854
20855
20856
20857
20858
20859
20860
20861
20862
20863
20864
20865
20866
20867
20868
20869
20870
20871
20872
20873
20874
20875
20876
20877
20878
20879
20880
20881
20882
20883
20884
20885
20886
20887
20888
20889
20890
20891
20892
20893
20894
20895
20896
20897
20898
20899
20900
20901
20902
20903
20904
20905
20906
20907
20908
20909
20910
20911
20912
20913
20914
20915
20916
20917
20918
20919
20920
20921
20922
20923
20924
20925
20926
20927
20928
20929
20930
20931
20932
20933
20934
20935
20936
20937
20938
20939
20940
20941
20942
20943
20944
20945
20946
20947
20948
20949
20950
20951
20952
20953
20954
20955
20956
20957
20958
20959
20960
20961
20962
20963
20964
20965
20966
20967
20968
20969
20970
20971
20972
20973
20974
20975
20976
20977
20978
20979
20980
20981
20982
20983
20984
20985
20986
20987
20988
20989
20990
20991
20992
20993
20994
20995
20996
20997
20998
20999
21000
21001
21002
21003
21004
21005
21006
21007
21008
21009
21010
21011
21012
21013
21014
21015
21016
21017
21018
21019
21020
21021
21022
21023
21024
21025
21026
21027
21028
21029
21030
21031
21032
21033
21034
21035
21036
21037
21038
21039
21040
21041
21042
21043
21044
21045
21046
21047
21048
21049
21050
21051
21052
21053
21054
21055
21056
21057
21058
21059
21060
21061
21062
21063
21064
21065
21066
21067
21068
21069
21070
21071
21072
21073
21074
21075
21076
21077
21078
21079
21080
21081
21082
21083
21084
21085
21086
21087
21088
21089
21090
21091
21092
21093
21094
21095
21096
21097
21098
21099
21100
21101
21102
21103
21104
21105
21106
21107
21108
21109
21110
21111
21112
21113
21114
21115
21116
21117
21118
21119
21120
21121
21122
21123
21124
21125
21126
21127
21128
21129
21130
21131
21132
21133
21134
21135
21136
21137
21138
21139
21140
21141
21142
21143
21144
21145
21146
21147
21148
21149
21150
21151
21152
21153
21154
21155
21156
21157
21158
21159
21160
21161
21162
21163
21164
21165
21166
21167
21168
21169
21170
21171
21172
21173
21174
21175
21176
21177
21178
21179
21180
21181
21182
21183
21184
21185
21186
21187
21188
21189
21190
21191
21192
21193
21194
21195
21196
21197
21198
21199
21200
21201
21202
21203
21204
21205
21206
21207
21208
21209
21210
21211
21212
21213
21214
21215
21216
21217
21218
21219
21220
21221
21222
21223
21224
21225
21226
21227
21228
21229
21230
21231
21232
21233
21234
21235
21236
21237
21238
21239
21240
21241
21242
21243
21244
21245
21246
21247
21248
21249
21250
21251
21252
21253
21254
21255
21256
21257
21258
21259
21260
21261
21262
21263
21264
21265
21266
21267
21268
21269
21270
21271
21272
21273
21274
21275
21276
21277
21278
21279
21280
21281
21282
21283
21284
21285
21286
21287
21288
21289
21290
21291
21292
21293
21294
21295
21296
21297
21298
21299
21300
21301
21302
21303
21304
21305
21306
21307
21308
21309
21310
21311
21312
21313
21314
21315
21316
21317
21318
21319
21320
21321
21322
21323
21324
21325
21326
21327
21328
21329
21330
21331
21332
21333
21334
21335
21336
21337
21338
21339
21340
21341
21342
21343
21344
21345
21346
21347
21348
21349
21350
21351
21352
21353
21354
21355
21356
21357
21358
21359
21360
21361
21362
21363
21364
21365
21366
21367
21368
21369
21370
21371
21372
21373
21374
21375
21376
21377
21378
21379
21380
21381
21382
21383
21384
21385
21386
21387
21388
21389
21390
21391
21392
21393
21394
21395
21396
21397
21398
21399
21400
21401
21402
21403
21404
21405
21406
21407
21408
21409
21410
21411
21412
21413
21414
21415
21416
21417
21418
21419
21420
21421
21422
21423
21424
21425
21426
21427
21428
21429
21430
21431
21432
21433
21434
21435
21436
21437
21438
21439
21440
21441
21442
21443
21444
21445
21446
21447
21448
21449
21450
21451
21452
21453
21454
21455
21456
21457
21458
21459
21460
21461
21462
21463
21464
21465
21466
21467
21468
21469
21470
21471
21472
21473
21474
21475
21476
21477
21478
21479
21480
21481
21482
21483
21484
21485
21486
21487
21488
21489
21490
21491
21492
21493
21494
21495
21496
21497
21498
21499
21500
21501
21502
21503
21504
21505
21506
21507
21508
21509
21510
21511
21512
21513
21514
21515
21516
21517
21518
21519
21520
21521
21522
21523
21524
21525
21526
21527
21528
21529
21530
21531
21532
21533
21534
21535
21536
21537
21538
21539
21540
21541
21542
21543
21544
21545
21546
21547
21548
21549
21550
21551
21552
21553
21554
21555
21556
21557
21558
21559
21560
21561
21562
21563
21564
21565
21566
21567
21568
21569
21570
21571
21572
21573
21574
21575
21576
21577
21578
21579
21580
21581
21582
21583
21584
21585
21586
21587
21588
21589
21590
21591
21592
21593
21594
21595
21596
21597
21598
21599
21600
21601
21602
21603
21604
21605
21606
21607
21608
21609
21610
21611
21612
21613
21614
21615
21616
21617
21618
21619
21620
21621
21622
21623
21624
21625
21626
21627
21628
21629
21630
21631
21632
21633
21634
21635
21636
21637
21638
21639
21640
21641
21642
21643
21644
21645
21646
21647
21648
21649
21650
21651
21652
21653
21654
21655
21656
21657
21658
21659
21660
21661
21662
21663
21664
21665
21666
21667
21668
21669
21670
21671
21672
21673
21674
21675
21676
21677
21678
21679
21680
21681
21682
21683
21684
21685
21686
21687
21688
21689
21690
21691
21692
21693
21694
21695
21696
21697
21698
21699
21700
21701
21702
21703
21704
21705
21706
21707
21708
21709
21710
21711
21712
21713
21714
21715
21716
21717
21718
21719
21720
21721
21722
21723
21724
21725
21726
21727
21728
21729
21730
21731
21732
21733
21734
21735
21736
21737
21738
21739
21740
21741
21742
21743
21744
21745
21746
21747
21748
21749
21750
21751
21752
21753
21754
21755
21756
21757
21758
21759
21760
21761
21762
21763
21764
21765
21766
21767
21768
21769
21770
21771
21772
21773
21774
21775
21776
21777
21778
21779
21780
21781
21782
21783
21784
21785
21786
21787
21788
21789
21790
21791
21792
21793
21794
21795
21796
21797
21798
21799
21800
21801
21802
21803
21804
21805
21806
21807
21808
21809
21810
21811
21812
21813
21814
21815
21816
21817
21818
21819
21820
21821
21822
21823
21824
21825
21826
21827
21828
21829
21830
21831
21832
21833
21834
21835
21836
21837
21838
21839
21840
21841
21842
21843
21844
21845
21846
21847
21848
21849
21850
21851
21852
21853
21854
21855
21856
21857
21858
21859
21860
21861
21862
21863
21864
21865
21866
21867
21868
21869
21870
21871
21872
21873
21874
21875
21876
21877
21878
21879
21880
21881
21882
21883
21884
21885
21886
21887
21888
21889
21890
21891
21892
21893
21894
21895
21896
21897
21898
21899
21900
21901
21902
21903
21904
21905
21906
21907
21908
21909
21910
21911
21912
21913
21914
21915
21916
21917
21918
21919
21920
21921
21922
21923
21924
21925
21926
21927
21928
21929
21930
21931
21932
21933
21934
21935
21936
21937
21938
21939
21940
21941
21942
21943
21944
21945
21946
21947
21948
21949
21950
21951
21952
21953
21954
21955
21956
21957
21958
21959
21960
21961
21962
21963
21964
21965
21966
21967
21968
21969
21970
21971
21972
21973
21974
21975
21976
21977
21978
21979
21980
21981
21982
21983
21984
21985
21986
21987
21988
21989
21990
21991
21992
21993
21994
21995
21996
21997
21998
21999
22000
22001
22002
22003
22004
22005
22006
22007
22008
22009
22010
22011
22012
22013
22014
22015
22016
22017
22018
22019
22020
22021
22022
22023
22024
22025
22026
22027
22028
22029
22030
22031
22032
22033
22034
22035
22036
22037
22038
22039
22040
22041
22042
22043
22044
22045
22046
22047
22048
22049
22050
22051
22052
22053
22054
22055
22056
22057
22058
22059
22060
22061
22062
22063
22064
22065
22066
22067
22068
22069
22070
22071
22072
22073
22074
22075
22076
22077
22078
22079
22080
22081
22082
22083
22084
22085
22086
22087
22088
22089
22090
22091
22092
22093
22094
22095
22096
22097
22098
22099
22100
22101
22102
22103
22104
22105
22106
22107
22108
22109
22110
22111
22112
22113
22114
22115
22116
22117
22118
22119
22120
22121
22122
22123
22124
22125
22126
22127
22128
22129
22130
22131
22132
22133
22134
22135
22136
22137
22138
22139
22140
22141
22142
22143
22144
22145
22146
22147
22148
22149
22150
22151
22152
22153
22154
22155
22156
22157
22158
22159
22160
22161
22162
22163
22164
22165
22166
22167
22168
22169
22170
22171
22172
22173
22174
22175
22176
22177
22178
22179
22180
22181
22182
22183
22184
22185
22186
22187
22188
22189
22190
22191
22192
22193
22194
22195
22196
22197
22198
22199
22200
22201
22202
22203
22204
22205
22206
22207
22208
22209
22210
22211
22212
22213
22214
22215
22216
22217
22218
22219
22220
22221
22222
22223
22224
22225
22226
22227
22228
22229
22230
22231
22232
22233
22234
22235
22236
22237
22238
22239
22240
22241
22242
22243
22244
22245
22246
22247
22248
22249
22250
22251
22252
22253
22254
22255
22256
22257
22258
22259
22260
22261
22262
22263
22264
22265
22266
22267
22268
22269
22270
22271
22272
22273
22274
22275
22276
22277
22278
22279
22280
22281
22282
22283
22284
22285
22286
22287
22288
22289
22290
22291
22292
22293
22294
22295
22296
22297
22298
22299
22300
22301
22302
22303
22304
22305
22306
22307
22308
22309
22310
22311
22312
22313
22314
22315
22316
22317
22318
22319
22320
22321
22322
22323
22324
22325
22326
22327
22328
22329
22330
22331
22332
22333
22334
22335
22336
22337
22338
22339
22340
22341
22342
22343
22344
22345
22346
22347
22348
22349
22350
22351
22352
22353
22354
22355
22356
22357
22358
22359
22360
22361
22362
22363
22364
22365
22366
22367
22368
22369
22370
22371
22372
22373
22374
22375
22376
22377
22378
22379
22380
22381
22382
22383
22384
22385
22386
22387
22388
22389
22390
22391
22392
22393
22394
22395
22396
22397
22398
22399
22400
22401
22402
22403
22404
22405
22406
22407
22408
22409
22410
22411
22412
22413
22414
22415
22416
22417
22418
22419
22420
22421
22422
22423
22424
22425
22426
22427
22428
22429
22430
22431
22432
22433
22434
22435
22436
22437
22438
22439
22440
22441
22442
22443
22444
22445
22446
22447
22448
22449
22450
22451
22452
22453
22454
22455
22456
22457
22458
22459
22460
22461
22462
22463
22464
22465
22466
22467
22468
22469
22470
22471
22472
22473
22474
22475
22476
22477
22478
22479
22480
22481
22482
22483
22484
22485
22486
22487
22488
22489
22490
22491
22492
22493
22494
22495
22496
22497
22498
22499
22500
22501
22502
22503
22504
22505
22506
22507
22508
22509
22510
22511
22512
22513
22514
22515
22516
22517
22518
22519
22520
22521
22522
22523
22524
22525
22526
22527
22528
22529
22530
22531
22532
22533
22534
22535
22536
22537
22538
22539
22540
22541
22542
22543
22544
22545
22546
22547
22548
22549
22550
22551
22552
22553
22554
22555
22556
22557
22558
22559
22560
22561
22562
22563
22564
22565
22566
22567
22568
22569
22570
22571
22572
22573
22574
22575
22576
22577
22578
22579
22580
22581
22582
22583
22584
22585
22586
22587
22588
22589
22590
22591
22592
22593
22594
22595
22596
22597
22598
22599
22600
22601
22602
22603
22604
22605
22606
22607
22608
22609
22610
22611
22612
22613
22614
22615
22616
22617
22618
22619
22620
22621
22622
22623
22624
22625
22626
22627
22628
22629
22630
22631
22632
22633
22634
22635
22636
22637
22638
22639
22640
22641
22642
22643
22644
22645
22646
22647
22648
22649
22650
22651
22652
22653
22654
22655
22656
22657
22658
22659
22660
22661
22662
22663
22664
22665
22666
22667
22668
22669
22670
22671
22672
22673
22674
22675
22676
22677
22678
22679
22680
22681
22682
22683
22684
22685
22686
22687
22688
22689
22690
22691
22692
22693
22694
22695
22696
22697
22698
22699
22700
22701
22702
22703
22704
22705
22706
22707
22708
22709
22710
22711
22712
22713
22714
22715
22716
22717
22718
22719
22720
22721
22722
22723
22724
22725
22726
22727
22728
22729
22730
22731
22732
22733
22734
22735
22736
22737
22738
22739
22740
22741
22742
22743
22744
22745
22746
22747
22748
22749
22750
22751
22752
22753
22754
22755
22756
22757
22758
22759
22760
22761
22762
22763
22764
22765
22766
22767
22768
22769
22770
22771
22772
22773
22774
22775
22776
22777
22778
22779
22780
22781
22782
22783
22784
22785
22786
22787
22788
22789
22790
22791
22792
22793
22794
22795
22796
22797
22798
22799
22800
22801
22802
22803
22804
22805
22806
22807
22808
22809
22810
22811
22812
22813
22814
22815
22816
22817
22818
22819
22820
22821
22822
22823
22824
22825
22826
22827
22828
22829
22830
22831
22832
22833
22834
22835
22836
22837
22838
22839
22840
22841
22842
22843
22844
22845
22846
22847
22848
22849
22850
22851
22852
22853
22854
22855
22856
22857
22858
22859
22860
22861
22862
22863
22864
22865
22866
22867
22868
22869
22870
22871
22872
22873
22874
22875
22876
22877
22878
22879
22880
22881
22882
22883
22884
22885
22886
22887
22888
22889
22890
22891
22892
22893
22894
22895
22896
22897
22898
22899
22900
22901
22902
22903
22904
22905
22906
22907
22908
22909
22910
22911
22912
22913
22914
22915
22916
22917
22918
22919
22920
22921
22922
22923
22924
22925
22926
22927
22928
22929
22930
22931
22932
22933
22934
22935
22936
22937
22938
22939
22940
22941
22942
22943
22944
22945
22946
22947
22948
22949
22950
22951
22952
22953
22954
22955
22956
22957
22958
22959
22960
22961
22962
22963
22964
22965
22966
22967
22968
22969
22970
22971
22972
22973
22974
22975
22976
22977
22978
22979
22980
22981
22982
22983
22984
22985
22986
22987
22988
22989
22990
22991
22992
22993
22994
22995
22996
22997
22998
22999
23000
23001
23002
23003
23004
23005
23006
23007
23008
23009
23010
23011
23012
23013
23014
23015
23016
23017
23018
23019
23020
23021
23022
23023
23024
23025
23026
23027
23028
23029
23030
23031
23032
23033
23034
23035
23036
23037
23038
23039
23040
23041
23042
23043
23044
23045
23046
23047
23048
23049
23050
23051
23052
23053
23054
23055
23056
23057
23058
23059
23060
23061
23062
23063
23064
23065
23066
23067
23068
23069
23070
23071
23072
23073
23074
23075
23076
23077
23078
23079
23080
23081
23082
23083
23084
23085
23086
23087
23088
23089
23090
23091
23092
23093
23094
23095
23096
23097
23098
23099
23100
23101
23102
23103
23104
23105
23106
23107
23108
23109
23110
23111
23112
23113
23114
23115
23116
23117
23118
23119
23120
23121
23122
23123
23124
23125
23126
23127
23128
23129
23130
23131
23132
23133
23134
23135
23136
23137
23138
23139
23140
23141
23142
23143
23144
23145
23146
23147
23148
23149
23150
23151
23152
23153
23154
23155
23156
23157
23158
23159
23160
23161
23162
23163
23164
23165
23166
23167
23168
23169
23170
23171
23172
23173
23174
23175
23176
23177
23178
23179
23180
23181
23182
23183
23184
23185
23186
23187
23188
23189
23190
23191
23192
23193
23194
23195
23196
23197
23198
23199
23200
23201
23202
23203
23204
23205
23206
23207
23208
23209
23210
23211
23212
23213
23214
23215
23216
23217
23218
23219
23220
23221
23222
23223
23224
23225
23226
23227
23228
23229
23230
23231
23232
23233
23234
23235
23236
23237
23238
23239
23240
23241
23242
23243
23244
23245
23246
23247
23248
23249
23250
23251
23252
23253
23254
23255
23256
23257
23258
23259
23260
23261
23262
23263
23264
23265
23266
23267
23268
23269
23270
23271
23272
23273
23274
23275
23276
23277
23278
23279
23280
23281
23282
23283
23284
23285
23286
23287
23288
23289
23290
23291
23292
23293
23294
23295
23296
23297
23298
23299
23300
23301
23302
23303
23304
23305
23306
23307
23308
23309
23310
23311
23312
23313
23314
23315
23316
23317
23318
23319
23320
23321
23322
23323
23324
23325
23326
23327
23328
23329
23330
23331
23332
23333
23334
23335
23336
23337
23338
23339
23340
23341
23342
23343
23344
23345
23346
23347
23348
23349
23350
23351
23352
23353
23354
23355
23356
23357
23358
23359
23360
23361
23362
23363
23364
23365
23366
23367
23368
23369
23370
23371
23372
23373
23374
23375
23376
23377
23378
23379
23380
23381
23382
23383
23384
23385
23386
23387
23388
23389
23390
23391
23392
23393
23394
23395
23396
23397
23398
23399
23400
23401
23402
23403
23404
23405
23406
23407
23408
23409
23410
23411
23412
23413
23414
23415
23416
23417
23418
23419
23420
23421
23422
23423
23424
23425
23426
23427
23428
23429
23430
23431
23432
23433
23434
23435
23436
23437
23438
23439
23440
23441
23442
23443
23444
23445
23446
23447
23448
23449
23450
23451
23452
23453
23454
23455
23456
23457
23458
23459
23460
23461
23462
23463
23464
23465
23466
23467
23468
23469
23470
23471
23472
23473
23474
23475
23476
23477
23478
23479
23480
23481
23482
23483
23484
23485
23486
23487
23488
23489
23490
23491
23492
23493
23494
23495
23496
23497
23498
23499
23500
23501
23502
23503
23504
23505
23506
23507
23508
23509
23510
23511
23512
23513
23514
23515
23516
23517
23518
23519
23520
23521
23522
23523
23524
23525
23526
23527
23528
23529
23530
23531
23532
23533
23534
23535
23536
23537
23538
23539
23540
23541
23542
23543
23544
23545
23546
23547
23548
23549
23550
23551
23552
23553
23554
23555
23556
23557
23558
23559
23560
23561
23562
23563
23564
23565
23566
23567
23568
23569
23570
23571
23572
23573
23574
23575
23576
23577
23578
23579
23580
23581
23582
23583
23584
23585
23586
23587
23588
23589
23590
23591
23592
23593
23594
23595
23596
23597
23598
23599
23600
23601
23602
23603
23604
23605
23606
23607
23608
23609
23610
23611
23612
23613
23614
23615
23616
23617
23618
23619
23620
23621
23622
23623
23624
23625
23626
23627
23628
23629
23630
23631
23632
23633
23634
23635
23636
23637
23638
23639
23640
23641
23642
23643
23644
23645
23646
23647
23648
23649
23650
23651
23652
23653
23654
23655
23656
23657
23658
23659
23660
23661
23662
23663
23664
23665
23666
23667
23668
23669
23670
23671
23672
23673
23674
23675
23676
23677
23678
23679
23680
23681
23682
23683
23684
23685
23686
23687
23688
23689
23690
23691
23692
23693
23694
23695
23696
23697
23698
23699
23700
23701
23702
23703
23704
23705
23706
23707
23708
23709
23710
23711
23712
23713
23714
23715
23716
23717
23718
23719
23720
23721
23722
23723
23724
23725
23726
23727
23728
23729
23730
23731
23732
23733
23734
23735
23736
23737
23738
23739
23740
23741
23742
23743
23744
23745
23746
23747
23748
23749
23750
23751
23752
23753
23754
23755
23756
23757
23758
23759
23760
23761
23762
23763
23764
23765
23766
23767
23768
23769
23770
23771
23772
23773
23774
23775
23776
23777
23778
23779
23780
23781
23782
23783
23784
23785
23786
23787
23788
23789
23790
23791
23792
23793
23794
23795
23796
23797
23798
23799
23800
23801
23802
23803
23804
23805
23806
23807
23808
23809
23810
23811
23812
23813
23814
23815
23816
23817
23818
23819
23820
23821
23822
23823
23824
23825
23826
23827
23828
23829
23830
23831
23832
23833
23834
23835
23836
23837
23838
23839
23840
23841
23842
23843
23844
23845
23846
23847
23848
23849
23850
23851
23852
23853
23854
23855
23856
23857
23858
23859
23860
23861
23862
23863
23864
23865
23866
23867
23868
23869
23870
23871
23872
23873
23874
23875
23876
23877
23878
23879
23880
23881
23882
23883
23884
23885
23886
23887
23888
23889
23890
23891
23892
23893
23894
23895
23896
23897
23898
23899
23900
23901
23902
23903
23904
23905
23906
23907
23908
23909
23910
23911
23912
23913
23914
23915
23916
23917
23918
23919
23920
23921
23922
23923
23924
23925
23926
23927
23928
23929
23930
23931
23932
23933
23934
23935
23936
23937
23938
23939
23940
23941
23942
23943
23944
23945
23946
23947
23948
23949
23950
23951
23952
23953
23954
23955
23956
23957
23958
23959
23960
23961
23962
23963
23964
23965
23966
23967
23968
23969
23970
23971
23972
23973
23974
23975
23976
23977
23978
23979
23980
23981
23982
23983
23984
23985
23986
23987
23988
23989
23990
23991
23992
23993
23994
23995
23996
23997
23998
23999
24000
24001
24002
24003
24004
24005
24006
24007
24008
24009
24010
24011
24012
24013
24014
24015
24016
24017
24018
24019
24020
24021
24022
24023
24024
24025
24026
24027
24028
24029
24030
24031
24032
24033
24034
24035
24036
24037
24038
24039
24040
24041
24042
24043
24044
24045
24046
24047
24048
24049
24050
24051
24052
24053
24054
24055
24056
24057
24058
24059
24060
24061
24062
24063
24064
24065
24066
24067
24068
24069
24070
24071
24072
24073
24074
24075
24076
24077
24078
24079
24080
24081
24082
24083
24084
24085
24086
24087
24088
24089
24090
24091
24092
24093
24094
24095
24096
24097
24098
24099
24100
24101
24102
24103
24104
24105
24106
24107
24108
24109
24110
24111
24112
24113
24114
24115
24116
24117
24118
24119
24120
24121
24122
24123
24124
24125
24126
24127
24128
24129
24130
24131
24132
24133
24134
24135
24136
24137
24138
24139
24140
24141
24142
24143
24144
24145
24146
24147
24148
24149
24150
24151
24152
24153
24154
24155
24156
24157
24158
24159
24160
24161
24162
24163
24164
24165
24166
24167
24168
24169
24170
24171
24172
24173
24174
24175
24176
24177
24178
24179
24180
24181
24182
24183
24184
24185
24186
24187
24188
24189
24190
24191
24192
24193
24194
24195
24196
24197
24198
24199
24200
24201
24202
24203
24204
24205
24206
24207
24208
24209
24210
24211
24212
24213
24214
24215
24216
24217
24218
24219
24220
24221
24222
24223
24224
24225
24226
24227
24228
24229
24230
24231
24232
24233
24234
24235
24236
24237
24238
24239
24240
24241
24242
24243
24244
24245
24246
24247
24248
24249
24250
24251
24252
24253
24254
24255
24256
24257
24258
24259
24260
24261
24262
24263
24264
24265
24266
24267
24268
24269
24270
24271
24272
24273
24274
24275
24276
24277
24278
24279
24280
24281
24282
24283
24284
24285
24286
24287
24288
24289
24290
24291
24292
24293
24294
24295
24296
24297
24298
24299
24300
24301
24302
24303
24304
24305
24306
24307
24308
24309
24310
24311
24312
24313
24314
24315
24316
24317
24318
24319
24320
24321
24322
24323
24324
24325
24326
24327
24328
24329
24330
24331
24332
24333
24334
24335
24336
24337
24338
24339
24340
24341
24342
24343
24344
24345
24346
24347
24348
24349
24350
24351
24352
24353
24354
24355
24356
24357
24358
24359
24360
24361
24362
24363
24364
24365
24366
24367
24368
24369
24370
24371
24372
24373
24374
24375
24376
24377
24378
24379
24380
24381
24382
24383
24384
24385
24386
24387
24388
24389
24390
24391
24392
24393
24394
24395
24396
24397
24398
24399
24400
24401
24402
24403
24404
24405
24406
24407
24408
24409
24410
24411
24412
24413
24414
24415
24416
24417
24418
24419
24420
24421
24422
24423
24424
24425
24426
24427
24428
24429
24430
24431
24432
24433
24434
24435
24436
24437
24438
24439
24440
24441
24442
24443
24444
24445
24446
24447
24448
24449
24450
24451
24452
24453
24454
24455
24456
24457
24458
24459
24460
24461
24462
24463
24464
24465
24466
24467
24468
24469
24470
24471
24472
24473
24474
24475
24476
24477
24478
24479
24480
24481
24482
24483
24484
24485
24486
24487
24488
24489
24490
24491
24492
24493
24494
24495
24496
24497
24498
24499
24500
24501
24502
24503
24504
24505
24506
24507
24508
24509
24510
24511
24512
24513
24514
24515
24516
24517
24518
24519
24520
24521
24522
24523
24524
24525
24526
24527
24528
24529
24530
24531
24532
24533
24534
24535
24536
24537
24538
24539
24540
24541
24542
24543
24544
24545
24546
24547
24548
24549
24550
24551
24552
24553
24554
24555
24556
24557
24558
24559
24560
24561
24562
24563
24564
24565
24566
24567
24568
24569
24570
24571
24572
24573
24574
24575
24576
24577
24578
24579
24580
24581
24582
24583
24584
24585
24586
24587
24588
24589
24590
24591
24592
24593
24594
24595
24596
24597
24598
24599
24600
24601
24602
24603
24604
24605
24606
24607
24608
24609
24610
24611
24612
24613
24614
24615
24616
24617
24618
24619
24620
24621
24622
24623
24624
24625
24626
24627
24628
24629
24630
24631
24632
24633
24634
24635
24636
24637
24638
24639
24640
24641
24642
24643
24644
24645
24646
24647
24648
24649
24650
24651
24652
24653
24654
24655
24656
24657
24658
24659
24660
24661
24662
24663
24664
24665
24666
24667
24668
24669
24670
24671
24672
24673
24674
24675
24676
24677
24678
24679
24680
24681
24682
24683
24684
24685
24686
24687
24688
24689
24690
24691
24692
24693
24694
24695
24696
24697
24698
24699
24700
24701
24702
24703
24704
24705
24706
24707
24708
24709
24710
24711
24712
24713
24714
24715
24716
24717
24718
24719
24720
24721
24722
24723
24724
24725
24726
24727
24728
24729
24730
24731
24732
24733
24734
24735
24736
24737
24738
24739
24740
24741
24742
24743
24744
24745
24746
24747
24748
24749
24750
24751
24752
24753
24754
24755
24756
24757
24758
24759
24760
24761
24762
24763
24764
24765
24766
24767
24768
24769
24770
24771
24772
24773
24774
24775
24776
24777
24778
24779
24780
24781
24782
24783
24784
24785
24786
24787
24788
24789
24790
24791
24792
24793
24794
24795
24796
24797
24798
24799
24800
24801
24802
24803
24804
24805
24806
24807
24808
24809
24810
24811
24812
24813
24814
24815
24816
24817
24818
24819
24820
24821
24822
24823
24824
24825
24826
24827
24828
24829
24830
24831
24832
24833
24834
24835
24836
24837
24838
24839
24840
24841
24842
24843
24844
24845
24846
24847
24848
24849
24850
24851
24852
24853
24854
24855
24856
24857
24858
24859
24860
24861
24862
24863
24864
24865
24866
24867
24868
24869
24870
24871
24872
24873
24874
24875
24876
24877
24878
24879
24880
24881
24882
24883
24884
24885
24886
24887
24888
24889
24890
24891
24892
24893
24894
24895
24896
24897
24898
24899
24900
24901
24902
24903
24904
24905
24906
24907
24908
24909
24910
24911
24912
24913
24914
24915
24916
24917
24918
24919
24920
24921
24922
24923
24924
24925
24926
24927
24928
24929
24930
24931
24932
24933
24934
24935
24936
24937
24938
24939
24940
24941
24942
24943
24944
24945
24946
24947
24948
24949
24950
24951
24952
24953
24954
24955
24956
24957
24958
24959
24960
24961
24962
24963
24964
24965
24966
24967
24968
24969
24970
24971
24972
24973
24974
24975
24976
24977
24978
24979
24980
24981
24982
24983
24984
24985
24986
24987
24988
24989
24990
24991
24992
24993
24994
24995
24996
24997
24998
24999
25000
25001
25002
25003
25004
25005
25006
25007
25008
25009
25010
25011
25012
25013
25014
25015
25016
25017
25018
25019
25020
25021
25022
25023
25024
25025
25026
25027
25028
25029
25030
25031
25032
25033
25034
25035
25036
25037
25038
25039
25040
25041
25042
25043
25044
25045
25046
25047
25048
25049
25050
25051
25052
25053
25054
25055
25056
25057
25058
25059
25060
25061
25062
25063
25064
25065
25066
25067
25068
25069
25070
25071
25072
25073
25074
25075
25076
25077
25078
25079
25080
25081
25082
25083
25084
25085
25086
25087
25088
25089
25090
25091
25092
25093
25094
25095
25096
25097
25098
25099
25100
25101
25102
25103
25104
25105
25106
25107
25108
25109
25110
25111
25112
25113
25114
25115
25116
25117
25118
25119
25120
25121
25122
25123
25124
25125
25126
25127
25128
25129
25130
25131
25132
25133
25134
25135
25136
25137
25138
25139
25140
25141
25142
25143
25144
25145
25146
25147
25148
25149
25150
25151
25152
25153
25154
25155
25156
25157
25158
25159
25160
25161
25162
25163
25164
25165
25166
25167
25168
25169
25170
25171
25172
25173
25174
25175
25176
25177
25178
25179
25180
25181
25182
25183
25184
25185
25186
25187
25188
25189
25190
25191
25192
25193
25194
25195
25196
25197
25198
25199
25200
25201
25202
25203
25204
25205
25206
25207
25208
25209
25210
25211
25212
25213
25214
25215
25216
25217
25218
25219
25220
25221
25222
25223
25224
25225
25226
25227
25228
25229
25230
25231
25232
25233
25234
25235
25236
25237
25238
25239
25240
25241
25242
25243
25244
25245
25246
25247
25248
25249
25250
25251
25252
25253
25254
25255
25256
25257
25258
25259
25260
25261
25262
25263
25264
25265
25266
25267
25268
25269
25270
25271
25272
25273
25274
25275
25276
25277
25278
25279
25280
25281
25282
25283
25284
25285
25286
25287
25288
25289
25290
25291
25292
25293
25294
25295
25296
25297
25298
25299
25300
25301
25302
25303
25304
25305
25306
25307
25308
25309
25310
25311
25312
25313
25314
25315
25316
25317
25318
25319
25320
25321
25322
25323
25324
25325
25326
25327
25328
25329
25330
25331
25332
25333
25334
25335
25336
25337
25338
25339
25340
25341
25342
25343
25344
25345
25346
25347
25348
25349
25350
25351
25352
25353
25354
25355
25356
25357
25358
25359
25360
25361
25362
25363
25364
25365
25366
25367
25368
25369
25370
25371
25372
25373
25374
25375
25376
25377
25378
25379
25380
25381
25382
25383
25384
25385
25386
25387
25388
25389
25390
25391
25392
25393
25394
25395
25396
25397
25398
25399
25400
25401
25402
25403
25404
25405
25406
25407
25408
25409
25410
25411
25412
25413
25414
25415
25416
25417
25418
25419
25420
25421
25422
25423
25424
25425
25426
25427
25428
25429
25430
25431
25432
25433
25434
25435
25436
25437
25438
25439
25440
25441
25442
25443
25444
25445
25446
25447
25448
25449
25450
25451
25452
25453
25454
25455
25456
25457
25458
25459
25460
25461
25462
25463
25464
25465
25466
25467
25468
25469
25470
25471
25472
25473
25474
25475
25476
25477
25478
25479
25480
25481
25482
25483
25484
25485
25486
25487
25488
25489
25490
25491
25492
25493
25494
25495
25496
25497
25498
25499
25500
25501
25502
25503
25504
25505
25506
25507
25508
25509
25510
25511
25512
25513
25514
25515
25516
25517
25518
25519
25520
25521
25522
25523
25524
25525
25526
25527
25528
25529
25530
25531
25532
25533
25534
25535
25536
25537
25538
25539
25540
25541
25542
25543
25544
25545
25546
25547
25548
25549
25550
25551
25552
25553
25554
25555
25556
25557
25558
25559
25560
25561
25562
25563
25564
25565
25566
25567
25568
25569
25570
25571
25572
25573
25574
25575
25576
25577
25578
25579
25580
25581
25582
25583
25584
25585
25586
25587
25588
25589
25590
25591
25592
25593
25594
25595
25596
25597
25598
25599
25600
25601
25602
25603
25604
25605
25606
25607
25608
25609
25610
25611
25612
25613
25614
25615
25616
25617
25618
25619
25620
25621
25622
25623
25624
25625
25626
25627
25628
25629
25630
25631
25632
25633
25634
25635
25636
25637
25638
25639
25640
25641
25642
25643
25644
25645
25646
25647
25648
25649
25650
25651
25652
25653
25654
25655
25656
25657
25658
25659
25660
25661
25662
25663
25664
25665
25666
25667
25668
25669
25670
25671
25672
25673
25674
25675
25676
25677
25678
25679
25680
25681
25682
25683
25684
25685
25686
25687
25688
25689
25690
25691
25692
25693
25694
25695
25696
25697
25698
25699
25700
25701
25702
25703
25704
25705
25706
25707
25708
25709
25710
25711
25712
25713
25714
25715
25716
25717
25718
25719
25720
25721
25722
25723
25724
25725
25726
25727
25728
25729
25730
25731
25732
25733
25734
25735
25736
25737
25738
25739
25740
25741
25742
25743
25744
25745
25746
25747
25748
25749
25750
25751
25752
25753
25754
25755
25756
25757
25758
25759
25760
25761
25762
25763
25764
25765
25766
25767
25768
25769
25770
25771
25772
25773
25774
25775
25776
25777
25778
25779
25780
25781
25782
25783
25784
25785
25786
25787
25788
25789
25790
25791
25792
25793
25794
25795
25796
25797
25798
25799
25800
25801
25802
25803
25804
25805
25806
25807
25808
25809
25810
25811
25812
25813
25814
25815
25816
25817
25818
25819
25820
25821
25822
25823
25824
25825
25826
25827
25828
25829
25830
25831
25832
25833
25834
25835
25836
25837
25838
25839
25840
25841
25842
25843
25844
25845
25846
25847
25848
25849
25850
25851
25852
25853
25854
25855
25856
25857
25858
25859
25860
25861
25862
25863
25864
25865
25866
25867
25868
25869
25870
25871
25872
25873
25874
25875
25876
25877
25878
25879
25880
25881
25882
25883
25884
25885
25886
25887
25888
25889
25890
25891
25892
25893
25894
25895
25896
25897
25898
25899
25900
25901
25902
25903
25904
25905
25906
25907
25908
25909
25910
25911
25912
25913
25914
25915
25916
25917
25918
25919
25920
25921
25922
25923
25924
25925
25926
25927
25928
25929
25930
25931
25932
25933
25934
25935
25936
25937
25938
25939
25940
25941
25942
25943
25944
25945
25946
25947
25948
25949
25950
25951
25952
25953
25954
25955
25956
25957
25958
25959
25960
25961
25962
25963
25964
25965
25966
25967
25968
25969
25970
25971
25972
25973
25974
25975
25976
25977
25978
25979
25980
25981
25982
25983
25984
25985
25986
25987
25988
25989
25990
25991
25992
25993
25994
25995
25996
25997
25998
25999
26000
26001
26002
26003
26004
26005
26006
26007
26008
26009
26010
26011
26012
26013
26014
26015
26016
26017
26018
26019
26020
26021
26022
26023
26024
26025
26026
26027
26028
26029
26030
26031
26032
26033
26034
26035
26036
26037
26038
26039
26040
26041
26042
26043
26044
26045
26046
26047
26048
26049
26050
26051
26052
26053
26054
26055
26056
26057
26058
26059
26060
26061
26062
26063
26064
26065
26066
26067
26068
26069
26070
26071
26072
26073
26074
26075
26076
26077
26078
26079
26080
26081
26082
26083
26084
26085
26086
26087
26088
26089
26090
26091
26092
26093
26094
26095
26096
26097
26098
26099
26100
26101
26102
26103
26104
26105
26106
26107
26108
26109
26110
26111
26112
26113
26114
26115
26116
26117
26118
26119
26120
26121
26122
26123
26124
26125
26126
26127
26128
26129
26130
26131
26132
26133
26134
26135
26136
26137
26138
26139
26140
26141
26142
26143
26144
26145
26146
26147
26148
26149
26150
26151
26152
26153
26154
26155
26156
26157
26158
26159
26160
26161
26162
26163
26164
26165
26166
26167
26168
26169
26170
26171
26172
26173
26174
26175
26176
26177
26178
26179
26180
26181
26182
26183
26184
26185
26186
26187
26188
26189
26190
26191
26192
26193
26194
26195
26196
26197
26198
26199
26200
26201
26202
26203
26204
26205
26206
26207
26208
26209
26210
26211
26212
26213
26214
26215
26216
26217
26218
26219
26220
26221
26222
26223
26224
26225
26226
26227
26228
26229
26230
26231
26232
26233
26234
26235
26236
26237
26238
26239
26240
26241
26242
26243
26244
26245
26246
26247
26248
26249
26250
26251
26252
26253
26254
26255
26256
26257
26258
26259
26260
26261
26262
26263
26264
26265
26266
26267
26268
26269
26270
26271
26272
26273
26274
26275
26276
26277
26278
26279
26280
26281
26282
26283
26284
26285
26286
26287
26288
26289
26290
26291
26292
26293
26294
26295
26296
26297
26298
26299
26300
26301
26302
26303
26304
26305
26306
26307
26308
26309
26310
26311
26312
26313
26314
26315
26316
26317
26318
26319
26320
26321
26322
26323
26324
26325
26326
26327
26328
26329
26330
26331
26332
26333
26334
26335
26336
26337
26338
26339
26340
26341
26342
26343
26344
26345
26346
26347
26348
26349
26350
26351
26352
26353
26354
26355
26356
26357
26358
26359
26360
26361
26362
26363
26364
26365
26366
26367
26368
26369
26370
26371
26372
26373
26374
26375
26376
26377
26378
26379
26380
26381
26382
26383
26384
26385
26386
26387
26388
26389
26390
26391
26392
26393
26394
26395
26396
26397
26398
26399
26400
26401
26402
26403
26404
26405
26406
26407
26408
26409
26410
26411
26412
26413
26414
26415
26416
26417
26418
26419
26420
26421
26422
26423
26424
26425
26426
26427
26428
26429
26430
26431
26432
26433
26434
26435
26436
26437
26438
26439
26440
26441
26442
26443
26444
26445
26446
26447
26448
26449
26450
26451
26452
26453
26454
26455
26456
26457
26458
26459
26460
26461
26462
26463
26464
26465
26466
26467
26468
26469
26470
26471
26472
26473
26474
26475
26476
26477
26478
26479
26480
26481
26482
26483
26484
26485
26486
26487
26488
26489
26490
26491
26492
26493
26494
26495
26496
26497
26498
26499
26500
26501
26502
26503
26504
26505
26506
26507
26508
26509
26510
26511
26512
26513
26514
26515
26516
26517
26518
26519
26520
26521
26522
26523
26524
26525
26526
26527
26528
26529
26530
26531
26532
26533
26534
26535
26536
26537
26538
26539
26540
26541
26542
26543
26544
26545
26546
26547
26548
26549
26550
26551
26552
26553
26554
26555
26556
26557
26558
26559
26560
26561
26562
26563
26564
26565
26566
26567
26568
26569
26570
26571
26572
26573
26574
26575
26576
26577
26578
26579
26580
26581
26582
26583
26584
26585
26586
26587
26588
26589
26590
26591
26592
26593
26594
26595
26596
26597
26598
26599
26600
26601
26602
26603
26604
26605
26606
26607
26608
26609
26610
26611
26612
26613
26614
26615
26616
26617
26618
26619
26620
26621
26622
26623
26624
26625
26626
26627
26628
26629
26630
26631
26632
26633
26634
26635
26636
26637
26638
26639
26640
26641
26642
26643
26644
26645
26646
26647
26648
26649
26650
26651
26652
26653
26654
26655
26656
26657
26658
26659
26660
26661
26662
26663
26664
26665
26666
26667
26668
26669
26670
26671
26672
26673
26674
26675
26676
26677
26678
26679
26680
26681
26682
26683
26684
26685
26686
26687
26688
26689
26690
26691
26692
26693
26694
26695
26696
26697
26698
26699
26700
26701
26702
26703
26704
26705
26706
26707
26708
26709
26710
26711
26712
26713
26714
26715
26716
26717
26718
26719
26720
26721
26722
26723
26724
26725
26726
26727
26728
26729
26730
26731
26732
26733
26734
26735
26736
26737
26738
26739
26740
26741
26742
26743
26744
26745
26746
26747
26748
26749
26750
26751
26752
26753
26754
26755
26756
26757
26758
26759
26760
26761
26762
26763
26764
26765
26766
26767
26768
26769
26770
26771
26772
26773
26774
26775
26776
26777
26778
26779
26780
26781
26782
26783
26784
26785
26786
26787
26788
26789
26790
26791
26792
26793
26794
26795
26796
26797
26798
26799
26800
26801
26802
26803
26804
26805
26806
26807
26808
26809
26810
26811
26812
26813
26814
26815
26816
26817
26818
26819
26820
26821
26822
26823
26824
26825
26826
26827
26828
26829
26830
26831
26832
26833
26834
26835
26836
26837
26838
26839
26840
26841
26842
26843
26844
26845
26846
26847
26848
26849
26850
26851
26852
26853
26854
26855
26856
26857
26858
26859
26860
26861
26862
26863
26864
26865
26866
26867
26868
26869
26870
26871
26872
26873
26874
26875
26876
26877
26878
26879
26880
26881
26882
26883
26884
26885
26886
26887
26888
26889
26890
26891
26892
26893
26894
26895
26896
26897
26898
26899
26900
26901
26902
26903
26904
26905
26906
26907
26908
26909
26910
26911
26912
26913
26914
26915
26916
26917
26918
26919
26920
26921
26922
26923
26924
26925
26926
26927
26928
26929
26930
26931
26932
26933
26934
26935
26936
26937
26938
26939
26940
26941
26942
26943
26944
26945
26946
26947
26948
26949
26950
26951
26952
26953
26954
26955
26956
26957
26958
26959
26960
26961
26962
26963
26964
26965
26966
26967
26968
26969
26970
26971
26972
26973
26974
26975
26976
26977
26978
26979
26980
26981
26982
26983
26984
26985
26986
26987
26988
26989
26990
26991
26992
26993
26994
26995
26996
26997
26998
26999
27000
27001
27002
27003
27004
27005
27006
27007
27008
27009
27010
27011
27012
27013
27014
27015
27016
27017
27018
27019
27020
27021
27022
27023
27024
27025
27026
27027
27028
27029
27030
27031
27032
27033
27034
27035
27036
27037
27038
27039
27040
27041
27042
27043
27044
27045
27046
27047
27048
27049
27050
27051
27052
27053
27054
27055
27056
27057
27058
27059
27060
27061
27062
27063
27064
27065
27066
27067
27068
27069
27070
27071
27072
27073
27074
27075
27076
27077
27078
27079
27080
27081
27082
27083
27084
27085
27086
27087
27088
27089
27090
27091
27092
27093
27094
27095
27096
27097
27098
27099
27100
27101
27102
27103
27104
27105
27106
27107
27108
27109
27110
27111
27112
27113
27114
27115
27116
27117
27118
27119
27120
27121
27122
27123
27124
27125
27126
27127
27128
27129
27130
27131
27132
27133
27134
27135
27136
27137
27138
27139
27140
27141
27142
27143
27144
27145
27146
27147
27148
27149
27150
27151
27152
27153
27154
27155
27156
27157
27158
27159
27160
27161
27162
27163
27164
27165
27166
27167
27168
27169
27170
27171
27172
27173
27174
27175
27176
27177
27178
27179
27180
27181
27182
27183
27184
27185
27186
27187
27188
27189
27190
27191
27192
27193
27194
27195
27196
27197
27198
27199
27200
27201
27202
27203
27204
27205
27206
27207
27208
27209
27210
27211
27212
27213
27214
27215
27216
27217
27218
27219
27220
27221
27222
27223
27224
27225
27226
27227
27228
27229
27230
27231
27232
27233
27234
27235
27236
27237
27238
27239
27240
27241
27242
27243
27244
27245
27246
27247
27248
27249
27250
27251
27252
27253
27254
27255
27256
27257
27258
27259
27260
27261
27262
27263
27264
27265
27266
27267
27268
27269
27270
27271
27272
27273
27274
27275
27276
27277
27278
27279
27280
27281
27282
27283
27284
27285
27286
27287
27288
27289
27290
27291
27292
27293
27294
27295
27296
27297
27298
27299
27300
27301
27302
27303
27304
27305
27306
27307
27308
27309
27310
27311
27312
27313
27314
27315
27316
27317
27318
27319
27320
27321
27322
27323
27324
27325
27326
27327
27328
27329
27330
27331
27332
27333
27334
27335
27336
27337
27338
27339
27340
27341
27342
27343
27344
27345
27346
27347
27348
27349
27350
27351
27352
27353
27354
27355
27356
27357
27358
27359
27360
27361
27362
27363
27364
27365
27366
27367
27368
27369
27370
27371
27372
27373
27374
27375
27376
27377
27378
27379
27380
27381
27382
27383
27384
27385
27386
27387
27388
27389
27390
27391
27392
27393
27394
27395
27396
27397
27398
27399
27400
27401
27402
27403
27404
27405
27406
27407
27408
27409
27410
27411
27412
27413
27414
27415
27416
27417
27418
27419
27420
27421
27422
27423
27424
27425
27426
27427
27428
27429
27430
27431
27432
27433
27434
27435
27436
27437
27438
27439
27440
27441
27442
27443
27444
27445
27446
27447
27448
27449
27450
27451
27452
27453
27454
27455
27456
27457
27458
27459
27460
27461
27462
27463
27464
27465
27466
27467
27468
27469
27470
27471
27472
27473
27474
27475
27476
27477
27478
27479
27480
27481
27482
27483
27484
27485
27486
27487
27488
27489
27490
27491
27492
27493
27494
27495
27496
27497
27498
27499
27500
27501
27502
27503
27504
27505
27506
27507
27508
27509
27510
27511
27512
27513
27514
27515
27516
27517
27518
27519
27520
27521
27522
27523
27524
27525
27526
27527
27528
27529
27530
27531
27532
27533
27534
27535
27536
27537
27538
27539
27540
27541
27542
27543
27544
27545
27546
27547
27548
27549
27550
27551
27552
27553
27554
27555
27556
27557
27558
27559
27560
27561
27562
27563
27564
27565
27566
27567
27568
27569
27570
27571
27572
27573
27574
27575
27576
27577
27578
27579
27580
27581
27582
27583
27584
27585
27586
27587
27588
27589
27590
27591
27592
27593
27594
27595
27596
27597
27598
27599
27600
27601
27602
27603
27604
27605
27606
27607
27608
27609
27610
27611
27612
27613
27614
27615
27616
27617
27618
27619
27620
27621
27622
27623
27624
27625
27626
27627
27628
27629
27630
27631
27632
27633
27634
27635
27636
27637
27638
27639
27640
27641
27642
27643
27644
27645
27646
27647
27648
27649
27650
27651
27652
27653
27654
27655
27656
27657
27658
27659
27660
27661
27662
27663
27664
27665
27666
27667
27668
27669
27670
27671
27672
27673
27674
27675
27676
27677
27678
27679
27680
27681
27682
27683
27684
27685
27686
27687
27688
27689
27690
27691
27692
27693
27694
27695
27696
27697
27698
27699
27700
27701
27702
27703
27704
27705
27706
27707
27708
27709
27710
27711
27712
27713
27714
27715
27716
27717
27718
27719
27720
27721
27722
27723
27724
27725
27726
27727
27728
27729
27730
27731
27732
27733
27734
27735
27736
27737
27738
27739
27740
27741
27742
27743
27744
27745
27746
27747
27748
27749
27750
27751
27752
27753
27754
27755
27756
27757
27758
27759
27760
27761
27762
27763
27764
27765
27766
27767
27768
27769
27770
27771
27772
27773
27774
27775
27776
27777
27778
27779
27780
27781
27782
27783
27784
27785
27786
27787
27788
27789
27790
27791
27792
27793
27794
27795
27796
27797
27798
27799
27800
27801
27802
27803
27804
27805
27806
27807
27808
27809
27810
27811
27812
27813
27814
27815
27816
27817
27818
27819
27820
27821
27822
27823
27824
27825
27826
27827
27828
27829
27830
27831
27832
27833
27834
27835
27836
27837
27838
27839
27840
27841
27842
27843
27844
27845
27846
27847
27848
27849
27850
27851
27852
27853
27854
27855
27856
27857
27858
27859
27860
27861
27862
27863
27864
27865
27866
27867
27868
27869
27870
27871
27872
27873
27874
27875
27876
27877
27878
27879
27880
27881
27882
27883
27884
27885
27886
27887
27888
27889
27890
27891
27892
27893
27894
27895
27896
27897
27898
27899
27900
27901
27902
27903
27904
27905
27906
27907
27908
27909
27910
27911
27912
27913
27914
27915
27916
27917
27918
27919
27920
27921
27922
27923
27924
27925
27926
27927
27928
27929
27930
27931
27932
27933
27934
27935
27936
27937
27938
27939
27940
27941
27942
27943
27944
27945
27946
27947
27948
27949
27950
27951
27952
27953
27954
27955
27956
27957
27958
27959
27960
27961
27962
27963
27964
27965
27966
27967
27968
27969
27970
27971
27972
27973
27974
27975
27976
27977
27978
27979
27980
27981
27982
27983
27984
27985
27986
27987
27988
27989
27990
27991
27992
27993
27994
27995
27996
27997
27998
27999
28000
28001
28002
28003
28004
28005
28006
28007
28008
28009
28010
28011
28012
28013
28014
28015
28016
28017
28018
28019
28020
28021
28022
28023
28024
28025
28026
28027
28028
28029
28030
28031
28032
28033
28034
28035
28036
28037
28038
28039
28040
28041
28042
28043
28044
28045
28046
28047
28048
28049
28050
28051
28052
28053
28054
28055
28056
28057
28058
28059
28060
28061
28062
28063
28064
28065
28066
28067
28068
28069
28070
28071
28072
28073
28074
28075
28076
28077
28078
28079
28080
28081
28082
28083
28084
28085
28086
28087
28088
28089
28090
28091
28092
28093
28094
28095
28096
28097
28098
28099
28100
28101
28102
28103
28104
28105
28106
28107
28108
28109
28110
28111
28112
28113
28114
28115
28116
28117
28118
28119
28120
28121
28122
28123
28124
28125
28126
28127
28128
28129
28130
28131
28132
28133
28134
28135
28136
28137
28138
28139
28140
28141
28142
28143
28144
28145
28146
28147
28148
28149
28150
28151
28152
28153
28154
28155
28156
28157
28158
28159
28160
28161
28162
28163
28164
28165
28166
28167
28168
28169
28170
28171
28172
28173
28174
28175
28176
28177
28178
28179
28180
28181
28182
28183
28184
28185
28186
28187
28188
28189
28190
28191
28192
28193
28194
28195
28196
28197
28198
28199
28200
28201
28202
28203
28204
28205
28206
28207
28208
28209
28210
28211
28212
28213
28214
28215
28216
28217
28218
28219
28220
28221
28222
28223
28224
28225
28226
28227
28228
28229
28230
28231
28232
28233
28234
28235
28236
28237
28238
28239
28240
28241
28242
28243
28244
28245
28246
28247
28248
28249
28250
28251
28252
28253
28254
28255
28256
28257
28258
28259
28260
28261
28262
28263
28264
28265
28266
28267
28268
28269
28270
28271
28272
28273
28274
28275
28276
28277
28278
28279
28280
28281
28282
28283
28284
28285
28286
28287
28288
28289
28290
28291
28292
28293
28294
28295
28296
28297
28298
28299
28300
28301
28302
28303
28304
28305
28306
28307
28308
28309
28310
28311
28312
28313
28314
28315
28316
28317
28318
28319
28320
28321
28322
28323
28324
28325
28326
28327
28328
28329
28330
28331
28332
28333
28334
28335
28336
28337
28338
28339
28340
28341
28342
28343
28344
28345
28346
28347
28348
28349
28350
28351
28352
28353
28354
28355
28356
28357
28358
28359
28360
28361
28362
28363
28364
28365
28366
28367
28368
28369
28370
28371
28372
28373
28374
28375
28376
28377
28378
28379
28380
28381
28382
28383
28384
28385
28386
28387
28388
28389
28390
28391
28392
28393
28394
28395
28396
28397
28398
28399
28400
28401
28402
28403
28404
28405
28406
28407
28408
28409
28410
28411
28412
28413
28414
28415
28416
28417
28418
28419
28420
28421
28422
28423
28424
28425
28426
28427
28428
28429
28430
28431
28432
28433
28434
28435
28436
28437
28438
28439
28440
28441
28442
28443
28444
28445
28446
28447
28448
28449
28450
28451
28452
28453
28454
28455
28456
28457
28458
28459
28460
28461
28462
28463
28464
28465
28466
28467
28468
28469
28470
28471
28472
28473
28474
28475
28476
28477
28478
28479
28480
28481
28482
28483
28484
28485
28486
28487
28488
28489
28490
28491
28492
28493
28494
28495
28496
28497
28498
28499
28500
28501
28502
28503
28504
28505
28506
28507
28508
28509
28510
28511
28512
28513
28514
28515
28516
28517
28518
28519
28520
28521
28522
28523
28524
28525
28526
28527
28528
28529
28530
28531
28532
28533
28534
28535
28536
28537
28538
28539
28540
28541
28542
28543
28544
28545
28546
28547
28548
28549
28550
28551
28552
28553
28554
28555
28556
28557
28558
28559
28560
28561
28562
28563
28564
28565
28566
28567
28568
28569
28570
28571
28572
28573
28574
28575
28576
28577
28578
28579
28580
28581
28582
28583
28584
28585
28586
28587
28588
28589
28590
28591
28592
28593
28594
28595
28596
28597
28598
28599
28600
28601
28602
28603
28604
28605
28606
28607
28608
28609
28610
28611
28612
28613
28614
28615
28616
28617
28618
28619
28620
28621
28622
28623
28624
28625
28626
28627
28628
28629
28630
28631
28632
28633
28634
28635
28636
28637
28638
28639
28640
28641
28642
28643
28644
28645
28646
28647
28648
28649
28650
28651
28652
28653
28654
28655
28656
28657
28658
28659
28660
28661
28662
28663
28664
28665
28666
28667
28668
28669
28670
28671
28672
28673
28674
28675
28676
28677
28678
28679
28680
28681
28682
28683
28684
28685
28686
28687
28688
28689
28690
28691
28692
28693
28694
28695
28696
28697
28698
28699
28700
28701
28702
28703
28704
28705
28706
28707
28708
28709
28710
28711
28712
28713
28714
28715
28716
28717
28718
28719
28720
28721
28722
28723
28724
28725
28726
28727
28728
28729
28730
28731
28732
28733
28734
28735
28736
28737
28738
28739
28740
28741
28742
28743
28744
28745
28746
28747
28748
28749
28750
28751
28752
28753
28754
28755
28756
28757
28758
28759
28760
28761
28762
28763
28764
28765
28766
28767
28768
28769
28770
28771
28772
28773
28774
28775
28776
28777
28778
28779
28780
28781
28782
28783
28784
28785
28786
28787
28788
28789
28790
28791
28792
28793
28794
28795
28796
28797
28798
28799
28800
28801
28802
28803
28804
28805
28806
28807
28808
28809
28810
28811
28812
28813
28814
28815
28816
28817
28818
28819
28820
28821
28822
28823
28824
28825
28826
28827
28828
28829
28830
28831
28832
28833
28834
28835
28836
28837
28838
28839
28840
28841
28842
28843
28844
28845
28846
28847
28848
28849
28850
28851
28852
28853
28854
28855
28856
28857
28858
28859
28860
28861
28862
28863
28864
28865
28866
28867
28868
28869
28870
28871
28872
28873
28874
28875
28876
28877
28878
28879
28880
28881
28882
28883
28884
28885
28886
28887
28888
28889
28890
28891
28892
28893
28894
28895
28896
28897
28898
28899
28900
28901
28902
28903
28904
28905
28906
28907
28908
28909
28910
28911
28912
28913
28914
28915
28916
28917
28918
28919
28920
28921
28922
28923
28924
28925
28926
28927
28928
28929
28930
28931
28932
28933
28934
28935
28936
28937
28938
28939
28940
28941
28942
28943
28944
28945
28946
28947
28948
28949
28950
28951
28952
28953
28954
28955
28956
28957
28958
28959
28960
28961
28962
28963
28964
28965
28966
28967
28968
28969
28970
28971
28972
28973
28974
28975
28976
28977
28978
28979
28980
28981
28982
28983
28984
28985
28986
28987
28988
28989
28990
28991
28992
28993
28994
28995
28996
28997
28998
28999
29000
29001
29002
29003
29004
29005
29006
29007
29008
29009
29010
29011
29012
29013
29014
29015
29016
29017
29018
29019
29020
29021
29022
29023
29024
29025
29026
29027
29028
29029
29030
29031
29032
29033
29034
29035
29036
29037
29038
29039
29040
29041
29042
29043
29044
29045
29046
29047
29048
29049
29050
29051
29052
29053
29054
29055
29056
29057
29058
29059
29060
29061
29062
29063
29064
29065
29066
29067
29068
29069
29070
29071
29072
29073
29074
29075
29076
29077
29078
29079
29080
29081
29082
29083
29084
29085
29086
29087
29088
29089
29090
29091
29092
29093
29094
29095
29096
29097
29098
29099
29100
29101
29102
29103
29104
29105
29106
29107
29108
29109
29110
29111
29112
29113
29114
29115
29116
29117
29118
29119
29120
29121
29122
29123
29124
29125
29126
29127
29128
29129
29130
29131
29132
29133
29134
29135
29136
29137
29138
29139
29140
29141
29142
29143
29144
29145
29146
29147
29148
29149
29150
29151
29152
29153
29154
29155
29156
29157
29158
29159
29160
29161
29162
29163
29164
29165
29166
29167
29168
29169
29170
29171
29172
29173
29174
29175
29176
29177
29178
29179
29180
29181
29182
29183
29184
29185
29186
29187
29188
29189
29190
29191
29192
29193
29194
29195
29196
29197
29198
29199
29200
29201
29202
29203
29204
29205
29206
29207
29208
29209
29210
29211
29212
29213
29214
29215
29216
29217
29218
29219
29220
29221
29222
29223
29224
29225
29226
29227
29228
29229
29230
29231
29232
29233
29234
29235
29236
29237
29238
29239
29240
29241
29242
29243
29244
29245
29246
29247
29248
29249
29250
29251
29252
29253
29254
29255
29256
29257
29258
29259
29260
29261
29262
29263
29264
29265
29266
29267
29268
29269
29270
29271
29272
29273
29274
29275
29276
29277
29278
29279
29280
29281
29282
29283
29284
29285
29286
29287
29288
29289
29290
29291
29292
29293
29294
29295
29296
29297
29298
29299
29300
29301
29302
29303
29304
29305
29306
29307
29308
29309
29310
29311
29312
29313
29314
29315
29316
29317
29318
29319
29320
29321
29322
29323
29324
29325
29326
29327
29328
29329
29330
29331
29332
29333
29334
29335
29336
29337
29338
29339
29340
29341
29342
29343
29344
29345
29346
29347
29348
29349
29350
29351
29352
29353
29354
29355
29356
29357
29358
29359
29360
29361
29362
29363
29364
29365
29366
29367
29368
29369
29370
29371
29372
29373
29374
29375
29376
29377
29378
29379
29380
29381
29382
29383
29384
29385
29386
29387
29388
29389
29390
29391
29392
29393
29394
29395
29396
29397
29398
29399
29400
29401
29402
29403
29404
29405
29406
29407
29408
29409
29410
29411
29412
29413
29414
29415
29416
29417
29418
29419
29420
29421
29422
29423
29424
29425
29426
29427
29428
29429
29430
29431
29432
29433
29434
29435
29436
29437
29438
29439
29440
29441
29442
29443
29444
29445
29446
29447
29448
29449
29450
29451
29452
29453
29454
29455
29456
29457
29458
29459
29460
29461
29462
29463
29464
29465
29466
29467
29468
29469
29470
29471
29472
29473
29474
29475
29476
29477
29478
29479
29480
29481
29482
29483
29484
29485
29486
29487
29488
29489
29490
29491
29492
29493
29494
29495
29496
29497
29498
29499
29500
29501
29502
29503
29504
29505
29506
29507
29508
29509
29510
29511
29512
29513
29514
29515
29516
29517
29518
29519
29520
29521
29522
29523
29524
29525
29526
29527
29528
29529
29530
29531
29532
29533
29534
29535
29536
29537
29538
29539
29540
29541
29542
29543
29544
29545
29546
29547
29548
29549
29550
29551
29552
29553
29554
29555
29556
29557
29558
29559
29560
29561
29562
29563
29564
29565
29566
29567
29568
29569
29570
29571
29572
29573
29574
29575
29576
29577
29578
29579
29580
29581
29582
29583
29584
29585
29586
29587
29588
29589
29590
29591
29592
29593
29594
29595
29596
29597
29598
29599
29600
29601
29602
29603
29604
29605
29606
29607
29608
29609
29610
29611
29612
29613
29614
29615
29616
29617
29618
29619
29620
29621
29622
29623
29624
29625
29626
29627
29628
29629
29630
29631
29632
29633
29634
29635
29636
29637
29638
29639
29640
29641
29642
29643
29644
29645
29646
29647
29648
29649
29650
29651
29652
29653
29654
29655
29656
29657
29658
29659
29660
29661
29662
29663
29664
29665
29666
29667
29668
29669
29670
29671
29672
29673
29674
29675
29676
29677
29678
29679
29680
29681
29682
29683
29684
29685
29686
29687
29688
29689
29690
29691
29692
29693
29694
29695
29696
29697
29698
29699
29700
29701
29702
29703
29704
29705
29706
29707
29708
29709
29710
29711
29712
29713
29714
29715
29716
29717
29718
29719
29720
29721
29722
29723
29724
29725
29726
29727
29728
29729
29730
29731
29732
29733
29734
29735
29736
29737
29738
29739
29740
29741
29742
29743
29744
29745
29746
29747
29748
29749
29750
29751
29752
29753
29754
29755
29756
29757
29758
29759
29760
29761
29762
29763
29764
29765
29766
29767
29768
29769
29770
29771
29772
29773
29774
29775
29776
29777
29778
29779
29780
29781
29782
29783
29784
29785
29786
29787
29788
29789
29790
29791
29792
29793
29794
29795
29796
29797
29798
29799
29800
29801
29802
29803
29804
29805
29806
29807
29808
29809
29810
29811
29812
29813
29814
29815
29816
29817
29818
29819
29820
29821
29822
29823
29824
29825
29826
29827
29828
29829
29830
29831
29832
29833
29834
29835
29836
29837
29838
29839
29840
29841
29842
29843
29844
29845
29846
29847
29848
29849
29850
29851
29852
29853
29854
29855
29856
29857
29858
29859
29860
29861
29862
29863
29864
29865
29866
29867
29868
29869
29870
29871
29872
29873
29874
29875
29876
29877
29878
29879
29880
29881
29882
29883
29884
29885
29886
29887
29888
29889
29890
29891
29892
29893
29894
29895
29896
29897
29898
29899
29900
29901
29902
29903
29904
29905
29906
29907
29908
29909
29910
29911
29912
29913
29914
29915
29916
29917
29918
29919
29920
29921
29922
29923
29924
29925
29926
29927
29928
29929
29930
29931
29932
29933
29934
29935
29936
29937
29938
29939
29940
29941
29942
29943
29944
29945
29946
29947
29948
29949
29950
29951
29952
29953
29954
29955
29956
29957
29958
29959
29960
29961
29962
29963
29964
29965
29966
29967
29968
29969
29970
29971
29972
29973
29974
29975
29976
29977
29978
29979
29980
29981
29982
29983
29984
29985
29986
29987
29988
29989
29990
29991
29992
29993
29994
29995
29996
29997
29998
29999
30000
30001
30002
30003
30004
30005
30006
30007
30008
30009
30010
30011
30012
30013
30014
30015
30016
30017
30018
30019
30020
30021
30022
30023
30024
30025
30026
30027
30028
30029
30030
30031
30032
30033
30034
30035
30036
30037
30038
30039
30040
30041
30042
30043
30044
30045
30046
30047
30048
30049
30050
30051
30052
30053
30054
30055
30056
30057
30058
30059
30060
30061
30062
30063
30064
30065
30066
30067
30068
30069
30070
30071
30072
30073
30074
30075
30076
30077
30078
30079
30080
30081
30082
30083
30084
30085
30086
30087
30088
30089
30090
30091
30092
30093
30094
30095
30096
30097
30098
30099
30100
30101
30102
30103
30104
30105
30106
30107
30108
30109
30110
30111
30112
30113
30114
30115
30116
30117
30118
30119
30120
30121
30122
30123
30124
30125
30126
30127
30128
30129
30130
30131
30132
30133
30134
30135
30136
30137
30138
30139
30140
30141
30142
30143
30144
30145
30146
30147
30148
30149
30150
30151
30152
30153
30154
30155
30156
30157
30158
30159
30160
30161
30162
30163
30164
30165
30166
30167
30168
30169
30170
30171
30172
30173
30174
30175
30176
30177
30178
30179
30180
30181
30182
30183
30184
30185
30186
30187
30188
30189
30190
30191
30192
30193
30194
30195
30196
30197
30198
30199
30200
30201
30202
30203
30204
30205
30206
30207
30208
30209
30210
30211
30212
30213
30214
30215
30216
30217
30218
30219
30220
30221
30222
30223
30224
30225
30226
30227
30228
30229
30230
30231
30232
30233
30234
30235
30236
30237
30238
30239
30240
30241
30242
30243
30244
30245
30246
30247
30248
30249
30250
30251
30252
30253
30254
30255
30256
30257
30258
30259
30260
30261
30262
30263
30264
30265
30266
30267
30268
30269
30270
30271
30272
30273
30274
30275
30276
30277
30278
30279
30280
30281
30282
30283
30284
30285
30286
30287
30288
30289
30290
30291
30292
30293
30294
30295
30296
30297
30298
30299
30300
30301
30302
30303
30304
30305
30306
30307
30308
30309
30310
30311
30312
30313
30314
30315
30316
30317
30318
30319
30320
30321
30322
30323
30324
30325
30326
30327
30328
30329
30330
30331
30332
30333
30334
30335
30336
30337
30338
30339
30340
30341
30342
30343
30344
30345
30346
30347
30348
30349
30350
30351
30352
30353
30354
30355
30356
30357
30358
30359
30360
30361
30362
30363
30364
30365
30366
30367
30368
30369
30370
30371
30372
30373
30374
30375
30376
30377
30378
30379
30380
30381
30382
30383
30384
30385
30386
30387
30388
30389
30390
30391
30392
30393
30394
30395
30396
30397
30398
30399
30400
30401
30402
30403
30404
30405
30406
30407
30408
30409
30410
30411
30412
30413
30414
30415
30416
30417
30418
30419
30420
30421
30422
30423
30424
30425
30426
30427
30428
30429
30430
30431
30432
30433
30434
30435
30436
30437
30438
30439
30440
30441
30442
30443
30444
30445
30446
30447
30448
30449
30450
30451
30452
30453
30454
30455
30456
30457
30458
30459
30460
30461
30462
30463
30464
30465
30466
30467
30468
30469
30470
30471
30472
30473
30474
30475
30476
30477
30478
30479
30480
30481
30482
30483
30484
30485
30486
30487
30488
30489
30490
30491
30492
30493
30494
30495
30496
30497
30498
30499
30500
30501
30502
30503
30504
30505
30506
30507
30508
30509
30510
30511
30512
30513
30514
30515
30516
30517
30518
30519
30520
30521
30522
30523
30524
30525
30526
30527
30528
30529
30530
30531
30532
30533
30534
30535
30536
30537
30538
30539
30540
30541
30542
30543
30544
30545
30546
30547
30548
30549
30550
30551
30552
30553
30554
30555
30556
30557
30558
30559
30560
30561
30562
30563
30564
30565
30566
30567
30568
30569
30570
30571
30572
30573
30574
30575
30576
30577
30578
30579
30580
30581
30582
30583
30584
30585
30586
30587
30588
30589
30590
30591
30592
30593
30594
30595
30596
30597
30598
30599
30600
30601
30602
30603
30604
30605
30606
30607
30608
30609
30610
30611
30612
30613
30614
30615
30616
30617
30618
30619
30620
30621
30622
30623
30624
30625
30626
30627
30628
30629
30630
30631
30632
30633
30634
30635
30636
30637
30638
30639
30640
30641
30642
30643
30644
30645
30646
30647
30648
30649
30650
30651
30652
30653
30654
30655
30656
30657
30658
30659
30660
30661
30662
30663
30664
30665
30666
30667
30668
30669
30670
30671
30672
30673
30674
30675
30676
30677
30678
30679
30680
30681
30682
30683
30684
30685
30686
30687
30688
30689
30690
30691
30692
30693
30694
30695
30696
30697
30698
30699
30700
30701
30702
30703
30704
30705
30706
30707
30708
30709
30710
30711
30712
30713
30714
30715
30716
30717
30718
30719
30720
30721
30722
30723
30724
30725
30726
30727
30728
30729
30730
30731
30732
30733
30734
30735
30736
30737
30738
30739
30740
30741
30742
30743
30744
30745
30746
30747
30748
30749
30750
30751
30752
30753
30754
30755
30756
30757
30758
30759
30760
30761
30762
30763
30764
30765
30766
30767
30768
30769
30770
30771
30772
30773
30774
30775
30776
30777
30778
30779
30780
30781
30782
30783
30784
30785
30786
30787
30788
30789
30790
30791
30792
30793
30794
30795
30796
30797
30798
30799
30800
30801
30802
30803
30804
30805
30806
30807
30808
30809
30810
30811
30812
30813
30814
30815
30816
30817
30818
30819
30820
30821
30822
30823
30824
30825
30826
30827
30828
30829
30830
30831
30832
30833
30834
30835
30836
30837
30838
30839
30840
30841
30842
30843
30844
30845
30846
30847
30848
30849
30850
30851
30852
30853
30854
30855
30856
30857
30858
30859
30860
30861
30862
30863
30864
30865
30866
30867
30868
30869
30870
30871
30872
30873
30874
30875
30876
30877
30878
30879
30880
30881
30882
30883
30884
30885
30886
30887
30888
30889
30890
30891
30892
30893
30894
30895
30896
30897
30898
30899
30900
30901
30902
30903
30904
30905
30906
30907
30908
30909
30910
30911
30912
30913
30914
30915
30916
30917
30918
30919
30920
30921
30922
30923
30924
30925
30926
30927
30928
30929
30930
30931
30932
30933
30934
30935
30936
30937
30938
30939
30940
30941
30942
30943
30944
30945
30946
30947
30948
30949
30950
30951
30952
30953
30954
30955
30956
30957
30958
30959
30960
30961
30962
30963
30964
30965
30966
30967
30968
30969
30970
30971
30972
30973
30974
30975
30976
30977
30978
30979
30980
30981
30982
30983
30984
30985
30986
30987
30988
30989
30990
30991
30992
30993
30994
30995
30996
30997
30998
30999
31000
31001
31002
31003
31004
31005
31006
31007
31008
31009
31010
31011
31012
31013
31014
31015
31016
31017
31018
31019
31020
31021
31022
31023
31024
31025
31026
31027
31028
31029
31030
31031
31032
31033
31034
31035
31036
31037
31038
31039
31040
31041
31042
31043
31044
31045
31046
31047
31048
31049
31050
31051
31052
31053
31054
31055
31056
31057
31058
31059
31060
31061
31062
31063
31064
31065
31066
31067
31068
31069
31070
31071
31072
31073
31074
31075
31076
31077
31078
31079
31080
31081
31082
31083
31084
31085
31086
31087
31088
31089
31090
31091
31092
31093
31094
31095
31096
31097
31098
31099
31100
31101
31102
31103
31104
31105
31106
31107
31108
31109
31110
31111
31112
31113
31114
31115
31116
31117
31118
31119
31120
31121
31122
31123
31124
31125
31126
31127
31128
31129
31130
31131
31132
31133
31134
31135
31136
31137
31138
31139
31140
31141
31142
31143
31144
31145
31146
31147
31148
31149
31150
31151
31152
31153
31154
31155
31156
31157
31158
31159
31160
31161
31162
31163
31164
31165
31166
31167
31168
31169
31170
31171
31172
31173
31174
31175
31176
31177
31178
31179
31180
31181
31182
31183
31184
31185
31186
31187
31188
31189
31190
31191
31192
31193
31194
31195
31196
31197
31198
31199
31200
31201
31202
31203
31204
31205
31206
31207
31208
31209
31210
31211
31212
31213
31214
31215
31216
31217
31218
31219
31220
31221
31222
31223
31224
31225
31226
31227
31228
31229
31230
31231
31232
31233
31234
31235
31236
31237
31238
31239
31240
31241
31242
31243
31244
31245
31246
31247
31248
31249
31250
31251
31252
31253
31254
31255
31256
31257
31258
31259
31260
31261
31262
31263
31264
31265
31266
31267
31268
31269
31270
31271
31272
31273
31274
31275
31276
31277
31278
31279
31280
31281
31282
31283
31284
31285
31286
31287
31288
31289
31290
31291
31292
31293
31294
31295
31296
31297
31298
31299
31300
31301
31302
31303
31304
31305
31306
31307
31308
31309
31310
31311
31312
31313
31314
31315
31316
31317
31318
31319
31320
31321
31322
31323
31324
31325
31326
31327
31328
31329
31330
31331
31332
31333
31334
31335
31336
31337
31338
31339
31340
31341
31342
31343
31344
31345
31346
31347
31348
31349
31350
31351
31352
31353
31354
31355
31356
31357
31358
31359
31360
31361
31362
31363
31364
31365
31366
31367
31368
31369
31370
31371
31372
31373
31374
31375
31376
31377
31378
31379
31380
31381
31382
31383
31384
31385
31386
31387
31388
31389
31390
31391
31392
31393
31394
31395
31396
31397
31398
31399
31400
31401
31402
31403
31404
31405
31406
31407
31408
31409
31410
31411
31412
31413
31414
31415
31416
31417
31418
31419
31420
31421
31422
31423
31424
31425
31426
31427
31428
31429
31430
31431
31432
31433
31434
31435
31436
31437
31438
31439
31440
31441
31442
31443
31444
31445
31446
31447
31448
31449
31450
31451
31452
31453
31454
31455
31456
31457
31458
31459
31460
31461
31462
31463
31464
31465
31466
31467
31468
31469
31470
31471
31472
31473
31474
31475
31476
31477
31478
31479
31480
31481
31482
31483
31484
31485
31486
31487
31488
31489
31490
31491
31492
31493
31494
31495
31496
31497
31498
31499
31500
31501
31502
31503
31504
31505
31506
31507
31508
31509
31510
31511
31512
31513
31514
31515
31516
31517
31518
31519
31520
31521
31522
31523
31524
31525
31526
31527
31528
31529
31530
31531
31532
31533
31534
31535
31536
31537
31538
31539
31540
31541
31542
31543
31544
31545
31546
31547
31548
31549
31550
31551
31552
31553
31554
31555
31556
31557
31558
31559
31560
31561
31562
31563
31564
31565
31566
31567
31568
31569
31570
31571
31572
31573
31574
31575
31576
31577
31578
31579
31580
31581
31582
31583
31584
31585
31586
31587
31588
31589
31590
31591
31592
31593
31594
31595
31596
31597
31598
31599
31600
31601
31602
31603
31604
31605
31606
31607
31608
31609
31610
31611
31612
31613
31614
31615
31616
31617
31618
31619
31620
31621
31622
31623
31624
31625
31626
31627
31628
31629
31630
31631
31632
31633
31634
31635
31636
31637
31638
31639
31640
31641
31642
31643
31644
31645
31646
31647
31648
31649
31650
31651
31652
31653
31654
31655
31656
31657
31658
31659
31660
31661
31662
31663
31664
31665
31666
31667
31668
31669
31670
31671
31672
31673
31674
31675
31676
31677
31678
31679
31680
31681
31682
31683
31684
31685
31686
31687
31688
31689
31690
31691
31692
31693
31694
31695
31696
31697
31698
31699
31700
31701
31702
31703
31704
31705
31706
31707
31708
31709
31710
31711
31712
31713
31714
31715
31716
31717
31718
31719
31720
31721
31722
31723
31724
31725
31726
31727
31728
31729
31730
31731
31732
31733
31734
31735
31736
31737
31738
31739
31740
31741
31742
31743
31744
31745
31746
31747
31748
31749
31750
31751
31752
31753
31754
31755
31756
31757
31758
31759
31760
31761
31762
31763
31764
31765
31766
31767
31768
31769
31770
31771
31772
31773
31774
31775
31776
31777
31778
31779
31780
31781
31782
31783
31784
31785
31786
31787
31788
31789
31790
31791
31792
31793
31794
31795
31796
31797
31798
31799
31800
31801
31802
31803
31804
31805
31806
31807
31808
31809
31810
31811
31812
31813
31814
31815
31816
31817
31818
31819
31820
31821
31822
31823
31824
31825
31826
31827
31828
31829
31830
31831
31832
31833
31834
31835
31836
31837
31838
31839
31840
31841
31842
31843
31844
31845
31846
31847
31848
31849
31850
31851
31852
31853
31854
31855
31856
31857
31858
31859
31860
31861
31862
31863
31864
31865
31866
31867
31868
31869
31870
31871
31872
31873
31874
31875
31876
31877
31878
31879
31880
31881
31882
31883
31884
31885
31886
31887
31888
31889
31890
31891
31892
31893
31894
31895
31896
31897
31898
31899
31900
31901
31902
31903
31904
31905
31906
31907
31908
31909
31910
31911
31912
31913
31914
31915
31916
31917
31918
31919
31920
31921
31922
31923
31924
31925
31926
31927
31928
31929
31930
31931
31932
31933
31934
31935
31936
31937
31938
31939
31940
31941
31942
31943
31944
31945
31946
31947
31948
31949
31950
31951
31952
31953
31954
31955
31956
31957
31958
31959
31960
31961
31962
31963
31964
31965
31966
31967
31968
31969
31970
31971
31972
31973
31974
31975
31976
31977
31978
31979
31980
31981
31982
31983
31984
31985
31986
31987
31988
31989
31990
31991
31992
31993
31994
31995
31996
31997
31998
31999
32000
32001
32002
32003
32004
32005
32006
32007
32008
32009
32010
32011
32012
32013
32014
32015
32016
32017
32018
32019
32020
32021
32022
32023
32024
32025
32026
32027
32028
32029
32030
32031
32032
32033
32034
32035
32036
32037
32038
32039
32040
32041
32042
32043
32044
32045
32046
32047
32048
32049
32050
32051
32052
32053
32054
32055
32056
32057
32058
32059
32060
32061
32062
32063
32064
32065
32066
32067
32068
32069
32070
32071
32072
32073
32074
32075
32076
32077
32078
32079
32080
32081
32082
32083
32084
32085
32086
32087
32088
32089
32090
32091
32092
32093
32094
32095
32096
32097
32098
32099
32100
32101
32102
32103
32104
32105
32106
32107
32108
32109
32110
32111
32112
32113
32114
32115
32116
32117
32118
32119
32120
32121
32122
32123
32124
32125
32126
32127
32128
32129
32130
32131
32132
32133
32134
32135
32136
32137
32138
32139
32140
32141
32142
32143
32144
32145
32146
32147
32148
32149
32150
32151
32152
32153
32154
32155
32156
32157
32158
32159
32160
32161
32162
32163
32164
32165
32166
32167
32168
32169
32170
32171
32172
32173
32174
32175
32176
32177
32178
32179
32180
32181
32182
32183
32184
32185
32186
32187
32188
32189
32190
32191
32192
32193
32194
32195
32196
32197
32198
32199
32200
32201
32202
32203
32204
32205
32206
32207
32208
32209
32210
32211
32212
32213
32214
32215
32216
32217
32218
32219
32220
32221
32222
32223
32224
32225
32226
32227
32228
32229
32230
32231
32232
32233
32234
32235
32236
32237
32238
32239
32240
32241
32242
32243
32244
32245
32246
32247
32248
32249
32250
32251
32252
32253
32254
32255
32256
32257
32258
32259
32260
32261
32262
32263
32264
32265
32266
32267
32268
32269
32270
32271
32272
32273
32274
32275
32276
32277
32278
32279
32280
32281
32282
32283
32284
32285
32286
32287
32288
32289
32290
32291
32292
32293
32294
32295
32296
32297
32298
32299
32300
32301
32302
32303
32304
32305
32306
32307
32308
32309
32310
32311
32312
32313
32314
32315
32316
32317
32318
32319
32320
32321
32322
32323
32324
32325
32326
32327
32328
32329
32330
32331
32332
32333
32334
32335
32336
32337
32338
32339
32340
32341
32342
32343
32344
32345
32346
32347
32348
32349
32350
32351
32352
32353
32354
32355
32356
32357
32358
32359
32360
32361
32362
32363
32364
32365
32366
32367
32368
32369
32370
32371
32372
32373
32374
32375
32376
32377
32378
32379
32380
32381
32382
32383
32384
32385
32386
32387
32388
32389
32390
32391
32392
32393
32394
32395
32396
32397
32398
32399
32400
32401
32402
32403
32404
32405
32406
32407
32408
32409
32410
32411
32412
32413
32414
32415
32416
32417
32418
32419
32420
32421
32422
32423
32424
32425
32426
32427
32428
32429
32430
32431
32432
32433
32434
32435
32436
32437
32438
32439
32440
32441
32442
32443
32444
32445
32446
32447
32448
32449
32450
32451
32452
32453
32454
32455
32456
32457
32458
32459
32460
32461
32462
32463
32464
32465
32466
32467
32468
32469
32470
32471
32472
32473
32474
32475
32476
32477
32478
32479
32480
32481
32482
32483
32484
32485
32486
32487
32488
32489
32490
32491
32492
32493
32494
32495
32496
32497
32498
32499
32500
32501
32502
32503
32504
32505
32506
32507
32508
32509
32510
32511
32512
32513
32514
32515
32516
32517
32518
32519
32520
32521
32522
32523
32524
32525
32526
32527
32528
32529
32530
32531
32532
32533
32534
32535
32536
32537
32538
32539
32540
32541
32542
32543
32544
32545
32546
32547
32548
32549
32550
32551
32552
32553
32554
32555
32556
32557
32558
32559
32560
32561
32562
32563
32564
32565
32566
32567
32568
32569
32570
32571
32572
32573
32574
32575
32576
32577
32578
32579
32580
32581
32582
32583
32584
32585
32586
32587
32588
32589
32590
32591
32592
32593
32594
32595
32596
32597
32598
32599
32600
32601
32602
32603
32604
32605
32606
32607
32608
32609
32610
32611
32612
32613
32614
32615
32616
32617
32618
32619
32620
32621
32622
32623
32624
32625
32626
32627
32628
32629
32630
32631
32632
32633
32634
32635
32636
32637
32638
32639
32640
32641
32642
32643
32644
32645
32646
32647
32648
32649
32650
32651
32652
32653
32654
32655
32656
32657
32658
32659
32660
32661
32662
32663
32664
32665
32666
32667
32668
32669
32670
32671
32672
32673
32674
32675
32676
32677
32678
32679
32680
32681
32682
32683
32684
32685
32686
32687
32688
32689
32690
32691
32692
32693
32694
32695
32696
32697
32698
32699
32700
32701
32702
32703
32704
32705
32706
32707
32708
32709
32710
32711
32712
32713
32714
32715
32716
32717
32718
32719
32720
32721
32722
32723
32724
32725
32726
32727
32728
32729
32730
32731
32732
32733
32734
32735
32736
32737
32738
32739
32740
32741
32742
32743
32744
32745
32746
32747
32748
32749
32750
32751
32752
32753
32754
32755
32756
32757
32758
32759
32760
32761
32762
32763
32764
32765
32766
32767
32768
32769
32770
32771
32772
32773
32774
32775
32776
32777
32778
32779
32780
32781
32782
32783
32784
32785
32786
32787
32788
32789
32790
32791
32792
32793
32794
32795
32796
32797
32798
32799
32800
32801
32802
32803
32804
32805
32806
32807
32808
32809
32810
32811
32812
32813
32814
32815
32816
32817
32818
32819
32820
32821
32822
32823
32824
32825
32826
32827
32828
32829
32830
32831
32832
32833
32834
32835
32836
32837
32838
32839
32840
32841
32842
32843
32844
32845
32846
32847
32848
32849
32850
32851
32852
32853
32854
32855
32856
32857
32858
32859
32860
32861
32862
32863
32864
32865
32866
32867
32868
32869
32870
32871
32872
32873
32874
32875
32876
32877
32878
32879
32880
32881
32882
32883
32884
32885
32886
32887
32888
32889
32890
32891
32892
32893
32894
32895
32896
32897
32898
32899
32900
32901
32902
32903
32904
32905
32906
32907
32908
32909
32910
32911
32912
32913
32914
32915
32916
32917
32918
32919
32920
32921
32922
32923
32924
32925
32926
32927
32928
32929
32930
32931
32932
32933
32934
32935
32936
32937
32938
32939
32940
32941
32942
32943
32944
32945
32946
32947
32948
32949
32950
32951
32952
32953
32954
32955
32956
32957
32958
32959
32960
32961
32962
32963
32964
32965
32966
32967
32968
32969
32970
32971
32972
32973
32974
32975
32976
32977
32978
32979
32980
32981
32982
32983
32984
32985
32986
32987
32988
32989
32990
32991
32992
32993
32994
32995
32996
32997
32998
32999
33000
33001
33002
33003
33004
33005
33006
33007
33008
33009
33010
33011
33012
33013
33014
33015
33016
33017
33018
33019
33020
33021
33022
33023
33024
33025
33026
33027
33028
33029
33030
33031
33032
33033
33034
33035
33036
33037
33038
33039
33040
33041
33042
33043
33044
33045
33046
33047
33048
33049
33050
33051
33052
33053
33054
33055
33056
33057
33058
33059
33060
33061
33062
33063
33064
33065
33066
33067
33068
33069
33070
33071
33072
33073
33074
33075
33076
33077
33078
33079
33080
33081
33082
33083
33084
33085
33086
33087
33088
33089
33090
33091
33092
33093
33094
33095
33096
33097
33098
33099
33100
33101
33102
33103
33104
33105
33106
33107
33108
33109
33110
33111
33112
33113
33114
33115
33116
33117
33118
33119
33120
33121
33122
33123
33124
33125
33126
33127
33128
33129
33130
33131
33132
33133
33134
33135
33136
33137
33138
33139
33140
33141
33142
33143
33144
33145
33146
33147
33148
33149
33150
33151
33152
33153
33154
33155
33156
33157
33158
33159
33160
33161
33162
33163
33164
33165
33166
33167
33168
33169
33170
33171
33172
33173
33174
33175
33176
33177
33178
33179
33180
33181
33182
33183
33184
33185
33186
33187
33188
33189
33190
33191
33192
33193
33194
33195
33196
33197
33198
33199
33200
33201
33202
33203
33204
33205
33206
33207
33208
33209
33210
33211
33212
33213
33214
33215
33216
33217
33218
33219
33220
33221
33222
33223
33224
33225
33226
33227
33228
33229
33230
33231
33232
33233
33234
33235
33236
33237
33238
33239
33240
33241
33242
33243
33244
33245
33246
33247
33248
33249
33250
33251
33252
33253
33254
33255
33256
33257
33258
33259
33260
33261
33262
33263
33264
33265
33266
33267
33268
33269
33270
33271
33272
33273
33274
33275
33276
33277
33278
33279
33280
33281
33282
33283
33284
33285
33286
33287
33288
33289
33290
33291
33292
33293
33294
33295
33296
33297
33298
33299
33300
33301
33302
33303
33304
33305
33306
33307
33308
33309
33310
33311
33312
33313
33314
33315
33316
33317
33318
33319
33320
33321
33322
33323
33324
33325
33326
33327
33328
33329
33330
33331
33332
33333
33334
33335
33336
33337
33338
33339
33340
33341
33342
33343
33344
33345
33346
33347
33348
33349
33350
33351
33352
33353
33354
33355
33356
33357
33358
33359
33360
33361
33362
33363
33364
33365
33366
33367
33368
33369
33370
33371
33372
33373
33374
33375
33376
33377
33378
33379
33380
33381
33382
33383
33384
33385
33386
33387
33388
33389
33390
33391
33392
33393
33394
33395
33396
33397
33398
33399
33400
33401
33402
33403
33404
33405
33406
33407
33408
33409
33410
33411
33412
33413
33414
33415
33416
33417
33418
33419
33420
33421
33422
33423
33424
33425
33426
33427
33428
33429
33430
33431
33432
33433
33434
33435
33436
33437
33438
33439
33440
33441
33442
33443
33444
33445
33446
33447
33448
33449
33450
33451
33452
33453
33454
33455
33456
33457
33458
33459
33460
33461
33462
33463
33464
33465
33466
33467
33468
Please review changes against upstream code using SCM,
see the Vcs-* tags in debian/control for its location.

--- mksh-59c.orig/Build.sh
+++ mksh-59c/Build.sh
@@ -1,10 +1,12 @@
 #!/bin/sh
-srcversion='$MirOS: src/bin/mksh/Build.sh,v 1.763 2020/09/04 21:01:37 tg Exp $'
+# -*- mode: sh -*-
+srcversion='$MirOS: src/bin/mksh/Build.sh,v 1.862 2025/12/23 19:26:14 tg Exp $'
+set +evx
 #-
 # Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
 #		2011, 2012, 2013, 2014, 2015, 2016, 2017, 2019,
-#		2020
-#	mirabilos <m@mirbsd.org>
+#		2020, 2021, 2022, 2023, 2024, 2025
+#	mirabilos <m$(date +%Y)@mirbsd.de>
 #
 # Provided that these terms and disclaimer and all copyright notices
 # are retained or reproduced in an accompanying document, permission
@@ -29,6 +31,8 @@ srcversion='$MirOS: src/bin/mksh/Build.s
 LC_ALL=C; LANGUAGE=C
 export LC_ALL; unset LANGUAGE
 
+use_ach=x; unset use_ach
+
 case $ZSH_VERSION:$VERSION in
 :zsh*) ZSH_VERSION=2 ;;
 esac
@@ -44,10 +48,25 @@ if test -d /usr/xpg4/bin/. >/dev/null 2>
 	export PATH
 fi
 
+test_tool() {
+	x=`echo $2 | $3`
+	y=$?
+
+	test x"$y" = x"0" && test x"$x" = x"$4" && return
+	echo >&2 "E: your $1 does not work correctly!"
+	echo >&2 "N: 'echo $2 | $3' exited $y and returned '$x'; expected '$4'"
+	echo >&2 'N: install a better one and prepend its location to $PATH'
+	exit 1
+}
+test_tool grep foobarbaz 'grep bar' foobarbaz
+test_tool sed abc 'sed y/ac/AC/' AbC
+test_tool tr abc 'tr ac AC' AbC
+
+sp=' '
+ht='	'
 nl='
 '
-safeIFS='	'
-safeIFS=" $safeIFS$nl"
+safeIFS="$sp$ht$nl"
 IFS=$safeIFS
 allu=QWERTYUIOPASDFGHJKLZXCVBNM
 alll=qwertyuiopasdfghjklzxcvbnm
@@ -149,7 +168,7 @@ do_genopt() {
 			;;
 		*:@@*)
 			genopt_die ;;
-		0:/\*-|0:\ \**|0:)
+		0:/\*-|0:"$sp"\**|0:)
 			o_hdr=$o_hdr$nl$line
 			;;
 		0:@*|1:@*)
@@ -203,7 +222,8 @@ do_genopt() {
 	done | {
 		echo "$o_hdr"
 		echo "#ifndef $o_sym$o_gen"
-		echo "#else"
+		echo "#endif"
+		echo "#ifdef $o_sym"
 		cat
 		echo "#undef $o_sym"
 		echo "#endif"
@@ -223,6 +243,17 @@ fi
 
 echo "For the build logs, demonstrate that /dev/null and /dev/tty exist:"
 ls -l /dev/null /dev/tty
+cat <<EOF
+Flags on entry (plus HAVE_* which are not shown here):
+- CC        <$CC>
+- CFLAGS    <$CFLAGS>
+- CPPFLAGS  <$CPPFLAGS>
+- LDFLAGS   <$LDFLAGS>
+- LIBS      <$LIBS>
+- LDSTATIC  <$LDSTATIC>
+- TARGET_OS <$TARGET_OS> TARGET_OSREV <$TARGET_OSREV>
+
+EOF
 
 v() {
 	$e "$*"
@@ -244,7 +275,7 @@ vq() {
 rmf() {
 	for _f in "$@"; do
 		case $_f in
-		*.1|*.faq|*.ico) ;;
+		lksh.1|mksh.1|mksh.faq|mksh.ico) ;;
 		*) rm -f "$_f" ;;
 		esac
 	done
@@ -258,7 +289,7 @@ fx=
 me=`basename "$0"`
 orig_CFLAGS=$CFLAGS
 phase=x
-oldish_ed=stdout-ed,no-stderr-ed
+oldish_ed='stdout-ed no-stderr-ed'
 
 if test -t 1; then
 	bi=''
@@ -313,6 +344,11 @@ ac_testinit() {
 			shift
 		fi
 		eval ft=\$HAVE_`upper $2`
+		if test_z "$ft"; then
+			echo >&2
+			echo >&2 "E: test $f depends on $2 which is not defined yet"
+			exit 255
+		fi
 		shift
 	fi
 	fd=${3-$f}
@@ -326,17 +362,28 @@ ac_testinit() {
 	return 0
 }
 
+cat_h_blurb() {
+	echo '#ifdef MKSH_USE_AUTOCONF_H
+/* things that "should" have been on the command line */
+#include "autoconf.h"
+#undef MKSH_USE_AUTOCONF_H
+#endif
+
+'
+	cat
+}
+
 # pipe .c | ac_test[n] [!] label [!] checkif[!]0 [setlabelifcheckis[!]0] useroutput
-ac_testnnd() {
+ac_testnndnd() {
 	if test x"$1" = x"!"; then
 		fr=1
 		shift
 	else
 		fr=0
 	fi
+	cat_h_blurb >conftest.c
 	ac_testinit "$@" || return 1
-	cat >conftest.c
-	vv ']' "$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN conftest.c $LIBS $ccpr"
+	vv ']' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN conftest.c $LIBS $ccpr"
 	test $tcfn = no && test -f a.out && tcfn=a.out
 	test $tcfn = no && test -f a.exe && tcfn=a.exe
 	test $tcfn = no && test -f conftest.exe && tcfn=conftest.exe
@@ -348,18 +395,28 @@ ac_testnnd() {
 	fi
 	vscan=
 	if test $phase = u; then
-		test $ct = gcc && vscan='unrecogni[sz]ed'
-		test $ct = hpcc && vscan='unsupported'
-		test $ct = pcc && vscan='unsupported'
-		test $ct = sunpro && vscan='-e ignored -e turned.off'
+		case $ct in
+		gcc*) vscan='unrecogni[sz]ed' ;;
+		hpcc) vscan='unsupported' ;;
+		pcc) vscan='unsupported' ;;
+		sunpro) vscan='-e ignored -e turned.off' ;;
+		esac
 	fi
 	test_n "$vscan" && grep $vscan vv.out >/dev/null 2>&1 && fv=$fr
 	return 0
 }
 ac_testn() {
-	ac_testnnd "$@" || return
-	rmf conftest.c conftest.o ${tcfn}* vv.out
-	ac_testdone
+	if ac_testnndnd "$@"; then
+		rmf conftest.c conftest.o ${tcfn}* vv.out
+		ac_testdone
+	else
+		rm -f conftest.c
+	fi
+}
+ac_testnnd() {
+	if ac_testnndnd "$@"; then
+		ac_testdone
+	fi
 }
 
 # ac_ifcpp cppexpr [!] label [!] checkif[!]0 [setlabelifcheckis[!]0] useroutput
@@ -384,6 +441,31 @@ EOF
 	test x"$fv" = x"1"
 }
 
+addtoach() {
+	if echo "$1" >>autoconf.h; then
+		echo ">>> $1"
+	else
+		echo >&2 "E: could not write autoconf.h"
+		exit 255
+	fi
+}
+
+# simple only (is IFS-split by shell)
+cpp_define() {
+	case $use_ach in
+	0)
+		add_cppflags "-D$1=$2"
+		;;
+	1)
+		addtoach "#define $1 $2"
+		;;
+	*)
+		echo >&2 "E: cpp_define() called too early!"
+		exit 255
+		;;
+	esac
+}
+
 add_cppflags() {
 	CPPFLAGS="$CPPFLAGS $*"
 }
@@ -392,7 +474,7 @@ ac_cppflags() {
 	test x"$1" = x"" || fu=$1
 	fv=$2
 	test x"$2" = x"" && eval fv=\$HAVE_$fu
-	add_cppflags -DHAVE_$fu=$fv
+	cpp_define HAVE_$fu $fv
 }
 
 ac_test() {
@@ -424,7 +506,7 @@ ac_flags() {
 		ac_testn can_$vn '' "$ft" <<-'EOF'
 			/* evil apo'stroph in comment test */
 			#include <unistd.h>
-			int main(void) { return (isatty(0)); }
+			int main(void) { int t[2]; return (isatty(pipe(t))); }
 		EOF
 		#'
 	fi
@@ -448,14 +530,17 @@ ac_header() {
 	do
 		case $i in
 		_time)
-			echo '#if HAVE_BOTH_TIME_H' >>x
+			echo '#if HAVE_BOTH_TIME_H && HAVE_SELECT_TIME_H' >>x
 			echo '#include <sys/time.h>' >>x
 			echo '#include <time.h>' >>x
-			echo '#elif HAVE_SYS_TIME_H' >>x
+			echo '#elif HAVE_SYS_TIME_H && HAVE_SELECT_TIME_H' >>x
 			echo '#include <sys/time.h>' >>x
 			echo '#elif HAVE_TIME_H' >>x
 			echo '#include <time.h>' >>x
 			echo '#endif' >>x
+			echo '#if HAVE_SYS_SELECT_H' >>x
+			echo '#include <sys/select.h>' >>x
+			echo '#endif' >>x
 			;;
 		*)
 			echo "#include <$i>" >>x
@@ -478,35 +563,66 @@ addsrcs() {
 		fr=1
 	fi
 	eval i=\$$1
-	test $fr = "$i" && case " $SRCS " in
-	*\ $2\ *)	;;
-	*)		SRCS="$SRCS $2" ;;
+	test $fr = "$i" && case "$sp$SRCS$sp" in
+	*"$sp$2$sp"*)	;;
+	*)		SRCS="$SRCS$sp$2" ;;
 	esac
 }
 
+# --- main ---
 
 curdir=`pwd` srcdir=`dirname "$0" 2>/dev/null`
+curdisp=.
+case x$curdir in
+x)
+	curdir=.
+	;;
+*"$sp"*|*"$ht"*|*"$nl"*)
+	echo >&2 Current directory should not contain space or tab or newline.
+	echo >&2 Errors may occur.
+	;;
+*"'"*)
+	echo >&2 Current directory should not contain single quotes.
+	echo >&2 Errors may occur.
+	;;
+*)
+	curdisp=$curdir
+	;;
+esac
 case x$srcdir in
 x)
 	srcdir=.
 	;;
-*\ *|*"	"*|*"$nl"*)
+*"$sp"*|*"$ht"*|*"$nl"*)
 	echo >&2 Source directory should not contain space or tab or newline.
 	echo >&2 Errors may occur.
 	;;
 *"'"*)
-	echo Source directory must not contain single quotes.
+	echo >&2 Source directory must not contain single quotes.
 	exit 1
 	;;
 esac
+test -d "$srcdir" || {
+	echo >&2 Source directory must exist.
+	exit 1
+}
+srcdisp=`cd "$srcdir" && pwd` || srcdisp=
+test_n "$srcdisp" || srcdisp=$srcdir
+if test x"$srcdisp" = x"$curdir"; then
+	srcdisp=
+else
+	srcdisp=$srcdir/
+fi
 dstversion=`sed -n '/define MKSH_VERSION/s/^.*"\([^"]*\)".*$/\1/p' "$srcdir/sh.h"`
-add_cppflags -DMKSH_BUILDSH
+whatlong='The MirBSD Korn Shell (mksh)'
+whatshort=mksh
 
 e=echo
 r=0
 eq=0
 pm=0
 cm=normal
+Cg=
 optflags=-std-compile-opts
 check_categories=
 last=
@@ -518,7 +634,7 @@ ebcdic=false
 for i
 do
 	case $last:$i in
-	c:dragonegg|c:llvm)
+	c:dragonegg|c:llvm|c:trace)
 		cm=$i
 		last=
 		;;
@@ -530,6 +646,12 @@ do
 		optflags=$i
 		last=
 		;;
+	:-A)
+		rm -f autoconf.h
+		addtoach '/* work around NeXTstep bug */'
+		use_ach=1
+		add_cppflags -DMKSH_USE_AUTOCONF_H
+		;;
 	:-c)
 		last=c
 		;;
@@ -543,7 +665,7 @@ do
 	:-g)
 		# checker, debug, valgrind build
 		add_cppflags -DDEBUG
-		CFLAGS="$CFLAGS -g3 -fno-builtin"
+		Cg=' '
 		;;
 	:-j)
 		pm=1
@@ -577,7 +699,7 @@ do
 		;;
 	:-v)
 		echo "Build.sh $srcversion"
-		echo "for mksh $dstversion"
+		echo "for $whatlong $dstversion"
 		exit 0
 		;;
 	:*)
@@ -604,8 +726,11 @@ if test -d $tfn || test -d $tfn.exe; the
 	echo "$me: Error: ./$tfn is a directory!" >&2
 	exit 1
 fi
-rmf a.exe* a.out* conftest.c conftest.exe* *core core.* ${tfn}* *.bc *.dbg \
-    *.ll *.o *.gen *.cat1 Rebuild.sh lft no signames.inc test.sh x vv.out *.htm
+test x"$use_ach" = x"1" || use_ach=0
+cpp_define MKSH_BUILDSH 1
+rmf a.exe* a.out* conftest.* *core core.* ${tfn}* *.bc *.dbg *.ll *.o *.cat? \
+    *.gen signames.inc test.sh *.htm \
+    Rebuild.sh Makefrag.inc lft no x vv.out
 
 SRCS="lalloc.c edit.c eval.c exec.c expr.c funcs.c histrap.c jobs.c"
 SRCS="$SRCS lex.c main.c misc.c shf.c syn.c tree.c var.c"
@@ -614,21 +739,21 @@ if test $legacy = 0; then
 	check_categories="$check_categories shell:legacy-no int:32"
 else
 	check_categories="$check_categories shell:legacy-yes"
-	add_cppflags -DMKSH_LEGACY_MODE
+	cpp_define MKSH_LEGACY_MODE 1
 fi
 
 if $ebcdic; then
-	add_cppflags -DMKSH_EBCDIC
+	cpp_define MKSH_EBCDIC 1
 fi
 
 if test $textmode = 0; then
 	check_categories="$check_categories shell:textmode-no shell:binmode-yes"
 else
 	check_categories="$check_categories shell:textmode-yes shell:binmode-no"
-	add_cppflags -DMKSH_WITH_TEXTMODE
+	cpp_define MKSH_WITH_TEXTMODE 1
 fi
 
-if test x"$srcdir" = x"."; then
+if test_z "$srcdisp"; then
 	CPPFLAGS="-I. $CPPFLAGS"
 else
 	CPPFLAGS="-I. -I'$srcdir' $CPPFLAGS"
@@ -641,17 +766,31 @@ fi
 
 if test_z "$TARGET_OS"; then
 	x=`uname -s 2>/dev/null || uname`
-	test x"$x" = x"`uname -n 2>/dev/null`" || TARGET_OS=$x
+	case $x in
+	scosysv)
+		# SVR4 Unix with uname -s = uname -n, whitelist
+		TARGET_OS=$x
+		;;
+	syllable)
+		# other OS with uname -s = uname = uname -n, whitelist
+		TARGET_OS=$x
+		;;
+	*)
+		test x"$x" = x"`uname -n 2>/dev/null`" || TARGET_OS=$x
+		;;
+	esac
 fi
 if test_z "$TARGET_OS"; then
 	echo "$me: Set TARGET_OS, your uname is broken!" >&2
 	exit 1
 fi
+osnote=
 oswarn=
+oswerr=
 ccpc=-Wc,
 ccpl=-Wl,
 tsts=
-ccpr='|| for _f in ${tcfn}*; do case $_f in *.1|*.faq|*.ico) ;; *) rm -f "$_f" ;; esac; done'
+ccpr='|| for _f in ${tcfn}*; do case $_f in lksh.1|mksh.1|mksh.faq|mksh.ico) ;; *) rm -f "$_f" ;; esac; done'
 
 # Evil hack
 if test x"$TARGET_OS" = x"Android"; then
@@ -665,7 +804,7 @@ if test x"$TARGET_OS" = x"Minix"; then
 WARNING: additional checks before running Build.sh required!
 You can avoid these by calling Build.sh correctly, see below.
 "
-	cat >conftest.c <<'EOF'
+	cat_h_blurb >conftest.c <<'EOF'
 #include <sys/types.h>
 const char *
 #ifdef _NETBSD_SOURCE
@@ -676,7 +815,7 @@ ct="Minix3"
 ;
 EOF
 	ct=unknown
-	vv ']' "${CC-cc} -E $CFLAGS $CPPFLAGS $NOWARN conftest.c | grep ct= | tr -d \\\\015 >x"
+	vv ']' "${CC-cc} -E $CFLAGS $Cg $CPPFLAGS $NOWARN conftest.c | grep ct= | tr -d \\\\015 >x"
 	sed 's/^/[ /' x
 	eval `cat x`
 	rmf x vv.out
@@ -709,17 +848,24 @@ NEXTSTEP)
 	    grep 'NeXT Mach [0-9][0-9.]*:' | \
 	    sed 's/^.*NeXT Mach \([0-9][0-9.]*\):.*$/\1/'`
 	;;
-QNX|SCO_SV)
+BeOS|HP-UX|QNX|SCO_SV)
 	test_n "$TARGET_OSREV" || TARGET_OSREV=`uname -r`
 	;;
 esac
 
+cmplrflgs=
+
 # Configuration depending on OS name
 case $TARGET_OS in
 386BSD)
 	: "${HAVE_CAN_OTWO=0}"
-	add_cppflags -DMKSH_NO_SIGSETJMP
-	add_cppflags -DMKSH_TYPEDEF_SIG_ATOMIC_T=int
+	cpp_define MKSH_NO_SIGSETJMP 1
+	cpp_define MKSH_TYPEDEF_SIG_ATOMIC_T int
+	;;
+4.4BSD)
+	osnote='; assuming BOW (BSD on Windows)'
+	check_categories="$check_categories nopiddependent noxperms"
+	check_categories="$check_categories nosymlink noweirdfilenames"
 	;;
 A/UX)
 	add_cppflags -D_POSIX_SOURCE
@@ -730,36 +876,54 @@ A/UX)
 	;;
 AIX)
 	add_cppflags -D_ALL_SOURCE
-	: "${HAVE_SETLOCALE_CTYPE=0}"
 	;;
 BeOS)
+	: "${CC=gcc}"
+	case $TARGET_OSREV in
+	[012345].*)
+		oswarn="; it has MAJOR issues"
+		test x"$TARGET_OSREV" = x"5.1" || \
+		    cpp_define MKSH_NO_SIGSUSPEND 1
+		;;
+	*)
+		oswarn="; it has minor issues"
+		;;
+	esac
 	case $KSH_VERSION in
 	*MIRBSD\ KSH*)
-		oswarn="; it has minor issues"
 		;;
 	*)
-		oswarn="; you must recompile mksh with"
-		oswarn="$oswarn${nl}itself in a second stage"
+		case $ZSH_VERSION in
+		*[0-9]*)
+			;;
+		*)
+			oswarn="; you must recompile mksh with"
+			oswarn="$oswarn${nl}itself in a second stage"
+			;;
+		esac
 		;;
 	esac
+	: "${MKSH_UNLIMITED=1}"
 	# BeOS has no real tty either
-	add_cppflags -DMKSH_UNEMPLOYED
-	add_cppflags -DMKSH_DISABLE_TTY_WARNING
-	# BeOS doesn't have different UIDs and GIDs
-	add_cppflags -DMKSH__NO_SETEUGID
+	cpp_define MKSH_UNEMPLOYED 1
+	cpp_define MKSH_DISABLE_TTY_WARNING 1
+	# BeOS does not have different UIDs and GIDs
+	cpp_define MKSH__NO_SETEUGID 1
+	: "${HAVE_SETRESUGID=0}"
 	;;
 BSD/OS)
-	: "${HAVE_SETLOCALE_CTYPE=0}"
+	: "${HAVE_POSIX_UTF8_LOCALE=0}"
 	;;
 Coherent)
 	oswarn="; it has major issues"
-	add_cppflags -DMKSH__NO_SYMLINK
+	cpp_define MKSH__NO_SYMLINK 1
 	check_categories="$check_categories nosymlink"
-	add_cppflags -DMKSH__NO_SETEUGID
-	add_cppflags -DMKSH_DISABLE_TTY_WARNING
+	cpp_define MKSH__NO_SETEUGID 1
+	: "${HAVE_SETRESUGID=0}"
+	cpp_define MKSH_DISABLE_TTY_WARNING 1
 	;;
 CYGWIN*)
-	: "${HAVE_SETLOCALE_CTYPE=0}"
+	: "${HAVE_POSIX_UTF8_LOCALE=0}"
 	;;
 Darwin)
 	add_cppflags -D_DARWIN_C_SOURCE
@@ -771,26 +935,24 @@ FreeBSD)
 FreeMiNT)
 	oswarn="; it has minor issues"
 	add_cppflags -D_GNU_SOURCE
-	: "${HAVE_SETLOCALE_CTYPE=0}"
+	: "${HAVE_POSIX_UTF8_LOCALE=0}"
 	;;
 GNU)
 	case $CC in
 	*tendracc*) ;;
 	*) add_cppflags -D_GNU_SOURCE ;;
 	esac
-	add_cppflags -DSETUID_CAN_FAIL_WITH_EAGAIN
-	# define MKSH__NO_PATH_MAX to use Hurd-only functions
-	add_cppflags -DMKSH__NO_PATH_MAX
+	cpp_define SETUID_CAN_FAIL_WITH_EAGAIN 1
 	;;
 GNU/kFreeBSD)
 	case $CC in
 	*tendracc*) ;;
 	*) add_cppflags -D_GNU_SOURCE ;;
 	esac
-	add_cppflags -DSETUID_CAN_FAIL_WITH_EAGAIN
+	cpp_define SETUID_CAN_FAIL_WITH_EAGAIN 1
 	;;
 Haiku)
-	add_cppflags -DMKSH_ASSUME_UTF8
+	cpp_define MKSH_ASSUME_UTF8 1
 	HAVE_ISSET_MKSH_ASSUME_UTF8=1
 	HAVE_ISOFF_MKSH_ASSUME_UTF8=0
 	;;
@@ -800,42 +962,52 @@ Harvey)
 	add_cppflags -D_BSD_EXTENSION
 	add_cppflags -D_SUSV2_SOURCE
 	add_cppflags -D_GNU_SOURCE
-	add_cppflags -DMKSH_ASSUME_UTF8
+	cpp_define MKSH_ASSUME_UTF8 1
 	HAVE_ISSET_MKSH_ASSUME_UTF8=1
 	HAVE_ISOFF_MKSH_ASSUME_UTF8=0
-	add_cppflags -DMKSH__NO_SYMLINK
+	: "${HAVE_POSIX_UTF8_LOCALE=0}"
+	cpp_define MKSH__NO_SYMLINK 1
 	check_categories="$check_categories nosymlink"
-	add_cppflags -DMKSH_NO_CMDLINE_EDITING
-	add_cppflags -DMKSH__NO_SETEUGID
+	cpp_define MKSH_NO_CMDLINE_EDITING 1
+	cpp_define MKSH__NO_SETEUGID 1
+	: "${HAVE_SETRESUGID=0}"
 	oswarn=' and will currently not work'
-	add_cppflags -DMKSH_UNEMPLOYED
-	add_cppflags -DMKSH_NOPROSPECTOFWORK
+	cpp_define MKSH_UNEMPLOYED 1
+	cpp_define MKSH_NOPROSPECTOFWORK 1
 	# these taken from Harvey-OS github and need re-checking
-	add_cppflags -D_setjmp=setjmp -D_longjmp=longjmp
+	cpp_define _setjmp setjmp
+	cpp_define _longjmp longjmp
 	: "${HAVE_CAN_NO_EH_FRAME=0}"
 	: "${HAVE_CAN_FNOSTRICTALIASING=0}"
 	: "${HAVE_CAN_FSTACKPROTECTORSTRONG=0}"
 	;;
 HP-UX)
+	case $TARGET_OSREV in
+	B.09.*)
+		: "${CC=c89}"
+		add_cppflags -D_HPUX_SOURCE
+		cpp_define MBSDINT_H_SMALL_SYSTEM 1
+		;;
+	esac
 	;;
 Interix)
 	ccpc='-X '
 	ccpl='-Y '
 	add_cppflags -D_ALL_SOURCE
 	: "${LIBS=-lcrypt}"
-	: "${HAVE_SETLOCALE_CTYPE=0}"
+	: "${HAVE_POSIX_UTF8_LOCALE=0}"
 	;;
 IRIX*)
-	: "${HAVE_SETLOCALE_CTYPE=0}"
 	;;
 Jehanne)
-	add_cppflags -DMKSH_ASSUME_UTF8
+	cpp_define MKSH_ASSUME_UTF8 1
 	HAVE_ISSET_MKSH_ASSUME_UTF8=1
 	HAVE_ISOFF_MKSH_ASSUME_UTF8=0
-	add_cppflags -DMKSH__NO_SYMLINK
+	: "${HAVE_POSIX_UTF8_LOCALE=0}"
+	cpp_define MKSH__NO_SYMLINK 1
 	check_categories="$check_categories nosymlink"
-	add_cppflags -DMKSH_NO_CMDLINE_EDITING
-	add_cppflags -DMKSH_DISABLE_REVOKE_WARNING
+	cpp_define MKSH_NO_CMDLINE_EDITING 1
+	cpp_define MKSH_DISABLE_REVOKE_WARNING 1
 	add_cppflags '-D_PATH_DEFPATH=\"/cmd\"'
 	add_cppflags '-DMKSH_DEFAULT_EXECSHELL=\"/cmd/mksh\"'
 	add_cppflags '-DMKSH_DEFAULT_PROFILEDIR=\"/cfg/mksh\"'
@@ -847,7 +1019,7 @@ Linux)
 	*tendracc*) ;;
 	*) add_cppflags -D_GNU_SOURCE ;;
 	esac
-	add_cppflags -DSETUID_CAN_FAIL_WITH_EAGAIN
+	cpp_define SETUID_CAN_FAIL_WITH_EAGAIN 1
 	: "${HAVE_REVOKE=0}"
 	;;
 LynxOS)
@@ -855,32 +1027,39 @@ LynxOS)
 	;;
 midipix)
 	add_cppflags -D_GNU_SOURCE
-	# their Perl (currently…) identifies as os:linux ☹
+	# their Perl (currently...) identifies as os:linux :(
 	check_categories="$check_categories os:midipix"
 	;;
 MidnightBSD)
 	;;
 Minix-vmd)
-	add_cppflags -DMKSH__NO_SETEUGID
-	add_cppflags -DMKSH_UNEMPLOYED
 	add_cppflags -D_MINIX_SOURCE
+	cpp_define MKSH__NO_SETEUGID 1
+	: "${HAVE_SETRESUGID=0}"
+	cpp_define MKSH_UNEMPLOYED 1
 	oldish_ed=no-stderr-ed		# no /bin/ed, maybe see below
-	: "${HAVE_SETLOCALE_CTYPE=0}"
+	: "${HAVE_POSIX_UTF8_LOCALE=0}"
 	;;
 Minix3)
-	add_cppflags -DMKSH_UNEMPLOYED
 	add_cppflags -D_POSIX_SOURCE -D_POSIX_1_SOURCE=2 -D_MINIX
+	cpp_define MKSH_UNEMPLOYED 1
 	oldish_ed=no-stderr-ed		# /usr/bin/ed(!) is broken
-	: "${HAVE_SETLOCALE_CTYPE=0}${MKSH_UNLIMITED=1}" #XXX recheck ulimit
+	: "${HAVE_POSIX_UTF8_LOCALE=0}"
+	: "${MKSH_UNLIMITED=1}"		#XXX recheck ulimit
+	;;
+Minoca)
+	: "${CC=gcc}"
 	;;
 MirBSD)
+	# for testing HAVE_SIGACTION=0 builds only (but fulfills the contract)
+	cpp_define MKSH_USABLE_SIGNALFUNC bsd_signal
 	;;
 MSYS_*)
-	add_cppflags -DMKSH_ASSUME_UTF8=0
+	cpp_define MKSH_ASSUME_UTF8 0
 	HAVE_ISSET_MKSH_ASSUME_UTF8=1
 	HAVE_ISOFF_MKSH_ASSUME_UTF8=1
 	# almost same as CYGWIN* (from RT|Chatzilla)
-	: "${HAVE_SETLOCALE_CTYPE=0}"
+	: "${HAVE_POSIX_UTF8_LOCALE=0}"
 	# broken on this OE (from ir0nh34d)
 	: "${HAVE_STDINT_H=0}"
 	;;
@@ -890,10 +1069,10 @@ NEXTSTEP)
 	add_cppflags -D_NEXT_SOURCE
 	add_cppflags -D_POSIX_SOURCE
 	: "${AWK=gawk}"
-	: "${CC=cc -posix}"
-	add_cppflags -DMKSH_NO_SIGSETJMP
+	: "${CC=cc -posix -traditional-cpp}"
+	cpp_define MKSH_NO_SIGSETJMP 1
 	# NeXTstep cannot get a controlling tty
-	add_cppflags -DMKSH_UNEMPLOYED
+	cpp_define MKSH_UNEMPLOYED 1
 	case $TARGET_OSREV in
 	4.2*)
 		# OpenStep 4.2 is broken by default
@@ -903,27 +1082,29 @@ NEXTSTEP)
 	;;
 Ninix3)
 	# similar to Minix3
-	add_cppflags -DMKSH_UNEMPLOYED
-	: "${MKSH_UNLIMITED=1}" #XXX recheck ulimit
+	cpp_define MKSH_UNEMPLOYED 1
+	: "${MKSH_UNLIMITED=1}"		#XXX recheck ulimit
 	# but no idea what else could be needed
 	oswarn="; it has unknown issues"
 	;;
 OpenBSD)
-	: "${HAVE_SETLOCALE_CTYPE=0}"
 	;;
 OS/2)
-	add_cppflags -DMKSH_ASSUME_UTF8=0
+	cpp_define MKSH_ASSUME_UTF8 0
 	HAVE_ISSET_MKSH_ASSUME_UTF8=1
 	HAVE_ISOFF_MKSH_ASSUME_UTF8=1
+	: "${HAVE_POSIX_UTF8_LOCALE=0}"
+	: "${HAVE_SELECT=0}"
+	# cf. https://github.com/komh/pdksh-os2/commit/590f2b19b0ff92a9a373295bce914654f9f5bf22
 	HAVE_TERMIOS_H=0
 	HAVE_MKNOD=0	# setmode() incompatible
 	check_categories="$check_categories nosymlink"
 	: "${CC=gcc}"
 	: "${SIZE=: size}"
 	SRCS="$SRCS os2.c"
-	add_cppflags -DMKSH_UNEMPLOYED
-	add_cppflags -DMKSH_NOPROSPECTOFWORK
-	add_cppflags -DMKSH_DOSPATH
+	cpp_define MKSH_UNEMPLOYED 1
+	cpp_define MKSH_NOPROSPECTOFWORK 1
+	cpp_define MKSH_DOSPATH 1
 	: "${MKSH_UNLIMITED=1}"
 	if test $textmode = 0; then
 		x='dis'
@@ -948,13 +1129,15 @@ the mksh-os2 porter.
 "
 	;;
 OS/390)
-	add_cppflags -DMKSH_ASSUME_UTF8=0
+	cpp_define MKSH_ASSUME_UTF8 0
 	HAVE_ISSET_MKSH_ASSUME_UTF8=1
 	HAVE_ISOFF_MKSH_ASSUME_UTF8=1
+	: "${HAVE_POSIX_UTF8_LOCALE=0}"
 	: "${CC=xlc}"
 	: "${SIZE=: size}"
-	add_cppflags -DMKSH_FOR_Z_OS
+	cpp_define MKSH_FOR_Z_OS 1
 	add_cppflags -D_ALL_SOURCE
+	$ebcdic || add_cppflags -D_ENHANCED_ASCII_EXT=0xFFFFFFFF
 	oswarn='; EBCDIC support is incomplete'
 	;;
 OSF1)
@@ -963,29 +1146,31 @@ OSF1)
 	add_cppflags -D_POSIX_C_SOURCE=200112L
 	add_cppflags -D_XOPEN_SOURCE=600
 	add_cppflags -D_XOPEN_SOURCE_EXTENDED
-	: "${HAVE_SETLOCALE_CTYPE=0}"
+	: "${HAVE_POSIX_UTF8_LOCALE=0}"
 	;;
 Plan9)
 	add_cppflags -D_POSIX_SOURCE
 	add_cppflags -D_LIMITS_EXTENSION
 	add_cppflags -D_BSD_EXTENSION
 	add_cppflags -D_SUSV2_SOURCE
-	add_cppflags -DMKSH_ASSUME_UTF8
+	cpp_define MKSH_ASSUME_UTF8 1
 	HAVE_ISSET_MKSH_ASSUME_UTF8=1
 	HAVE_ISOFF_MKSH_ASSUME_UTF8=0
-	add_cppflags -DMKSH__NO_SYMLINK
+	: "${HAVE_POSIX_UTF8_LOCALE=0}"
+	cpp_define MKSH__NO_SYMLINK 1
 	check_categories="$check_categories nosymlink"
-	add_cppflags -DMKSH_NO_CMDLINE_EDITING
-	add_cppflags -DMKSH__NO_SETEUGID
+	cpp_define MKSH_NO_CMDLINE_EDITING 1
+	cpp_define MKSH__NO_SETEUGID 1
+	: "${HAVE_SETRESUGID=0}"
 	oswarn=' and will currently not work'
-	add_cppflags -DMKSH_UNEMPLOYED
+	cpp_define MKSH_UNEMPLOYED 1
 	# this is for detecting kencc
-	add_cppflags -DMKSH_MAYBE_KENCC
+	cmplrflgs=-DMKSH_MAYBE_KENCC
 	;;
 PW32*)
 	HAVE_SIG_T=0	# incompatible
 	oswarn=' and will currently not work'
-	: "${HAVE_SETLOCALE_CTYPE=0}"
+	: "${HAVE_POSIX_UTF8_LOCALE=0}"
 	;;
 QNX)
 	add_cppflags -D__NO_EXT_QNX
@@ -995,13 +1180,20 @@ QNX)
 		oldish_ed=no-stderr-ed		# oldish /bin/ed is broken
 		;;
 	esac
-	: "${HAVE_SETLOCALE_CTYPE=0}"
+	: "${HAVE_POSIX_UTF8_LOCALE=0}"
+	;;
+scosysv)
+	cmplrflgs=-DMKSH_MAYBE_QUICK_C
+	cpp_define MKSH__NO_SETEUGID 1
+	: "${HAVE_SETRESUGID=0}"
+	cpp_define MKSH_UNEMPLOYED 1
+	: "${HAVE_POSIX_UTF8_LOCALE=0}${HAVE_TERMIOS_H=0}"
 	;;
 SCO_SV)
 	case $TARGET_OSREV in
 	3.2*)
 		# SCO OpenServer 5
-		add_cppflags -DMKSH_UNEMPLOYED
+		cpp_define MKSH_UNEMPLOYED 1
 		;;
 	5*)
 		# SCO OpenServer 6
@@ -1013,6 +1205,16 @@ SCO_SV)
 	esac
 	: "${HAVE_SYS_SIGLIST=0}${HAVE__SYS_SIGLIST=0}"
 	;;
+SerenityOS)
+	oswarn="; it has issues"
+	: "${MKSH_UNLIMITED=1}${HAVE_GETRUSAGE=0}"
+	cpp_define MKSH_UNEMPLOYED 1
+	cpp_define MKSH_DISABLE_TTY_WARNING 1
+	;;
+SINIX-Z)
+	: "${CC=cc -Xa}"
+	cmplrflgs=-DMKSH_MAYBE_SCDE
+	;;
 skyos)
 	oswarn="; it has minor issues"
 	;;
@@ -1022,13 +1224,12 @@ SunOS)
 	;;
 syllable)
 	add_cppflags -D_GNU_SOURCE
-	add_cppflags -DMKSH_NO_SIGSUSPEND
-	oswarn=' and will currently not work'
+	cpp_define MKSH_NO_SIGSUSPEND 1
+	: "${MKSH_UNLIMITED=1}"
 	;;
 ULTRIX)
 	: "${CC=cc -YPOSIX}"
-	add_cppflags -DMKSH_TYPEDEF_SSIZE_T=int
-	: "${HAVE_SETLOCALE_CTYPE=0}"
+	: "${HAVE_POSIX_UTF8_LOCALE=0}"
 	;;
 UnixWare|UNIX_SV)
 	# SCO UnixWare
@@ -1040,21 +1241,39 @@ UWIN*)
 	tsts=" 3<>/dev/tty"
 	oswarn="; it will compile, but the target"
 	oswarn="$oswarn${nl}platform itself is very flakey/unreliable"
-	: "${HAVE_SETLOCALE_CTYPE=0}"
+	: "${HAVE_POSIX_UTF8_LOCALE=0}"
+	;;
+XENIX)
+	# mostly when crosscompiling from scosysv
+	cmplrflgs=-DMKSH_MAYBE_QUICK_C
+	# this can barely do anything
+	cpp_define MKSH__NO_SETEUGID 1
+	: "${HAVE_SETRESUGID=0}"
+	cpp_define MKSH_NO_SIGSETJMP 1
+	cpp_define _setjmp setjmp
+	cpp_define _longjmp longjmp
+	cpp_define USE_REALLOC_MALLOC 0
+	# per http://www.polarhome.com/service/man/?qf=signal&of=Xenix
+	cpp_define MKSH_USABLE_SIGNALFUNC signal
+	cpp_define MKSH_UNEMPLOYED 1
+	cpp_define MKSH_NOPROSPECTOFWORK 1
+	cpp_define MKSH__NO_SYMLINK 1
+	check_categories="$check_categories nosymlink"
+	: "${HAVE_POSIX_UTF8_LOCALE=0}"
+	# these are broken
+	HAVE_TERMIOS_H=0
 	;;
 _svr4)
 	# generic target for SVR4 Unix with uname -s = uname -n
-	# this duplicates the * target below
 	oswarn='; it may or may not work'
-	test_n "$TARGET_OSREV" || TARGET_OSREV=`uname -r`
+	: "${CC=cc -Xa}"
+	cmplrflgs=-DMKSH_MAYBE_SCDE
 	;;
 *)
 	oswarn='; it may or may not work'
-	test_n "$TARGET_OSREV" || TARGET_OSREV=`uname -r`
 	;;
 esac
-
-: "${HAVE_MKNOD=0}"
+test_n "$TARGET_OSREV" || TARGET_OSREV=`uname -r`
 
 : "${AWK=awk}${CC=cc}${NROFF=nroff}${SIZE=size}"
 test 0 = $r && echo | $NROFF -v 2>&1 | grep GNU >/dev/null 2>&1 && \
@@ -1085,7 +1304,7 @@ OSF1)
 	vv '|' "uname -a >&2"
 	vv '|' "/usr/sbin/sizer -v >&2"
 	;;
-SCO_SV|UnixWare|UNIX_SV)
+scosysv|SCO_SV|UnixWare|UNIX_SV|XENIX)
 	vv '|' "uname -a >&2"
 	vv '|' "uname -X >&2"
 	;;
@@ -1093,14 +1312,20 @@ SCO_SV|UnixWare|UNIX_SV)
 	vv '|' "uname -a >&2"
 	;;
 esac
-test_z "$oswarn" || echo >&2 "
-Warning: mksh has not yet been ported to or tested on your
-operating system '$TARGET_OS'$oswarn. If you can provide
-a shell account to the developer, this may improve; please
-drop us a success or failure notice or even send in diffs,
-at the very least, complete logs (Build.sh + test.sh) will help.
+test_z "$oswarn$oswerr" || echo >&2 "
+Warning: $whatshort has not yet been ported to or tested on your
+operating system '$TARGET_OS'$oswarn$oswerr."
+test_z "$osnote" || echo >&2 "
+Note: $whatshort is not fully ported to or tested yet on your
+operating system '$TARGET_OS'$osnote."
+test_z "$osnote$oswarn" || echo >&2 "
+If you can provide a shell account to the developer, this
+may improve; please drop us a success or failure notice or
+even send patches for the remaining issues, or, at the very
+least, complete logs (Build.sh + test.sh) will help.
 "
-$e "$bi$me: Building the MirBSD Korn Shell$ao $ui$dstversion$ao on $TARGET_OS ${TARGET_OSREV}..."
+test_z "$osnote$oswarn$oswerr" || sleep 3
+$e "$bi$me: Building $whatlong$ao $ui$dstversion$ao on $TARGET_OS ${TARGET_OSREV}..."
 
 #
 # Start of mirtoconf checks
@@ -1117,7 +1342,7 @@ $e $bi$me: Scanning for functions... ple
 # - nwcc defines __GNUC__ too
 CPP="$CC -E"
 $e ... which compiler type seems to be used
-cat >conftest.c <<'EOF'
+cat_h_blurb >conftest.c <<'EOF'
 const char *
 #if defined(__ICC) || defined(__INTEL_COMPILER)
 ct="icc"
@@ -1163,6 +1388,8 @@ ct="tcc"
 ct="clang"
 #elif defined(__NWCC__)
 ct="nwcc"
+#elif defined(__GNUC__) && ((__GNUC__) < 2)
+ct="gcc1"
 #elif defined(__GNUC__)
 ct="gcc"
 #elif defined(_COMPILER_VERSION)
@@ -1177,9 +1404,13 @@ ct="ucode"
 ct="uslc"
 #elif defined(__LCC__)
 ct="lcc"
+#elif defined(MKSH_MAYBE_QUICK_C) && defined(_M_BITFIELDS)
+ct="quickc"
 #elif defined(MKSH_MAYBE_KENCC)
 /* and none of the above matches */
 ct="kencc"
+#elif defined(MKSH_MAYBE_SCDE)
+ct="tryscde"
 #else
 ct="unknown"
 #endif
@@ -1187,6 +1418,8 @@ ct="unknown"
 const char *
 #if defined(__KLIBC__) && !defined(__OS2__)
 et="klibc"
+#elif defined(__dietlibc__)
+et="dietlibc"
 #else
 et="unknown"
 #endif
@@ -1194,24 +1427,43 @@ et="unknown"
 EOF
 ct=untested
 et=untested
-vv ']' "$CPP $CFLAGS $CPPFLAGS $NOWARN conftest.c | \
+vv ']' "$CPP $CFLAGS $CPPFLAGS $NOWARN $cmplrflgs conftest.c | \
     sed -n '/^ *[ce]t *= */s/^ *\([ce]t\) *= */\1=/p' | tr -d \\\\015 >x"
 sed 's/^/[ /' x
 eval `cat x`
 rmf x vv.out
-cat >conftest.c <<'EOF'
+cat_h_blurb >conftest.c <<'EOF'
 #include <unistd.h>
 int main(void) { return (isatty(0)); }
 EOF
+test_z "$Cg" || Cg=-g  # generic
+case $ct:$TARGET_OS in
+tryscde:*)
+	case `LC_ALL=C; export LC_ALL; $CC -V 2>&1` in
+	*'Standard C Development Environment'*)
+		ct=scde ;;
+	*)
+		ct=unknown ;;
+	esac
+	;;
+gcc:_svr4)
+	# weirdly needed to find NSIG
+	case $CC$CPPFLAGS in
+	*STDC*) ;;
+	*) CC="$CC -U__STDC__ -D__STDC__=0" ;;
+	esac
+	;;
+esac
 case $ct in
 ack)
 	# work around "the famous ACK const bug"
 	CPPFLAGS="-Dconst= $CPPFLAGS"
+	: "${HAVE_ATTRIBUTE_EXTENSION=0}"  # skip checking as we know it absent
 	;;
 adsp)
 	echo >&2 'Warning: Analog Devices C++ compiler for Blackfin, TigerSHARC
     and SHARC (21000) DSPs detected. This compiler has not yet
-    been tested for compatibility with mksh. Continue at your
+    been tested for compatibility with this. Continue at your
     own risk, please report success/failure to the developers.'
 	;;
 bcc)
@@ -1221,10 +1473,9 @@ bcc)
 	;;
 clang)
 	# does not work with current "ccc" compiler driver
-	vv '|' "$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN $LIBS -version"
+	vv '|' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN $LIBS --version"
 	# one of these two works, for now
 	vv '|' "${CLANG-clang} -version"
-	vv '|' "${CLANG-clang} --version"
 	# ensure compiler and linker are in sync unless overridden
 	case $CCC_CC:$CCC_LD in
 	:*)	;;
@@ -1233,8 +1484,9 @@ clang)
 	: "${HAVE_STRING_POOLING=i1}"
 	;;
 dec)
-	vv '|' "$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN $LIBS -V"
-	vv '|' "$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN -Wl,-V conftest.c $LIBS"
+	vv '|' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN $LIBS -V"
+	vv '|' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN -Wl,-V conftest.c $LIBS"
+	: "${HAVE_ATTRIBUTE_EXTENSION=0}"  # skip checking as we know it absent
 	;;
 dmc)
 	echo >&2 "Warning: Digital Mars Compiler detected. When running under"
@@ -1242,41 +1494,58 @@ dmc)
 	echo >&2 "    of this platform. Continue at your own risk,"
 	echo >&2 "    please report success/failure to the developers."
 	;;
+gcc1)
+	vv '|' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN -v conftest.c $LIBS"
+	vv '|' 'eval echo "\`$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN $LIBS -dumpmachine\`" \
+		 "gcc\`$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN $LIBS -dumpversion\`"'
+	: "${HAVE_ATTRIBUTE_EXTENSION=0}" # false positive
+	;;
 gcc)
-	vv '|' "$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN -v conftest.c $LIBS"
-	vv '|' 'eval echo "\`$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN $LIBS -dumpmachine\`" \
-		 "gcc\`$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN $LIBS -dumpversion\`"'
+	test_z "$Cg" || Cg='-g3 -fno-builtin'
+	vv '|' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN -v conftest.c $LIBS"
+	vv '|' 'eval echo "\`$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN $LIBS -dumpmachine\`" \
+		 "gcc\`$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN $LIBS -dumpversion\`"'
 	: "${HAVE_STRING_POOLING=i2}"
 	;;
 hpcc)
-	vv '|' "$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN -V conftest.c $LIBS"
+	vv '|' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN -V conftest.c $LIBS"
+	case $TARGET_OS,$TARGET_OSREV in
+	HP-UX,B.09.*)
+		: "${HAVE_ATTRIBUTE_EXTENSION=0}"
+		;;
+	esac
 	;;
 iar)
 	echo >&2 'Warning: IAR Systems (http://www.iar.com) compiler for embedded
     systems detected. This unsupported compiler has not yet
-    been tested for compatibility with mksh. Continue at your
+    been tested for compatibility with this. Continue at your
     own risk, please report success/failure to the developers.'
 	;;
 icc)
-	vv '|' "$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN $LIBS -V"
+	vv '|' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN $LIBS -V"
 	;;
 kencc)
-	vv '|' "$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN -v conftest.c $LIBS"
+	vv '|' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN -v conftest.c $LIBS"
+	: "${HAVE_ATTRIBUTE_EXTENSION=0}"  # skip checking as we know it absent
 	;;
 lacc)
 	# no version information
 	;;
 lcc)
-	vv '|' "$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN -v conftest.c $LIBS"
-	add_cppflags -D__inline__=__inline
+	vv '|' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN -v conftest.c $LIBS"
+	cpp_define __inline__ __inline
+	: "${HAVE_ATTRIBUTE_EXTENSION=0}"  # skip checking as we know it absent
 	;;
 metrowerks)
 	echo >&2 'Warning: Metrowerks C compiler detected. This has not yet
-    been tested for compatibility with mksh. Continue at your
+    been tested for compatibility with this. Continue at your
     own risk, please report success/failure to the developers.'
 	;;
 mipspro)
-	vv '|' "$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN $LIBS -version"
+	test_z "$Cg" || Cg='-g3'
+	vv '|' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN $LIBS -version"
+	: "${HAVE_STDINT_H=0}" # broken unless building with __c99
+	: "${HAVE_ATTRIBUTE_EXTENSION=0}"  # skip checking as we know it absent
 	;;
 msc)
 	ccpr=		# errorlevels are not reliable
@@ -1298,41 +1567,51 @@ msc)
 	esac
 	;;
 neatcc)
-	add_cppflags -DMKSH_DONT_EMIT_IDSTRING
-	add_cppflags -DMKSH_NO_SIGSETJMP
-	add_cppflags -Dsig_atomic_t=int
+	cpp_define MKSH_DONT_EMIT_IDSTRING 1
+	cpp_define MKSH_NO_SIGSETJMP 1
+	cpp_define sig_atomic_t int
 	vv '|' "$CC"
 	;;
 nwcc)
-	vv '|' "$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN $LIBS -version"
+	vv '|' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN $LIBS -version"
 	;;
 pcc)
-	vv '|' "$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN $LIBS -v"
+	vv '|' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN $LIBS -v"
 	;;
 pgi)
 	echo >&2 'Warning: PGI detected. This unknown compiler has not yet
-    been tested for compatibility with mksh. Continue at your
+    been tested for compatibility with this. Continue at your
     own risk, please report success/failure to the developers.'
 	;;
+quickc)
+	# no version information
+	: "${HAVE_ATTRIBUTE_EXTENSION=0}"  # skip checking as we know it absent
+	;;
+scde)
+	vv '|' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN -V conftest.c $LIBS"
+	: "${HAVE_ATTRIBUTE_EXTENSION=0}"  # skip checking as we know it absent
+	;;
 sdcc)
 	echo >&2 'Warning: sdcc (http://sdcc.sourceforge.net), the small devices
     C compiler for embedded systems detected. This has not yet
-    been tested for compatibility with mksh. Continue at your
+    been tested for compatibility with this. Continue at your
     own risk, please report success/failure to the developers.'
 	;;
 sunpro)
-	vv '|' "$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN -V conftest.c $LIBS"
+	vv '|' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN -V conftest.c $LIBS"
 	;;
 tcc)
-	vv '|' "$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN $LIBS -v"
+	vv '|' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN $LIBS -v"
 	;;
 tendra)
-	vv '|' "$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN $LIBS -V 2>&1 | \
-	    grep -F -i -e version -e release"
+	vv '|' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN $LIBS -V 2>&1 | \
+	    grep -i -e version -e release"
+	: "${HAVE_ATTRIBUTE_EXTENSION=0}" # false positive
 	;;
 ucode)
-	vv '|' "$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN $LIBS -V"
-	vv '|' "$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN -Wl,-V conftest.c $LIBS"
+	vv '|' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN $LIBS -V"
+	vv '|' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN -Wl,-V conftest.c $LIBS"
+	: "${HAVE_ATTRIBUTE_EXTENSION=0}"  # skip checking as we know it absent
 	;;
 uslc)
 	case $TARGET_OS:$TARGET_OSREV in
@@ -1342,36 +1621,56 @@ uslc)
 		: "${HAVE_CAN_OTWO=0}${HAVE_CAN_OPTIMISE=0}"
 		;;
 	esac
-	vv '|' "$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN -V conftest.c $LIBS"
+	vv '|' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN -V conftest.c $LIBS"
+	: "${HAVE_ATTRIBUTE_EXTENSION=0}"  # skip checking as we know it absent
 	;;
 watcom)
-	vv '|' "$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN -v conftest.c $LIBS"
+	vv '|' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN -v conftest.c $LIBS"
 	;;
 xlc)
-	vv '|' "$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN $LIBS -qversion"
-	vv '|' "$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN $LIBS -qversion=verbose"
+	vv '|' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN $LIBS -qversion"
+	vv '|' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN $LIBS -qversion=verbose"
 	vv '|' "ld -V"
 	;;
 *)
 	test x"$ct" = x"untested" && $e "!!! detecting preprocessor failed"
 	ct=unknown
 	vv '|' "$CC --version"
-	vv '|' "$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN -v conftest.c $LIBS"
-	vv '|' "$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN -V conftest.c $LIBS"
+	vv '|' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN -v conftest.c $LIBS"
+	vv '|' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN -V conftest.c $LIBS"
 	;;
 esac
 case $cm in
 dragonegg|llvm)
 	vv '|' "llc -version"
 	;;
+trace)
+	case $ct in
+	gcc) ;;
+	*)
+		echo >&2 "E: -c trace does not work with $cm"
+		exit 1
+		;;
+	esac
+	;;
 esac
 etd=" on $et"
+# still imake style but... cannot be helped
 case $et in
+dietlibc)
+	# live, BSD, live\u2763
+	add_cppflags -D_BSD_SOURCE
+	# broken
+	HAVE_POSIX_UTF8_LOCALE=0
+	;;
 klibc)
+	cpp_define MKSH_NO_SIGSETJMP 1
+	cpp_define _setjmp setjmp
+	cpp_define _longjmp longjmp
 	: "${MKSH_UNLIMITED=1}"
 	;;
 unknown)
-	# nothing special detected, don’t worry
+	# nothing special detected, do not worry
 	etd=
 	;;
 *)
@@ -1453,6 +1752,10 @@ msc)
 	save_NOWARN="${ccpc}/w"
 	DOWARN="${ccpc}/WX"
 	;;
+quickc)
+	;;
+scde)
+	;;
 sunpro)
 	test x"$save_NOWARN" = x"" && save_NOWARN='-errwarn=%none'
 	ac_flags 0 errwarnnone "$save_NOWARN"
@@ -1505,7 +1808,7 @@ hpcc)
 	ac_flags 1 otwo +O2
 	phase=x
 	;;
-kencc|tcc|tendra)
+kencc|quickc|scde|tcc|tendra)
 	# no special optimisation
 	;;
 sunpro)
@@ -1525,7 +1828,16 @@ xlc)
 	test 1 = $HAVE_CAN_OTHREE || ac_flags 1 otwo -O2
 	;;
 *)
-	ac_flags 1 otwo -O2
+	if test_n "$Cg"; then
+		ac_flags 1 ogee -Og
+		if test 1 = $HAVE_CAN_OGEE; then
+			HAVE_CAN_OTWO=1 # for below
+		else
+			ac_flags 1 otwo -O2
+		fi
+	else
+		ac_flags 1 otwo -O2
+	fi
 	test 1 = $HAVE_CAN_OTWO || ac_flags 1 optimise -O
 	;;
 esac
@@ -1546,18 +1858,28 @@ dmc)
 	ac_flags 1 decl "${ccpc}-r" 'for strict prototype checks'
 	ac_flags 1 schk "${ccpc}-s" 'for stack overflow checking'
 	;;
+gcc1)
+	# The following tests run with -Werror (gcc only) if possible
+	NOWARN=$DOWARN; phase=u
+	ac_flags 1 wnodeprecateddecls -Wno-deprecated-declarations
+	# we do not even use CFrustFrust in MirBSD so do not code in it...
+	ac_flags 1 no_eh_frame -fno-asynchronous-unwind-tables
+	ac_flags 1 fnostrictaliasing -fno-strict-aliasing
+	ac_flags 1 data_abi_align -malign-data=abi
+	i=1
+	;;
 gcc)
 	ac_flags 1 fnolto -fno-lto 'whether we can explicitly disable buggy GCC LTO' -fno-lto
 	# The following tests run with -Werror (gcc only) if possible
 	NOWARN=$DOWARN; phase=u
 	ac_flags 1 wnodeprecateddecls -Wno-deprecated-declarations
-	# mksh is not written in CFrustFrust!
+	# we do not even use CFrustFrust in MirBSD so do not code in it...
 	ac_flags 1 no_eh_frame -fno-asynchronous-unwind-tables
 	ac_flags 1 fnostrictaliasing -fno-strict-aliasing
 	ac_flags 1 fstackprotectorstrong -fstack-protector-strong
 	test 1 = $HAVE_CAN_FSTACKPROTECTORSTRONG || \
 	    ac_flags 1 fstackprotectorall -fstack-protector-all
-	test $cm = dragonegg && case " $CC $CFLAGS $LDFLAGS " in
+	test $cm = dragonegg && case " $CC $CFLAGS $Cg $LDFLAGS " in
 	*\ -fplugin=*dragonegg*) ;;
 	*) ac_flags 1 fplugin_dragonegg -fplugin=dragonegg ;;
 	esac
@@ -1618,6 +1940,9 @@ icc)
 	;;
 mipspro)
 	ac_flags 1 fullwarn -fullwarn 'for remark output support'
+	# unreachable-from-prevline loop, unused variable, enum vs int @exec.c
+	# unused parameter, conversion pointer/same-sized integer
+	ac_flags 1 diagsupp '-diag_suppress 1127,1174,1185,3201,3970' 'to quieten MIPSpro down'
 	;;
 msc)
 	ac_flags 1 strpool "${ccpc}/GF" 'if string pooling can be enabled'
@@ -1679,8 +2004,8 @@ if test 1 = $i; then
 	ac_flags 1 fwrapv -fwrapv
 fi
 
-# “on demand” means: GCC version >= 4
-fd='if to rely on compiler for string pooling'
+# "on demand" means: GCC version >= 4
+fd='whether to rely on compiler for string pooling'
 ac_cache string_pooling || case $HAVE_STRING_POOLING in
 2) fx=' (on demand, cached)' ;;
 i1) fv=1 ;;
@@ -1697,12 +2022,13 @@ test $ct = pcc && phase=u
 #
 # Compiler: check for stuff that only generates warnings
 #
-ac_test attribute_bounded '' 'for __attribute__((__bounded__))' <<-'EOF'
-	#if defined(__TenDRA__) || (defined(__GNUC__) && (__GNUC__ < 2))
-	extern int thiswillneverbedefinedIhope(void);
-	/* force a failure: TenDRA and gcc 1.42 have false positive here */
-	int main(void) { return (thiswillneverbedefinedIhope()); }
-	#else
+: "${HAVE_ATTRIBUTE_EXTENSION=1}" # not a separate test but a dependency
+ac_test attribute_bounded attribute_extension 0 'for __attribute__((__bounded__))' <<-'EOF'
+	#ifdef __has_attribute
+	# if !__has_attribute(__bounded__)
+	#  error nope
+	# endif
+	#endif
 	#include <string.h>
 	#undef __attribute__
 	int xcopy(const void *, void *, size_t)
@@ -1716,14 +2042,13 @@ ac_test attribute_bounded '' 'for __attr
 		 */
 		memmove(d, s, n); return ((int)n);
 	}
-	#endif
 EOF
-ac_test attribute_format '' 'for __attribute__((__format__))' <<-'EOF'
-	#if defined(__TenDRA__) || (defined(__GNUC__) && (__GNUC__ < 2))
-	extern int thiswillneverbedefinedIhope(void);
-	/* force a failure: TenDRA and gcc 1.42 have false positive here */
-	int main(void) { return (thiswillneverbedefinedIhope()); }
-	#else
+ac_test attribute_format attribute_extension 0 'for __attribute__((__format__))' <<-'EOF'
+	#ifdef __has_attribute
+	# if !__has_attribute(__format__)
+	#  error nope
+	# endif
+	#endif
 	#define fprintf printfoo
 	#include <stdio.h>
 	#undef __attribute__
@@ -1731,57 +2056,40 @@ ac_test attribute_format '' 'for __attri
 	extern int fprintf(FILE *, const char *format, ...)
 	    __attribute__((__format__(__printf__, 2, 3)));
 	int main(int ac, char *av[]) { return (fprintf(stderr, "%s%d", *av, ac)); }
-	#endif
 EOF
-ac_test attribute_noreturn '' 'for __attribute__((__noreturn__))' <<-'EOF'
-	#if defined(__TenDRA__) || (defined(__GNUC__) && (__GNUC__ < 2))
-	extern int thiswillneverbedefinedIhope(void);
-	/* force a failure: TenDRA and gcc 1.42 have false positive here */
-	int main(void) { return (thiswillneverbedefinedIhope()); }
-	#else
+ac_test attribute_noreturn attribute_extension 0 'for __attribute__((__noreturn__))' <<-'EOF'
+	#ifdef __has_attribute
+	# if !__has_attribute(__noreturn__)
+	#  error nope
+	# endif
+	#endif
 	#include <stdlib.h>
 	#undef __attribute__
 	void fnord(void) __attribute__((__noreturn__));
 	int main(void) { fnord(); }
 	void fnord(void) { exit(0); }
-	#endif
 EOF
-ac_test attribute_pure '' 'for __attribute__((__pure__))' <<-'EOF'
-	#if defined(__TenDRA__) || (defined(__GNUC__) && (__GNUC__ < 2))
-	extern int thiswillneverbedefinedIhope(void);
-	/* force a failure: TenDRA and gcc 1.42 have false positive here */
-	int main(void) { return (thiswillneverbedefinedIhope()); }
-	#else
-	#include <unistd.h>
-	#undef __attribute__
-	int foo(const char *) __attribute__((__pure__));
-	int main(int ac, char *av[]) { return (foo(av[ac - 1]) + isatty(0)); }
-	int foo(const char *s) { return ((int)s[0]); }
+ac_test attribute_unused attribute_extension 0 'for __attribute__((__unused__))' <<-'EOF'
+	#ifdef __has_attribute
+	# if !__has_attribute(__unused__)
+	#  error nope
+	# endif
 	#endif
-EOF
-ac_test attribute_unused '' 'for __attribute__((__unused__))' <<-'EOF'
-	#if defined(__TenDRA__) || (defined(__GNUC__) && (__GNUC__ < 2))
-	extern int thiswillneverbedefinedIhope(void);
-	/* force a failure: TenDRA and gcc 1.42 have false positive here */
-	int main(void) { return (thiswillneverbedefinedIhope()); }
-	#else
 	#include <unistd.h>
 	#undef __attribute__
 	int main(int ac __attribute__((__unused__)), char *av[]
 	    __attribute__((__unused__))) { return (isatty(0)); }
-	#endif
 EOF
-ac_test attribute_used '' 'for __attribute__((__used__))' <<-'EOF'
-	#if defined(__TenDRA__) || (defined(__GNUC__) && (__GNUC__ < 2))
-	extern int thiswillneverbedefinedIhope(void);
-	/* force a failure: TenDRA and gcc 1.42 have false positive here */
-	int main(void) { return (thiswillneverbedefinedIhope()); }
-	#else
+ac_test attribute_used attribute_extension 0 'for __attribute__((__used__))' <<-'EOF'
+	#ifdef __has_attribute
+	# if !__has_attribute(__used__)
+	#  error nope
+	# endif
+	#endif
 	#include <unistd.h>
 	#undef __attribute__
 	static const char fnord[] __attribute__((__used__)) = "42";
 	int main(void) { return (isatty(0)); }
-	#endif
 EOF
 
 # End of tests run with -Werror
@@ -1807,7 +2115,7 @@ ac_ifcpp 'ifdef MKSH_NOPROSPECTOFWORK' i
     "if mksh will be built without job signals" && \
     check_categories="$check_categories arge nojsig"
 ac_ifcpp 'ifdef MKSH_ASSUME_UTF8' isset_MKSH_ASSUME_UTF8 '' \
-    'if the default UTF-8 mode is specified' && : "${HAVE_SETLOCALE_CTYPE=0}"
+    'if the default UTF-8 mode is specified' && : "${HAVE_POSIX_UTF8_LOCALE=0}"
 ac_ifcpp 'if !MKSH_ASSUME_UTF8' isoff_MKSH_ASSUME_UTF8 \
     isset_MKSH_ASSUME_UTF8 0 \
     'if the default UTF-8 mode is disabled' && \
@@ -1833,15 +2141,24 @@ ac_test both_time_h '' 'whether <sys/tim
 	#include <sys/time.h>
 	#include <time.h>
 	#include <unistd.h>
-	int main(void) { struct tm tm; return ((int)sizeof(tm) + isatty(0)); }
+	int main(void) { struct timeval tv; return ((int)sizeof(tv) + isatty(0)); }
+EOF
+ac_header sys/select.h sys/types.h
+test "11" = "$HAVE_SYS_TIME_H$HAVE_SYS_SELECT_H" || HAVE_SELECT_TIME_H=1
+ac_test select_time_h '' 'whether <sys/time.h> and <sys/select.h> can both be included' <<-'EOF'
+	#include <sys/types.h>
+	#include <sys/time.h>
+	#include <sys/select.h>
+	#include <unistd.h>
+	int main(void) { struct timeval tv; return ((int)sizeof(tv) + isatty(0)); }
 EOF
 ac_header sys/bsdtypes.h
 ac_header sys/file.h sys/types.h
 ac_header sys/mkdev.h sys/types.h
 ac_header sys/mman.h sys/types.h
 ac_header sys/param.h
+ac_header sys/ptem.h sys/types.h sys/stream.h
 ac_header sys/resource.h sys/types.h _time
-ac_header sys/select.h sys/types.h
 ac_header sys/sysmacros.h
 ac_header bstring.h
 ac_header grp.h sys/types.h
@@ -1854,18 +2171,16 @@ ac_header stdint.h stdarg.h
 ac_header strings.h sys/types.h string.h
 ac_header termios.h
 ac_header ulimit.h sys/types.h
-ac_header values.h
 
 #
 # Environment: definitions
 #
 echo '#include <sys/types.h>
 #include <unistd.h>
-/* check that off_t can represent 2^63-1 correctly, thx FSF */
-#define LARGE_OFF_T ((((off_t)1 << 31) << 31) - 1 + (((off_t)1 << 31) << 31))
-int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721 &&
-    LARGE_OFF_T % 2147483647 == 1) ? 1 : -1];
-int main(void) { return (isatty(0)); }' >lft.c
+struct ctassert_offt {
+	off_t min63bits:63;
+};
+int main(void) { return ((int)sizeof(struct ctassert_offt)); }' >lft.c
 ac_testn can_lfs '' "for large file support" <lft.c
 save_CPPFLAGS=$CPPFLAGS
 add_cppflags -D_FILE_OFFSET_BITS=64
@@ -1882,27 +2197,52 @@ rmf lft*	# end of large file support tes
 #
 # Environment: types
 #
-ac_test can_inttypes '!' stdint_h 1 "for standard 32-bit integer types" <<-'EOF'
-	#include <sys/types.h>
-	#include <stddef.h>
-	int main(int ac, char *av[]) { return ((uint32_t)(size_t)*av + (int32_t)ac); }
-EOF
-ac_test can_ucbints '!' can_inttypes 1 "for UCB 32-bit integer types" <<-'EOF'
-	#include <sys/types.h>
-	#include <stddef.h>
-	int main(int ac, char *av[]) { return ((u_int32_t)(size_t)*av + (int32_t)ac); }
-EOF
-ac_test can_int8type '!' stdint_h 1 "for standard 8-bit integer type" <<-'EOF'
+HAVE_MBI_CTAS=x
+ac_testn mbi_ctas '' 'if integer types are sane enough' <<-'EOF'
 	#include <sys/types.h>
+	#if HAVE_STDINT_H
+	#include <stdarg.h>
+	#include <stdint.h>
+	#endif
+	#include <limits.h>
 	#include <stddef.h>
-	int main(int ac, char *av[]) { return ((uint8_t)(size_t)av[ac]); }
+	#undef MBSDINT_H_SKIP_CTAS
+	#include "mbsdcc.h"
+	#include "mbsdint.h"
+	#include <unistd.h>
+	int main(void) { return (isatty(0)); }
 EOF
-ac_test can_ucbint8 '!' can_int8type 1 "for UCB 8-bit integer type" <<-'EOF'
-	#include <sys/types.h>
-	#include <stddef.h>
-	int main(int ac, char *av[]) { return ((u_int8_t)(size_t)av[ac]); }
+test 1 = $HAVE_MBI_CTAS || exit 1
+
+ac_testn ssize_t <<-'EOF'
+	#define MKSH_INCLUDES_ONLY
+	#define MKSH_DO_MBI_CTAS
+	#include "sh.h"
+	int main(int ac, char *av[]) {
+		return (ac + (int)(ssize_t)*av);
+	}
 EOF
 
+if test 0 = $HAVE_SSIZE_T; then
+	# SCO, Ultrix, Xenix and the likes
+	cpp_define SSIZE_MIN INT_MIN
+	cpp_define SSIZE_MAX INT_MAX
+	cpp_define ssize_t int
+	unset HAVE_SSIZE_T
+	ac_testn ssize_t '' 'whether int can be used as ssize_t' <<-'EOF'
+		#define MKSH_INCLUDES_ONLY
+		#define MKSH_DO_MBI_CTAS
+		#include "sh.h"
+		int main(int ac, char *av[]) {
+			ssize_t s = ac > 1 ? SSIZE_MAX : SSIZE_MIN;
+			size_t z = ac > 2 ? SIZE_MAX : 0U;
+			return (printf("%" mbiSIZE_P(d) ",%" mbiSIZE_P(u),
+			    (mbiSIZE_S)s, mbiSIZE_PV(z)));
+		}
+	EOF
+	test 1 = $HAVE_SSIZE_T || exit 1
+fi
+
 # only testn: added later below
 ac_testn sig_t <<-'EOF'
 	#include <sys/types.h>
@@ -1920,7 +2260,7 @@ ac_testn sighandler_t '!' sig_t 0 <<-'EO
 	int main(void) { return (foo == (sighandler_t)0); }
 EOF
 if test 1 = $HAVE_SIGHANDLER_T; then
-	add_cppflags -Dsig_t=sighandler_t
+	cpp_define sig_t sighandler_t
 	HAVE_SIG_T=1
 fi
 
@@ -1932,11 +2272,11 @@ ac_testn __sighandler_t '!' sig_t 0 <<-'
 	int main(void) { return (foo == (__sighandler_t)0); }
 EOF
 if test 1 = $HAVE___SIGHANDLER_T; then
-	add_cppflags -Dsig_t=__sighandler_t
+	cpp_define sig_t __sighandler_t
 	HAVE_SIG_T=1
 fi
 
-test 1 = $HAVE_SIG_T || add_cppflags -Dsig_t=nosig_t
+test 1 = $HAVE_SIG_T || cpp_define sig_t nosig_t
 ac_cppflags SIG_T
 
 #
@@ -1946,13 +2286,17 @@ if test $cm = makefile; then
 	: nothing to check
 else
 	HAVE_LINK_WORKS=x
-	ac_testinit link_works '' 'checking if the final link command may succeed'
+	ac_testinit link_works '' 'if the final link command may succeed'
 	fv=1
 	cat >conftest.c <<-EOF
 		#define EXTERN
 		#define MKSH_INCLUDES_ONLY
+		#define MKSH_DO_MBI_CTAS
 		#include "sh.h"
 		__RCSID("$srcversion");
+		__IDSTRING(mbsdcc_h_rcsid, SYSKERN_MBSDCC_H);
+		__IDSTRING(mbsdint_h_rcsid, SYSKERN_MBSDINT_H);
+		__IDSTRING(sh_h_rcsid, MKSH_SH_H_ID);
 		int main(void) {
 			struct timeval tv;
 			printf("Hello, World!\\n");
@@ -1961,27 +2305,33 @@ else
 EOF
 	case $cm in
 	llvm)
-		v "$CC $CFLAGS $CPPFLAGS $NOWARN -emit-llvm -c conftest.c" || fv=0
+		v "$CC $CFLAGS $Cg $CPPFLAGS $NOWARN -emit-llvm -c conftest.c" || fv=0
 		rmf $tfn.s
 		test $fv = 0 || v "llvm-link -o - conftest.o | opt $optflags | llc -o $tfn.s" || fv=0
-		test $fv = 0 || v "$CC $CFLAGS $LDFLAGS -o $tcfn $tfn.s $LIBS $ccpr"
+		test $fv = 0 || v "$CC $CFLAGS $Cg $LDFLAGS -o $tcfn $tfn.s $LIBS $ccpr"
 		;;
 	dragonegg)
-		v "$CC $CFLAGS $CPPFLAGS $NOWARN -S -flto conftest.c" || fv=0
+		v "$CC $CFLAGS $Cg $CPPFLAGS $NOWARN -S -flto conftest.c" || fv=0
 		test $fv = 0 || v "mv conftest.s conftest.ll"
 		test $fv = 0 || v "llvm-as conftest.ll" || fv=0
 		rmf $tfn.s
 		test $fv = 0 || v "llvm-link -o - conftest.bc | opt $optflags | llc -o $tfn.s" || fv=0
-		test $fv = 0 || v "$CC $CFLAGS $LDFLAGS -o $tcfn $tfn.s $LIBS $ccpr"
+		test $fv = 0 || v "$CC $CFLAGS $Cg $LDFLAGS -o $tcfn $tfn.s $LIBS $ccpr"
 		;;
 	combine)
-		v "$CC $CFLAGS $CPPFLAGS $LDFLAGS -fwhole-program --combine $NOWARN -o $tcfn conftest.c $LIBS $ccpr"
+		v "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS -fwhole-program --combine $NOWARN -o $tcfn conftest.c $LIBS $ccpr"
 		;;
 	lto|normal)
 		cm=normal
-		v "$CC $CFLAGS $CPPFLAGS $NOWARN -c conftest.c" || fv=0
-		test $fv = 0 || v "$CC $CFLAGS $LDFLAGS -o $tcfn conftest.o $LIBS $ccpr"
+		v "$CC $CFLAGS $Cg $CPPFLAGS $NOWARN -c conftest.c" || fv=0
+		test $fv = 0 || v "$CC $CFLAGS $Cg $LDFLAGS -o $tcfn conftest.o $LIBS $ccpr"
 		;;
+	trace)
+		rm -f conftest.d conftest.o
+		v "$CC $CFLAGS $Cg $CPPFLAGS $NOWARN -MD -c conftest.c" || fv=0
+		test -f conftest.d && test -s conftest.d || fv=0
+		test -f conftest.o && test -s conftest.o || fv=0
+		test $fv = 0 || v "$CC $CFLAGS $Cg $LDFLAGS -o $tcfn conftest.o $LIBS -Wl,-t,-t $ccpr"
 	esac
 	test -f $tcfn || fv=0
 	ac_testdone
@@ -1991,43 +2341,65 @@ fi
 #
 # Environment: errors and signals
 #
-test x"NetBSD" = x"$TARGET_OS" && $e Ignore the compatibility warning.
 
-ac_testn sys_errlist '' "the sys_errlist[] array and sys_nerr" <<-'EOF'
+HAVE_SOME_ERRLIST=0
+
+ac_test strerrordesc_np '!' some_errlist 0 "GNU strerrordesc_np()" <<-'EOF'
+	extern const char *strerrordesc_np(int);
+	int main(int ac, char *av[]) { return (*strerrordesc_np(*av[ac])); }
+EOF
+test 1 = "$HAVE_STRERRORDESC_NP" && HAVE_SOME_ERRLIST=1
+
+ac_testn sys_errlist '!' some_errlist 0 "the sys_errlist[] array and sys_nerr" <<-'EOF'
 	extern const int sys_nerr;
 	extern const char * const sys_errlist[];
 	extern int isatty(int);
 	int main(void) { return (*sys_errlist[sys_nerr - 1] + isatty(0)); }
 EOF
-ac_testn _sys_errlist '!' sys_errlist 0 "the _sys_errlist[] array and _sys_nerr" <<-'EOF'
+test 1 = "$HAVE_SYS_ERRLIST" && HAVE_SOME_ERRLIST=1
+
+ac_testn _sys_errlist '!' some_errlist 0 "the _sys_errlist[] array and _sys_nerr" <<-'EOF'
 	extern const int _sys_nerr;
 	extern const char * const _sys_errlist[];
 	extern int isatty(int);
 	int main(void) { return (*_sys_errlist[_sys_nerr - 1] + isatty(0)); }
 EOF
 if test 1 = "$HAVE__SYS_ERRLIST"; then
-	add_cppflags -Dsys_nerr=_sys_nerr
-	add_cppflags -Dsys_errlist=_sys_errlist
+	cpp_define sys_nerr _sys_nerr
+	cpp_define sys_errlist _sys_errlist
 	HAVE_SYS_ERRLIST=1
+	HAVE_SOME_ERRLIST=1
 fi
+
 ac_cppflags SYS_ERRLIST
 
 for what in name list; do
 	uwhat=`upper $what`
-	ac_testn sys_sig$what '' "the sys_sig$what[] array" <<-EOF
+	eval HAVE_SOME_SIG$uwhat=0
+
+	case $what in name) x=sigabbrev_np ;; list) x=sigdescr_np ;; esac
+	ac_test $x '!' some_sig$what 0 "GNU $x()" <<-EOF
+		extern const char *$x(int);
+		int main(int ac, char *av[]) { return (*$x(*av[ac])); }
+	EOF
+	test x"1" = x"$fv" && eval HAVE_SOME_SIG$uwhat=1
+
+	ac_testn sys_sig$what '!' some_sig$what 0 "the sys_sig$what[] array" <<-EOF
 		extern const char * const sys_sig$what[];
 		extern int isatty(int);
 		int main(void) { return (sys_sig$what[0][0] + isatty(0)); }
 	EOF
-	ac_testn _sys_sig$what '!' sys_sig$what 0 "the _sys_sig$what[] array" <<-EOF
+	test x"1" = x"$fv" && eval HAVE_SOME_SIG$uwhat=1
+
+	ac_testn _sys_sig$what '!' some_sig$what 0 "the _sys_sig$what[] array" <<-EOF
 		extern const char * const _sys_sig$what[];
 		extern int isatty(int);
 		int main(void) { return (_sys_sig$what[0][0] + isatty(0)); }
 	EOF
-	eval uwhat_v=\$HAVE__SYS_SIG$uwhat
-	if test 1 = "$uwhat_v"; then
-		add_cppflags -Dsys_sig$what=_sys_sig$what
+	if test x"1" = x"$fv"; then
+		cpp_define sys_sig$what _sys_sig$what
 		eval HAVE_SYS_SIG$uwhat=1
+		eval HAVE_SOME_SIG$uwhat=1
 	fi
 	ac_cppflags SYS_SIG$uwhat
 done
@@ -2067,16 +2439,19 @@ ac_test rlimit '' 'getrlimit and setrlim
 	}
 EOF
 
-ac_test rlim_t rlimit 0 <<-'EOF'
+ac_testnnd rlim_t rlimit 0 <<-'EOF'
 	#include <sys/types.h>
-	#if HAVE_BOTH_TIME_H
+	#if HAVE_BOTH_TIME_H && HAVE_SELECT_TIME_H
 	#include <sys/time.h>
 	#include <time.h>
-	#elif HAVE_SYS_TIME_H
+	#elif HAVE_SYS_TIME_H && HAVE_SELECT_TIME_H
 	#include <sys/time.h>
 	#elif HAVE_TIME_H
 	#include <time.h>
 	#endif
+	#if HAVE_SYS_SELECT_H
+	#include <sys/select.h>
+	#endif
 	#if HAVE_SYS_RESOURCE_H
 	#include <sys/resource.h>
 	#endif
@@ -2084,6 +2459,95 @@ ac_test rlim_t rlimit 0 <<-'EOF'
 	int main(void) { return (((int)(rlim_t)0) + isatty(0)); }
 EOF
 
+if test 10 = "$HAVE_RLIMIT$HAVE_RLIM_T"; then
+	fv=$MKSH_RLIM_T
+	fd='for what rlim_t could have been'
+	# reuses here document from above
+	if test x"$fv" = x"" || test x"$fv" = x"x"; then
+		$e ... $fd
+		vv ']' "$CPP $CFLAGS $Cg $CPPFLAGS $NOWARN conftest.c | grep -v '^#' | tr -d \\\\015 >x"
+		fx=0
+		fr=
+		while read line; do
+			case $fx in
+			0)
+				case $line in
+				*struct*[\	\ ]rlimit|*struct*[\	\ ]rlimit[\	\ \{]*)
+					fr=$line
+					fx=1
+					;;
+				esac ;;
+			1)
+				fr="$fr $line"
+				case $line in
+				*\}*)
+					fx=2
+					;;
+				esac ;;
+			esac
+		done <x
+		echo "[ $fr"
+		fr=`echo " $fr" | sed \
+		    -e 's/[	 ][	 ]*/ /g' \
+		    -e 's/^ *struct rlimit *[{] *//' \
+		    -e 's/ *;.*$//'`
+		fx=
+		case $fr in
+		*\ rlim_cur)
+			fr=`echo " $fr" | sed \
+			    -e 's/^ //' \
+			    -e 's/ rlim_cur$//'`
+			;;
+		*\ rlim_max)
+			fr=`echo " $fr" | sed \
+			    -e 's/^ //' \
+			    -e 's/ rlim_max$//'`
+			;;
+		*)
+			fr=
+			;;
+		esac
+		case $fr in
+		int|signed\ int)
+			fv=RLT_SI ;;
+		u_int|unsigned|unsigned\ int)
+			fv=RLT_UI ;;
+		long|long\ int|signed\ long|signed\ long\ int)
+			fv=RLT_SL ;;
+		u_long|unsigned\ long|unsigned\ long\ int)
+			fv=RLT_UL ;;
+		long\ long|long\ long\ int|signed\ long\ long|signed\ long\ long\ int)
+			fv=RLT_SQ ;;
+		unsigned\ long\ long|unsigned\ long\ long\ int)
+			fv=RLT_UQ ;;
+		[a-z_]*_t)
+			fv=`echo " $fr" | sed -n '/^ \([a-z0-9_]*_t\)$/s//\1/p'` ;;
+		*)
+			fv= ;;
+		esac
+		test_n "$fv" || fx="(could not be determined from $fr)"
+	else
+		fx=' (cached)'
+	fi
+	test_z "$fv" || cpp_define MKSH_RLIM_T "$fv"
+	$e "$bi==> $fd...$ao $ui$fv$ao$fx"
+	fx=
+fi
+
+ac_test get_current_dir_name <<-'EOF'
+	#define MKSH_INCLUDES_ONLY
+	#include "sh.h"
+	int main(void) { return (!get_current_dir_name()); }
+EOF
+
+ac_test getrandom <<-'EOF'
+	#define MKSH_INCLUDES_ONLY
+	#define HAVE_GETRANDOM 1
+	#include "sh.h"
+	char buf;
+	int main(void) { return ((int)getrandom(&buf, 1, GRND_NONBLOCK)); }
+EOF
+
 ac_test getrusage <<-'EOF'
 	#define MKSH_INCLUDES_ONLY
 	#include "sh.h"
@@ -2122,6 +2586,7 @@ ac_test memmove <<-'EOF'
 	}
 EOF
 
+: "${HAVE_MKNOD=0}"
 ac_test mknod '' 'if to use mknod(), makedev() and friends' <<-'EOF'
 	#define MKSH_INCLUDES_ONLY
 	#include "sh.h"
@@ -2144,7 +2609,7 @@ ac_test mmap lock_fcntl 0 'for mmap and
 	#include <stddef.h>
 	#include <stdlib.h>
 	int main(void) { return ((void *)mmap(NULL, (size_t)0,
-	    PROT_READ, MAP_PRIVATE, 0, (off_t)0) == (void *)NULL ? 1 :
+	    PROT_READ, MAP_PRIVATE, 0, (off_t)0) == (void *)0UL ? 1 :
 	    munmap(NULL, 0)); }
 EOF
 
@@ -2158,6 +2623,13 @@ ac_test nice <<-'EOF'
 	int main(void) { return (nice(4)); }
 EOF
 
+ac_test rename <<-'EOF'
+	#include <fcntl.h>
+	#include <stdio.h>
+	#include <unistd.h>
+	int main(int ac, char *av[]) { return (rename(*av, av[ac - 1])); }
+EOF
+
 ac_test revoke <<-'EOF'
 	#include <sys/types.h>
 	#if HAVE_LIBUTIL_H
@@ -2167,34 +2639,33 @@ ac_test revoke <<-'EOF'
 	int main(int ac, char *av[]) { return (ac + revoke(av[0])); }
 EOF
 
-ac_test setlocale_ctype '' 'setlocale(LC_CTYPE, "")' <<-'EOF'
+ac_test posix_utf8_locale '' 'for setlocale(LC_CTYPE, "") and nl_langinfo(CODESET)' <<-'EOF'
 	#include <locale.h>
-	#include <stddef.h>
-	int main(void) { return ((int)(size_t)(void *)setlocale(LC_CTYPE, "")); }
+	#include <langinfo.h>
+	int main(void) { return (!setlocale(LC_CTYPE, "") || !nl_langinfo(CODESET)); }
 EOF
 
-ac_test langinfo_codeset setlocale_ctype 0 'nl_langinfo(CODESET)' <<-'EOF'
-	#include <langinfo.h>
-	#include <stddef.h>
-	int main(void) { return ((int)(size_t)(void *)nl_langinfo(CODESET)); }
+$ebcdic && ac_test setlocale_lcall <<-'EOF'
+	#include <locale.h>
+	int main(void) { return (!setlocale(LC_ALL, "")); }
 EOF
 
 ac_test select <<-'EOF'
 	#include <sys/types.h>
-	#if HAVE_BOTH_TIME_H
+	#if HAVE_BOTH_TIME_H && HAVE_SELECT_TIME_H
 	#include <sys/time.h>
 	#include <time.h>
-	#elif HAVE_SYS_TIME_H
+	#elif HAVE_SYS_TIME_H && HAVE_SELECT_TIME_H
 	#include <sys/time.h>
 	#elif HAVE_TIME_H
 	#include <time.h>
 	#endif
-	#if HAVE_SYS_BSDTYPES_H
-	#include <sys/bsdtypes.h>
-	#endif
 	#if HAVE_SYS_SELECT_H
 	#include <sys/select.h>
 	#endif
+	#if HAVE_SYS_BSDTYPES_H
+	#include <sys/bsdtypes.h>
+	#endif
 	#if HAVE_BSTRING_H
 	#include <bstring.h>
 	#endif
@@ -2227,6 +2698,23 @@ ac_test setgroups setresugid 0 <<-'EOF'
 	int main(void) { gid_t gid = 0; return (setgroups(0, &gid)); }
 EOF
 
+ac_test sigaction <<-'EOF'
+	#define MKSH_INCLUDES_ONLY
+	#include "sh.h"
+	int main(int ac, char *av[]) {
+		struct sigaction sa, osa;
+		ssize_t n;
+
+		memset(&sa, 0, sizeof(sa));
+		sigemptyset(&sa.sa_mask);
+		sa.sa_handler = SIG_IGN;
+		sigaction(ac, &sa, &osa);
+		n = write(1, *av, strlen(*av));
+		sigaction(ac, &osa, NULL);
+		return ((size_t)n != strlen(*av));
+	}
+EOF
+
 if test x"$et" = x"klibc"; then
 
 	ac_testn __rt_sigsuspend '' 'whether klibc uses RT signals' <<-'EOF'
@@ -2255,16 +2743,16 @@ EOF
 
 	if test "000" = "$HAVE___RT_SIGSUSPEND$HAVE___SIGSUSPEND_S$HAVE___SIGSUSPEND_XXS"; then
 		# no usable sigsuspend(), use pause() *ugh*
-		add_cppflags -DMKSH_NO_SIGSUSPEND
+		cpp_define MKSH_NO_SIGSUSPEND 1
 	fi
 fi
 
-ac_test strerror '!' sys_errlist 0 <<-'EOF'
+ac_test strerror '!' some_errlist 0 <<-'EOF'
 	extern char *strerror(int);
 	int main(int ac, char *av[]) { return (*strerror(*av[ac])); }
 EOF
 
-ac_test strsignal '!' sys_siglist 0 <<-'EOF'
+ac_test strsignal '!' some_siglist 0 <<-'EOF'
 	#include <string.h>
 	#include <signal.h>
 	int main(void) { return (strsignal(1)[0]); }
@@ -2276,6 +2764,11 @@ ac_test strlcpy <<-'EOF'
 	    (size_t)ac)); }
 EOF
 
+ac_test strstr <<-'EOF'
+	#include <string.h>
+	int main(int ac, char *av[]) { return (!strstr(av[ac - 1], "meow")); }
+EOF
+
 #
 # check headers for declarations
 #
@@ -2303,15 +2796,49 @@ ac_test sys_siglist_decl sys_siglist 0 '
 	int main(void) { return (sys_siglist[0][0] + isatty(0)); }
 EOF
 
-ac_test st_mtim '' 'for struct stat.st_mtim.tv_nsec' <<-'EOF'
+ac_testn st_mtimensec '' 'for struct stat.st_mtimensec' <<-'EOF'
+	#define MKSH_INCLUDES_ONLY
+	#include "sh.h"
+	int main(void) { struct stat sb; return (sizeof(sb.st_mtimensec)); }
+EOF
+ac_testn st_mtimespec '!' st_mtimensec 0 'for struct stat.st_mtimespec.tv_nsec' <<-'EOF'
+	#define MKSH_INCLUDES_ONLY
+	#include "sh.h"
+	int main(void) { struct stat sb; return (sizeof(sb.st_mtimespec.tv_nsec)); }
+EOF
+if test 1 = "$HAVE_ST_MTIMESPEC"; then
+	cpp_define st_mtimensec st_mtimespec.tv_nsec
+	HAVE_ST_MTIMENSEC=1
+fi
+ac_testn st_mtim '!' st_mtimensec 0 'for struct stat.st_mtim.tv_nsec' <<-'EOF'
 	#define MKSH_INCLUDES_ONLY
 	#include "sh.h"
 	int main(void) { struct stat sb; return (sizeof(sb.st_mtim.tv_nsec)); }
 EOF
-ac_test st_mtimensec '!' st_mtim 0 'for struct stat.st_mtimensec' <<-'EOF'
+if test 1 = "$HAVE_ST_MTIM"; then
+	cpp_define st_mtimensec st_mtim.tv_nsec
+	HAVE_ST_MTIMENSEC=1
+fi
+ac_testn st_mtime_nsec '!' st_mtimensec 0 'for struct stat.st_mtime_nsec' <<-'EOF'
 	#define MKSH_INCLUDES_ONLY
 	#include "sh.h"
-	int main(void) { struct stat sb; return (sizeof(sb.st_mtimensec)); }
+	int main(void) { struct stat sb; return (sizeof(sb.st_mtime_nsec)); }
+EOF
+if test 1 = "$HAVE_ST_MTIME_NSEC"; then
+	cpp_define st_mtimensec st_mtime_nsec
+	HAVE_ST_MTIMENSEC=1
+fi
+ac_cppflags ST_MTIMENSEC
+
+ac_test intconstexpr_rsize_max '' 'whether RSIZE_MAX is an integer constant expression' <<-'EOF'
+	#define MKSH_INCLUDES_ONLY
+	#include "sh.h"
+	int tstarr[((int)(RSIZE_MAX) & 1) + 1] = {0};
+	mbCTA_BEG(conftest_c);
+	 mbCTA(rsizemax_check,
+	    ((mbiHUGE_U)(RSIZE_MAX) == (mbiHUGE_U)(size_t)(RSIZE_MAX)));
+	mbCTA_END(conftest_c);
+	int main(void) { return (isatty(0)); }
 EOF
 
 #
@@ -2335,12 +2862,13 @@ if test $legacy = 1; then
 		#ifndef CHAR_BIT
 		#define CHAR_BIT 0
 		#endif
-		struct ctasserts {
-		#define cta(name,assertion) char name[(assertion) ? 1 : -1]
-			cta(char_is_8_bits, (CHAR_BIT) == 8);
-			cta(long_is_32_bits, sizeof(long) == 4);
-		};
-		int main(void) { return (sizeof(struct ctasserts)); }
+		mbCTA_BEG(conftest);
+			mbCTA(char_is_8_bits, (CHAR_BIT) == 8);
+			mbCTA(long_is_4_chars, sizeof(long) == 4);
+			mbCTA(ulong_is_32_bits, mbiTYPE_UBITS(unsigned long) == 32U);
+			mbCTA(slong_is_31_bits, mbiMASK_BITS(LONG_MAX) == 31U);
+		mbCTA_END(conftest);
+		int main(void) { return (sizeof(struct ctassert_conftest)); }
 EOF
 
 	ac_test long_64bit '!' long_32bit 0 'whether long is 64 bit wide' <<-'EOF'
@@ -2349,12 +2877,13 @@ EOF
 		#ifndef CHAR_BIT
 		#define CHAR_BIT 0
 		#endif
-		struct ctasserts {
-		#define cta(name,assertion) char name[(assertion) ? 1 : -1]
-			cta(char_is_8_bits, (CHAR_BIT) == 8);
-			cta(long_is_64_bits, sizeof(long) == 8);
-		};
-		int main(void) { return (sizeof(struct ctasserts)); }
+		mbCTA_BEG(conftest);
+			mbCTA(char_is_8_bits, (CHAR_BIT) == 8);
+			mbCTA(long_is_8_chars, sizeof(long) == 8);
+			mbCTA(ulong_is_64_bits, mbiTYPE_UBITS(unsigned long) == 64U);
+			mbCTA(slong_is_63_bits, mbiMASK_BITS(LONG_MAX) == 63U);
+		mbCTA_END(conftest);
+		int main(void) { return (sizeof(struct ctassert_conftest)); }
 EOF
 
 	case $HAVE_LONG_32BIT$HAVE_LONG_64BIT in
@@ -2367,10 +2896,10 @@ fi
 #
 # Compiler: Praeprocessor (only if needed)
 #
-test 0 = $HAVE_SYS_SIGNAME && if ac_testinit cpp_dd '' \
+test 0 = $HAVE_SOME_SIGNAME && if ac_testinit cpp_dd '' \
     'checking if the C Preprocessor supports -dD'; then
 	echo '#define foo bar' >conftest.c
-	vv ']' "$CPP $CFLAGS $CPPFLAGS $NOWARN -dD conftest.c >x"
+	vv ']' "$CPP $CFLAGS $Cg $CPPFLAGS $NOWARN -dD conftest.c >x"
 	grep '#define foo bar' x >/dev/null 2>&1 && fv=1
 	rmf conftest.c x vv.out
 	ac_testdone
@@ -2386,9 +2915,10 @@ $e ... done.
 echo wq >x
 ed x <x 2>/dev/null | grep 3 >/dev/null 2>&1 && \
     check_categories="$check_categories $oldish_ed"
+
 rmf x vv.out
 
-if test 0 = $HAVE_SYS_SIGNAME; then
+if test 0 = $HAVE_SOME_SIGNAME; then
 	if test 1 = $HAVE_CPP_DD; then
 		$e Generating list of signal names...
 	else
@@ -2407,15 +2937,12 @@ if test 0 = $HAVE_SYS_SIGNAME; then
 #define cfg_NSIG (SIGMAX + 1)
 #elif defined(_SIGMAX)
 #define cfg_NSIG (_SIGMAX + 1)
-#else
-/*XXX better error out, see sh.h */
-#define cfg_NSIG 64
 #endif
 int
 mksh_cfg= cfg_NSIG
-;' >conftest.c
+;' | cat_h_blurb >conftest.c
 	# GNU sed 2.03 segfaults when optimising this to sed -n
-	NSIG=`vq "$CPP $CFLAGS $CPPFLAGS $NOWARN conftest.c" | \
+	NSIG=`vq "$CPP $CFLAGS $Cg $CPPFLAGS $NOWARN conftest.c" | \
 	    grep -v '^#' | \
 	    sed '/mksh_cfg.*= *$/{
 		N
@@ -2436,8 +2963,9 @@ mksh_cfg= cfg_NSIG
 	sigs="$sigs STOP TSTP TTIN TTOU USR1 USR2 POLL PROF SYS TRAP URG VTALRM"
 	sigs="$sigs XCPU XFSZ INFO WINCH EMT IO DIL LOST PWR SAK CLD IOT STKFLT"
 	sigs="$sigs ABND DCE DUMP IOERR TRACE DANGER THCONT THSTOP RESV UNUSED"
+	sigs="$sigs PROT"
 	test 1 = $HAVE_CPP_DD && test $NSIG -gt 1 && sigs="$sigs "`vq \
-	    "$CPP $CFLAGS $CPPFLAGS $NOWARN -dD conftest.c" | \
+	    "$CPP $CFLAGS $Cg $CPPFLAGS $NOWARN -dD conftest.c" | \
 	    grep '[	 ]SIG[A-Z0-9][A-Z0-9]*[	 ]' | \
 	    sed 's/^.*[	 ]SIG\([A-Z0-9][A-Z0-9]*\)[	 ].*$/\1/' | sort`
 	test $NSIG -gt 1 || sigs=
@@ -2451,7 +2979,7 @@ mksh_cfg= cfg_NSIG
 		echo mksh_cfg= SIG$name >>conftest.c
 		echo ';' >>conftest.c
 		# GNU sed 2.03 croaks on optimising this, too
-		vq "$CPP $CFLAGS $CPPFLAGS $NOWARN conftest.c" | \
+		vq "$CPP $CFLAGS $Cg $CPPFLAGS $NOWARN conftest.c" | \
 		    grep -v '^#' | \
 		    sed '/mksh_cfg.*= *$/{
 			N
@@ -2474,58 +3002,58 @@ mksh_cfg= cfg_NSIG
 	$e done.
 fi
 
+check_categories="$check_categories have:select:$HAVE_SELECT"
+
 if test 1 = "$MKSH_UNLIMITED"; then
-	add_cppflags -DMKSH_UNLIMITED
+	cpp_define MKSH_UNLIMITED 1
 else
 	MKSH_UNLIMITED=0
 fi
 
 if test 1 = "$USE_PRINTF_BUILTIN"; then
-	add_cppflags -DMKSH_PRINTF_BUILTIN
+	cpp_define MKSH_PRINTF_BUILTIN 1
+	check_categories="$check_categories printf-builtin"
 else
 	USE_PRINTF_BUILTIN=0
 fi
 
+test 1 = "$HAVE_CAN_VERB" && CFLAGS="$CFLAGS -verbose"
+
 addsrcs '!' HAVE_STRLCPY strlcpy.c
 addsrcs USE_PRINTF_BUILTIN printf.c
 addsrcs '!' MKSH_UNLIMITED ulimit.c
-
-test 1 = "$HAVE_CAN_VERB" && CFLAGS="$CFLAGS -verbose"
-add_cppflags -DMKSH_BUILD_R=593
+cpp_define MKSH_BUILD_R 599
 
 $e $bi$me: Finished configuration testing, now producing output.$ao
 
 files=
 objs=
-sp=
+fsp=
 case $tcfn in
 a.exe|conftest.exe)
-	mkshexe=$tfn.exe
-	add_cppflags -DMKSH_EXE_EXT
+	buildoutput=$tfn.exe
+	cpp_define MKSH_EXE_EXT 1
 	;;
 *)
-	mkshexe=$tfn
+	buildoutput=$tfn
 	;;
 esac
-case $curdir in
-*\ *)	mkshshebang="#!./$mkshexe" ;;
-*)	mkshshebang="#!$curdir/$mkshexe" ;;
-esac
 cat >test.sh <<-EOF
-	$mkshshebang
+	#!$curdisp/$buildoutput
 	LC_ALL=C PATH='$PATH'; export LC_ALL PATH
 	case \$KSH_VERSION in
 	*MIRBSD*|*LEGACY*) ;;
 	*) exit 1 ;;
 	esac
 	set -A check_categories -- $check_categories
-	pflag='$curdir/$mkshexe'
+	pflag='$curdisp/$buildoutput'
 	sflag='$srcdir/check.t'
-	usee=0 useU=0 Pflag=0 Sflag=0 uset=0 vflag=1 xflag=0
+	usee=0 usef=1 useU=0 Pflag=0 Sflag=0 uset=0 vflag=1 xflag=0
 	while getopts "C:e:fPp:QSs:t:U:v" ch; do case \$ch {
 	(C)	check_categories[\${#check_categories[*]}]=\$OPTARG ;;
 	(e)	usee=1; eflag=\$OPTARG ;;
-	(f)	check_categories[\${#check_categories[*]}]=fastbox ;;
+	(f)	usef=1 ;;
+	(+f)	usef=0 ;;
 	(P)	Pflag=1 ;;
 	(+P)	Pflag=0 ;;
 	(p)	pflag=\$OPTARG ;;
@@ -2546,6 +3074,11 @@ cat >test.sh <<-EOF
 	if $ebcdic; then
 		args[\${#args[*]}]=-E
 	fi
+	if (( usef )); then
+		check_categories[\${#check_categories[*]}]=system:fast-yes
+	else
+		check_categories[\${#check_categories[*]}]=system:fast-no
+	fi
 	x=
 	for y in "\${check_categories[@]}"; do
 		x=\$x,\$y
@@ -2574,7 +3107,7 @@ cat >test.sh <<-EOF
 		args[\${#args[*]}]=\$TMPDIR
 	fi
 	print Testing mksh for conformance:
-	grep -F -e 'KSH R' -e Mir''OS: "\$sflag" | sed '/KSH/s/^./&           /'
+	grep -e 'KSH R' -e Mir''OS: "\$sflag" | sed '/KSH/s/^./&           /'
 	print "This shell is actually:\\n\\t\$KSH_VERSION"
 	print 'test.sh built for mksh $dstversion'
 	cstr='\$os = defined \$^O ? \$^O : "unknown";'
@@ -2622,9 +3155,7 @@ llvm)
 	;;
 esac
 echo ": # work around NeXTstep bug" >Rebuild.sh
-cd "$srcdir"
-optfiles=`echo *.opt`
-cd "$curdir"
+optfiles=`cd "$srcdir" && echo *.opt`
 for file in $optfiles; do
 	echo "echo + Running genopt on '$file'..."
 	echo "(srcfile='$srcdir/$file'; BUILDSH_RUN_GENOPT=1; . '$srcdir/Build.sh')"
@@ -2633,16 +3164,16 @@ echo set -x >>Rebuild.sh
 for file in $SRCS; do
 	op=`echo x"$file" | sed 's/^x\(.*\)\.c$/\1./'`
 	test -f $file || file=$srcdir/$file
-	files="$files$sp$file"
-	echo "$CC $CFLAGS $CPPFLAGS $emitbc $file || exit 1" >>Rebuild.sh
+	files="$files$fsp$file"
+	echo "$CC $CFLAGS $Cg $CPPFLAGS $emitbc $file || exit 1" >>Rebuild.sh
 	if test $cm = dragonegg; then
 		echo "mv ${op}s ${op}ll" >>Rebuild.sh
 		echo "llvm-as ${op}ll || exit 1" >>Rebuild.sh
-		objs="$objs$sp${op}bc"
+		objs="$objs$fsp${op}bc"
 	else
-		objs="$objs$sp${op}o"
+		objs="$objs$fsp${op}o"
 	fi
-	sp=' '
+	fsp=$sp
 done
 case $cm in
 dragonegg|llvm)
@@ -2654,41 +3185,54 @@ dragonegg|llvm)
 	lobjs=$objs
 	;;
 esac
-echo tcfn=$mkshexe >>Rebuild.sh
-echo "$CC $CFLAGS $LDFLAGS -o \$tcfn $lobjs $LIBS $ccpr" >>Rebuild.sh
+echo tcfn=$buildoutput >>Rebuild.sh
+echo "$CC $CFLAGS $Cg $LDFLAGS -o \$tcfn $lobjs $LIBS $ccpr" >>Rebuild.sh
 echo "test -f \$tcfn || exit 1; $SIZE \$tcfn" >>Rebuild.sh
 if test $cm = makefile; then
-	extras='emacsfn.h exprtok.h rlimits.opt sh.h sh_flags.opt ulimits.opt var_spec.h'
-	test 0 = $HAVE_SYS_SIGNAME && extras="$extras signames.inc"
+	extras='emacsfn.h exprtok.h mbsdcc.h mbsdint.h mirhash.h mksh.faq rlimits.opt sh.h sh_flags.opt ulimits.opt var_spec.h'
+	test 0 = $HAVE_SOME_SIGNAME && extras="$extras signames.inc"
 	gens= genq=
 	for file in $optfiles; do
 		genf=`basename "$file" | sed 's/.opt$/.gen/'`
 		gens="$gens $genf"
-		genq="$genq$nl$genf: $srcdir/Build.sh $srcdir/$file
-			srcfile=$srcdir/$file; BUILDSH_RUN_GENOPT=1; . $srcdir/Build.sh"
+		genq="$genq$nl$genf: \$(SRCDIR)/Build.sh \$(SRCDIR)/$file
+	srcfile='\$(SRCDIR)/$file'; BUILDSH_RUN_GENOPT=1; . '\$(SRCDIR)/Build.sh'"
 	done
+	if test $legacy = 0; then
+		manpage=mksh.1
+	else
+		manpage=lksh.1
+	fi
 	cat >Makefrag.inc <<EOF
-# Makefile fragment for building mksh $dstversion
+# Makefile fragment for building $whatlong $dstversion
 
-PROG=		$mkshexe
-MAN=		mksh.1
+PROG=		$buildoutput
+MAN=		$manpage
+FAQ=		FAQ.htm
+SRCDIR=		$srcdir
+MF_DIR=		$curdisp
 SRCS=		$SRCS
 SRCS_FP=	$files
 OBJS_BP=	$objs
 INDSRCS=	$extras
 NONSRCS_INST=	dot.mkshrc \$(MAN)
-NONSRCS_NOINST=	Build.sh Makefile Rebuild.sh check.pl check.t test.sh
+NONSRCS_NOINST=	Build.sh FAQ2HTML.sh Makefile Rebuild.sh check.pl check.t mksh.ico test.sh
 CC=		$CC
-CPPFLAGS=	$CPPFLAGS
-CFLAGS=		$CFLAGS
+CPPFLAGS=	$CPPFLAGS -I'\$(MF_DIR)'
+CFLAGS=		$CFLAGS $Cg
 LDFLAGS=	$LDFLAGS
 LIBS=		$LIBS
 
+# for all make variants:
+#all: \$(PROG) \$(FAQ)
+
 .depend \$(OBJS_BP):$gens$genq
 
+FAQ.htm: \$(SRCDIR)/FAQ2HTML.sh \$(SRCDIR)/mksh.faq
+	\$(SHELL) '\$(SRCDIR)/FAQ2HTML.sh' '\$(SRCDIR)/mksh.faq'
+
 # not BSD make only:
-#VPATH=		$srcdir
-#all: \$(PROG)
+#VPATH=		\$(SRCDIR)
 #\$(PROG): \$(OBJS_BP)
 #	\$(CC) \$(CFLAGS) \$(LDFLAGS) -o \$@ \$(OBJS_BP) \$(LIBS)
 #\$(OBJS_BP): \$(SRCS_FP) \$(NONSRCS)
@@ -2698,11 +3242,18 @@ LIBS=		$LIBS
 # for all make variants:
 #REGRESS_FLAGS=	-f
 #regress:
-#	./test.sh \$(REGRESS_FLAGS)
+#	'\$(MF_DIR)/test.sh' \$(REGRESS_FLAGS)
 check_categories=$check_categories
+#PERL=		perl
+#UTFLOCALE=	C.UTF-8
+#TESTONLY=
+#altregress:
+#	\$(PERL) '\$(SRCDIR)/check.pl' -p ./$buildoutput \\
+#	    -C \`echo "X\$(check_categories)" | sed -e 's/^X[	 ]*//' -e 's/ /,/g'\` \\
+#	    -U \$(UTFLOCALE) -v -s '\$(SRCDIR)/check.t' \$(TESTONLY)
 
 # for BSD make only:
-#.PATH: $srcdir
+#.PATH: \$(SRCDIR)
 #.include <bsd.prog.mk>
 EOF
 	$e
@@ -2713,18 +3264,22 @@ for file in $optfiles; do
 	$e "+ Running genopt on '$file'..."
 	do_genopt "$srcdir/$file" || exit 1
 done
+if test $cm = trace; then
+	emitbc='-MD -c'
+	rm -f *.d
+fi
 if test $cm = combine; then
-	objs="-o $mkshexe"
+	objs="-o $buildoutput"
 	for file in $SRCS; do
 		test -f $file || file=$srcdir/$file
 		objs="$objs $file"
 	done
 	emitbc="-fwhole-program --combine"
-	v "$CC $CFLAGS $CPPFLAGS $LDFLAGS $emitbc $objs $LIBS $ccpr"
+	v "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $emitbc $objs $LIBS $ccpr"
 elif test 1 = $pm; then
 	for file in $SRCS; do
 		test -f $file || file=$srcdir/$file
-		v "$CC $CFLAGS $CPPFLAGS $emitbc $file" &
+		v "$CC $CFLAGS $Cg $CPPFLAGS $emitbc $file" &
 	done
 	wait
 else
@@ -2732,7 +3287,7 @@ else
 		test $cm = dragonegg && \
 		    op=`echo x"$file" | sed 's/^x\(.*\)\.c$/\1./'`
 		test -f $file || file=$srcdir/$file
-		v "$CC $CFLAGS $CPPFLAGS $emitbc $file" || exit 1
+		v "$CC $CFLAGS $Cg $CPPFLAGS $emitbc $file" || exit 1
 		if test $cm = dragonegg; then
 			v "mv ${op}s ${op}ll"
 			v "llvm-as ${op}ll" || exit 1
@@ -2745,12 +3300,99 @@ dragonegg|llvm)
 	v "llvm-link -o - $objs | opt $optflags | llc -o $tfn.s"
 	;;
 esac
-tcfn=$mkshexe
-test $cm = combine || v "$CC $CFLAGS $LDFLAGS -o $tcfn $lobjs $LIBS $ccpr"
+tcfn=$buildoutput
+case $cm in
+combine)
+	;;
+trace)
+	rm -f $tfn.*.t
+	v "$CC $CFLAGS $Cg $LDFLAGS -o $tcfn $lobjs $LIBS -Wl,-t,-t >$tfn.l.t $ccpr"
+	;;
+*)
+	v "$CC $CFLAGS $Cg $LDFLAGS -o $tcfn $lobjs $LIBS $ccpr"
+	;;
+esac
 test -f $tcfn || exit 1
 test 1 = $r || v "$NROFF -mdoc <'$srcdir/lksh.1' >lksh.cat1" || rmf lksh.cat1
 test 1 = $r || v "$NROFF -mdoc <'$srcdir/mksh.1' >mksh.cat1" || rmf mksh.cat1
 test 1 = $r || v "(set -- ''; . '$srcdir/FAQ2HTML.sh')" || rmf FAQ.htm
+if test $cm = trace; then
+	echo >&2 "I: tracing compilation, linking and binding inputs"
+    (
+	if test -n "$KSH_VERSION"; then
+		Xe() { print -r -- "$1"; }
+	elif test -n "$BASH_VERSION"; then
+		Xe() { printf '%s\n' "$1"; }
+	else
+		Xe() { echo "$1"; }
+	fi
+	Xgrep() {
+		set +e
+		grep "$@"
+		XgrepRV=$?
+		set -e
+		test $XgrepRV -lt 2
+	}
+	set -e
+	tsrc=`readlink -f "$srcdir"`
+	tdst=`readlink -f .`
+	# some sh do not like ${foo#bar} or ${#foo} at parse time
+	eval 'if test ${#tsrc} -lt ${#tdst}; then
+		mkr() {
+			r=`readlink -f "$1"`
+			case $r in #((
+			"$tdst"|"$tdst/"*) r="<<BLDDIR>>${r#"$tdst"}" ;;
+			"$tsrc"|"$tsrc/"*) r="<<SRCDIR>>${r#"$tsrc"}" ;;
+			esac
+		}
+	else
+		mkr() {
+			r=`readlink -f "$1"`
+			case $r in #((
+			"$tsrc"|"$tsrc/"*) r="<<SRCDIR>>${r#"$tsrc"}" ;;
+			"$tdst"|"$tdst/"*) r="<<BLDDIR>>${r#"$tdst"}" ;;
+			esac
+		}
+	fi'
+
+	cat *.d >$tfn.c1.t
+	set -o noglob
+	while read dst src; do
+		for f in $src; do
+			Xe "$f"
+		done
+	done <$tfn.c1.t >$tfn.c2.t
+	set +o noglob
+	sort -u <$tfn.c2.t >$tfn.c3.t
+	while IFS= read -r name; do
+		mkr "$name"
+		Xe "$r"
+	done <$tfn.c3.t >$tfn.c4.t
+	sort -u <$tfn.c4.t >$tfn.cz.t
+
+	sort -u <$tfn.l.t >$tfn.l1.t
+	sed -n '/^(/s///p' <$tfn.l1.t >$tfn.l2l.t #)
+	Xgrep -v '^(' <$tfn.l1.t >$tfn.l2.t
+	b=
+	while IFS=')' read -r lib memb; do
+		test x"$lib" = x"$b" || {
+			Xgrep -F -v -x "$lib" <$tfn.l2.t >$tfn.l2a.t
+			mv $tfn.l2a.t $tfn.l2.t
+			b=$lib
+			mkr "$lib"
+		}
+		Xe "$r($memb)"
+	done <$tfn.l2l.t >$tfn.l3.t
+	while IFS= read -r name; do
+		mkr "$name"
+		Xe "$r"
+	done <$tfn.l2.t >>$tfn.l3.t
+	sort -u <$tfn.l3.t >$tfn.lz.t
+	cat $tfn.cz.t $tfn.lz.t >$tfn.trace
+	rm $tfn.*.t
+    )
+	test 0 = $eq && sed 's/^/- /' <$tfn.trace
+fi
 test 0 = $eq && v $SIZE $tcfn
 i=install
 test -f /usr/ucb/$i && i=/usr/ucb/$i
@@ -2760,7 +3402,7 @@ $e Installing the shell:
 $e "# $i -c -s -o root -g bin -m 555 $tfn /bin/$tfn"
 if test $legacy = 0; then
 	$e "# grep -x /bin/$tfn /etc/shells >/dev/null || echo /bin/$tfn >>/etc/shells"
-	$e "# $i -c -o root -g bin -m 444 dot.mkshrc /usr/share/doc/mksh/examples/"
+	$e "# $i -c -o root -g bin -m 444 ${srcdisp}dot.mkshrc /usr/share/doc/mksh/examples/"
 fi
 $e
 $e Installing the manual:
@@ -2777,12 +3419,12 @@ if test -f mksh.cat1; then
 	    "/usr/share/man/cat1/mksh.0"
 	$e or
 fi
-$e "# $i -c -o root -g bin -m 444 lksh.1 mksh.1 /usr/share/man/man1/"
+$e "# $i -c -o root -g bin -m 444 ${srcdisp}lksh.1 ${srcdisp}mksh.1 /usr/share/man/man1/"
 $e
 $e Run the regression test suite: ./test.sh
-$e Please also read the sample file dot.mkshrc and the fine manual.
+$e Please also read the sample file ${srcdisp}dot.mkshrc and the fine manual.
 test -f FAQ.htm || \
-    $e Run FAQ2HTML.sh and place FAQ.htm into a suitable location as well.
+    $e Run ${srcdisp}FAQ2HTML.sh and place FAQ.htm into a suitable location as well.
 exit 0
 
 : <<'EOD'
@@ -2801,8 +3443,8 @@ LIBS				default empty; added after sourc
 				[Interix] default: -lcrypt (XXX still needed?)
 NOWARN				-Wno-error or similar
 NROFF				default: nroff
-TARGET_OS			default: $(uname -s || uname)
-TARGET_OSREV			[QNX] default: $(uname -r)
+TARGET_OS			default: `uname -s || uname`
+TARGET_OSREV			default: `uname -r` [only needed on some OS]
 
 ==== feature selectors ====
 MKSH_UNLIMITED			1 to omit ulimit builtin completely
@@ -2813,12 +3455,13 @@ HAVE_STRING_H			ac_header
 HAVE_CAN_FSTACKPROTECTORALL	ac_flags
 
 ==== cpp definitions ====
-DEBUG				don’t use in production, wants gcc, implies:
+DEBUG				do not use in production, wants gcc, implies:
 DEBUG_LEAKS			enable freeing resources before exiting
 KSH_VERSIONNAME_VENDOR_EXT	when patching; space+plus+word (e.g. " +SuSE")
 MKSHRC_PATH			"~/.mkshrc" (do not change)
 MKSH_A4PB			force use of arc4random_pushb
 MKSH_ASSUME_UTF8		(0=disabled, 1=enabled; default: unset)
+				note will vanish with full locale tracking!
 MKSH_BINSHPOSIX			if */sh or */-sh, enable set -o posix
 MKSH_BINSHREDUCED		if */sh or */-sh, enable set -o sh
 MKSH_CLS_STRING			KSH_ESC_STRING "[;H" KSH_ESC_STRING "[J"
@@ -2841,7 +3484,6 @@ MKSH_SMALL			omit some code, optimise ha
 MKSH_SMALL_BUT_FAST		disable some hard-for-size optim. (modern sys.)
 MKSH_S_NOVI=1			disable Vi editing mode (default if MKSH_SMALL)
 MKSH_TYPEDEF_SIG_ATOMIC_T	define to e.g. 'int' if sig_atomic_t is missing
-MKSH_TYPEDEF_SSIZE_T		define to e.g. 'long' if your OS has no ssize_t
 MKSH_UNEMPLOYED			disable job control (but not jobs/co-processes)
 USE_REALLOC_MALLOC		define as 0 to not use realloc as malloc
 
@@ -2849,11 +3491,12 @@ USE_REALLOC_MALLOC		define as 0 to not u
 
 Set CC and possibly CFLAGS, CPPFLAGS, LDFLAGS, LIBS. If cross-compiling,
 also set TARGET_OS. To disable tests, set e.g. HAVE_STRLCPY=0; to enable
-them, set to a value other than 0 or 1. Ensure /bin/ed is installed. For
-MKSH_SMALL but with Vi mode, add -DMKSH_S_NOVI=0 to CPPFLAGS as well.
+them, set to a value other than 0 or 1 (e.g. to x).
+Ensure /bin/ed is installed.
+For MKSH_SMALL but with Vi mode, add -DMKSH_S_NOVI=0 to CPPFLAGS as well.
 
 Normally, the following command is what you want to run, then:
-$ (sh Build.sh -r && ./test.sh -f) 2>&1 | tee log
+$ (sh Build.sh -r && ./test.sh) 2>&1 | tee log
 
 Copy dot.mkshrc to /etc/skel/.mkshrc; install mksh into $prefix/bin; or
 /bin; install the manpage, if omitting the -r flag a catmanpage is made
--- mksh-59c.orig/FAQ2HTML.sh
+++ mksh-59c/FAQ2HTML.sh
@@ -1,8 +1,9 @@
 #!/bin/sh
-rcsid='$MirOS: src/bin/mksh/FAQ2HTML.sh,v 1.2 2020/10/31 04:17:36 tg Exp $'
+# -*- mode: sh -*-
+rcsid='$MirOS: src/bin/mksh/FAQ2HTML.sh,v 1.10 2025/04/25 23:14:50 tg Exp $'
 #-
-# Copyright © 2020
-#	mirabilos <m@mirbsd.org>
+# Copyright © 2020, 2023
+#	mirabilos <m$(date +%Y)@mirbsd.de>
 #
 # Provided that these terms and disclaimer and all copyright notices
 # are retained or reproduced in an accompanying document, permission
@@ -19,34 +20,45 @@ rcsid='$MirOS: src/bin/mksh/FAQ2HTML.sh,
 # damage or existence of a defect, except proven that it results out
 # of said person’s immediate fault when using the work as intended.
 #-
+# Generates a ./FAQ.htm out of source in the script directory.
+
+die() {
+	echo >&2 "E: $*"
+	exit 1
+}
 
-set -e
 LC_ALL=C; LANGUAGE=C
 export LC_ALL; unset LANGUAGE
 nl='
 '
-srcdir=$(dirname "$0")
+srcdir=`dirname "$0" 2>/dev/null` || die 'cannot find srcdir'
 
 p=--posix
 sed $p -e q </dev/null >/dev/null 2>&1 || p=
 
 v=$1
 if test -z "$v"; then
-	v=$(sed $p -n '/^#define MKSH_VERSION "\(.*\)"$/s//\1/p' "$srcdir"/sh.h)
+	v=`sed $p -n '/^#define MKSH_VERSION "\(.*\)"$/s//\1/p' "$srcdir"/sh.h`
 fi
-src_id=$(sed $p -n '/^RCSID: /s///p' "$srcdir"/mksh.faq)
+test -n "$v" || die 'cannot find version'
+src_id=`sed $p -n '/^RCSID: /s///p' "$srcdir"/mksh.faq`
 # sanity check
-case $src_id in
+case x$src_id in
+x)
+	die 'cannot find RCSID'
+	;;
 *"$nl"*)
-	echo >&2 "E: more than one RCSID in mksh.faq?"
-	exit 1 ;;
+	die 'more than one RCSID in mksh.faq?'
+	;;
 esac
 
 sed $p \
     -e '/^RCSID: \$/s/^.*$/----/' \
     -e 's!@@RELPATH@@!http://www.mirbsd.org/!g' \
     -e 's^	<span style="display:none;">	</span>' \
-    "$srcdir"/mksh.faq | tr '\n' '' | sed $p \
+    "$srcdir"/mksh.faq >FAQ.tm1 || die 'sed (1)'
+tr '\n' '' <FAQ.tm1 >FAQ.tm2 || die 'tr (2)'
+sed $p \
     -e 'sg' \
     -e 's----g' \
     -e 's\([^]*\)\1g' \
@@ -56,14 +68,16 @@ sed $p \
     -e 's^</div>*' \
     -e 's$</div>' \
     -e 's<><error><>g' \
-    -e 'sg' | tr '' '\n' >FAQ.tmp
+    -e 'sg' <FAQ.tm2 >FAQ.tm3 || die 'sed (3)'
+tr '' '\n' <FAQ.tm3 >FAQ.tm4 || die 'tr (4)'
 
-exec >FAQ.htm~
+exec >FAQ.tm5
 cat <<EOF
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
  "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"><head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
+ <meta name="tdm-reservation" content="1" />
  <title>mksh $v FAQ (local copy)</title>
  <meta name="source" content="$src_id" />
  <meta name="generator" content="$rcsid" />
@@ -109,7 +123,7 @@ cat <<EOF
  }
  /*]]>*/--></style>
 </head><body>
-<p>Note: Links marked like <a href="irc://chat.freenode.net/!/bin/mksh">this
+<p>Note: Links marked like <a href="irc://irc.mirbsd.org/!/bin/mksh">this
  one to the mksh IRC channel</a> connect to external resources.</p>
 <p>⚠ <b>Notice:</b> the website will have <a
  href="http://www.mirbsd.org/mksh-faq.htm">the latest version of the
@@ -119,18 +133,19 @@ cat <<EOF
 EOF
 sed $p -n \
     '/^<h2 id="\([^"]*"\)><a[^>]*\(>.*<\/a><\/\)h2>$/s//<li><a href="#\1\2li>/p' \
-    <FAQ.tmp
+    <FAQ.tm4 || die 'sed (ToC)'
 cat <<EOF
 </ul>
 
 <h1>Frequently Asked Questions</h1>
 EOF
-cat FAQ.tmp - <<EOF
+cat FAQ.tm4 - <<EOF
 <h1>Imprint</h1>
 <p>This offline HTML page for mksh $v was automatically generated
  from the sources.</p>
 </body></html>
 EOF
 exec >/dev/null
-rm FAQ.tmp
-mv FAQ.htm~ FAQ.htm
+rm FAQ.tm1 FAQ.tm2 FAQ.tm3 FAQ.tm4
+mv FAQ.tm5 FAQ.htm || die 'final mv'
+exit 0
--- mksh-59c.orig/check.pl
+++ mksh-59c/check.pl
@@ -1,9 +1,9 @@
-# $MirOS: src/bin/mksh/check.pl,v 1.51 2020/06/22 17:10:59 tg Exp $
+# $MirOS: src/bin/mksh/check.pl,v 1.58 2025/04/26 22:42:59 tg Exp $
 # $OpenBSD: th,v 1.1 2013/12/02 20:39:44 millert Exp $
 #-
 # Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2011,
-#		2012, 2013, 2014, 2015, 2017
-#	mirabilos <m@mirbsd.org>
+#		2012, 2013, 2014, 2015, 2017, 2021, 2025
+#	mirabilos <m$(date +%Y)@mirbsd.de>
 #
 # Provided that these terms and disclaimer and all copyright notices
 # are retained or reproduced in an accompanying document, permission
@@ -40,6 +40,19 @@
 #	is expected to produce "hi*" (no trailing newline) on standard output,
 #	"+ echo hi*\n+false\n" on standard error, and an exit code of 1.
 #
+# The test-program is invoked with a new environment vector by default which
+# is composed of the following parameters from the inherited environ if set:
+#	HOME, LD_LIBRARY_PATH, LOCPATH, LOGNAME,
+#	PATH, PERLIO, SHELL, UNIXMODE, UNIXROOT, USER
+# Additionally, some parameters are set as follows (without the quotes):
+#	CYGWIN to "nodosfilewarning"
+#	ENV to "/nonexisting"
+#	LANG to "C"
+#	__perlname to $^X (perlexe)
+# Any -e option arguments are added, or, if no equals sign is given, removed.
+# Each test's env-setup (see below) is processed in the same way affecting
+# the environment of that test. Finally, in the per-test environ, __progname
+# is set to the -p argument or (if -P) its first word.
 #
 # Format of test files:
 # - blank lines and lines starting with # are ignored
@@ -65,22 +78,12 @@
 #	perl-cleanup		m	Value is a perl script which is executed
 #					just after the test is run. Try to
 #					avoid using this...
-#	env-setup		M	Value is a list of NAME=VALUE elements
-#					which are put in the environment before
-#					the test is run. If the =VALUE is
-#					missing, NAME is removed from the
-#					environment. Programs are run with
-#					the following minimal environment:
-#					    HOME, LD_LIBRARY_PATH, LOCPATH,
-#					    LOGNAME, PATH, SHELL, UNIXMODE,
-#					    UNIXROOT, USER
-#					(values taken from the environment of
-#					the test harness).
-#					CYGWIN is set to nodosfilewarning.
-#					ENV is set to /nonexistant.
-#					__progname is set to the -p argument.
-#					__perlname is set to $^X (perlexe).
-#					@utflocale@ is substituted from -U.
+#	env-setup		M	Value is a list of elements that are
+#					removed from the per-test environment
+#					(if no equals sign present) or added
+#					to it if of the NAME=VALUE form, after
+#					substituting @utflocale@ for -U option.
+#					For more about test environ see above.
 #	file-setup		mps	Used to create files, directories
 #					and symlinks. First word is either
 #					file, dir or symlink; second word is
@@ -141,6 +144,8 @@
 #					eg, linux, dec_osf).
 #	need-ctty			'yes' if the test needs a ctty, run
 #					with -C regress:no-ctty to disable.
+#	info-pre			shown before the test
+#	info-post			shown after the test
 # Flag meanings:
 #	r	tag is required (eg, a test must have a name tag).
 #	m	value can be multiple lines. Lines must be prefixed with
@@ -198,7 +203,7 @@ Usage: $prog [-Pv] [-C cat] [-e e=v] [-p
 		scanned for test files (which end in .t).
 	-T dir	Use dir instead of /tmp to hold temporary files
 	-t t	Use t as default time limit for tests (default is unlimited)
-	-U lcl	Use lcl as UTF-8 locale (e.g. C.UTF-8) instead of the default
+	-U lcl	Specify UTF-8 locale (e.g. en_US.UTF-8) instead of the default
 	-v	Verbose mode: print reason test failed.
 	name	specifies the name of the test(s) to run; if none are
 		specified, all tests are run.
@@ -226,6 +231,8 @@ EOF
 	'category',			'm',
 	'need-ctty',			'',
 	'need-pass',			'',
+	'info-pre',			'',
+	'info-post',			'',
 	);
 # Filled in by read_test()
 %internal_test_fields = (
@@ -259,7 +266,7 @@ $verbose = defined $opt_v && $opt_v;
 $is_ebcdic = defined $opt_E && $opt_E;
 $test_set = $opt_s;
 $temp_base = $opt_T || "/tmp";
-$utflocale = $opt_U || (($os eq "hpux") ? "en_US.utf8" : "en_US.UTF-8");
+$utflocale = $opt_U || (($os eq "hpux") ? "en_US.utf8" : ($os eq "darwin") ? "UTF-8" : "C.UTF-8");
 if (defined $opt_t) {
     die "$prog: bad -t argument (should be number > 0): $opt_t\n"
 	if $opt_t !~ /^\d+$/ || $opt_t <= 0;
@@ -296,24 +303,27 @@ foreach $env (('HOME', 'LD_LIBRARY_PATH'
     $new_env{$env} = $ENV{$env} if defined $ENV{$env};
 }
 $new_env{'CYGWIN'} = 'nodosfilewarning';
-$new_env{'ENV'} = '/nonexistant';
+$new_env{'ENV'} = '/nonexisting';
+$new_env{'LANG'} = 'C';
 
-if (($os eq 'VMS') || ($Config{perlpath} =~ m/$Config{_exe}$/i)) {
-	$new_env{'__perlname'} = $Config{perlpath};
-} else {
-	$new_env{'__perlname'} = $Config{perlpath} . $Config{_exe};
+$pn = $Config{perlpath};
+if ($pn ne '' and $os ne 'VMS' and $pn !~ m/$Config{_exe}$/i) {
+	$pn .= $Config{_exe};
+}
+if (($pn eq '' or ! -f $pn or ! -x $pn) and -f $^X and -x $^X) {
+	$pn = $^X;
 }
-$new_env{'__perlname'} = $^X if ($new_env{'__perlname'} eq '') and -f $^X and -x $^X;
-if ($new_env{'__perlname'} eq '') {
-	foreach $pathelt (split /:/,$ENV{'PATH'}) {
+if ($pn eq '' or ! -f $pn or ! -x $pn) {
+	foreach $pathelt (split /:/, $ENV{'PATH'}) {
 		chomp($pathelt = `pwd`) if $pathelt eq '';
 		my $x = $pathelt . '/' . $^X;
 		next unless -f $x and -x $x;
-		$new_env{'__perlname'} = $x;
+		$pn = $x;
 		last;
 	}
 }
-$new_env{'__perlname'} = $^X if ($new_env{'__perlname'} eq '');
+$pn = $^X if ($pn eq '');
+$new_env{'__perlname'} = $pn;
 
 if (defined $opt_e) {
     # XXX need a way to allow many -e arguments...
@@ -482,6 +492,10 @@ run_test
     local(*test) = @_;
     local($name) = $test{':full-name'};
 
+    if ($test{'info-pre'} ne '') {
+	print "info v[$test{'info-pre'}]\n";
+    }
+
     return undef if !&scrub_dir($tempdir);
 
     if (defined $test{'stdin'}) {
@@ -719,6 +733,9 @@ run_test
 	$npassed++;
     }
     print $why if $verbose;
+    if ($test{'info-post'} ne '') {
+	print "info ^[$test{'info-post'}]\n";
+    }
     return 0;
 }
 
--- mksh-59c.orig/check.t
+++ mksh-59c/check.t
@@ -1,26 +1,28 @@
-# $MirOS: src/bin/mksh/check.t,v 1.853 2020/10/31 03:53:03 tg Exp $
 # -*- mode: sh -*-
+# $MirOS: src/bin/mksh/check.t,v 1.927 2025/12/24 04:51:49 tg Exp $
 #-
-# Copyright © 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
-#	      2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018,
-#	      2019, 2020
-#	mirabilos <m@mirbsd.org>
+# Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
+#		2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018,
+#		2019, 2020, 2021, 2022, 2023, 2024, 2025
+#	mirabilos <m$(date +%Y)@mirbsd.de>
 #
 # Provided that these terms and disclaimer and all copyright notices
 # are retained or reproduced in an accompanying document, permission
-# is granted to deal in this work without restriction, including un‐
+# is granted to deal in this work without restriction, including un-
 # limited rights to use, publicly perform, distribute, sell, modify,
 # merge, give away, or sublicence.
 #
-# This work is provided “AS IS” and WITHOUT WARRANTY of any kind, to
+# This work is provided "AS IS" and WITHOUT WARRANTY of any kind, to
 # the utmost extent permitted by applicable law, neither express nor
 # implied; without malicious intent or gross negligence. In no event
 # may a licensor, author or contributor be held liable for indirect,
 # direct, other damage, loss, or other issues arising in any way out
 # of dealing in the work, even if advised of the possibility of such
 # damage or existence of a defect, except proven that it results out
-# of said person’s immediate fault when using the work as intended.
+# of said person's immediate fault when using the work as intended.
 #-
+# WARNING: this file mixes UTF-8 with raw octets without encoding!
+#
 # You may also want to test IFS with the script at
 # http://www.research.att.com/~gsf/public/ifs.sh
 #
@@ -30,8 +32,9 @@
 # Integrated testsuites from:
 # (2013/12/02 20:39:44) http://cvsweb.openbsd.org/cgi-bin/cvsweb/src/regress/bin/ksh/?sortby=date
 
+info-pre: testing begins
 expected-stdout:
-	KSH R59 2020/10/31
+	KSH R59 2025/12/23
 description:
 	Check base version of full shell
 stdin:
@@ -136,8 +139,36 @@ stdin:
 	print '#!'"$__progname"'\necho tf' >lq
 	chmod +x lq
 	./lq
+	echo = $?
 expected-stdout:
 	tf
+	= 0
+---
+name: selftest-exec-perl
+description:
+	Ensure we can run perl scriptlets in tests as well
+stdin:
+	print '#!'"$__perlname"'\nprint 3x"3"."\\n";' >lq
+	chmod +x lq
+	./lq
+	echo = $?
+expected-stdout:
+	333
+	= 0
+---
+name: selftest-exec-a
+description:
+	Ensure using 'exec -a' to change argv[0] works
+file-setup: file 644 "pass"
+	print -r -- "fail, args:"
+	i=-1
+	for x in "$0" "$@"; do
+		print -r -- "$((++i))<$x>"
+	done
+stdin:
+	exec -a -print "$__progname" pass '\u20AC'
+expected-stdout:
+	pass €
 ---
 name: selftest-env
 description:
@@ -150,9 +181,8 @@ name: selftest-direct-builtin-call
 description:
 	Check that direct builtin calls work
 stdin:
-	ln -s "$__progname" cat || cp "$__progname" cat
-	ln -s "$__progname" echo || cp "$__progname" echo
-	./echo -c 'echo  foo' | ./cat -u
+	ln -s "$__progname" echo 2>/dev/null || cp "$__progname" echo
+	./echo -c 'echo  foo'
 expected-stdout:
 	-c echo  foo
 ---
@@ -176,6 +206,25 @@ stdin:
 expected-stdout:
 	;
 ---
+name: selftest-tools
+description:
+	Check that relevant tools work as expected. If not, e.g. on SerenityOS,
+	install better tools from ports and prepend /usr/local/bin to $PATH.
+stdin:
+	echo foobarbaz | grep bar
+	echo = $?
+	echo abc | sed y/ac/AC/
+	echo = $?
+	echo abc | tr ac AC
+	echo = $?
+expected-stdout:
+	foobarbaz
+	= 0
+	AbC
+	= 0
+	AbC
+	= 0
+---
 name: selftest-tty-absent
 description:
 	Check that a controlling tty is not present as regress:no-ctty was used
@@ -191,7 +240,7 @@ stdin:
 expected-stdout:
 	ok
 expected-stderr-pattern:
-	/ksh: warning: won't have full job control\nXX/
+	/^W: .*find tty fd.*\nW: .*have full job control\nXX$/
 ---
 name: selftest-tty-present
 description:
@@ -395,6 +444,21 @@ stdin:
 expected-stderr:
 	1
 ---
+name: arith-divnull
+description:
+	Check what happens if dividing by 0
+stdin:
+	echo 1 $((0 ? 2/0 : 666)) .
+	echo 2 $?
+	echo 3 $((1 ? 2/0 : 666)) .
+	echo 4 $?
+expected-stdout:
+	1 666 .
+	2 0
+expected-exit: e != 0
+expected-stderr-pattern:
+	/^[^\n]*: zero divisor$/
+---
 name: arith-lazy-1
 description:
 	Check that only one side of ternary operator is evaluated
@@ -566,7 +630,7 @@ expected-stderr-pattern:
 name: arith-div-intmin-by-minusone
 description:
 	Check division overflow wraps around silently
-category: int:32
+category: shell:legacy-no
 stdin:
 	echo signed:$((-2147483648 / -1))r$((-2147483648 % -1)).
 	echo unsigned:$((# -2147483648 / -1))r$((# -2147483648 % -1)).
@@ -574,17 +638,6 @@ expected-stdout:
 	signed:-2147483648r0.
 	unsigned:0r2147483648.
 ---
-name: arith-div-intmin-by-minusone-64
-description:
-	Check division overflow wraps around silently
-category: int:64
-stdin:
-	echo signed:$((-9223372036854775808 / -1))r$((-9223372036854775808 % -1)).
-	echo unsigned:$((# -9223372036854775808 / -1))r$((# -9223372036854775808 % -1)).
-expected-stdout:
-	signed:-9223372036854775808r0.
-	unsigned:0r9223372036854775808.
----
 name: arith-assop-assoc-1
 description:
 	Check associativity of assignment-operator operator
@@ -1402,10 +1455,11 @@ name: cd-pe
 description:
 	Check package for cd -Pe
 need-pass: no
-# the mv command fails on Cygwin and z/OS
+info-pre: test is flaky on at least Cygwin, LynxOS, z/OS, Hurd, QNX, ...
+# the mv command fails on Cygwin, LynxOS 3.0, z/OS
 # Hurd aborts the testsuite (permission denied)
 # QNX does not find subdir to cd into
-category: !os:cygwin,!os:gnu,!os:midipix,!os:msys,!os:nto,!os:os390,!nosymlink
+category: !os:cygwin,!os:gnu,!os:lynxos,!os:midipix,!os:msys,!os:nto,!os:os390,!nosymlink
 file-setup: file 644 "x"
 	mkdir noread noread/target noread/target/subdir
 	ln -s noread link
@@ -1423,7 +1477,8 @@ file-setup: file 644 "x"
 	cd -P$1 subdir
 	echo 2=$?,${PWD#$bwd/}
 	cd $bwd
-	chmod 755 noread renamed 2>/dev/null
+	chmod 755 noread 2>/dev/null
+	chmod 755 renamed 2>/dev/null
 	rm -rf noread link renamed
 stdin:
 	export TSHELL="$__progname"
@@ -1447,14 +1502,13 @@ file-setup: file 644 "foo"
 	XXX=_
 	PS1=X
 	false && echo hmmm
-need-ctty: yes
 arguments: !-i!
 stdin:
 	echo hi${XXX}there
 expected-stdout:
 	hi_there
-expected-stderr: !
-	XX
+expected-stderr-pattern:
+	/^(?:W: [^\n]*(?:find tty fd|have full job control)[^\n]*\n)*XX$/
 ---
 name: expand-ugly
 description:
@@ -1933,6 +1987,8 @@ expected-stderr-pattern: /not set/
 name: expand-bang-2
 description:
 	Check corner case of ${!var} vs. ${var op} with var=!
+category: !nopiddependent
+time-limit: 15
 stdin:
 	echo 1 $! .
 	echo 2 ${!#} .
@@ -2012,7 +2068,7 @@ expected-stdout:
 name: eglob-bad-1
 description:
 	Check that globbing isn't done when glob has syntax error
-category: !os:cygwin,!os:midipix,!os:msys,!os:os2
+category: !os:cygwin,!os:lynxos,!os:midipix,!os:msys,!os:os2,!noweirdfilenames
 file-setup: file 644 "@(a[b|)c]foo"
 stdin:
 	echo @(a[b|)c]*
@@ -2473,18 +2529,21 @@ stdin:
 	echo [-ab]*
 	echo [!-ab]*
 	echo [!ab]*
+	echo [\!ab]*
 	echo []ab]*
 	echo [^ab]*
+	echo [\^ab]*
 	echo [+--]*
 	echo [--1]*
-
 expected-stdout:
 	-bc abc bbc
 	-bc abc bbc
 	!bc +bc ,bc 0bc 1bc ^bc cbc
 	!bc +bc ,bc -bc 0bc 1bc ^bc cbc
+	!bc abc bbc
 	abc bbc
 	^bc abc bbc
+	^bc abc bbc
 	+bc ,bc -bc
 	-bc 0bc 1bc
 ---
@@ -2504,8 +2563,9 @@ description:
 # breaks on Mac OSX (HFS+ non-standard UTF-8 canonical decomposition)
 # breaks on Cygwin 1.7 (files are now UTF-16 or something)
 # breaks on QNX 6.4.1 (says RT)
-category: !os:cygwin,!os:midipix,!os:darwin,!os:msys,!os:nto,!os:os2,!os:os390
+category: !os:cygwin,!os:midipix,!os:darwin,!os:msys,!os:nto,!os:os2,!os:os390,!noweirdfilenames
 need-pass: no
+info-pre: test breaks on non-POSIX filesystems, weird locales, etc.
 file-setup: file 644 "ac"
 stdin:
 	echo a[-]*
@@ -3073,7 +3133,7 @@ description:
 	Check high-bit7 separators work
 stdin:
 	u=ä
-	tr a-z A-Z <<-…
+	tr abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ <<-…
 		m${u}h
 	echo ok
@@ -3271,6 +3331,7 @@ name: heredoc-tmpfile-1
 description:
 	Check that heredoc temp files aren't removed too soon or too late.
 	Heredoc in simple command.
+info-pre: next couple of tests sleep for a few seconds each
 stdin:
 	TMPDIR=$PWD
 	eval '
@@ -3423,30 +3484,32 @@ description:
 	Check that heredoc temp files aren't removed too soon or too
 	late. Heredoc in function, backgrounded call to function.
 	This check can fail on slow machines (<100 MHz), or Cygwin,
-	that's normal.
+	please help fix this as it also triggers sometimes on Debian
+	reproducible-builds package rebuilds or debci tests somehow
 need-pass: no
+info-post: can fail on slow (<100 MHz) or Cygwin, but ought not to
 stdin:
 	TMPDIR=$PWD
 	# Background eval so main shell doesn't do parsing
 	eval '
 		foo() {
-			cat <<- EOF
-			hi
+			sed -e "s/^/N: /" -e "s/\\.[a-z]*\$//" <<-EOF
+			hi$1
 			EOF
 		}
-		foo
+		foo 1
 		# sleep so eval can die
-		(sleep 1; foo) &
-		(sleep 1; foo) &
-		foo
+		(sleep 1; foo 3.a) &
+		(sleep 1; foo 3.b) &
+		foo 2
 	    ' &
-	sleep 5
+	sleep 3
 	echo Left overs: *
 expected-stdout:
-	hi
-	hi
-	hi
-	hi
+	N: hi1
+	N: hi2
+	N: hi3
+	N: hi3
 	Left overs: *
 ---
 name: heredoc-quoting-unsubst
@@ -4144,7 +4207,8 @@ description:
 category: stdout-ed
 need-ctty: yes
 need-pass: no
-arguments: !-i!
+info-pre: these three tests depend on ed(1) existing and working...
+arguments: !-ie!
 env-setup: !ENV=./Env!HISTFILE=hist.file!
 file-setup: file 644 "Env"
 	PS1=X
@@ -4168,7 +4232,7 @@ description:
 category: stdout-ed
 need-ctty: yes
 need-pass: no
-arguments: !-i!
+arguments: !-ie!
 env-setup: !ENV=./Env!HISTFILE=hist.file!
 file-setup: file 644 "Env"
 	PS1=X
@@ -4200,7 +4264,8 @@ description:
 category: stdout-ed
 need-ctty: yes
 need-pass: no
-arguments: !-i!
+info-post: above three tests need real (non-busybox) ed(1), too
+arguments: !-ie!
 env-setup: !ENV=./Env!HISTFILE=hist.file!
 file-setup: file 644 "Env"
 	PS1=X
@@ -4233,7 +4298,8 @@ description:
 category: !no-stderr-ed
 need-ctty: yes
 need-pass: no
-arguments: !-i!
+info-pre: these three tests depend on ed(1) existing and working...
+arguments: !-ie!
 env-setup: !ENV=./Env!HISTFILE=hist.file!
 file-setup: file 644 "Env"
 	PS1=X
@@ -4255,7 +4321,7 @@ description:
 category: !no-stderr-ed
 need-ctty: yes
 need-pass: no
-arguments: !-i!
+arguments: !-ie!
 env-setup: !ENV=./Env!HISTFILE=hist.file!
 file-setup: file 644 "Env"
 	PS1=X
@@ -4284,7 +4350,8 @@ description:
 category: !no-stderr-ed
 need-ctty: yes
 need-pass: no
-arguments: !-i!
+info-post: above three tests need real (non-busybox) ed(1), too
+arguments: !-ie!
 env-setup: !ENV=./Env!HISTFILE=hist.file!
 file-setup: file 644 "Env"
 	PS1=X
@@ -4786,7 +4853,7 @@ description:
 	'emulate sh' zsh has extra fields in
 	- a5ins (IFS_NWS unquoted $*)
 	- b5ins, matching mksh’s
-	!!WARNING!! more to come: http://austingroupbugs.net/view.php?id=888
+	!!WARNING!! more to come: https://www.austingroupbugs.net/view.php?id=888
 stdin:
 	"$__progname" -c 'pfb() { for s_arg in "$@"; do print -r -- "[$s_arg]"; done; }; pfn() { for s_arg in "$@"; do print -r -- "<$s_arg>"; done; };
 		IFS=; set -- "" 2 ""; pfb $*; x=$*; pfn "$x"'
@@ -4936,7 +5003,7 @@ expected-stdout:
 ---
 name: IFS-subst-8
 description:
-	http://austingroupbugs.net/view.php?id=221
+	https://www.austingroupbugs.net/view.php?id=221
 stdin:
 	n() { echo "$#"; }; n "${foo-$@}"
 expected-stdout:
@@ -4996,7 +5063,7 @@ expected-stdout:
 ---
 name: IFS-arith-1
 description:
-	http://austingroupbugs.net/view.php?id=832
+	https://www.austingroupbugs.net/view.php?id=832
 stdin:
 	${ZSH_VERSION+false} || emulate sh
 	${BASH_VERSION+set -o posix}
@@ -5036,7 +5103,6 @@ description:
 	Syntax errors in expressions and effects on bases
 	(interactive so errors don't cause exits)
 	(ksh88 fails this test - shell exits, even with -i)
-need-ctty: yes
 arguments: !-i!
 stdin:
 	PS1= # minimise prompt hassles
@@ -5047,7 +5113,7 @@ stdin:
 	typeset -i2 a=2+
 	echo $a
 expected-stderr-pattern:
-	/^([#\$] )?.*:.*2+.*\n.*:.*2+.*\n$/
+	/^(?:W: [^\n]*(?:find tty fd|have full job control)[^\n]*\n)*([#\$] )?.*:.*2\+.*\n.*:.*2\+.*\n$/
 expected-stdout:
 	4#22
 	4#22
@@ -5264,48 +5330,47 @@ description:
 	Check behaviour for base two to 36, and that 37 degrades to 10
 stdin:
 	i=1
-	while (( ++i <= 37 )); do
-		eval 'echo '$i':$(('$i'#10)).'
+	while (( ++i <= 36 )); do
+		eval 'echo '$i':$(('$i'#100)).'
 	done
-	echo 37:$($__progname -c 'echo $((37#10))').$?:
+	echo 37:$($__progname -c 'echo $((37#100))').$?:
 expected-stdout:
-	2:2.
-	3:3.
-	4:4.
-	5:5.
-	6:6.
-	7:7.
-	8:8.
-	9:9.
-	10:10.
-	11:11.
-	12:12.
-	13:13.
-	14:14.
-	15:15.
-	16:16.
-	17:17.
-	18:18.
-	19:19.
-	20:20.
-	21:21.
-	22:22.
-	23:23.
-	24:24.
-	25:25.
-	26:26.
-	27:27.
-	28:28.
-	29:29.
-	30:30.
-	31:31.
-	32:32.
-	33:33.
-	34:34.
-	35:35.
-	36:36.
-	37:10.
-	37:10.0:
+	2:4.
+	3:9.
+	4:16.
+	5:25.
+	6:36.
+	7:49.
+	8:64.
+	9:81.
+	10:100.
+	11:121.
+	12:144.
+	13:169.
+	14:196.
+	15:225.
+	16:256.
+	17:289.
+	18:324.
+	19:361.
+	20:400.
+	21:441.
+	22:484.
+	23:529.
+	24:576.
+	25:625.
+	26:676.
+	27:729.
+	28:784.
+	29:841.
+	30:900.
+	31:961.
+	32:1024.
+	33:1089.
+	34:1156.
+	35:1225.
+	36:1296.
+	37:100.0:
 ---
 name: integer-base-check-numeric-to-1
 description:
@@ -5379,10 +5444,10 @@ expected-stdout:
 	36:36#1S.64.
 	37:64.64.
 ---
-name: integer-arithmetic-span
+name: integer-arithmetic-span-signed
 description:
 	Check wraparound and size that is defined in mksh
-category: int:32
+category: shell:legacy-no
 stdin:
 	echo s:$((2147483647+1)).$(((2147483647*2)+1)).$(((2147483647*2)+2)).
 	echo u:$((#2147483647+1)).$((#(2147483647*2)+1)).$((#(2147483647*2)+2)).
@@ -5390,15 +5455,22 @@ expected-stdout:
 	s:-2147483648.-1.0.
 	u:2147483648.4294967295.0.
 ---
+name: integer-arithmetic-span-32
+description:
+	Check unsigned wraparound and size that should also work in lksh
+category: int:32
+stdin:
+	echo u:$((#2147483647+1)).$((#(2147483647*2)+1)).$((#(2147483647*2)+2)).
+expected-stdout:
+	u:2147483648.4294967295.0.
+---
 name: integer-arithmetic-span-64
 description:
-	Check wraparound and size that is defined in mksh
+	Check unsigned wraparound and size that should also work in lksh
 category: int:64
 stdin:
-	echo s:$((9223372036854775807+1)).$(((9223372036854775807*2)+1)).$(((9223372036854775807*2)+2)).
 	echo u:$((#9223372036854775807+1)).$((#(9223372036854775807*2)+1)).$((#(9223372036854775807*2)+2)).
 expected-stdout:
-	s:-9223372036854775808.-1.0.
 	u:9223372036854775808.18446744073709551615.0.
 ---
 name: integer-size-FAIL-to-detect
@@ -5554,17 +5626,34 @@ stdin:
 	echo =1
 	trap "echo trap 2 executed" UNKNOWNSIGNAL EXIT 999999 FNORD
 	echo = $?
-	) 2>&1 | sed "s^${__progname%.exe}\.*e*x*e*: <stdin>\[[0-9]*]PROG"
+	) 2>&1 | sed \
+	    -e "s^${__progname%.exe}\.*e*x*e*: <stdin>\[[0-9]*]PROG" \
+	    -e "s^[EW]: ${__progname%.exe}\.*e*x*e*: <stdin>\[[0-9]*]PROG" \
+	    -e "s/bad signal '\\(.*\\)'\$/bad signal: \\1/"
 expected-stdout:
-	PROG: trap: bad signal 'UNKNOWNSIGNAL'
+	PROG: trap: bad signal: UNKNOWNSIGNAL
 	foo
 	=1
-	PROG: trap: bad signal 'UNKNOWNSIGNAL'
-	PROG: trap: bad signal '999999'
-	PROG: trap: bad signal 'FNORD'
+	PROG: trap: bad signal: UNKNOWNSIGNAL
+	PROG: trap: bad signal: 999999
+	PROG: trap: bad signal: FNORD
 	= 1
 	trap 2 executed
 ---
+name: uncatchable-trap
+description:
+	Ensure trying to trap SIGKILL is a nop (POSIX says undefined)
+stdin:
+	trap 'echo sighit $? .' KILL EXIT
+	"$__perlname" -e 'print $=.$/;'
+	echo meow $? .
+	(exit 7)
+expected-exit: 7
+expected-stdout:
+	60
+	meow 0 .
+	sighit 7 .
+---
 name: read-IFS-1
 description:
 	Simple test, default IFS
@@ -6173,6 +6262,8 @@ expected-stdout:
 name: regression-33
 description:
 	Does umask print a leading 0 when umask is 3 digits?
+# prints 0600…
+category: !os:skyos
 stdin:
 	# on MiNT, the first umask call seems to fail
 	umask 022
@@ -6184,7 +6275,7 @@ expected-stdout:
 ---
 name: regression-35
 description:
-	Temporay files used for here-docs in functions get trashed after
+	Temporary files used for heredocs in functions get trashed after
 	the function is parsed (before it is executed)
 stdin:
 	f1() {
@@ -6228,8 +6319,8 @@ description:
 	Machines with broken times() (reported by <sjg@void.zen.oz.au>)
 	time does not report correct real time
 stdin:
-	time sleep 1
-expected-stderr-pattern: !/^\s*0\.0[\s\d]+real|^\s*real[\s]+0+\.0/
+	time -p sleep 1
+expected-stderr-pattern: /^real +(?![0.]*$)[0-9]+(?:\.[0-9]+)?$/m
 ---
 name: regression-38
 description:
@@ -6279,7 +6370,7 @@ expected-stdout:
 ---
 name: regression-42
 description:
-	Can't use command line assignments to assign readonly parameters.
+	Can't use command line assignments to assign read-only parameters.
 stdin:
 	print '#!'"$__progname"'\nunset RANDOM\nexport | while IFS= read -r' \
 	    'RANDOM; do eval '\''print -r -- "$RANDOM=$'\''"$RANDOM"'\'\"\'\; \
@@ -6728,7 +6819,7 @@ stdin:
 		echo FNORD-7
 		typeset -
 		echo FNORD-8
-	} | fgrep FNORD
+	} | grep FNORD
 	fnord=(42 23)
 	typeset -p fnord
 	echo FNORD-9
@@ -6799,19 +6890,6 @@ stdin:
 		time
 	}
 ---
-name: regression-65
-description:
-	check for a regression with sleep builtin and signal mask
-category: !nojsig
-time-limit: 5
-stdin:
-	sleep 1
-	echo blub |&
-	while read -p line; do :; done
-	echo ok
-expected-stdout:
-	ok
----
 name: regression-66
 description:
 	Check that quoting is sane
@@ -6861,17 +6939,17 @@ stdin:
 	echo 13 $(( a &= 4 )) .
 	echo 14 $(( a ^= a )) .
 	echo 15 $(( a |= 5 )) .
-	echo 16 $(( 5 << 1 )) .
-	echo 17 $(( 5 >> 1 )) .
+	echo 16 $(( 5 << 1 )) , $(( 5 << 0 )) .
+	echo 17 $(( 5 >> 1 )) , $(( 5 >> 0 )) .
 	echo 18 $(( 5 <= 6 )) , $(( 5 <= 5 )) , $(( 5 <= 4 )) .
 	echo 19 $(( 5 >= 6 )) , $(( 5 >= 5 )) , $(( 5 >= 4 )) .
 	echo 20 $(( 5 < 6 )) , $(( 5 < 5 )) , $(( 5 < 4 )) .
 	echo 21 $(( 5 > 6 )) , $(( 5 > 5 )) , $(( 5 > 4 )) .
 	echo 22 $(( 0 && 0 )) , $(( 0 && 1 )) , $(( 1 && 0 )) , $(( 1 && 1 )) .
 	echo 23 $(( 0 || 0 )) , $(( 0 || 1 )) , $(( 1 || 0 )) , $(( 1 || 1 )) .
-	echo 24 $(( 5 * 3 )) .
+	echo 24 $(( 5 * 3 )) , $(( 5 * 0 )) .
 	echo 25 $(( 7 / 2 )) .
-	echo 26 $(( 5 % 5 )) , $(( 5 % 4 )) , $(( 5 % 1 )) , $(( 5 % -1 )) , $(( 5 % -2 )) .
+	echo 26 $(( 5 % 5 )) , $(( 5 % 4 )) , $(( 5 % 1 )) :
 	echo 27 $(( 5 + 2 )) , $(( 5 + 0 )) , $(( 5 + -2 )) .
 	echo 28 $(( 5 - 2 )) , $(( 5 - 0 )) , $(( 5 - -2 )) .
 	echo 29 $(( 6 & 4 )) , $(( 6 & 8 )) .
@@ -6898,17 +6976,17 @@ expected-stdout:
 	13 4 .
 	14 0 .
 	15 5 .
-	16 10 .
-	17 2 .
+	16 10 , 5 .
+	17 2 , 5 .
 	18 1 , 1 , 0 .
 	19 0 , 1 , 1 .
 	20 1 , 0 , 0 .
 	21 0 , 0 , 1 .
 	22 0 , 0 , 0 , 1 .
 	23 0 , 1 , 1 , 1 .
-	24 15 .
+	24 15 , 0 .
 	25 3 .
-	26 0 , 1 , 0 , 0 , 1 .
+	26 0 , 1 , 0 :
 	27 7 , 5 , 3 .
 	28 3 , 5 , 7 .
 	29 4 , 0 .
@@ -6920,6 +6998,15 @@ expected-stdout:
 	35 1 , 0 , 1 , 1 .
 	36 5 .
 ---
+name: regression-68-nolksh
+description:
+	Things POSIX/C arithmetics don’t guarantee
+category: shell:legacy-no
+stdin:
+	echo '1(26)' , $(( 5 % -1 )) , $(( 5 % -2 )) .
+expected-stdout:
+	1(26) , 0 , 1 .
+---
 name: regression-69
 description:
 	Check that all non-lksh arithmetic operators work as expected
@@ -6928,13 +7015,15 @@ stdin:
 	a=5 b=0x80000005
 	echo 1 $(( a ^<= 1 )) , $(( b ^<= 1 )) .
 	echo 2 $(( a ^>= 2 )) , $(( b ^>= 2 )) .
-	echo 3 $(( 5 ^< 1 )) .
-	echo 4 $(( 5 ^> 1 )) .
+	echo 3 $(( 5 ^< 1 )) , $(( 5 ^< 0 )) .
+	echo 4 $(( 5 ^> 1 )) , $((# 5 ^> 1 )) .
+	echo 5 $(( 5 ^> 0 )) , $((# 5 ^> 0 )) .
 expected-stdout:
 	1 10 , 11 .
 	2 -2147483646 , -1073741822 .
-	3 10 .
-	4 -2147483646 .
+	3 10 , 5 .
+	4 -2147483646 , 2147483650 .
+	5 5 , 5 .
 ---
 name: export-1
 description:
@@ -6971,7 +7060,7 @@ expected-stderr-pattern:
 ---
 name: readonly-1
 description:
-	http://austingroupbugs.net/view.php?id=367 for export
+	https://www.austingroupbugs.net/view.php?id=367 for export
 stdin:
 	"$__progname" -c 'readonly foo; export foo=a; echo $?' || echo aborted, $?
 expected-stdout:
@@ -6990,7 +7079,7 @@ expected-stdout:
 ---
 name: readonly-2b
 description:
-	http://austingroupbugs.net/view.php?id=367 for getopts
+	https://www.austingroupbugs.net/view.php?id=367 for getopts
 stdin:
 	"$__progname" -c 'readonly c; set -- -a b; getopts a c; echo $? $c .' || echo aborted, $?
 expected-stdout:
@@ -7000,7 +7089,7 @@ expected-stderr-pattern:
 ---
 name: readonly-3
 description:
-	http://austingroupbugs.net/view.php?id=367 for read
+	https://www.austingroupbugs.net/view.php?id=367 for read
 stdin:
 	echo x | "$__progname" -c 'read s; echo $? $s .' || echo aborted, $?
 	echo y | "$__progname" -c 'readonly s; read s; echo $? $s .' || echo aborted, $?
@@ -7130,7 +7219,7 @@ expected-stdout:
 ---
 name: xxx-exec-environment-1
 description:
-	Check to see if exec sets it's environment correctly
+	Check to see if exec sets its environment correctly
 stdin:
 	print '#!'"$__progname"'\nunset RANDOM\nexport | while IFS= read -r' \
 	    'RANDOM; do eval '\''print -r -- "$RANDOM=$'\''"$RANDOM"'\'\"\'\; \
@@ -7162,47 +7251,91 @@ expected-stdout:
 	y1-
 	x-3- z-
 ---
-name: exec-modern-korn-shell
+name: exec-execs
+description:
+	Ensure that exec never returns
+need-ctty: yes
+env-setup: !ENV=./envf!
+file-setup: file 644 "envf"
+	PS1=X
+arguments: !-i!
+stdin:
+	oldPATH=$PATH
+	PATH=$PWD
+	exec bla
+	PATH=$oldPATH
+	echo fail
+expected-stderr-pattern:
+	/X+.*: bla: (?:inaccessible or )?not found\n/
+expected-exit: 127
+---
+name: exec-execs-not-in-posix
+description:
+	Ensure that exec returns in POSIX mode
+need-ctty: yes
+env-setup: !ENV=./envf!
+file-setup: file 644 "envf"
+	PS1=X
+arguments: !-i!-o!posix!
+stdin:
+	oldPATH=$PATH
+	PATH=$PWD
+	exec bla; echo fail=$?
+	echo ok=$?
+expected-stdout:
+	ok=127
+expected-stderr-pattern:
+	/X+.*: bla: (?:inaccessible or )?not found\n/
+---
+name: exec-modern
 description:
 	Check that exec can execute any command that makes it
 	through syntax and parser
 stdin:
-	print '#!'"$__progname"'\necho tf' >lq
-	chmod +x lq
+	echo '#!'"$__progname" >f
+	echo 'echo >&3 FAIL' >>f
+	echo '#!'"$__progname" >lq
+	echo 'echo tf' >>lq
+	chmod +x lq f
 	PATH=$PWD
-	exec 2>&1
-	foo() { print two; }
-	print =1
-	(exec print one)
-	print =2
-	(exec foo)
-	print =3
-	(exec ls)
-	print =4
-	(exec lq)
+	exec 3>&2 2>&1
+	foo() { echo two; }
+	echo =1
+	(exec echo one; ./f)
+	echo =2
+	(exec foo; ./f)
+	echo =3
+	(exec ls; ./f)
+	echo =4
+	(exec lq; ./f)
 expected-stdout-pattern:
-	/=1\none\n=2\ntwo\n=3\n.*: ls: inaccessible or not found\n=4\ntf\n/
+	/=1\none\n=2\ntwo\n=3\n.*: ls: (?:inaccessible or )?not found\n=4\ntf\n/
 ---
 name: exec-ksh88
 description:
 	Check that exec only executes after a PATH search
+	(POSIX Issue 8 uses utility ipv command for the synopsis)
+	cf. https://www.austingroupbugs.net/view.php?id=1157
 arguments: !-o!posix!
 stdin:
-	print '#!'"$__progname"'\necho tf' >lq
-	chmod +x lq
+	echo '#!'"$__progname" >f
+	echo 'echo >&3 FAIL' >>f
+	echo '#!'"$__progname" >lq
+	echo 'echo tf' >>lq
+	chmod +x lq f
 	PATH=$PWD
-	exec 2>&1
-	foo() { print two; }
-	print =1
-	(exec print one)
-	print =2
-	(exec foo)
-	print =3
-	(exec ls)
-	print =4
-	(exec lq)
+	exec 3>&2 2>&1
+	foo() { echo two; }
+	echo =1
+	(exec echo one; ./f)
+	echo =2
+	(exec foo; ./f)
+	echo =3
+	(exec ls; ./f)
+	echo =4
+	(exec lq; ./f)
 expected-stdout-pattern:
-	/=1\n.*: print: inaccessible or not found\n=2\n.*: foo: inaccessible or not found\n=3\n.*: ls: inaccessible or not found\n=4\ntf\n/
+	/=1\n.*: echo: (?:inaccessible or )?not found\n=2\n.*: foo: (?:inaccessible or )?not found\n=3\n.*: ls: (?:inaccessible or )?not found\n=4\ntf\n/
 ---
 name: xxx-what-do-you-call-this-1
 stdin:
@@ -7339,7 +7472,7 @@ need-ctty: yes
 arguments: !-i!
 stdin:
 	exec echo hi
-	echo still herre
+	echo still here
 expected-stdout:
 	hi
 expected-stderr-pattern: /.*/
@@ -7470,19 +7603,26 @@ name: xxx-param-subst-qmark-namespec
 description:
 	Check special names are output correctly
 stdin:
+	prgsub() {
+		sed \
+		    -e "s^${__progname%.exe}\.*e*x*e*: PROG: " \
+		    -e "s^[EW]: ${__progname%.exe}\.*e*x*e*: PROG: " \
+		    -e 's/^qmark_foo: /E: &/' \
+		    -e "s/^/$1: /g"
+	}
 	doit() {
 		"$__progname" -c "$@" >o1 2>o2
 		rv=$?
 		echo RETVAL: $rv
-		sed -e "s^${__progname%.exe}\.*e*x*e*: PROG: " -e 's/^/STDOUT: /g' <o1
-		sed -e "s^${__progname%.exe}\.*e*x*e*: PROG: " -e 's/^/STDERR: /g' <o2
+		prgsub STDOUT <o1
+		prgsub STDERR <o2
 	}
 	doit 'echo ${1x}'
 	doit 'echo "${1x}"'
 	doit 'echo ${1?}'
 	doit 'echo ${19?}'
 	doit 'echo ${!:?}'
-	doit -u 'echo ${*:?}' foo ""
+	doit -u 'echo ${*:?}' qmark_foo ""
 expected-stdout:
 	RETVAL: 1
 	STDERR: PROG: ${1x}: bad substitution
@@ -7495,7 +7635,7 @@ expected-stdout:
 	RETVAL: 1
 	STDERR: PROG: !: parameter null or not set
 	RETVAL: 1
-	STDERR: foo: ${*:?}: bad substitution
+	STDERR: E: qmark_foo: ${*:?}: bad substitution
 ---
 name: xxx-param-_-1
 # fails due to weirdness of execv stuff
@@ -7827,25 +7967,35 @@ expected-stdout:
 ---
 name: exit-enoent-1
 description:
-	SUSv4 says that the shell should exit with 126/127 in some situations
+	SUSv4 says that the shell should exit with 127 in some situations
 stdin:
-	i=0
 	(echo; echo :) >x
-	"$__progname" ./x >/dev/null 2>&1; r=$?; echo $((i++)) $r .
-	"$__progname" -c ./x >/dev/null 2>&1; r=$?; echo $((i++)) $r .
+	"$__progname" ./x >/dev/null 2>&1; r=$?; echo 0 $r .
 	echo exit 42 >x
-	"$__progname" ./x >/dev/null 2>&1; r=$?; echo $((i++)) $r .
-	"$__progname" -c ./x >/dev/null 2>&1; r=$?; echo $((i++)) $r .
+	"$__progname" ./x >/dev/null 2>&1; r=$?; echo 42 $r .
 	rm -f x
-	"$__progname" ./x >/dev/null 2>&1; r=$?; echo $((i++)) $r .
-	"$__progname" -c ./x >/dev/null 2>&1; r=$?; echo $((i++)) $r .
+	"$__progname" ./x >/dev/null 2>&1; r=$?; echo notexist $r .
 expected-stdout:
 	0 0 .
-	1 126 .
-	2 42 .
-	3 126 .
-	4 127 .
-	5 127 .
+	42 42 .
+	notexist 127 .
+---
+name: exit-enoent-2
+description:
+	SUSv4 says that the shell should exit with 126 in some situations
+# fails because x permissions handled wrong
+category: !os:skyos,!noxperms
+stdin:
+	(echo; echo :) >x
+	"$__progname" -c ./x >/dev/null 2>&1; r=$?; echo 0 $r .
+	echo exit 42 >x
+	"$__progname" -c ./x >/dev/null 2>&1; r=$?; echo 42 $r .
+	rm -f x
+	"$__progname" -c ./x >/dev/null 2>&1; r=$?; echo notexist $r .
+expected-stdout:
+	0 126 .
+	42 126 .
+	notexist 127 .
 ---
 name: exit-eval-1
 description:
@@ -7884,6 +8034,80 @@ expected-stdout:
 	G 12
 	H 0
 ---
+name: exit-stdout-1
+description:
+	cf. https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=990265, Austin ML
+# SIGPIPE seems hosed on BeOS and SkyOS
+category: !os:beos,!os:skyos
+stdin:
+	if test -c /dev/full && test -w /dev/full; then
+		if pwd >/dev/full 2>e; then
+			cat e
+			echo fail
+		else
+			echo pass
+		fi
+	else
+		echo skip
+	fi
+	case " $(echo $( (set -o posix) >/dev/null 2>&1 && set -o posix >/dev/null 2>&1; kill -l)) " in
+	(*' PIPE '*)
+		:>s
+		{ trap '' PIPE; sleep 1; pwd 2>e; echo $? >s; } | :
+		case x$(cat s) in
+		(x)
+			cat e
+			echo fail else ;;
+		(x0)
+			cat e
+			echo fail 0 ;;
+		(*)
+			echo pass ;;
+		esac
+		;;
+	(*)
+		echo skip ;;
+	esac
+expected-stdout-pattern:
+	/^(pass|skip)\n(pass|skip)\n$/
+---
+name: exit-stdout-2
+description:
+	same, except for external utility / direct builtin call
+category: !os:beos,!os:skyos
+stdin:
+	ln -s "$__progname" pwd 2>/dev/null || cp "$__progname" pwd
+	if test -c /dev/full && test -w /dev/full; then
+		if ./pwd >/dev/full 2>e; then
+			cat e
+			echo fail
+		else
+			echo pass
+		fi
+	else
+		echo skip
+	fi
+	case " $(echo $( (set -o posix) >/dev/null 2>&1 && set -o posix >/dev/null 2>&1; kill -l)) " in
+	(*' PIPE '*)
+		:>s
+		{ trap '' PIPE; sleep 1; ./pwd 2>e; echo $? >s; } | :
+		case x$(cat s) in
+		(x)
+			cat e
+			echo fail else ;;
+		(x0)
+			cat e
+			echo fail 0 ;;
+		(*)
+			echo pass ;;
+		esac
+		;;
+	(*)
+		echo skip ;;
+	esac
+expected-stdout-pattern:
+	/^(pass|skip)\n(pass|skip)\n$/
+---
 name: exit-trap-1
 description:
 	Check that "exit" with no arguments behaves SUSv4 conformant.
@@ -7899,7 +8123,7 @@ description:
 	Check that ERR and EXIT traps are run just like GNU bash does.
 	ksh93 runs ERtrap after “parameter null or not set” (which mksh
 	used to do) but (bug) continues “and out”, exit 0, in +e eval-undef.
-file-setup: file 644 "x"
+file-setup: file 644 "xe"
 	v=; unset v
 	trap 'echo EXtrap' EXIT
 	trap 'echo ERtrap' ERR
@@ -7940,15 +8164,16 @@ stdin:
 		) 2>&1 | sed \
 		    -e 's/parameter not set/parameter null or not set/' \
 		    -e 's/[[]6]//' -e 's/: eval: line 1//' -e 's/: line 6//' \
+		    -e 's/^x[etfu]: /E: &/' \
 		    -e "s^${__progname%.exe}\.*e*x*e*: <stdin>\[[0-9]*]PROG"
 	}
 	xe=-e
 	echo : $xe
-	runtest x $xe true
+	runtest xe $xe true
 	echo = eval-true $(<rc) .
-	runtest x $xe false
+	runtest xe $xe false
 	echo = eval-false $(<rc) .
-	runtest x $xe '${v?}'
+	runtest xe $xe '${v?}'
 	echo = eval-undef $(<rc) .
 	runtest xt $xe
 	echo = noeval-true $(<rc) .
@@ -7958,11 +8183,11 @@ stdin:
 	echo = noeval-undef $(<rc) .
 	xe=+e
 	echo : $xe
-	runtest x $xe true
+	runtest xe $xe true
 	echo = eval-true $(<rc) .
-	runtest x $xe false
+	runtest xe $xe false
 	echo = eval-false $(<rc) .
-	runtest x $xe '${v?}'
+	runtest xe $xe '${v?}'
 	echo = eval-undef $(<rc) .
 	runtest xt $xe
 	echo = noeval-true $(<rc) .
@@ -7981,7 +8206,7 @@ expected-stdout:
 	EXtrap
 	= eval-false 1 .
 	and run ${v?}
-	x: v: parameter null or not set
+	E: xe: v: parameter null or not set
 	EXtrap
 	= eval-undef 1 .
 	and run true
@@ -7993,7 +8218,7 @@ expected-stdout:
 	EXtrap
 	= noeval-false 1 .
 	and run ${v?}
-	xu: v: parameter null or not set
+	E: xu: v: parameter null or not set
 	EXtrap
 	= noeval-undef 1 .
 	: +e
@@ -8008,7 +8233,7 @@ expected-stdout:
 	EXtrap
 	= eval-false 0 .
 	and run ${v?}
-	x: v: parameter null or not set
+	E: xe: v: parameter null or not set
 	EXtrap
 	= eval-undef 1 .
 	and run true
@@ -8021,7 +8246,7 @@ expected-stdout:
 	EXtrap
 	= noeval-false 0 .
 	and run ${v?}
-	xu: v: parameter null or not set
+	E: xu: v: parameter null or not set
 	EXtrap
 	= noeval-undef 1 .
 ---
@@ -8474,7 +8699,7 @@ stdin:
 	[[ -o !sh ]] && echo nosh
 	[[ -o braceexpand ]] && echo brex
 	[[ -o !braceexpand ]] && echo nobrex
-	[[ $(exec -a -set "$__progname" -o) = *login+(' ')on* ]]; echo $?
+	:
 expected-stdout:
 	nosh
 	brex
@@ -8487,6 +8712,15 @@ expected-stdout:
 	a b c
 	sh
 	brex
+---
+name: sh-mode-1-exec-a
+description:
+	Was part of sh-mode-1 but exclude where selftest-exec-a fails
+	or better fix that
+category: !os:beos
+stdin:
+	[[ $(exec -a -set "$__progname" -o) = *login+(' ')on* ]]; echo $?
+expected-stdout:
 	0
 ---
 name: sh-mode-2a
@@ -8495,7 +8729,7 @@ description:
 category: !binsh
 stdin:
 	for shell in {,-}{,r}{,k,mk}sh {,-}{,R}{,K,MK}SH.EXE; do
-		ln -s "$__progname" ./$shell || cp "$__progname" ./$shell
+		ln -s "$__progname" ./$shell 2>/dev/null || cp "$__progname" ./$shell
 		print -- $shell $(./$shell +l -c '
 			[[ -o sh || -o posix ]] && echo sh
 			[[ -o !sh && -o !posix ]] && echo nosh
@@ -8534,7 +8768,7 @@ description:
 category: binsh
 stdin:
 	for shell in {,-}{,r}{,k,mk}sh {,-}{,R}{,K,MK}SH.EXE; do
-		ln -s "$__progname" ./$shell || cp "$__progname" ./$shell
+		ln -s "$__progname" ./$shell 2>/dev/null || cp "$__progname" ./$shell
 		print -- $shell $(./$shell +l -c '
 			[[ -o sh || -o posix ]] && echo sh
 			[[ -o !sh && -o !posix ]] && echo nosh
@@ -8641,8 +8875,8 @@ stdin:
 	(echo x; exit 12) | (cat; exit 23) | (cat; exit 42)
 	echo 5 $? , $PIPESTATUS , ${PIPESTATUS[0]} , ${PIPESTATUS[1]} , ${PIPESTATUS[2]} , ${PIPESTATUS[3]} .
 	echo 6 ${PIPESTATUS[0]} .
-	set | fgrep PIPESTATUS
-	echo 8 $(set | fgrep PIPESTATUS) .
+	set | grep PIPESTATUS
+	echo 8 $(set | grep PIPESTATUS) .
 expected-stdout:
 	1 0 .
 	2 0 .
@@ -8792,13 +9026,46 @@ expected-stdout:
 	<12345678910 345678920
 	<               .  aẞ> 2)
 ---
+name: typeset-unset
+description:
+	Check that typeset -p correctly distinguishes unset and empty
+stdin:
+	unset u
+	typeset -p u
+	echo 1 ${u-a} ${u:-b} .
+	x1=$(typeset -p u)
+	export u
+	typeset -p u
+	echo 2 ${u-a} ${u:-b} .
+	x2=$(typeset -p u)
+	u=
+	typeset -p u
+	echo 3 ${u-a} ${u:-b} .
+	x3=$(typeset -p u)
+	unset u
+	eval "$x1"
+	echo 4 ${u-a} ${u:-b} .
+	unset u
+	eval "$x2"
+	echo 5 ${u-a} ${u:-b} .
+	unset u
+	eval "$x3"
+	echo 6 ${u-a} ${u:-b} .
+expected-stdout:
+	1 a b .
+	typeset -x u
+	2 a b .
+	typeset -x u=''
+	3 b .
+	4 a b .
+	5 a b .
+	6 b .
+---
 name: utf8bom-1
 description:
-	Check that the UTF-8 Byte Order Mark is ignored as the first
-	multibyte character of the shell input (with -c, from standard
-	input, as file, or as eval argument), but nowhere else
+	Check that the UTF-8 Byte Order Mark is not ignored any more
 # breaks on Mac OSX (HFS+ non-standard UTF-8 canonical decomposition)
-category: !os:darwin,!shell:ebcdic-yes
+category: !os:darwin,!shell:ebcdic-yes,!noweirdfilenames
 stdin:
 	mkdir foo
 	print '#!/bin/sh\necho ohne' >foo/fnord
@@ -8823,62 +9090,33 @@ stdin:
 	rm -rf foo
 expected-stdout:
 	got 4 files
-	ohne
+	mit
 	=
-	ohne
+	mit
 	ohne
 	mit
 	ohne
 	=
-	ohne
+	mit
 	ohne
 	mit
 	ohne
 	=
-	ohne
+	mit
 	ohne
 	mit
 	ohne
 	=
-	ohne
+	mit
 	ohne
 	mit
 	ohne
 	=
-	: ohne
----
-name: utf8bom-2
-description:
-	Check that we can execute BOM-shebangs (failures not fatal)
-	XXX if the OS can already execute them, we lose
-	note: cygwin execve(2) doesn't return to us with ENOEXEC, we lose
-	note: Ultrix perl5 t4 returns 65280 (exit-code 255) and no text
-	note: A/UX perl5 returns 6400 (exit-code 25), passes #1-3
-	XXX fails when LD_PRELOAD is set with -e and Perl chokes it (ASan)
-need-pass: no
-category: !os:aux,!os:cygwin,!os:midipix,!os:msys,!os:ultrix,!os:uwin-nt,!smksh
-env-setup: !FOO=BAR!
-stdin:
-	print '#!'"$__progname"'\nprint "1 a=$ENV{FOO}";' >t1
-	print '#!'"$__progname"'\nprint "2 a=$ENV{FOO}";' >t2
-	print '#!'"$__perlname"'\nprint "3 a=$ENV{FOO}\n";' >t3
-	print '#!'"$__perlname"'\nprint "4 a=$ENV{FOO}\n";' >t4
-	chmod +x t?
-	./t1
-	./t2
-	./t3
-	./t4
-expected-stdout:
-	1 a=/nonexistant{FOO}
-	2 a=/nonexistant{FOO}
-	3 a=BAR
-	4 a=BAR
-expected-stderr-pattern:
-	/(Unrecognized character .... ignored at \..t4 line 1)*/
+	: mit
 ---
 name: utf8opt-1
 description:
-	Check that the utf8-mode flag is not set at non-interactive startup
+	Check that the utf8-mode flag *is* set at non-interactive startup
 env-setup: !PS1=!PS2=!LC_CTYPE=@utflocale@!
 stdin:
 	if [[ $- = *U* ]]; then
@@ -8887,13 +9125,13 @@ stdin:
 		echo is not set
 	fi
 expected-stdout:
-	is not set
+	is set
 ---
 name: utf8opt-2
 description:
 	Check that the utf8-mode flag is set at interactive startup.
-	If your OS is old, try passing HAVE_SETLOCALE_CTYPE=0 to Build.sh
 need-pass: no
+info-pre: if your OS fails this, contact the mksh developer
 category: !noutf8
 need-ctty: yes
 arguments: !-i!
@@ -9886,13 +10124,23 @@ name: varexpand-special-hash
 description:
 	Check special ${var@x} expansion for x=hash
 category: !shell:ebcdic-yes
+perl-setup: open XF,">xf" or die; print XF "a"x1000000 or die; close XF or die;
 stdin:
 	typeset -i8 foo=10
 	bar=baz
 	unset baz
 	print ${foo@#} ${bar@#} ${baz@#} .
+	set -e
+	set -A vec -- '' a abc 'message digest' abcdefghijklmnopqrstuvwxyz \
+	    abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq \
+	    ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 \
+	    12345678901234567890123456789012345678901234567890123456789012345678901234567890 \
+	    $(<xf)
+	print ${vec[0]@#} ${vec[1]@#} ${vec[2]@#} ${vec[3]@#} ${vec[4]@#} \
+	    ${vec[5]@#} ${vec[6]@#} ${vec[7]@#} ${vec[8]@#} .
 expected-stdout:
-	9B15FBFB CFBDD32B 00000000 .
+	D2F7C7B5 FE93FA63 03010102 .
+	03010102 4ACF470E 92FC2A8B E5030FFA ED69F029 9C0E532B C155BDD9 BE5117B7 2A9728CB .
 ---
 name: varexpand-special-hash-ebcdic
 description:
@@ -9904,12 +10152,11 @@ stdin:
 	unset baz
 	print ${foo@#} ${bar@#} ${baz@#} .
 expected-stdout:
-	016AE33D 9769C4AF 00000000 .
+	7819D62A E1FC0712 00000000 .
 ---
 name: varexpand-special-quote
 description:
 	Check special ${var@Q} expansion for quoted strings
-category: !shell:faux-ebcdic
 stdin:
 	set +U
 	i=x
@@ -9921,36 +10168,46 @@ stdin:
 	print -r -- "s=\"$s\""
 	eval "$s"
 	typeset -p u v w
+	set -o asis
+	typeset -p w
+	set -U
+	typeset -p w
 expected-stdout:
 	<i=x j=a b k=c
 	de€f>
-	s="u=x v='a b' w=$'c\nd\240e\u20ACf'"
+	s="u=x v='a b' w=$'c\nde\202f'"
 	typeset u=x
 	typeset v='a b'
-	typeset w=$'c\nd\240e\u20ACf'
+	typeset w=$'c\nde\202f'
+	typeset w=$'c\nde€f'
+	typeset w=$'c\nd\240e€f'
 ---
-name: varexpand-special-quote-faux-EBCDIC
+name: varexpand-special-caret
 description:
-	Check special ${var@Q} expansion for quoted strings
-category: shell:faux-ebcdic
+	Check special ${var@^} expansion for quoted strings
 stdin:
-	set +U
-	i=x
-	j=a\ b
-	k=$'c
-	d\xA0''e€f'
-	print -r -- "<i=$i j=$j k=$k>"
-	s="u=${i@Q} v=${j@Q} w=${k@Q}"
-	print -r -- "s=\"$s\""
-	eval "$s"
-	typeset -p u v w
-expected-stdout:
-	<i=x j=a b k=c
-	de€f>
-	s="u=x v='a b' w=$'c\nde\u20ACf'"
-	typeset u=x
-	typeset v='a b'
-	typeset w=$'c\nde\u20ACf'
+	if (( 1#1 == 49 )); then
+		CSI=$'\x9B'	# ISO-8859-1
+	else
+		CSI=$'\x3B'	# EBCDIC
+	fi
+	s=$'a\cbc d\te f\c?g h'$CSI$'0mi j\u009B''0mk l^m\n'
+	set +U +o asis
+	# this works because check.t is iconv’d to EBCDIC copying to OS/390
+	print -r -- "raw <$s> ."
+	print -r -- "Ai <${s@^}> ."
+	set -o asis
+	print -r -- "Aa <${s@^}> ."
+	set -U +o asis
+	print -r -- "Ui <${s@^}> ."
+	set -o asis
+	print -r -- "Ua <${s@^}> ."
+expected-stdout:
+	raw <ac d	e fg h0mi j›0mk l^m\n> .
+	Ai <a^Bc d^Ie f^?g h^![0mi j^![0mk l\^m\\n> .
+	Aa <a^Bc d^Ie f^?g h0mi j›0mk l\^m\\n> .
+	Ui <a^Bc d^Ie f^?g h\x9B0mi j^+[0mk l\^m\\n> .
+	Ua <a^Bc d^Ie f^?g h\x9B0mi j^+[0mk l\^m\\n> .
 ---
 name: varexpand-null-1
 description:
@@ -10027,7 +10284,6 @@ expected-stdout:
 name: varexpand-funny-chars
 description:
 	Check some characters
-	XXX \uEF80 is asymmetric, possibly buggy so we don’t check this
 stdin:
 	x=$'<\x00>'; typeset -p x
 	x=$'<\x01>'; typeset -p x
@@ -10105,6 +10361,9 @@ stdin:
 	./foo | while IFS= read -r line; do
 		print -r -- "{$line}"
 	done
+	print -n -- '<220-blau.mirbsd.org ESMTP ready at Thu, 25 Jul 2013 15:57:57 GMT\r>\n<220->> Bitte keine Werbung einwerfen! <<\r\r>\n<220 Who do you wanna pretend to be today'
+	print -n \?
+	print \>
 expected-stdout:
 	[220-blau.mirbsd.org ESMTP ready at Thu, 25 Jul 2013 15:57:57 GMT
 	220->> Bitte keine Werbung einwerfen! <<

@@ -10112,6 +10371,9 @@ expected-stdout:
 	{220-blau.mirbsd.org ESMTP ready at Thu, 25 Jul 2013 15:57:57 GMT
}
 	{220->> Bitte keine Werbung einwerfen! <<

}
 	{220 Who do you wanna pretend to be today?
}
+	<220-blau.mirbsd.org ESMTP ready at Thu, 25 Jul 2013 15:57:57 GMT
>
+	<220->> Bitte keine Werbung einwerfen! <<

>
+	<220 Who do you wanna pretend to be today?
>
 ---
 name: print-crlf
 description:
@@ -10407,6 +10669,18 @@ stdin:
 expected-stdout:
 	1 0 .
 ---
+name: dot-args
+description:
+	Ensure dot can take arguments
+file-setup: file 644 "t"
+	print -r -- "$#,${1-},${2-},${3-}"
+stdin:
+	"$__progname" -c '. ./t a b'
+	"$__progname" -c 'source t c d'
+expected-stdout:
+	2,a,b,
+	2,c,d,
+---
 name: alias-function-no-conflict
 description:
 	make aliases not conflict with function definitions
@@ -10472,6 +10746,58 @@ expected-stdout:
 	dash: bar='./f-dash'
 	bash: bar='./f-bash'
 ---
+name: extfunc-1
+description:
+	check that extended mksh functions are handled (beta)
+stdin:
+	function () one {
+		echo "one,$#,$*."
+	}
+	# line 4 (next is 5)
+	function (x) two {
+		echo "two($x),$#,$*."
+	}
+	i=7
+	function (
+		a
+		b=$((++i))
+		c=
+	    ) three {
+		echo "three($i|$a,$b,$c),$#,$*."
+	}
+	one
+	one ii
+	# line 18 (next is 19)
+	two 2>tf
+	two ii $?
+	[[ $(<tf) = *'[19]: missing argument'* ]] && echo twopass || echo twofail
+	echo threebefore=$i
+	three eins zwo drei vier
+	echo threemid=$i
+	three allein
+	echo threeafter=$i
+	# line 27 (next is 28)
+	(PS4='<$LINENO>'; set -x; two miau) 2>tf
+	[[ $(<tf) = $'<28>two miau\n<5>local x=miau ; shift 1\n'* ]] && echo lastpass || echo lastfail
+	HOME=/etc
+	function (v=~/fsta* w="~/fsta*") four {
+		echo "four($v)($w),$#,$*."
+	}
+	four
+expected-stdout:
+	one,0,.
+	one,1,ii.
+	two(ii),1,2.
+	twopass
+	threebefore=7
+	three(7|eins,zwo,drei),1,vier.
+	threemid=7
+	three(8|allein,8,),0,.
+	threeafter=8
+	two(miau),0,.
+	lastpass
+	four(/etc/fsta*)(~/fsta*),0,.
+---
 name: integer-base-one-1
 description:
 	check if the use of fake integer base 1 works
@@ -10709,11 +11035,14 @@ stdin:
 			lpos=0
 			while (( lpos < ${#line} )); do
 				wc=1#${line:(lpos++):1}
+				let hv=wc
 				if (( (wc < 32) || \
 				    ((wc > 126) && (wc < 160)) )); then
 					dch=.
-				elif (( (wc & 0xFF80) == 0xEF80 )); then
+				elif (( (wc & ~0x7F) == 0xEF80 )); then
 					dch=�
+					# OPTU-8 value mapping, to keep test
+					#(( hv = 0xEF80 | (hv & 0x7F) ))
 				else
 					dch=${wc#1#}
 				fi
@@ -10725,7 +11054,6 @@ stdin:
 					print -n "${pos#16#}  "
 					dasc=' |'
 				fi
-				let hv=wc
 				print -n "${hv#16#} "
 				(( (pos++ & 7) == 3 )) && \
 				    print -n -- '- '
@@ -10876,8 +11204,10 @@ stdin:
 				if (( (hv < 32) || \
 				    ((hv > 126) && (hv < 160)) )); then
 					dch=.
-				elif (( (hv & 0xFF80) == 0xEF80 )); then
+				elif (( (hv & ~0x7F) == 0xEF80 )); then
 					dch=�
+					# OPTU-8 value mapping, to keep test
+					#(( hv = 0xEF80 | (hv & 0x7F) ))
 				else
 					dch=${line[i-1]#1#}
 				fi
@@ -11103,11 +11433,11 @@ stdin:
 		echo tri >&3
 	}
 	threeout &>foo
-	echo ===
+	echo === "$("$__progname" -c "echo $(: &>/dev/null) ok")"
 	cat foo
 expected-stdout:
 	tri
-	===
+	=== ok
 	ras
 	dwa
 ---
@@ -11193,7 +11523,7 @@ stdin:
 expected-stdout:
 	===
 	mir
-expected-stderr-pattern: /.*: can't (create|overwrite) .*/
+expected-stderr-pattern: /.*: foo: (create: |cannot overwrite existing file).*/
 ---
 name: bashiop-3b
 description:
@@ -11416,6 +11746,20 @@ description:
 stdin:
 	set foo bar baz ; for out in ; do echo $out ; done
 ---
+name: for-without-list
+description:
+	LP#2002250
+stdin:
+	set -- a b
+	for x
+	do
+		echo $x
+		shift $#
+	done
+expected-stdout:
+	a
+	b
+---
 name: oksh-varfunction-mod1
 description:
 	(Inspired by PR 2450 on OpenBSD.) Calling
@@ -11490,6 +11834,8 @@ name: fd-cloexec-1
 description:
 	Verify that file descriptors > 2 are private for Korn shells
 	AT&T ksh93 does this still, which means we must keep it as well
+# broken on Xenix and BeOS
+category: !os:beos,!os:sco_xenix
 stdin:
 	cat >cld <<-EOF
 		#!$__perlname
@@ -11507,6 +11853,7 @@ name: fd-cloexec-2
 description:
 	Verify that file descriptors > 2 are not private for POSIX shells
 	See Debian Bug #154540, Closes: #499139
+category: !os:beos,!os:sco_xenix
 stdin:
 	cat >cld <<-EOF
 		#!$__perlname
@@ -11514,11 +11861,16 @@ stdin:
 		syswrite(FH, "Fowl\\n", 5) or die "E: write \$!";
 	EOF
 	chmod +x cld
+	./cld 9>&2
+	echo >&2 =
 	test -n "$POSH_VERSION" || set -o posix
 	exec 9>&1
 	./cld
 expected-stdout:
 	Fowl
+expected-stderr:
+	Fowl
+	=
 ---
 name: fd-cloexec-3
 description:
@@ -11733,6 +12085,7 @@ stdin:
 	#TFUNCT_TBRACE_TASYNC
 	function  korn  {  echo eins; echo zwei ;  }
 	bourne  ()  {  logger *  &  }
+	function (	a b='x$y\z'$(echo w)$((++i)) c  ) extended { :; }
 	#IOREAD_IOCAT
 	tr  x  u  0<foo  >>bar
 	#IOWRITE_IOCLOB_IOHERE_noIOSKIP
@@ -12006,6 +12359,7 @@ expected-stdout:
 	inline_TFUNCT_TBRACE_TASYNC() {
 		function  korn  {  echo eins; echo zwei ;  }
 		bourne  ()  {  logger *  &  }
+		function (	a b='x$y\z'$(echo w)$((++i)) c  ) extended { :; }
 	}
 	inline_TFUNCT_TBRACE_TASYNC() {
 		function korn {
@@ -12015,20 +12369,25 @@ expected-stdout:
 		bourne() {
 			\logger * & 
 		} 
+		function (a b="x\$y\\z"$(\echo w )$((++i)) c) extended {
+			\: 
+		} 
 	} 
 	function comsub_TFUNCT_TBRACE_TASYNC { x=$(
 		function  korn  {  echo eins; echo zwei ;  }
 		bourne  ()  {  logger *  &  }
+		function (	a b='x$y\z'$(echo w)$((++i)) c  ) extended { :; }
 	); }
 	function comsub_TFUNCT_TBRACE_TASYNC {
-		x=$(function korn { \echo eins ; \echo zwei ; } ; bourne() { \logger * &  } ) 
+		x=$(function korn { \echo eins ; \echo zwei ; } ; bourne() { \logger * &  } ; function (a b="x\$y\\z"$(\echo w )$((++i)) c) extended { \: ; } ) 
 	} 
 	function reread_TFUNCT_TBRACE_TASYNC { x=$((
 		function  korn  {  echo eins; echo zwei ;  }
 		bourne  ()  {  logger *  &  }
+		function (	a b='x$y\z'$(echo w)$((++i)) c  ) extended { :; }
 	)|tr u x); }
 	function reread_TFUNCT_TBRACE_TASYNC {
-		x=$( ( function korn { \echo eins ; \echo zwei ; } ; bourne() { \logger * &  } ) | \tr u x ) 
+		x=$( ( function korn { \echo eins ; \echo zwei ; } ; bourne() { \logger * &  } ; function (a b="x\$y\\z"$(\echo w )$((++i)) c) extended { \: ; } ) | \tr u x ) 
 	} 
 	inline_IOREAD_IOCAT() {
 		tr  x  u  0<foo  >>bar
@@ -12728,7 +13087,6 @@ expected-stdout:
 name: funsub-2
 description:
 	You can now reliably use local and return in funsubs
-	(not exit though)
 stdin:
 	x=q; e=1; x=${ echo a; e=2; echo x$e;}; echo 1:y$x,$e,$?.
 	x=q; e=1; x=${ echo a; typeset e=2; echo x$e;}; echo 2:y$x,$e,$?.
@@ -12738,6 +13096,32 @@ expected-stdout:
 	2:ya x2,1,0.
 	3:ya,1,3.
 ---
+name: funsub-3
+description:
+	… not exit though, like in ksh93
+stdin:
+	function foo {
+		if [[ $1 = 2 ]]; then
+			print -u2 ERR
+			exit 42
+		fi
+		print -r -- "<$1>"
+	}
+	for i in 1 2 3; do
+		print $i ${ foo $i;} || {
+			print SUB=$?
+			exit 1
+		}
+	done
+	print END=$?
+expected-stdout:
+	1 <1>
+	2
+	3 <3>
+	END=0
+expected-stderr:
+	ERR
+---
 name: valsub-1
 description:
 	Check that "value substitutions" work as advertised
@@ -12770,6 +13154,51 @@ expected-stdout:
 	typeset t=$'foo\n\n'
 	this used to segfault.
 ---
+name: valsub-2
+description:
+	Can use exit here, in contrast to funsubs
+stdin:
+	function foo {
+		if [[ $1 = 2 ]]; then
+			print -u2 ERR
+			exit 42
+		fi
+		REPLY="<$1>"
+	}
+	for i in 1 2 3; do
+		print $i ${|foo $i;} || {
+			print SUB=$?
+			exit 1
+		}
+	done
+	print END=$?
+expected-exit: 42
+expected-stdout:
+	1 <1>
+expected-stderr:
+	ERR
+---
+name: funsub-valsub-1
+description:
+	This is what AT&T ksh93 does for shift
+stdin:
+	"$__progname" -c 'echo a. "$@"; : "${ shift;}"; echo b. "$@"' sh1 1a 1b
+	"$__progname" -c 'echo a. "$@"; : "${|shift;}"; echo b. "$@"' sh2 2a 2b
+	"$__progname" -c 'echo a. "$@"; : "${|shift;shift;}"; echo b. "$@"' sh3 3a 3b
+	echo >&2 =1
+	"$__progname" -c 'echo a. "$@"; : "${|shift;shift;shift;}"; echo b. "$@"' sh4 4a 4b
+	echo >&2 =2
+expected-stdout:
+	a. 1a 1b
+	b. 1b
+	a. 2a 2b
+	b. 2b
+	a. 3a 3b
+	b.
+	a. 4a 4b
+expected-stderr-pattern:
+	/^=1\n[^\n]*nothing to shift[^\n]*\n=2$/
+---
 name: event-subst-3
 description:
 	Check that '!' substitution in noninteractive mode is ignored
@@ -12875,22 +13304,26 @@ stdin:
 	echo =14
 	(mypid=$$; try mypid)
 	echo =15
-	) 2>&1 | sed -e 's/^[A-Za-z]://' -e 's/^[^]]*]//' -e 's/^[^:]*: *//'
+	) 2>&1 | sed \
+	    -e "s^${__progname%.exe}\.*e*x*e*: <stdin>\[[0-9]*]PROGl" \
+	    -e "s^[EW]: ${__progname%.exe}\.*e*x*e*: <stdin>\[[0-9]*]PROGl" \
+	    -e "s^${__progname%.exe}\.*e*x*e*: PROGn: " \
+	    -e "s^[EW]: ${__progname%.exe}\.*e*x*e*: PROGn: "
 	exit ${PIPESTATUS[0]}
 expected-stdout:
 	y
 	=1
-	y: parameter not set
+	PROGl: y: parameter not set
 	=2
 	x=nz
 	=3
-	y: parameter not set
+	PROGn: y: parameter not set
 	=4
 	0=nz
 	=5
-	2: parameter not set
+	PROGn: 2: parameter not set
 	=6
-	1: parameter not set
+	PROGl: 1: parameter not set
 	=7
 	at=
 	=8
@@ -12898,7 +13331,7 @@ expected-stdout:
 	=9
 	0
 	=10
-	!: parameter not set
+	PROGl: !: parameter not set
 	=11
 	ush
 	=12
@@ -13218,6 +13651,44 @@ expected-stdout:
 	2=\x7Cfoo-e \x4B
 	3=\x7Cfoo-e \x4B
 ---
+name: env-intvars
+description:
+	Check that importing integers fails except for numbers
+stdin:
+	print '#!'"$__perlname"'\n($k, $v) = split(/=/, shift(@ARGV),' \
+	    '2);\n$ENV{$k} = $v;\nexec { $ARGV[0] } @ARGV or die $!;' \
+	    >env; chmod +x env; PATH=.$PATHSEP$PATH
+	unset foo bar
+	print 1 $foo , $(typeset -p bar) .
+	print 2 $(foo=123 "$__progname" -c 'integer foo; print -- $foo' 2>&1) , \
+	    $(env 'bar[123]=baz' "$__progname" -c 'typeset -p bar') .
+	print 3 $(foo='abc[$(echo >&2 fowled)0]' "$__progname" -c 'integer foo; print -- $foo' 2>&1) , \
+	    $(env 'bar[$(echo >&2 fowled)0]=baz' "$__progname" -c 'typeset -p bar') .
+	print 4 $(foo=0123 "$__progname" +o posix -c 'integer foo; print -- $foo' 2>&1) , \
+	    $(env 'bar[0123]=baz' "$__progname" +o posix -c 'typeset -p bar') .
+	# ksh93 does not do this:
+	print 5 $(foo=0123 "$__progname" -o posix -c 'integer foo; print -- $foo' 2>&1) .
+	# at import time FPOSIX is not yet set
+	print 6 $(foo=0x123 "$__progname" -c 'integer foo; print -- $foo' 2>&1) , \
+	    $(env 'bar[0x123]=baz' "$__progname" -c 'typeset -p bar') .
+	print 7 $(foo=12#123 "$__progname" -c 'integer foo; print -- $foo' 2>&1) , \
+	    $(env 'bar[12#123]=baz' "$__progname" -c 'typeset -p bar') .
+	print 8 $(foo=1+1 "$__progname" -c 'integer foo; print -- $foo' 2>&1) , \
+	    $(env 'bar[1+1]=baz' "$__progname" -c 'typeset -p bar') .
+	print 9 $(a=1 b=2 c=a "$__progname" -c 'typeset -p c; c=b; typeset -p c; integer c; typeset -p c') .
+	print 0 $(a=1 b=2 c=a "$__progname" -c 'typeset -p c;      typeset -p c; integer c; typeset -p c') .
+expected-stdout:
+	1 , .
+	2 123 , set -A bar typeset -x bar[123]=baz .
+	3 0 , .
+	4 123 , set -A bar typeset -x bar[123]=baz .
+	5 8#123 .
+	6 16#123 , set -A bar typeset -x bar[291]=baz .
+	7 12#123 , set -A bar typeset -x bar[171]=baz .
+	8 0 , .
+	9 typeset -x c=a typeset -x c=b typeset -i -x c=2 .
+	0 typeset -x c=a typeset -x c=a typeset -i -x c=0 .
+---
 name: utilities-getopts-1
 description:
 	getopts sets OPTIND correctly for unparsed option
@@ -13459,6 +13930,12 @@ stdin:
 expected-stdout:
 	bar
 ---
+name: crash-2
+stdin:
+	<<<`$((`
+expected-exit: e != 0
+expected-stderr-pattern: /.*: no closing quote$/
+---
 name: debian-117-1
 description:
 	Check test - bug#465250
@@ -13730,7 +14207,7 @@ name: duffs-device
 description:
 	Check that the compiler did not optimise-break them
 	(lex.c has got a similar one in SHEREDELIM)
-category: !shell:faux-ebcdic,!shell:ebcdic-yes
+category: !shell:ebcdic-yes
 stdin:
 	set +U
 	s=
@@ -13740,8 +14217,14 @@ stdin:
 	done
 	s+=$'\xC2\xA0\xE2\x82\xAC\xEF\xBF\xBD\xEF\xBF\xBE\xEF\xBF\xBF\xF0\x90\x80\x80.'
 	typeset -p s
+	set -o asis
+	typeset -p s
+	set -U
+	typeset -p s
 expected-stdout:
-	typeset s=$'\001\002\003\004\005\006\a\b\t\n\v\f\r\016\017\020\021\022\023\024\025\026\027\030\031\032\E\034\035\036\037 !"#$%&\047()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377\u00A0\u20AC\uFFFD\357\277\276\357\277\277\360\220\200\200.'
+	typeset s=$'\001\002\003\004\005\006\a\b\t\n\v\f\r\016\017\020\021\022\023\024\025\026\027\030\031\032\E\034\035\036\037 !"#$%&\047()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237 \202�￾￿\220\200\200.'
+	typeset s=$'\001\002\003\004\005\006\a\b\t\n\v\f\r\016\017\020\021\022\023\024\025\026\027\030\031\032\E\034\035\036\037 !"#$%&\047()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\177 €�￾￿𐀀.'
+	typeset s=$'\001\002\003\004\005\006\a\b\t\n\v\f\r\016\017\020\021\022\023\024\025\026\027\030\031\032\E\034\035\036\037 !"#$%&\047()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377 €�\357\277\276\357\277\277\360\220\200\200.'
 ---
 name: duffs-device-ebcdic
 description:
@@ -13759,52 +14242,37 @@ stdin:
 expected-stdout:
 	typeset s=$'\001\002\003\004\t\006\007\010\011\012\v\f\r\016\017\020\021\022\023\024\n\b\027\030\031\032\033\034\035\036\037\040\041\042\043\044\045\046\E\050\051\052\053\054\055\056\a\060\061\062\063\064\065\066\067\070\071\072\073\074\075\076\077 .<(+|&!$*);^-/Ѧ,%_>?`:#@\175="abcdefghijklmnopqrƤ~stuvwxyz[ޮݨ]{ABCDEFGHI}JKLMNOPQR\\STUVWXYZ0123456789\377'
 ---
-name: duffs-device-faux-EBCDIC
-description:
-	Check that the compiler did not optimise-break them
-category: shell:faux-ebcdic
-stdin:
-	set +U
-	s=
-	typeset -i1 i=0
-	while (( ++i < 256 )); do
-		s+=${i#1#}
-	done
-	s+=$'\xC2\xA0\xE2\x82\xAC\xEF\xBF\xBD\xEF\xBF\xBE\xEF\xBF\xBF\xF0\x90\x80\x80.'
-	typeset -p s
-expected-stdout:
-	typeset s=$'\001\002\003\004\005\006\a\b\t\n\v\f\r\016\017\020\021\022\023\024\025\026\027\030\031\032\E\034\035\036\037 !"#$%&\047()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\u00A0\u20AC\uFFFD￾￿\220\200\200.'
----
 name: stateptr-underflow
 description:
 	This check overflows an Xrestpos stored in a short in R40
-category: fastbox
+info-pre: takes very long on retro systems
+category: !system:fast-no
 stdin:
 	function Lb64decode {
 		[[ -o utf8-mode ]]; local u=$?
 		set +U
 		local c s="$*" t=
-		[[ -n $s ]] || { s=$(cat;print x); s=${s%x}; }
-		local -i i=0 n=${#s} p=0 v x
+		[[ -n $s ]] || { s=$(cat;print .); s=${s%.}; }
+		local -i i=-1 n=${#s} p=0 v x
 		local -i16 o
 	
-		while (( i < n )); do
-			c=${s:(i++):1}
+		while ((# ++i < n )); do
+			c=${s:i:1}
 			case $c {
 			(=)	break ;;
-			([A-Z])	(( v = 1#$c - 65 )) ;;
-			([a-z])	(( v = 1#$c - 71 )) ;;
-			([0-9])	(( v = 1#$c + 4 )) ;;
+			([A-Z])	((# v = 1#$c - 65 )) ;;
+			([a-z])	((# v = 1#$c - 71 )) ;;
+			([0-9])	((# v = 1#$c + 4 )) ;;
 			(+)	v=62 ;;
 			(/)	v=63 ;;
 			(*)	continue ;;
 			}
-			(( x = (x << 6) | v ))
+			((# x = (x << 6) | v ))
 			case $((p++)) {
 			(0)	continue ;;
-			(1)	(( o = (x >> 4) & 255 )) ;;
-			(2)	(( o = (x >> 2) & 255 )) ;;
-			(3)	(( o = x & 255 ))
+			(1)	((# o = (x >> 4) & 255 )) ;;
+			(2)	((# o = (x >> 2) & 255 )) ;;
+			(3)	((# o = x & 255 ))
 				p=0
 				;;
 			}
@@ -13919,3 +14387,140 @@ expected-stdout:
 	2 eh .
 	3 eh .
 ---
+name: read-timeout-1
+description:
+	Check timeout functionality
+category: have:select:1
+time-limit: 5
+stdin:
+	sleep 2 | {
+		read -t1 foo
+		echo 1 $? "<$foo>"
+	}
+	: | {
+		read -t1 foo
+		echo 2 $? "<$foo>"
+	}
+	echo bla | {
+		read -t1 foo
+		echo 3 $? "<$foo>"
+	}
+expected-stdout:
+	1 142 <>
+	2 1 <>
+	3 0 <bla>
+---
+name: read-timeout-slow
+description:
+	Check timeout parser
+info-pre: takes 15, at most 20, seconds
+category: have:select:1
+time-limit: 20
+stdin:
+	(sleep 14; echo foo) | {
+		read -t12.3 foo
+		echo 1 $? "<$foo>"
+	} >o1 &
+	(sleep 11; echo foo) | {
+		read -t12.3 foo
+		echo 2 $? "<$foo>"
+	} > o2 &
+	wait
+	cat o1
+	cat o2
+expected-stdout:
+	1 142 <>
+	2 0 <foo>
+---
+name: time-stayalive
+description:
+	check time syntax element or builtin do not exit the shell on error
+stdin:
+	set -e
+	ln -s "$__progname" time 2>/dev/null || cp "$__progname" time
+	if time -f true; then echo 3 meh $? .; else echo 3 ok $? .; fi
+	if command time -f true; then echo 4 meh $? .; else echo 4 ok $? .; fi
+	if ./time -f true; then echo 5 meh $? .; else echo 5 ok $? .; fi
+	echo 6 out .; echo >&2 6 err .
+	time true
+expected-stdout:
+	3 ok 1 .
+	4 ok 1 .
+	5 ok 1 .
+	6 out .
+expected-stderr-pattern: /^(?:.*unknown option.*\n){3}6 err \.\n.*s real.*system$/
+---
+name: optional-printf-builtin
+description:
+	printf(1) minimal tests
+category: printf-builtin
+stdin:
+	t() {
+		o=$(\\builtin printf "$@"; echo .)
+		r=$?
+		print -r -- "$((++n)) ${o%.} : $r"
+	}
+	t '<%s>' a b\	c
+	t '%s - %c %s %d %i %o %u %x %X %b' 3
+	t '%% %c %s %d %i %o %u %x %X' 72 73 74 75 76 77 78 79
+	t '\\\a\b\f\n\r\t\v\01234'
+	let n+=2
+	t '%b foo %s bar' '\\\a\b\f\n\r\t\v\01234\cdefg'
+	let ++n
+	t '<%d>' 1 +2 -3 0x1a 0X1B 010 -011 +012 \'1 \"2
+	t '<%d|%d><%+d|%+d><% d|% d><%+ d|%+ d>' 1 -1 1 -1 1 -1 1 -1
+	t '<%o|%#o><%x|%#x><%X|%#X>' 8 9 10 11 12 13
+	#XXX replace with below
+	t '|%3d|%-3d|%+3d|%-+3d|%03d|%-03d|%3d|%.3d|notyet|' \
+	    1 2 3 4 5 6 7777 8
+	#t '|%3d|%-3d|%+3d|%-+3d|%03d|%-03d|%3d|%.3d|%5.3d|' \
+	#    1 2 3 4 5 6 7777 8 9
+	#12 |  1|2  | +3|+4 |005|6  |7777|008|  009| : 0
+expected-stdout:
+	1 <a><b	c> : 0
+	2 3 -   0 0 0 0 0 0  : 0
+	3 % 7 73 74 75 114 77 4e 4F : 0
+	4 \
+	
	
+	34 : 0
+	7 \
+	
	S4 : 0
+	9 <1><2><-3><26><27><8><-9><10><49><50> : 0
+	10 <1|-1><+1|-1>< 1|-1><+1|-1> : 0
+	11 <10|011><a|0xb><C|0XD> : 0
+	12 |  1|2  | +3|+4 |005|6  |7777|008|notyet| : 0
+---
+name: exit-trap-noninteractive
+description:
+	Check that !interactive shell does exit via EXIT trap on syntax error
+info-post: that was the last test
+file-setup: file 644 "t1"
+	<
+	echo in=$?
+file-setup: file 644 "t2"
+	trap -- EXIT
+	<
+	echo in=$?
+file-setup: file 644 "t3"
+	trap "echo tEXITrap" EXIT
+	<
+	echo in=$?
+stdin:
+	exec 2>se
+	echo "A 1["$("$__progname" t1; echo "]=$?")" 2["$("$__progname" t2; echo "]=$?")" 3["$("$__progname" t3; echo "]=$?")
+	echo "B 1["$("$__progname" -c '. ./t1; echo xd=$?'; echo "]=$?")" 2["$("$__progname" -c '. ./t2; echo xd=$?'; echo "]=$?")" 3["$("$__progname" -c '. ./t3; echo xd=$?'; echo "]=$?")
+	echo "C 1["$("$__progname" -c 'command . ./t1; echo xd=$?'; echo "]=$?")" 2["$("$__progname" -c 'command . ./t2; echo xd=$?'; echo "]=$?")" 3["$("$__progname" -c 'command . ./t3; echo xd=$?'; echo "]=$?")
+	exec 2>&1
+	cnt=0
+	while IFS= read -r line; do
+		[[ $line = *'syntax error'*'syntax error'* ]] && exit 4
+		[[ $line = *'syntax error'* ]] || exit 5
+		let ++count
+	done <se
+	(( count != 9 )) || echo 'stderr ok'
+expected-stdout:
+	A 1[]=1 2[]=1 3[tEXITrap ]=1
+	B 1[]=1 2[]=1 3[tEXITrap ]=1
+	C 1[]=1 2[]=1 3[tEXITrap ]=1
+	stderr ok
+---
--- mksh-59c.orig/dot.mkshrc
+++ mksh-59c/dot.mkshrc
@@ -1,10 +1,11 @@
+# -*- mode: sh -*-
 # $Id$
-# $MirOS: src/bin/mksh/dot.mkshrc,v 1.128 2020/04/13 18:39:03 tg Exp $
+# $MirOS: src/bin/mksh/dot.mkshrc,v 1.145 2025/04/25 23:14:53 tg Exp $
 #-
 # Copyright (c) 2002, 2003, 2004, 2006, 2007, 2008, 2009, 2010,
 #		2011, 2012, 2013, 2014, 2015, 2016, 2017, 2019,
-#		2020
-#	mirabilos <m@mirbsd.org>
+#		2020, 2021, 2022, 2023
+#	mirabilos <m$(date +%Y)@mirbsd.de>
 #
 # Provided that these terms and disclaimer and all copyright notices
 # are retained or reproduced in an accompanying document, permission
@@ -22,6 +23,7 @@
 # of said person's immediate fault when using the work as intended.
 #-
 # ${ENV:-~/.mkshrc}: mksh initialisation file for interactive shells
+# (see also FAQ.htm for more scripting examples)
 
 # catch non-mksh, non-lksh, trying to run this file
 case ${KSH_VERSION:-} in
@@ -38,24 +40,57 @@ function setenv {
 	fi
 }
 
+# internal helper function to cat all arguments if necessary
+function _dot_mkshrc_wrapped_cat {
+	\\builtin typeset fn=$1
+	\\builtin shift
+
+	if [[ $# = 0 || $#,$1 = 1,- ]]; then
+		"$fn"
+	else
+		\cat "$@" | "$fn"
+	fi
+}
+function _dot_mkshrc_cat_for_readNa {
+	\\builtin typeset fn=$1 s
+	\\builtin shift
+
+	if (( $# )); then
+		\\builtin read -raN-1 s <<<"$*" || \\builtin return $?
+		\\builtin unset s[${#s[*]}-1]
+	elif [[ -t 0 ]]; then
+		s=$(\cat || \\builtin exit $?; \\builtin print .) || \
+		    \\builtin return $?
+		\\builtin read -raN-1 s <<<"$s" || \\builtin return $?
+		\\builtin unset s[${#s[*]}-1]
+		\\builtin unset s[${#s[*]}-1]
+	else
+		\\builtin read -raN-1 s || \\builtin return $?
+	fi
+	"$fn"
+}
+
 # pager (not control character safe)
-smores() (
-	\\builtin set +m
-	\\builtin cat "$@" |&
-	\\builtin trap "rv=\$?; \\\\builtin kill $! >/dev/null 2>&1; \\\\builtin exit \$rv" EXIT
-	while IFS= \\builtin read -pr line; do
+function smores {
+	\_dot_mkshrc_wrapped_cat _dot_mkshrc_smores "$@"
+}
+function _dot_mkshrc_smores {
+	\\builtin set +e
+	\\builtin typeset line llen curlin=0 x
+
+	while IFS= \\builtin read -r line; do
 		llen=${%line}
-		(( llen == -1 )) && llen=${#line}
+		(( llen != -1 )) || llen=${#line}
 		(( llen = llen ? (llen + COLUMNS - 1) / COLUMNS : 1 ))
 		if (( (curlin += llen) >= LINES )); then
 			\\builtin print -nr -- $'\e[7m--more--\e[0m'
-			\\builtin read -u1 || \\builtin exit $?
-			[[ $REPLY = [Qq]* ]] && \\builtin exit 0
+			\\builtin read -u1 x || \\builtin return $?
+			[[ $x != [Qq]* ]] || \\builtin return 0
 			curlin=$llen
 		fi
 		\\builtin print -r -- "$line"
 	done
-)
+}
 
 # customise your favourite editor here; the first one found is used
 for EDITOR in "${EDITOR:-}" jupp jstar mcedit ed vi; do
@@ -82,10 +117,10 @@ fi
 
 # prompts
 PS4='[$EPOCHREALTIME] '; PS1='#'; (( USER_ID )) && PS1='$'; PS1=$'\001\r''${|
-	\\builtin typeset e=$?
+	\\builtin typeset e=$? hn=${HOSTNAME:-nil}
 
-	(( e )) && REPLY+="$e|"
-	REPLY+=${USER}@${HOSTNAME%%.*}:
+	(( !!e )) || REPLY+="$e|"
+	REPLY+=${USER:-?}@${hn%%.*}:
 
 	\\builtin typeset d=${PWD:-?}/ p=~; [[ $p = ?(*/) ]] || d=${d/#$p\//\~/}
 	d=${d%/}; \\builtin typeset m=${%d} n p=...; (( m > 0 )) || m=${#d}
@@ -104,12 +139,13 @@ if \\builtin command -v hd >/dev/null; t
 	\:
 elif \\builtin command -v hexdump >/dev/null; then
 	function hd {
-		hexdump -e '"%08.8_ax  " 8/1 "%02X " " - " 8/1 "%02X "' \
+		\hexdump -e '"%08.8_ax  " 8/1 "%02X " " - " 8/1 "%02X "' \
 		    -e '"  |" "%_p"' -e '"|\n"' "$@"
 	}
 else
 	function hd {
-		\\builtin cat "$@" | hd_mksh
+		# cannot use _dot_mkshrc_wrapped_cat as hd_mksh sets stdin raw
+		\cat "$@" | \hd_mksh
 	}
 fi
 
@@ -118,7 +154,7 @@ function hd_mksh {
 	\\builtin typeset -Uui16 -Z11 pos=0
 	\\builtin typeset -Uui16 -Z5 hv=2147483647
 	\\builtin typeset dasc dn line i
-	\\builtin set +U
+	\\builtin set +Ue
 
 	while \\builtin read -arn 512 line; do
 		\\builtin typeset -i1 'line[*]'
@@ -219,6 +255,7 @@ function cd_csh {
 	\cd "$t"
 }
 function dirs {
+	\\builtin set +e
 	\\builtin typeset d dwidth
 	\\builtin typeset -i fl=0 fv=0 fn=0 cpos=0
 
@@ -343,50 +380,56 @@ function pushd {
 
 # base64 encoder and decoder, RFC compliant, NUL safe, not EBCDIC safe
 function Lb64decode {
-	\\builtin set +U
-	\\builtin typeset c s="$*" t
-	[[ -n $s ]] || { s=$(\\builtin cat; \\builtin print x); s=${s%x}; }
-	\\builtin typeset -i i=0 j=0 n=${#s} p=0 v x
+	\\builtin set +Ue
+	\\builtin typeset c s t
+	if (( $# )); then
+		s="$*"
+	elif [[ -t 0 ]]; then
+		s=$(\cat || \\builtin exit $?; \\builtin print .) || \
+		    \\builtin return $?
+		s=${s%.}
+	else
+		\\builtin read -rN-1 s || \\builtin return $?
+	fi
+	\\builtin typeset -i i=-1 j=0 n=${#s} p=0 v x
 	\\builtin typeset -i16 o
 
-	while (( i < n )); do
-		c=${s:(i++):1}
+	while ((# ++i < n )); do
+		c=${s:i:1}
 		case $c {
 		(=)	\\builtin break ;;
-		([A-Z])	(( v = 1#$c - 65 )) ;;
-		([a-z])	(( v = 1#$c - 71 )) ;;
-		([0-9])	(( v = 1#$c + 4 )) ;;
+		([A-Z])	((# v = 1#$c - 65 )) ;;
+		([a-z])	((# v = 1#$c - 71 )) ;;
+		([0-9])	((# v = 1#$c + 4 )) ;;
 		(+)	v=62 ;;
 		(/)	v=63 ;;
 		(*)	\\builtin continue ;;
 		}
-		(( x = (x << 6) | v ))
+		((# x = (x << 6) | v ))
 		case $((p++)) {
 		(0)	\\builtin continue ;;
-		(1)	(( o = (x >> 4) & 255 )) ;;
-		(2)	(( o = (x >> 2) & 255 )) ;;
-		(3)	(( o = x & 255 ))
+		(1)	((# o = (x >> 4) & 255 )) ;;
+		(2)	((# o = (x >> 2) & 255 )) ;;
+		(3)	((# o = x & 255 ))
 			p=0
 			;;
 		}
 		t+=\\x${o#16#}
-		(( ++j & 4095 )) && \\builtin continue
-		\\builtin print -n $t
+		((# ++j & 4095 )) && \\builtin continue
+		\\builtin print -n -- "$t"
 		t=
 	done
-	\\builtin print -n $t
+	\\builtin print -n -- "$t"
 }
 function Lb64encode {
 	\\builtin set +U
-	\\builtin typeset c s t table
+	\_dot_mkshrc_cat_for_readNa _dot_mkshrc_b64encode "$@"
+}
+function _dot_mkshrc_b64encode {
+	\\builtin set +e
+	\\builtin typeset c t table
 	\\builtin set -A table -- A B C D E F G H I J K L M N O P Q R S T U V W X Y Z \
 	    a b c d e f g h i j k l m n o p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9 + /
-	if (( $# )); then
-		\\builtin read -raN-1 s <<<"$*"
-		\\builtin unset s[${#s[*]}-1]
-	else
-		\\builtin read -raN-1 s
-	fi
 	\\builtin typeset -i i=0 n=${#s[*]} v
 
 	while (( i < n )); do
@@ -403,34 +446,34 @@ function Lb64encode {
 			t+===
 		fi
 		if (( ${#t} == 76 || i >= n )); then
-			\\builtin print -r $t
+			\\builtin print -r -- "$t"
 			t=
 		fi
 	done
+	\:
 }
 
-# Better Avalanche for the Jenkins Hash
+# Better Avalanche for the Jenkins Hash, IV=1 INC=0
 \\builtin typeset -Z11 -Uui16 Lbafh_v
 function Lbafh_init {
-	Lbafh_v=0
+	Lbafh_v=1
 }
 function Lbafh_add {
 	\\builtin set +U
-	\\builtin typeset s
-	if (( $# )); then
-		\\builtin read -raN-1 s <<<"$*"
-		\\builtin unset s[${#s[*]}-1]
-	else
-		\\builtin read -raN-1 s
-	fi
+	\_dot_mkshrc_cat_for_readNa _dot_mkshrc_bafh_add "$@"
+}
+function _dot_mkshrc_bafh_add {
+	\\builtin set +e
 	\\builtin typeset -i i=0 n=${#s[*]}
 
 	while (( i < n )); do
-		((# Lbafh_v = (Lbafh_v + s[i++] + 1) * 1025 ))
+		((# Lbafh_v = (Lbafh_v + s[i++]) * 1025 ))
 		((# Lbafh_v ^= Lbafh_v >> 6 ))
 	done
+	\:
 }
 function Lbafh_finish {
+	\\builtin set +e
 	\\builtin typeset -Ui t
 
 	((# t = (((Lbafh_v >> 7) & 0x01010101) * 0x1B) ^ \
@@ -443,11 +486,20 @@ function Lbafh_finish {
 # strip comments (and leading/trailing whitespace if IFS is set) from
 # any file(s) given as argument, or stdin if none, and spew to stdout
 function Lstripcom {
+	\_dot_mkshrc_wrapped_cat _dot_mkshrc_stripcom "$@"
+}
+function _dot_mkshrc_stripcom {
+	\\builtin typeset line x
 	\\builtin set -o noglob
-	\\builtin cat "$@" | while \\builtin read _line; do
-		_line=${_line%%#*}
-		[[ -n $_line ]] && \\builtin print -r -- $_line
+	while \\builtin read -r line; do
+		while [[ $line = *\\ && $line != *'#'* ]] && \
+		    \\builtin read -r x; do
+			line=${line%\\}$x
+		done
+		line=${line%%#*}
+		[[ -z $line ]] || \\builtin print -r -- $line
 	done
+	\:
 }
 
 # toggle built-in aliases and utilities, and aliases and functions from mkshrc
@@ -479,7 +531,6 @@ function enable {
 	i_func[nfunc++]=break
 	# \\builtin cannot, by design, be overridden
 	i_func[nfunc++]=builtin
-	i_func[nfunc++]=cat
 	i_func[nfunc++]=cd
 	i_func[nfunc++]=chdir
 	i_func[nfunc++]=command
@@ -522,8 +573,6 @@ function enable {
 	i_func[nfunc++]=bind
 	i_func[nfunc++]=mknod
 	i_func[nfunc++]=printf
-	i_func[nfunc++]=sleep
-	i_func[nfunc++]=domainname
 	i_func[nfunc++]=extproc
 
 	# accumulate aliases from dot.mkshrc, in definition order
@@ -585,7 +634,7 @@ function enable {
 		(*)
 			\\builtin print -ru2 enable: usage: \
 			    "enable [-adnps] [-f filename] [name ...]"
-			return 2
+			\\builtin return 2
 			;;
 		}
 	done
@@ -595,7 +644,7 @@ function enable {
 	if (( doprnt || ($# == 0) )); then
 		for x in "${i_all[@]}"; do
 			y=$(\\builtin alias "$x") || y=
-			[[ $y = "$x='\\\\builtin whence -p $x >/dev/null || (\\\\builtin print -r mksh: $x: not found; \\\\builtin exit 127) && \$(\\\\builtin whence -p $x)'" ]]; z=$?
+			[[ $y = "$x='\\\\builtin whence -p $x >/dev/null || (\\\\builtin print -ru2 E: mksh: $x: inaccessible or not found; \\\\builtin exit 127) && \$(\\\\builtin whence -p $x)'" ]]; z=$?
 			case $mode:$z {
 			(-1:0|0:0)
 				\\builtin print -r -- "enable -n $x"
@@ -622,7 +671,7 @@ function enable {
 		fi
 		if (( !mode )); then
 			# disable this
-			\\builtin alias "$x=\\\\builtin whence -p $x >/dev/null || (\\\\builtin print -r mksh: $x: not found; \\\\builtin exit 127) && \$(\\\\builtin whence -p $x)"
+			\\builtin alias "$x=\\\\builtin whence -p $x >/dev/null || (\\\\builtin print -ru2 E: mksh: $x: inaccessible or not found; \\\\builtin exit 127) && \$(\\\\builtin whence -p $x)"
 		else
 			# find out if this is an alias or not, first
 			z=0
@@ -647,11 +696,11 @@ function enable {
 \: place customisations below this line
 
 # some defaults / samples which you are supposed to adjust to your
-# liking; by default we add ~/.etc/bin and ~/bin (whichever exist)
+# liking; by default we add user-local bin directories which exist
 # to $PATH, set $SHELL to mksh, set some defaults for man and less
 # and show a few more possible things for users to begin moving in
 
-for p in ~/.etc/bin ~/bin; do
+for p in ~/bin ~/.local/bin ~/.etc/bin; do
 	[[ -d $p/. ]] || \\builtin continue
 	[[ $PATHSEP$PATH$PATHSEP = *"$PATHSEP$p$PATHSEP"* ]] || \
 	    PATH=$p$PATHSEP$PATH
--- mksh-59c.orig/edit.c
+++ mksh-59c/edit.c
@@ -6,8 +6,8 @@
 /*-
  * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
  *		 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018,
- *		 2019, 2020
- *	mirabilos <m@mirbsd.org>
+ *		 2019, 2020, 2021, 2022, 2025
+ *	mirabilos <m$(date +%Y)@mirbsd.de>
  *
  * Provided that these terms and disclaimer and all copyright notices
  * are retained or reproduced in an accompanying document, permission
@@ -29,7 +29,7 @@
 
 #ifndef MKSH_NO_CMDLINE_EDITING
 
-__RCSID("$MirOS: src/bin/mksh/edit.c,v 1.357 2020/10/31 05:02:17 tg Exp $");
+__RCSID("$MirOS: src/bin/mksh/edit.c,v 1.405 2025/12/23 21:49:51 tg Exp $");
 
 /*
  * in later versions we might use libtermcap for this, but since external
@@ -58,14 +58,8 @@ static struct {
 } edchars;
 
 #define isched(x,e) ((unsigned short)(unsigned char)(x) == (e))
-#define isedchar(x) (!((x) & ~0xFF))
-#ifndef _POSIX_VDISABLE
-#define toedchar(x) ((unsigned short)(unsigned char)(x))
-#else
-#define toedchar(x) (((_POSIX_VDISABLE != -1) && ((x) == _POSIX_VDISABLE)) ? \
-			((unsigned short)EDCHAR_DISABLED) : \
-			((unsigned short)(unsigned char)(x)))
-#endif
+#define isedchar(x) (!((x) & ~0xFFU))
+#define toedchar(x) ((unsigned short)KSH_ISVDIS(x, EDCHAR_DISABLED))
 
 /* x_cf_glob() flags */
 #define XCF_COMMAND	BIT(0)	/* Do command completion */
@@ -74,6 +68,7 @@ static struct {
 #define XCF_COMMAND_FILE (XCF_COMMAND | XCF_FILE)
 #define XCF_IS_COMMAND	BIT(3)	/* return flag: is command */
 #define XCF_IS_NOSPACE	BIT(4)	/* return flag: do not append a space */
+#define XCF_IS_HOMEDIR	BIT(5)	/* return flag: tilde needs slash */
 
 static char editmode;
 static int xx_cols;			/* for Emacs mode */
@@ -81,28 +76,32 @@ static int modified;			/* buffer has bee
 static char *holdbufp;			/* place to hold last edit buffer */
 
 /* 0=dumb 1=tmux (for now) */
-static uint8_t x_term_mode;
+static kby x_term_mode;
 
 static void x_adjust(void);
 static int x_getc(void);
 static void x_putcf(int);
 static void x_modified(void);
-static void x_mode(bool);
+static void x_mode(Wahr);
 static int x_do_comment(char *, ssize_t, ssize_t *);
-static void x_print_expansions(int, char * const *, bool);
+static void x_print_expansions(int, char * const *, Wahr);
 static int x_cf_glob(int *, const char *, int, int, int *, int *, char ***);
 static size_t x_longest_prefix(int, char * const *);
-static void x_glob_hlp_add_qchar(char *);
-static char *x_glob_hlp_tilde_and_rem_qchar(char *, bool);
+static char *x_glob_hlp_add_qchar(char *);
+static char *x_glob_hlp_tilde_and_rem_qchar(char *, Wahr);
 static size_t x_basename(const char *, const char *);
 static void x_free_words(int, char **);
 static int x_escape(const char *, size_t, int (*)(const char *, size_t));
-static int x_emacs(char *);
-static void x_init_prompt(bool);
+static ssize_t x_emacs(char *);
+#ifdef DF
+static void x_emacs_DF(const char *);
+#endif
+static void x_init_prompt(Wahr);
 #if !MKSH_S_NOVI
-static int x_vi(char *);
+static ssize_t x_vi(char *);
 #endif
 static void x_intr(int, int) MKSH_A_NORETURN;
+static void x_clrtoeol(int, Wahr);
 
 #define x_flush()	shf_flush(shl_out)
 #if defined(MKSH_SMALL) && !defined(MKSH_SMALL_BUT_FAST)
@@ -116,7 +115,7 @@ static void glob_table(const char *, XPt
 static void glob_path(int, const char *, XPtrV *, const char *);
 static int x_file_glob(int *, char *, char ***);
 static int x_command_glob(int, char *, char ***);
-static int x_locate_word(const char *, int, int, int *, bool *);
+static int x_locate_word(const char *, int, int, int *, Wahr *);
 
 static int x_e_getmbc(char *);
 
@@ -125,12 +124,12 @@ static int x_e_getmbc(char *);
 /*
  * read an edited command line
  */
-int
+char *
 x_read(char *buf)
 {
-	int i;
+	ssize_t i;
 
-	x_mode(true);
+	x_mode(Ja);
 	modified = 1;
 	if (Flag(FEMACS) || Flag(FGMACS))
 		i = x_emacs(buf);
@@ -142,8 +141,13 @@ x_read(char *buf)
 		/* internal error */
 		i = -1;
 	editmode = 0;
-	x_mode(false);
-	return (i);
+	x_mode(Nee);
+	if (i < 0) {
+		/* pdksh had no error handling here, just return null */
+		return (buf);
+	}
+	buf += i;
+	return (buf);
 }
 
 /* tty I/O */
@@ -157,9 +161,17 @@ x_getc(void)
 	char c;
 	ssize_t n;
 
-	while ((n = blocking_read(0, &c, 1)) < 0 && errno == EINTR)
+	while ((n = blocking_read(0, &c, 1)) < 0) {
+		if (errno != EINTR) {
+			editmode = 0;
+			x_mode(Nee);
+			x_putc('\n');
+			kwarnf(KWF_ERR(128) | KWF_PREFIX | KWF_FILELINE |
+			    KWF_BUILTIN | KWF_ONEMSG | KWF_BIUNWIND, Trderr);
+			unwind(LRDERR);
+		}
 		if (trap) {
-			x_mode(false);
+			x_mode(Nee);
 			runtraps(0);
 #ifdef SIGWINCH
 			if (got_winch) {
@@ -167,13 +179,14 @@ x_getc(void)
 				if (x_cols != xx_cols && editmode == 1) {
 					/* redraw line in Emacs mode */
 					xx_cols = x_cols;
-					x_init_prompt(false);
+					x_init_prompt(Nee);
 					x_adjust();
 				}
 			}
 #endif
-			x_mode(true);
+			x_mode(Ja);
 		}
+	}
 	return ((n == 1) ? (int)(unsigned char)c : -1);
 #endif
 }
@@ -208,7 +221,7 @@ x_do_comment(char *buf, ssize_t bsize, s
 
 	/* Already commented? */
 	if (buf[0] == '#') {
-		bool saw_nl = false;
+		Wahr saw_nl = Nee;
 
 		for (j = 0, i = 1; i < len; i++) {
 			if (!saw_nl || buf[i] != '#')
@@ -243,12 +256,14 @@ x_do_comment(char *buf, ssize_t bsize, s
  ****************************************************/
 
 static void
-x_print_expansions(int nwords, char * const *words, bool is_command)
+x_print_expansions(int nwords, char * const *words, Wahr is_command)
 {
-	bool use_copy = false;
-	size_t prefix_len;
-	XPtrV l = { NULL, 0, 0 };
+	int i;
+	char **w;
+	size_t prefix_len = 0;
+	Wahr prefix_trim = Nee;
 	struct columnise_opts co;
+	struct shf S;
 
 	/*
 	 * Check if all matches are in the same directory (in this
@@ -256,8 +271,6 @@ x_print_expansions(int nwords, char * co
 	 */
 	if (!is_command &&
 	    (prefix_len = x_longest_prefix(nwords, words)) > 0) {
-		int i;
-
 		/* Special case for 1 match (prefix is whole word) */
 		if (nwords == 1)
 			prefix_len = x_basename(words[0], NULL);
@@ -271,66 +284,70 @@ x_print_expansions(int nwords, char * co
 			while (prefix_len > 0 &&
 			    !mksh_cdirsep(words[0][prefix_len - 1]))
 				prefix_len--;
-			use_copy = true;
-			XPinit(l, nwords + 1);
-			for (i = 0; i < nwords; i++)
-				XPput(l, words[i] + prefix_len);
-			XPput(l, NULL);
+			prefix_trim = Ja;
 		}
 	}
 	/*
+	 * Escape words, trimming prefix_len if needed
+	 */
+	if (!prefix_trim)
+		prefix_len = 0;
+	w = alloc2((kui)nwords + 1U, sizeof(char *), ATEMP);
+	for (i = 0; i < nwords; ++i) {
+		shf_sopen(NULL, 0, SHF_WR | SHF_DYNAMIC, &S);
+		uprntmbs(words[i] + prefix_len, Nee, &S);
+		w[i] = shf_sclose(&S);
+	}
+	w[nwords] = NULL;
+
+	/*
 	 * Enumerate expansions
 	 */
 	x_putc('\r');
 	x_putc('\n');
 	co.shf = shl_out;
 	co.linesep = '\n';
-	co.do_last = true;
-	co.prefcol = false;
-	pr_list(&co, use_copy ? (char **)XPptrv(l) : words);
-
-	if (use_copy)
-		/* not x_free_words() */
-		XPfree(l);
+	co.do_last = Ja;
+	co.prefcol = Nee;
+	pr_list(&co, w);
+	x_free_words(nwords, w);
 }
 
 /*
  * Convert backslash-escaped string to QCHAR-escaped
- * string useful for globbing; loses QCHAR unless it
- * can squeeze in, eg. by previous loss of backslash
+ * string useful for globbing
  */
-static void
+static char *
 x_glob_hlp_add_qchar(char *cp)
 {
-	char ch, *dp = cp;
-	bool escaping = false;
+	char ch, *dp;
+	Wahr escaping = Nee;
+	XString xs;
+	size_t n;
+
+	if (memchr(cp, QCHAR, (n = strlen(cp)))) {
+		Xinit(xs, dp, n, ATEMP);
+	} else {
+		xs.len = n + 1;
+		xs.areap = NULL; /* won’t be used */
+		xs.beg = dp = cp;
+		xs.end = xs.beg + xs.len;
+	}
 
 	while ((ch = *cp++)) {
 		if (ch == '\\' && !escaping) {
-			escaping = true;
+			escaping = Ja;
 			continue;
 		}
-		if (escaping || (ch == QCHAR && (cp - dp) > 1)) {
-			/*
-			 * empirically made list of chars to escape
-			 * for globbing as well as QCHAR itself
-			 */
-			switch (ord(ch)) {
-			case QCHAR:
-			case ORD('$'):
-			case ORD('*'):
-			case ORD('?'):
-			case ORD('['):
-			case ORD('\\'):
-			case ORD('`'):
-				*dp++ = QCHAR;
-				break;
-			}
-			escaping = false;
-		}
+		/* coverity[var_deref_model : SUPPRESS] */
+		XcheckN(xs, dp, 2);
+		if ((escaping && ctype(ch, C_EDGLB)) || ch == QCHAR)
+			*dp++ = QCHAR;
+		escaping = Nee;
 		*dp++ = ch;
 	}
 	*dp = '\0';
+	return (Xstring(xs, dp));
 }
 
 /*
@@ -340,7 +357,7 @@ x_glob_hlp_add_qchar(char *cp)
  * it is assumed QCHAR-escaped
  */
 static char *
-x_glob_hlp_tilde_and_rem_qchar(char *s, bool magic_flag)
+x_glob_hlp_tilde_and_rem_qchar(char *s, Wahr magic_flag)
 {
 	char ch, *cp, *dp;
 
@@ -349,7 +366,7 @@ x_glob_hlp_tilde_and_rem_qchar(char *s,
 	 * and if so, discern "~foo/bar" and "~/baz" from "~blah";
 	 * if we have a directory part (the former), try to expand
 	 */
-	if (*s == '~' && (cp = /* not sdirsep */ strchr(s, '/')) != NULL) {
+	if (*s == '~' && (cp = /* not sdirsep */ ucstrchr(s, '/')) != NULL) {
 		/* ok, so split into "~foo"/"bar" or "~"/"baz" */
 		*cp++ = 0;
 		/* try to expand the tilde */
@@ -366,8 +383,12 @@ x_glob_hlp_tilde_and_rem_qchar(char *s,
 	}
 
 	/* ... convert it from backslash-escaped via QCHAR-escaped... */
-	if (magic_flag)
-		x_glob_hlp_add_qchar(s);
+	if (magic_flag) {
+		cp = x_glob_hlp_add_qchar(s);
+		if (cp != s)
+			afree(s, ATEMP);
+		s = cp;
+	}
 	/* ... to unescaped, for comparison with the matches */
 	cp = dp = s;
 
@@ -390,25 +411,27 @@ x_glob_hlp_tilde_and_rem_qchar(char *s,
 static int
 x_file_glob(int *flagsp, char *toglob, char ***wordsp)
 {
-	char **words, *cp;
+	char **words, *cp, *qglob;
 	int nwords;
 	XPtrV w;
 	struct source *s, *sold;
 
 	/* remove all escaping backward slashes */
-	x_glob_hlp_add_qchar(toglob);
+	qglob = x_glob_hlp_add_qchar(toglob);
 
 	/*
 	 * Convert "foo*" (toglob) to an array of strings (words)
 	 */
 	sold = source;
 	s = pushs(SWSTR, ATEMP);
-	s->start = s->str = toglob;
+	s->start = s->str = qglob;
 	source = s;
 	if (yylex(ONEWORD | LQCHAR) != LWORD) {
 		source = sold;
-		internal_warningf(Tfg_badsubst);
-		return (0);
+		kwarnf(KWF_INTERNAL | KWF_WARNING | KWF_ONEMSG | KWF_NOERRNO,
+		    Tfg_badsubst);
+		nwords = 0;
+		goto out;
 	}
 	source = sold;
 	afree(s, ATEMP);
@@ -425,15 +448,17 @@ x_file_glob(int *flagsp, char *toglob, c
 	}
 	expand(yylval.cp, &w, nwords);
 	XPput(w, NULL);
-	words = (char **)XPclose(w);
+	nwords = 0;
+	while (XPptrv(w)[nwords])
+		++nwords;
+	/* XPclose(w) except for nwords plus a trailing NULL for pr_list */
+	words = aresize2(XPptrv(w), (kui)nwords + 1U, sizeof(void *), ATEMP);
 
-	for (nwords = 0; words[nwords]; nwords++)
-		;
 	if (nwords == 1) {
 		struct stat statb;
 
 		/* Expand any tilde and drop all QCHAR for comparison */
-		toglob = x_glob_hlp_tilde_and_rem_qchar(toglob, false);
+		qglob = x_glob_hlp_tilde_and_rem_qchar(qglob, Nee);
 
 		/*
 		 * Check if globbing failed (returned glob pattern),
@@ -443,7 +468,7 @@ x_file_glob(int *flagsp, char *toglob, c
 		 * to glob something which evaluated to an empty
 		 * string (e.g., "$FOO" when there is no FOO, etc).
 		 */
-		if ((strcmp(words[0], toglob) == 0 &&
+		if ((strcmp(words[0], qglob) == 0 &&
 		    stat(words[0], &statb) < 0) ||
 		    words[0][0] == '\0') {
 			x_free_words(nwords, words);
@@ -455,6 +480,9 @@ x_file_glob(int *flagsp, char *toglob, c
 	if ((*wordsp = nwords ? words : NULL) == NULL && words != NULL)
 		x_free_words(nwords, words);
 
+ out:
+	if (qglob != toglob)
+		afree(qglob, ATEMP);
 	return (nwords);
 }
 
@@ -562,14 +590,14 @@ x_command_glob(int flags, char *toglob,
 
 static int
 x_locate_word(const char *buf, int buflen, int pos, int *startp,
-    bool *is_commandp)
+    Wahr *is_commandp)
 {
 	int start, end;
 
 	/* Bad call? Probably should report error */
 	if (pos < 0 || pos > buflen) {
 		*startp = pos;
-		*is_commandp = false;
+		*is_commandp = Nee;
 		return (0);
 	}
 	/* The case where pos == buflen happens to take care of itself... */
@@ -589,7 +617,7 @@ x_locate_word(const char *buf, int bufle
 	}
 
 	if (is_commandp) {
-		bool iscmd;
+		Wahr iscmd;
 		int p = start - 1;
 
 		/* Figure out if this is a command */
@@ -620,11 +648,11 @@ x_cf_glob(int *flagsp, const char *buf,
 {
 	int len, nwords = 0;
 	char **words = NULL;
-	bool is_command;
+	Wahr is_command;
 
 	len = x_locate_word(buf, buflen, pos, startp, &is_command);
 	if (!((*flagsp) & XCF_COMMAND))
-		is_command = false;
+		is_command = Nee;
 	/*
 	 * Don't do command globing on zero length strings - it takes too
 	 * long and isn't very useful. File globs are more likely to be
@@ -670,7 +698,7 @@ x_cf_glob(int *flagsp, const char *buf,
 
 		if (*toglob == '~' && /* not vdirsep */ !vstrchr(toglob, '/')) {
 			/* neither for '~foo' (but '~foo/bar') */
-			*flagsp |= XCF_IS_NOSPACE;
+			*flagsp |= XCF_IS_HOMEDIR;
 			goto dont_add_glob;
 		}
 
@@ -782,7 +810,7 @@ glob_table(const char *pat, XPtrV *wp, s
 
 	ktwalk(&ts, tp);
 	while ((te = ktnext(&ts)))
-		if (gmatchx(te->name, pat, false)) {
+		if (gmatchx(te->name, pat, Nee)) {
 			char *cp;
 
 			strdupx(cp, te->name, ATEMP);
@@ -829,7 +857,7 @@ glob_path(int flags, const char *pat, XP
 
 		oldsize = XPsize(*wp);
 		/* mark dirs */
-		glob_str(Xstring(xs, xp), wp, true);
+		glob_str(Xstring(xs, xp), wp, Ja);
 		newsize = XPsize(*wp);
 
 		/* Check that each match is executable... */
@@ -886,9 +914,63 @@ x_escape(const char *s, size_t len, int
 	return (rval);
 }
 
-
 /* +++ emacs editing mode +++ */
 
+/*-
+ * The input buffer "buf" is pointed to by "xbuf" and its end is
+ * pointed to by "xend".  The current position in "xbuf" and end of
+ * the edit line are pointed to by "xcp" and "xep" respectively.
+ * "xbp" points to the start of a display window within "xbuf", and
+ * "xlp" points to the last visible character on screen, if valid;
+ * "xdp" points to the end of x_displen, adding one-column bytes if
+ * necessary when the input line is shorter.
+ *
+ * [A] starting position
+ *
+ *      buf
+ * |<--------- $COLUMNS -------->|
+ *      |<---- x_displen ------->|
+ *  PS1 |
+ *      +=====+=========+........+.............................+
+ *      |\     \        |\        \                             \
+ *   xbuf xbp   xcp   xlp xep      xdp                           xend
+ *
+ * [B] larger input line
+ *
+ *      buf
+ * |<--------- $COLUMNS -------->|
+ *      |<---- x_displen ------->|
+ *  PS1 |
+ *      +===========+============+---------------------+.......+
+ *      |\          \             \                     \       \
+ *   xbuf xbp        xcp           xlp=xdp               xep     xend
+ *
+ * [C] scrolled
+ *
+ *      buf
+ *      |       |<--------- $COLUMNS -------->|
+ *      |       |<--------- x_displen ------->|
+ *      |
+ *      +-------+==============+==============+--------+.......+
+ *      |        \              \              \        \       \
+ *   xbuf         xbp            xcp            xlp=xdp  xep     xend
+ *
+ * In the above -------- represents the current edit line while
+ * ===== represents that portion which is visible on the screen;
+ * ....... is unused space in buf. Note that initially xbp == xbuf
+ * and PS1 is displayed. PS1 uses some of the screen width and thus
+ * "x_displen" is less than $COLUMNS.
+ *
+ * Any time that "xcp" moves outside the region bounded by "xbp"
+ * and "xbp" + "x_displen", the function x_adjust() is called to
+ * relocate "xbp" appropriately and redraw the line.
+ *
+ * Excessive I/O is avoided where possible.  x_goto() for instance
+ * calculates whether the destination is outside the visible
+ * region, and if so simply adjusts "xcp" and calls x_adjust()
+ * directly.  Normally though x_adjust() is called from x_putc().
+ */
+
 static	Area	aedit;
 #define	AEDIT	&aedit		/* area for kill ring and macro defns */
 
@@ -913,9 +995,6 @@ struct x_defbindings {
 #define	XF_NOBIND	2	/* not allowed to bind to function */
 #define	XF_PREFIX	4	/* function sets prefix */
 
-#define X_NTABS		4			/* normal, meta1, meta2, pc */
-#define X_TABSZ		256			/* size of keydef tables etc */
-
 /*-
  * Arguments for do_complete()
  * 0 = enumerate	M-=	complete as much as possible and then list
@@ -937,18 +1016,20 @@ static char *xcp;		/* current position *
 static char *xep;		/* current end */
 static char *xbp;		/* start of visible portion of input buffer */
 static char *xlp;		/* last char visible on screen */
-static bool x_adj_ok;
+static char *xdp;		/* xbuf + x_displen except multibyte-aware */
+static Wahr x_adj_ok;
 /*
  * we use x_adj_done so that functions can tell
  * whether x_adjust() has been called while they are active.
  */
-static int x_adj_done;		/* is incremented by x_adjust() */
+static kby x_adj_done;		/* is incremented by x_adjust() */
 
 static int x_displen;
 static int x_arg;		/* general purpose arg */
-static bool x_arg_defaulted;	/* x_arg not explicitly set; defaulted to 1 */
+static Wahr x_arg_defaulted;	/* x_arg not explicitly set; defaulted to 1 */
 
-static bool xlp_valid;		/* lastvis pointer was recalculated */
+/* indicates both xlp and xdp are valid (x_goto needs the latter) */
+static Wahr xlp_valid;		/* lastvis pointer was recalculated */
 
 static char **x_histp;		/* history position */
 static int x_nextcmd;		/* for newline-and-next */
@@ -956,18 +1037,16 @@ static char **x_histncp;	/* saved x_hist
 static char **x_histmcp;	/* saved x_histp for " */
 static char *xmp;		/* mark pointer */
 static unsigned char x_last_command;
-static unsigned char (*x_tab)[X_TABSZ];	/* key definition */
+static kby x_curprefix;
+static kby *x_btab;		/* bitmap of keys bound by the user */
+static kby *x_ktab;		/* key definitions */
 #ifndef MKSH_SMALL
-static char *(*x_atab)[X_TABSZ];	/* macro definitions */
+static char **x_mtab;		/* macro definitions */
+static char *macroptr;		/* bind key macro active? */
 #endif
-static unsigned char x_bound[(X_TABSZ * X_NTABS + 7) / 8];
 #define KILLSIZE	20
 static char *killstack[KILLSIZE];
 static int killsp, killtp;
-static int x_curprefix;
-#ifndef MKSH_SMALL
-static char *macroptr;		/* bind key macro active? */
-#endif
 #if !MKSH_S_NOVI
 static int winwidth;		/* width of window */
 static char *wbuf[2];		/* window buffers */
@@ -980,17 +1059,22 @@ static int pwidth;		/* width of prompt *
 static int prompt_trunc;	/* how much of prompt to truncate or -1 */
 static int x_col;		/* current column on line */
 
-static int x_ins(const char *);
-static void x_delete(size_t, bool);
-static size_t x_bword(void);
-static size_t x_fword(bool);
+/* normal, prefix1, prefix2, IBM PC, ^V (literal) */
+#define X_NTABS			4U
+#define X_NOTAB			0xFFU
+/* array indicēs; x_btab is inlined, bitmap at only two places */
+#define X_xTABidx(pfx,key)	((KBI(pfx) << 8) | KBI(key))
+#define X_KTAB(pfx,key)		x_ktab[X_xTABidx((pfx), (key))]
+#define X_MTAB(pfx,key)		x_mtab[X_xTABidx((pfx), (key))]
+
+static int x_ins(const void *);
+static void x_delete(size_t, Wahr);
+static void x_bword(kui, Wahr);
+static void x_fword(kui, Wahr);
 static void x_goto(char *);
-static char *x_bs0(char *, char *) MKSH_A_PURE;
 static void x_bs3(char **);
-static int x_size2(char *, char **);
-static void x_zots(char *);
-static void x_zotc3(char **);
-static void x_vi_zotc(int);
+static void x_uescs(char *);
+static void x_uescmb(char **);
 static void x_load_hist(char **);
 static int x_search(const char *, int, int);
 #ifndef MKSH_SMALL
@@ -999,19 +1083,18 @@ static int x_search_dir(int);
 static int x_match(const char *, const char *);
 static void x_redraw(int);
 static void x_push(size_t);
-static void x_bind_showone(int, int);
+static void x_bind_showone(kui, kui);
 static void x_e_ungetc(int);
 static int x_e_getc(void);
-static void x_e_putc2(int);
-static void x_e_putc3(const char **);
+static void x_e_putb(int);
 static void x_e_puts(const char *);
 #ifndef MKSH_SMALL
-static int x_fold_case(int);
+static int x_fold_case(int, kui);
 #endif
 static char *x_lastcp(void);
 static void x_lastpos(void);
 static void do_complete(int, Comp_type);
-static size_t x_nb2nc(size_t) MKSH_A_PURE;
+static size_t x_nb2nc(size_t);
 
 static int unget_char = -1;
 
@@ -1042,6 +1125,12 @@ static struct x_defbindings const x_defb
 	{ XFUNC_mv_bword,		1,	'b'	},
 	{ XFUNC_mv_fword,		1,	'f'	},
 	{ XFUNC_del_fword,		1,	'd'	},
+#ifndef MKSH_SMALL
+	{ XFUNC_del_bbigword,		1,	'H'	},
+	{ XFUNC_mv_bbigword,		1,	'B'	},
+	{ XFUNC_mv_fbigword,		1,	'F'	},
+	{ XFUNC_del_fbigword,		1,	'D'	},
+#endif
 	{ XFUNC_mv_back,		0,  CTRL_B	},
 	{ XFUNC_mv_forw,		0,  CTRL_F	},
 	{ XFUNC_search_char_forw,	0,  CTRL_BC	},
@@ -1079,7 +1168,7 @@ static struct x_defbindings const x_defb
 	{ XFUNC_list_comm,		2,	'?'	},
 	{ XFUNC_list_file,		2,  CTRL_Y	},
 	{ XFUNC_set_mark,		1,	' '	},
-	{ XFUNC_kill_region,		0,  CTRL_W	},
+	{ XFUNC_kill_region,		1,  CTRL_W	},
 	{ XFUNC_xchg_point_mark,	2,  CTRL_X	},
 	{ XFUNC_literal,		0,  CTRL_V	},
 	{ XFUNC_version,		1,  CTRL_V	},
@@ -1096,11 +1185,11 @@ static struct x_defbindings const x_defb
 	{ XFUNC_set_arg,		1,	'8'	},
 	{ XFUNC_set_arg,		1,	'9'	},
 #ifndef MKSH_SMALL
-	{ XFUNC_fold_upper,		1,	'U'	},
+	{ XFUNC_foldb_upper,		1,	'U'	},
 	{ XFUNC_fold_upper,		1,	'u'	},
-	{ XFUNC_fold_lower,		1,	'L'	},
+	{ XFUNC_foldb_lower,		1,	'L'	},
 	{ XFUNC_fold_lower,		1,	'l'	},
-	{ XFUNC_fold_capitalise,	1,	'C'	},
+	{ XFUNC_foldb_capitalise,	1,	'C'	},
 	{ XFUNC_fold_capitalise,	1,	'c'	},
 #endif
 	/*
@@ -1114,6 +1203,7 @@ static struct x_defbindings const x_defb
 	{ XFUNC_next_com,		2,	'B'	},
 	{ XFUNC_mv_forw,		2,	'C'	},
 	{ XFUNC_mv_back,		2,	'D'	},
+	{ XFUNC_newline,		2,	'M'	},
 #ifndef MKSH_SMALL
 	{ XFUNC_vt_hack,		2,	'1'	},
 	{ XFUNC_mv_beg | 0x80,		2,	'7'	},
@@ -1158,7 +1248,7 @@ x_nb2nc(size_t nb)
 	size_t nc = 0;
 
 	for (cp = xcp; cp < (xcp + nb); ++nc)
-		cp += utf_ptradj(cp);
+		cp += ez_mbtoc(NULL, cp);
 	return (nc);
 }
 
@@ -1175,39 +1265,45 @@ x_modified(void)
 #ifdef MKSH_SMALL
 #define XFUNC_VALUE(f) (f)
 #else
-#define XFUNC_VALUE(f) (f & 0x7F)
+#define XFUNC_VALUE(f) (f & 0x7FU)
 #endif
 
 static int
-x_e_getmbc(char *sbuf)
+x_e_getmbc(char *buf)
 {
-	int c, pos = 0;
-	unsigned char *buf = (unsigned char *)sbuf;
+	int c, pos;
+	kby f;
 
-	memset(buf, 0, 4);
-	buf[pos++] = c = x_e_getc();
-	if (c == -1)
+	if ((c = x_e_getc()) == -1)
 		return (-1);
-	if (UTFMODE) {
-		if ((rtt2asc(buf[0]) >= (unsigned char)0xC2) &&
-		    (rtt2asc(buf[0]) < (unsigned char)0xF0)) {
-			c = x_e_getc();
-			if (c == -1)
-				return (-1);
-			if ((rtt2asc(c) & 0xC0) != 0x80) {
-				x_e_ungetc(c);
-				return (1);
-			}
-			buf[pos++] = c;
+	buf[0] = c;
+	if (!UTFMODE) {
+		buf[1] = '\0';
+		return (1);
+	}
+
+	pos = 1;
+	f = rtt2asc(c);
+	if (f >= 0xC2U && f < 0xF0U) {
+		if ((c = x_e_getc()) == -1)
+			return (-1);
+		if ((rtt2asc(c) & 0xC0U) != 0x80U) {
+			x_e_ungetc(c);
+			goto out;
 		}
-		if ((rtt2asc(buf[0]) >= (unsigned char)0xE0) &&
-		    (rtt2asc(buf[0]) < (unsigned char)0xF0)) {
-			/* XXX x_e_ungetc is one-octet only */
-			buf[pos++] = c = x_e_getc();
-			if (c == -1)
+		buf[pos++] = c;
+		if (f >= 0xE0U) {
+			if ((c = x_e_getc()) == -1)
 				return (-1);
+			/* XXX x_e_ungetc is one-octet only */
+			if ((rtt2asc(c) & 0xC0U) != 0x80U)
+				x_e_ungetc(c);
+			else
+				buf[pos++] = c;
 		}
 	}
+ out:
+	buf[pos] = '\0';
 	return (pos);
 }
 
@@ -1218,7 +1314,7 @@ x_e_getmbc(char *sbuf)
 #define MIN_EDIT_SPACE	7
 
 static void
-x_init_prompt(bool doprint)
+x_init_prompt(Wahr doprint)
 {
 	prompt_trunc = pprompt(prompt, doprint ? 0 : -1);
 	pwidth = prompt_trunc % x_cols;
@@ -1228,11 +1324,11 @@ x_init_prompt(bool doprint)
 		prompt_trunc = -1;
 		pwidth = 0;
 		if (doprint)
-			x_e_putc2('\n');
+			x_e_putb('\n');
 	}
 }
 
-static int
+static ssize_t
 x_emacs(char *buf)
 {
 	int c, i;
@@ -1242,16 +1338,19 @@ x_emacs(char *buf)
 	xend = buf + LINE;
 	xlp = xcp = xep = buf;
 	*xcp = 0;
-	xlp_valid = true;
 	xmp = NULL;
 	x_curprefix = 0;
 	x_histmcp = x_histp = histptr + 1;
 	x_last_command = XFUNC_error;
 
-	x_init_prompt(true);
-	x_displen = (xx_cols = x_cols) - 2 - (x_col = pwidth);
+	xx_cols = x_cols;
+	x_adj_ok = Nee;
+	x_init_prompt(Ja);
+	x_displen = xx_cols - 2 - (x_col = pwidth);
+	xdp = xbp + x_displen;
+	xlp_valid = Ja;
 	x_adj_done = 0;
-	x_adj_ok = true;
+	x_adj_ok = Ja;
 
 	x_histncp = NULL;
 	if (x_nextcmd >= 0) {
@@ -1266,10 +1365,10 @@ x_emacs(char *buf)
 	while (/* CONSTCOND */ 1) {
 		x_flush();
 		if ((c = x_e_getc()) < 0)
-			return (0);
+			return (-1);
 
-		f = x_curprefix == -1 ? XFUNC_insert :
-		    x_tab[x_curprefix][c];
+		f = x_curprefix == X_NOTAB ? XFUNC_insert :
+		    X_KTAB(x_curprefix, c);
 #ifndef MKSH_SMALL
 		if (f & 0x80) {
 			f &= 0x7F;
@@ -1285,9 +1384,9 @@ x_emacs(char *buf)
 		if (!(x_ftab[f].xf_flags & XF_PREFIX) &&
 		    x_last_command != XFUNC_set_arg) {
 			x_arg = 1;
-			x_arg_defaulted = true;
+			x_arg_defaulted = Ja;
 		}
-		i = c | (x_curprefix << 8);
+		i = (int)X_xTABidx(x_curprefix, c);
 		x_curprefix = 0;
 		switch ((*x_ftab[f].xf_func)(i)) {
 		case KSTD:
@@ -1295,71 +1394,71 @@ x_emacs(char *buf)
 				x_last_command = f;
 			break;
 		case KEOL:
-			i = xep - xbuf;
-			return (i);
+			return (xep - xbuf);
 		case KINTR:
 			/* special case for interrupt */
 			x_intr(SIGINT, c);
 		}
 		/* ad-hoc hack for fixing the cursor position */
 		x_goto(xcp);
+		/* and mark position */
+		if (xmp && xmp > xep)
+			xmp = xep;
 	}
 }
 
 static int
 x_insert(int c)
 {
-	static int left, pos, save_arg;
-	static char str[4];
+	static kby str[5], state;
+	static int save_arg;
+	kby b;
 
 	/*
 	 * Should allow tab and control chars.
 	 */
 	if (c == 0) {
- invmbs:
-		left = 0;
-		x_e_putc2(KSH_BEL);
+		x_e_putb(KSH_BEL);
+		state = 0;
 		return (KSTD);
 	}
-	if (UTFMODE) {
-		if (((rtt2asc(c) & 0xC0) == 0x80) && left) {
-			str[pos++] = c;
-			if (!--left) {
-				str[pos] = '\0';
-				x_arg = save_arg;
-				while (x_arg--)
-					x_ins(str);
-			}
-			return (KSTD);
-		}
-		if (left) {
-			if (x_curprefix == -1) {
-				/* flush invalid multibyte */
-				str[pos] = '\0';
-				while (save_arg--)
-					x_ins(str);
-			}
-		}
-		if ((c >= 0xC2) && (c < 0xE0))
-			left = 1;
-		else if ((c >= 0xE0) && (c < 0xF0))
-			left = 2;
-		else if (c > 0x7F)
-			goto invmbs;
-		else
-			left = 0;
-		if (left) {
-			save_arg = x_arg;
-			pos = 1;
-			str[0] = c;
-			return (KSTD);
-		}
+	if (!UTFMODE) {
+ sbc:
+		str[0] = c;
+		str[1] = '\0';
+ mbc:
+		while (x_arg--)
+			x_ins(str);
+		state = 0;
+		return (KSTD);
 	}
-	left = 0;
+	b = rtt2asc(c);
+	if (state) {
+		/* this a continuation octet? */
+		if ((b & 0xC0U) == 0x80U) {
+			/* states: 1, 5, 6 */
+			str[state & 3] = c;
+			++state;
+			/* states: 2, 6, 7 */
+			if (state == 6)
+				/* another octet needed */
+				return (KSTD);
+			/* finishing up this multibyte character */
+			str[state & 3] = '\0';
+			x_arg = save_arg;
+			goto mbc;
+		}
+		/* flush invalid multibyte octets */
+		str[state & 3] = '\0';
+		while (save_arg--)
+			x_ins(str);
+		/* begin a new multibyte character */
+	}
+	if (b < 0xC2U || b >= 0xF0)
+		goto sbc;
+	state = b < 0xE0U ? 1 : 5;
 	str[0] = c;
-	str[1] = '\0';
-	while (x_arg--)
-		x_ins(str);
+	save_arg = x_arg;
 	return (KSTD);
 }
 
@@ -1367,7 +1466,7 @@ x_insert(int c)
 static int
 x_ins_string(int c)
 {
-	macroptr = x_atab[c >> 8][c & 255];
+	macroptr = x_mtab[KUI(c)];
 	/*
 	 * we no longer need to bother checking if macroptr is
 	 * not NULL but first char is NUL; x_e_getc() does it
@@ -1380,11 +1479,13 @@ static int
 x_do_ins(const char *cp, size_t len)
 {
 	if (xep + len >= xend) {
-		x_e_putc2(KSH_BEL);
+		x_e_putb(KSH_BEL);
 		return (-1);
 	}
 	memmove(xcp + len, xcp, xep - xcp + 1);
 	memmove(xcp, cp, len);
+	if (xmp && xmp > xcp)
+		xmp += len;
 	xcp += len;
 	xep += len;
 	x_modified();
@@ -1392,25 +1493,25 @@ x_do_ins(const char *cp, size_t len)
 }
 
 static int
-x_ins(const char *s)
+x_ins(const void *s)
 {
 	char *cp = xcp;
-	int adj = x_adj_done;
+	kby adj = x_adj_done;
 
 	if (x_do_ins(s, strlen(s)) < 0)
 		return (-1);
 	/*
-	 * x_zots() may result in a call to x_adjust()
-	 * we want xcp to reflect the new position.
+	 * x_uescs() may result in a call to x_adjust()
+	 * we want xcp to reflect the new position
 	 */
-	xlp_valid = false;
+	xlp_valid = Nee;
 	x_lastcp();
-	x_adj_ok = tobool(xcp >= xlp);
-	x_zots(cp);
+	x_adj_ok = isWahr(xcp >= xlp);
+	x_uescs(cp);
 	if (adj == x_adj_done)
 		/* x_adjust() has not been called */
 		x_lastpos();
-	x_adj_ok = true;
+	x_adj_ok = Ja;
 	return (0);
 }
 
@@ -1420,13 +1521,13 @@ x_del_back(int c MKSH_A_UNUSED)
 	ssize_t i = 0;
 
 	if (xcp == xbuf) {
-		x_e_putc2(KSH_BEL);
+		x_e_putb(KSH_BEL);
 		return (KSTD);
 	}
 	do {
 		x_goto(xcp - 1);
 	} while ((++i < x_arg) && (xcp != xbuf));
-	x_delete(i, false);
+	x_delete(i, Nee);
 	return (KSTD);
 }
 
@@ -1438,7 +1539,7 @@ x_del_char(int c MKSH_A_UNUSED)
 
 	cp = xcp;
 	while (i < (size_t)x_arg) {
-		utf_ptradjx(cp, cp2);
+		cp2 = cp + ez_mbtoc(NULL, cp);
 		if (cp2 > xep)
 			break;
 		cp = cp2;
@@ -1446,16 +1547,16 @@ x_del_char(int c MKSH_A_UNUSED)
 	}
 
 	if (!i) {
-		x_e_putc2(KSH_BEL);
+		x_e_putb(KSH_BEL);
 		return (KSTD);
 	}
-	x_delete(i, false);
+	x_delete(i, Nee);
 	return (KSTD);
 }
 
 /* Delete nc chars to the right of the cursor (including cursor position) */
 static void
-x_delete(size_t nc, bool push)
+x_delete(size_t nc, Wahr push)
 {
 	size_t i, nb, nw;
 	char *cp;
@@ -1469,7 +1570,7 @@ x_delete(size_t nc, bool push)
 		char *cp2;
 		int j;
 
-		j = x_size2(cp, &cp2);
+		j = uwidthmbT(cp, &cp2);
 		if (cp2 > xep)
 			break;
 		cp = cp2;
@@ -1494,9 +1595,9 @@ x_delete(size_t nc, bool push)
 	/* Copies the NUL */
 	memmove(xcp, xcp + nb, xep - xcp + 1);
 	/* don't redraw */
-	x_adj_ok = false;
-	xlp_valid = false;
-	x_zots(xcp);
+	x_adj_ok = Nee;
+	xlp_valid = Nee;
+	x_uescs(xcp);
 	/*
 	 * if we are already filling the line,
 	 * there is no need to ' ', '\b'.
@@ -1505,17 +1606,17 @@ x_delete(size_t nc, bool push)
 	if ((i = xx_cols - 2 - x_col) > 0 || xep - xlp == 0) {
 		nw = i = (nw < i) ? nw : i;
 		while (i--)
-			x_e_putc2(' ');
+			x_e_putb(' ');
 		if (x_col == xx_cols - 2) {
-			x_e_putc2((xep > xlp) ? '>' : (xbp > xbuf) ? '<' : ' ');
+			x_e_putb((xep > xlp) ? '>' : (xbp > xbuf) ? '<' : ' ');
 			++nw;
 		}
 		while (nw--)
-			x_e_putc2('\b');
+			x_e_putb('\b');
 	}
 	/*x_goto(xcp);*/
-	x_adj_ok = true;
-	xlp_valid = false;
+	x_adj_ok = Ja;
+	xlp_valid = Nee;
 	x_lastpos();
 	x_modified();
 	return;
@@ -1524,82 +1625,121 @@ x_delete(size_t nc, bool push)
 static int
 x_del_bword(int c MKSH_A_UNUSED)
 {
-	x_delete(x_bword(), true);
+	x_bword(C_MFS, Ja);
 	return (KSTD);
 }
 
 static int
 x_mv_bword(int c MKSH_A_UNUSED)
 {
-	x_bword();
+	x_bword(C_MFS, Nee);
 	return (KSTD);
 }
 
 static int
 x_mv_fword(int c MKSH_A_UNUSED)
 {
-	x_fword(true);
+	x_fword(C_MFS, Nee);
 	return (KSTD);
 }
 
 static int
 x_del_fword(int c MKSH_A_UNUSED)
 {
-	x_delete(x_fword(false), true);
+	x_fword(C_MFS, Ja);
 	return (KSTD);
 }
 
-static size_t
-x_bword(void)
+#ifndef MKSH_SMALL
+static int
+x_del_bbigword(int c MKSH_A_UNUSED)
+{
+	x_bword(C_BLANK, Ja);
+	return (KSTD);
+}
+
+static int
+x_mv_bbigword(int c MKSH_A_UNUSED)
+{
+	x_bword(C_BLANK, Nee);
+	return (KSTD);
+}
+
+static int
+x_mv_fbigword(int c MKSH_A_UNUSED)
+{
+	x_fword(C_BLANK, Nee);
+	return (KSTD);
+}
+
+static int
+x_del_fbigword(int c MKSH_A_UNUSED)
+{
+	x_fword(C_BLANK, Ja);
+	return (KSTD);
+}
+#endif
+
+static void
+x_bword(kui separator, Wahr erase)
 {
 	size_t nb = 0;
 	char *cp = xcp;
 
 	if (cp == xbuf) {
-		x_e_putc2(KSH_BEL);
-		return (0);
+		x_e_putb(KSH_BEL);
+		return;
 	}
 	while (x_arg--) {
-		while (cp != xbuf && ctype(cp[-1], C_MFS)) {
+		while (cp != xbuf && ctype(cp[-1], separator)) {
 			cp--;
 			nb++;
 		}
-		while (cp != xbuf && !ctype(cp[-1], C_MFS)) {
+		while (cp != xbuf && !ctype(cp[-1], separator)) {
 			cp--;
 			nb++;
 		}
 	}
 	x_goto(cp);
-	return (x_nb2nc(nb));
+	if (erase)
+		x_delete(x_nb2nc(nb), Ja);
 }
 
-static size_t
-x_fword(bool move)
+static void
+x_fword(kui separator, Wahr erase)
 {
-	size_t nc;
 	char *cp = xcp;
 
 	if (cp == xep) {
-		x_e_putc2(KSH_BEL);
-		return (0);
+		x_e_putb(KSH_BEL);
+		return;
 	}
 	while (x_arg--) {
-		while (cp != xep && ctype(*cp, C_MFS))
+		while (cp != xep && ctype(*cp, separator))
 			cp++;
-		while (cp != xep && !ctype(*cp, C_MFS))
+		while (cp != xep && !ctype(*cp, separator))
 			cp++;
 	}
-	nc = x_nb2nc(cp - xcp);
-	if (move)
+	if (erase)
+		x_delete(x_nb2nc(cp - xcp), Ja);
+	else
 		x_goto(cp);
-	return (nc);
+}
+
+static void
+x_uescmb(char **cp)
+{
+	unsigned char esc[5];
+
+	uescmbT(esc, (const char **)cp);
+	x_e_puts((const void *)esc);
 }
 
 static void
 x_goto(char *cp)
 {
-	cp = cp >= xep ? xep : x_bs0(cp, xbuf);
-	if (cp < xbp || cp >= utf_skipcols(xbp, x_displen, NULL)) {
+	cp = cp >= xep ? xep : ez_bs(cp, xbuf);
+	if (cp < xbp || (x_lastcp(), cp >= xdp)) {
 		/* we are heading off screen */
 		xcp = cp;
 		x_adjust();
@@ -1610,81 +1750,36 @@ x_goto(char *cp)
 	} else if (cp > xcp) {
 		/* move forward */
 		while (cp > xcp)
-			x_zotc3(&xcp);
+			x_uescmb(&xcp);
 	}
 }
 
-static char *
-x_bs0(char *cp, char *lower_bound)
-{
-	if (UTFMODE)
-		while ((!lower_bound || (cp > lower_bound)) &&
-		    ((rtt2asc(*cp) & 0xC0) == 0x80))
-			--cp;
-	return (cp);
-}
-
 static void
 x_bs3(char **p)
 {
 	int i;
 
-	*p = x_bs0((*p) - 1, NULL);
-	i = x_size2(*p, NULL);
+	*p = ez_bs((*p) - 1, xbuf);
+	i = uwidthmbT(*p, NULL);
 	while (i--)
-		x_e_putc2('\b');
-}
-
-static int
-x_size2(char *cp, char **dcp)
-{
-	uint8_t c = *(unsigned char *)cp;
-
-	if (UTFMODE && (rtt2asc(c) > 0x7F))
-		return (utf_widthadj(cp, (const char **)dcp));
-	if (dcp)
-		*dcp = cp + 1;
-	if (c == '\t')
-		/* Kludge, tabs are always four spaces. */
-		return (4);
-	if (ksh_isctrl(c))
-		/* control unsigned char */
-		return (2);
-	return (1);
+		x_e_putb('\b');
 }
 
 static void
-x_zots(char *str)
+x_uescs(char *str)
 {
-	int adj = x_adj_done;
+	kby adj = x_adj_done;
 
 	x_lastcp();
 	while (*str && str < xlp && x_col < xx_cols && adj == x_adj_done)
-		x_zotc3(&str);
-}
-
-static void
-x_zotc3(char **cp)
-{
-	unsigned char c = **(unsigned char **)cp;
-
-	if (c == '\t') {
-		/* Kludge, tabs are always four spaces. */
-		x_e_puts(T4spaces);
-		(*cp)++;
-	} else if (ksh_isctrl(c)) {
-		x_e_putc2('^');
-		x_e_putc2(ksh_unctrl(c));
-		(*cp)++;
-	} else
-		x_e_putc3((const char **)cp);
+		x_uescmb(&str);
 }
 
 static int
 x_mv_back(int c MKSH_A_UNUSED)
 {
 	if (xcp == xbuf) {
-		x_e_putc2(KSH_BEL);
+		x_e_putb(KSH_BEL);
 		return (KSTD);
 	}
 	while (x_arg--) {
@@ -1701,11 +1796,11 @@ x_mv_forw(int c MKSH_A_UNUSED)
 	char *cp = xcp, *cp2;
 
 	if (xcp == xep) {
-		x_e_putc2(KSH_BEL);
+		x_e_putb(KSH_BEL);
 		return (KSTD);
 	}
 	while (x_arg--) {
-		utf_ptradjx(cp, cp2);
+		cp2 = cp + ez_mbtoc(NULL, cp);
 		if (cp2 > xep)
 			break;
 		cp = cp2;
@@ -1718,17 +1813,17 @@ static int
 x_search_char_forw(int c MKSH_A_UNUSED)
 {
 	char *cp = xcp;
-	char tmp[4];
+	char tmp[5];
 
 	*xep = '\0';
 	if (x_e_getmbc(tmp) < 0) {
-		x_e_putc2(KSH_BEL);
+		x_e_putb(KSH_BEL);
 		return (KSTD);
 	}
 	while (x_arg--) {
-		if ((cp = (cp == xep) ? NULL : strstr(cp + 1, tmp)) == NULL &&
-		    (cp = strstr(xbuf, tmp)) == NULL) {
-			x_e_putc2(KSH_BEL);
+		if ((cp = (cp == xep) ? NULL : ucstrstr(cp + 1, tmp)) == NULL &&
+		    (cp = ucstrstr(xbuf, tmp)) == NULL) {
+			x_e_putb(KSH_BEL);
 			return (KSTD);
 		}
 	}
@@ -1739,11 +1834,11 @@ x_search_char_forw(int c MKSH_A_UNUSED)
 static int
 x_search_char_back(int c MKSH_A_UNUSED)
 {
-	char *cp = xcp, *p, tmp[4];
-	bool b;
+	char *cp = xcp, *p, tmp[5];
+	Wahr b;
 
 	if (x_e_getmbc(tmp) < 0) {
-		x_e_putc2(KSH_BEL);
+		x_e_putb(KSH_BEL);
 		return (KSTD);
 	}
 	for (; x_arg--; cp = p)
@@ -1751,19 +1846,19 @@ x_search_char_back(int c MKSH_A_UNUSED)
 			if (p-- == xbuf)
 				p = xep;
 			if (p == cp) {
-				x_e_putc2(KSH_BEL);
+				x_e_putb(KSH_BEL);
 				return (KSTD);
 			}
 			if ((tmp[1] && ((p+1) > xep)) ||
 			    (tmp[2] && ((p+2) > xep)))
 				continue;
-			b = true;
+			b = Ja;
 			if (*p != tmp[0])
-				b = false;
+				b = Nee;
 			if (b && tmp[1] && p[1] != tmp[1])
-				b = false;
+				b = Nee;
 			if (b && tmp[2] && p[2] != tmp[2])
-				b = false;
+				b = Nee;
 			if (b)
 				break;
 		}
@@ -1774,21 +1869,24 @@ x_search_char_back(int c MKSH_A_UNUSED)
 static int
 x_newline(int c MKSH_A_UNUSED)
 {
-	x_e_putc2('\r');
-	x_e_putc2('\n');
+	x_e_putb('\r');
+	x_e_putb('\n');
 	x_flush();
 	*xep++ = '\n';
 	return (KEOL);
 }
 
 static int
-x_end_of_text(int c MKSH_A_UNUSED)
+x_end_of_text(int c)
 {
-	unsigned char tmp[1], *cp = tmp;
+	unsigned char tmp[2], *cp = tmp;
 
+	if (cur_prompt == PS2)
+		x_intr(0, c);
 	*tmp = isedchar(edchars.eof) ? (unsigned char)edchars.eof :
 	    (unsigned char)CTRL_D;
-	x_zotc3((char **)&cp);
+	tmp[1] = '\0';
+	x_uescmb((char **)&cp);
 	x_putc('\r');
 	x_putc('\n');
 	x_flush();
@@ -1847,7 +1945,7 @@ x_load_hist(char **hp)
 		sp = holdbufp;
 		modified = 0;
 	} else if (hp < history || hp > histptr) {
-		x_e_putc2(KSH_BEL);
+		x_e_putb(KSH_BEL);
 		return;
 	}
 	if (sp == NULL)
@@ -1901,12 +1999,12 @@ x_search_hist(int c)
 		x_flush();
 		if ((c = x_e_getc()) < 0)
 			return (KSTD);
-		f = x_tab[0][c];
-		if (c == CTRL_BO) {
+		f = X_KTAB(0, c);
+		if (ord(c) == CTRL_BO) {
 			if ((f & 0x7F) == XFUNC_meta1) {
 				if ((c = x_e_getc()) < 0)
 					return (KSTD);
-				f = x_tab[1][c] & 0x7F;
+				f = X_KTAB(1, c) & 0x7F;
 				if (f == XFUNC_meta1 || f == XFUNC_meta2)
 					x_meta1(CTRL_BO);
 				x_e_ungetc(c);
@@ -1928,7 +2026,7 @@ x_search_hist(int c)
 				break;
 			}
 			if (p > pat) {
-				p = x_bs0(p - 1, pat);
+				p = ez_bs(p - 1, pat);
 				*p = '\0';
 			}
 			if (p == pat)
@@ -1940,7 +2038,7 @@ x_search_hist(int c)
 			/* add char to pattern */
 			/* overflow check... */
 			if ((size_t)(p - pat) >= sizeof(pat) - 1) {
-				x_e_putc2(KSH_BEL);
+				x_e_putb(KSH_BEL);
 				continue;
 			}
 			*p++ = c, *p = '\0';
@@ -1983,13 +2081,13 @@ x_search(const char *pat, int sameline,
 		i = x_match(*hp, pat);
 		if (i >= 0) {
 			if (offset < 0)
-				x_e_putc2('\n');
+				x_e_putb('\n');
 			x_load_hist(hp);
 			x_goto(xbuf + i + patlen);
 			return (i);
 		}
 	}
-	x_e_putc2(KSH_BEL);
+	x_e_putb(KSH_BEL);
 	x_histp = histptr;
 	return (-1);
 }
@@ -2011,7 +2109,7 @@ x_search_hist_dn(int c MKSH_A_UNUSED)
 
 /* anchored search in the indicated direction */
 static int
-x_search_dir(int search_dir /* should've been bool */)
+x_search_dir(int search_dir /* should've been Wahr */)
 {
 	char **hp = x_histp + search_dir;
 	size_t curs = xcp - xbuf;
@@ -2035,7 +2133,7 @@ x_match(const char *str, const char *pat
 	if (*pat == '^') {
 		return ((strncmp(str, pat + 1, strlen(pat + 1)) == 0) ? 0 : -1);
 	} else {
-		char *q = strstr(str, pat);
+		const char *q = cstrstr(str, pat);
 		return ((q == NULL) ? -1 : q - str);
 	}
 }
@@ -2046,7 +2144,8 @@ x_del_line(int c MKSH_A_UNUSED)
 	*xep = 0;
 	x_push(xep - (xcp = xbuf));
 	xlp = xbp = xep = xbuf;
-	xlp_valid = true;
+	xdp = xbp + x_displen;
+	xlp_valid = Ja;
 	*xcp = 0;
 	xmp = NULL;
 	x_redraw('\r');
@@ -2079,6 +2178,11 @@ static int
 x_cls(int c MKSH_A_UNUSED)
 {
 	shf_puts(MKSH_CLS_STRING, shl_out);
+	if (prompt_trunc) {
+		/* multi-line prompt */
+		pprompt(prompt, 0);
+		/* x_redraw takes care of the last line */
+	}
 	x_redraw(0);
 	return (KSTD);
 }
@@ -2090,16 +2194,18 @@ x_cls(int c MKSH_A_UNUSED)
  * lastch MUST be an ASCII character with wcwidth(lastch) == 1
  */
 static void
-x_clrtoeol(int lastch, bool line_was_cleared)
+x_clrtoeol(int lastch, Wahr line_was_cleared)
 {
 	int col;
 
-	if (lastch == ' ' && !line_was_cleared && x_term_mode == 1) {
-		shf_puts(KSH_ESC_STRING "[K", shl_out);
-		line_was_cleared = true;
+	if (lastch == ' ') {
+		if (line_was_cleared)
+			return;
+		if (x_term_mode == 1) {
+			shf_puts(KSH_ESC_STRING "[K", shl_out);
+			return;
+		}
 	}
-	if (lastch == ' ' && line_was_cleared)
-		return;
 
 	col = x_col;
 	while (col < (xx_cols - 2)) {
@@ -2129,24 +2235,24 @@ x_redraw(int cr)
 {
 	int lch;
 
-	x_adj_ok = false;
+	x_adj_ok = Nee;
 	/* clear the line */
-	x_e_putc2(cr ? cr : '\r');
+	x_e_putb(cr ? cr : '\r');
 	x_flush();
 	/* display the prompt */
 	if (xbp == xbuf)
 		x_pprompt();
 	x_displen = xx_cols - 2 - x_col;
 	/* display the line content */
-	xlp_valid = false;
-	x_zots(xbp);
+	xlp_valid = Nee;
+	x_uescs(xbp);
 	/* check whether there is more off-screen */
 	lch = xep > xlp ? (xbp > xbuf ? '*' : '>') : (xbp > xbuf) ? '<' : ' ';
 	/* clear the rest of the line */
 	x_clrtoeol(lch, !cr || cr == '\n');
 	/* go back to actual cursor position */
 	x_lastpos();
-	x_adj_ok = true;
+	x_adj_ok = Ja;
 }
 
 static int
@@ -2161,19 +2267,20 @@ x_transpose(int c MKSH_A_UNUSED)
 	 *	Who			Before	After	Before	After
 	 *	AT&T ksh in emacs mode:	abCd	abdC	abcd_	(bell)
 	 *	AT&T ksh in gmacs mode:	abCd	baCd	abcd_	abdc_
-	 *	gnu emacs:		abCd	acbD	abcd_	abdc_
-	 * Pdksh currently goes with GNU behavior since I believe this is the
+	 *	GNU emacs:		abCd	acbD	abcd_	abdc_
+	 * pdksh currently goes with GNU behavior since I believe this is the
 	 * most common version of emacs, unless in gmacs mode, in which case
 	 * it does the AT&T ksh gmacs mode.
 	 * This should really be broken up into 3 functions so users can bind
 	 * to the one they want.
 	 */
 	if (xcp == xbuf) {
-		x_e_putc2(KSH_BEL);
+		x_e_putb(KSH_BEL);
 		return (KSTD);
-	} else if (xcp == xep || Flag(FGMACS)) {
+	}
+	if (xcp == xep || Flag(FGMACS)) {
 		if (xcp - xbuf == 1) {
-			x_e_putc2(KSH_BEL);
+			x_e_putb(KSH_BEL);
 			return (KSTD);
 		}
 		/*
@@ -2181,38 +2288,20 @@ x_transpose(int c MKSH_A_UNUSED)
 		 * the cursor, do not change cursor position
 		 */
 		x_bs3(&xcp);
-		if (utf_mbtowc(&tmpa, xcp) == (size_t)-1) {
-			x_e_putc2(KSH_BEL);
-			return (KSTD);
-		}
-		x_bs3(&xcp);
-		if (utf_mbtowc(&tmpb, xcp) == (size_t)-1) {
-			x_e_putc2(KSH_BEL);
-			return (KSTD);
-		}
-		utf_wctomb(xcp, tmpa);
-		x_zotc3(&xcp);
-		utf_wctomb(xcp, tmpb);
-		x_zotc3(&xcp);
-	} else {
-		/*
+	}
+	/* else
 		 * GNU emacs style: Swap the characters before and under the
 		 * cursor, move cursor position along one.
 		 */
-		if (utf_mbtowc(&tmpa, xcp) == (size_t)-1) {
-			x_e_putc2(KSH_BEL);
-			return (KSTD);
-		}
-		x_bs3(&xcp);
-		if (utf_mbtowc(&tmpb, xcp) == (size_t)-1) {
-			x_e_putc2(KSH_BEL);
-			return (KSTD);
-		}
-		utf_wctomb(xcp, tmpa);
-		x_zotc3(&xcp);
-		utf_wctomb(xcp, tmpb);
-		x_zotc3(&xcp);
-	}
+	ez_mbtoc(&tmpa, xcp);
+	x_bs3(&xcp);
+	ez_mbtoc(&tmpb, xcp);
+	/* ensure that swapping e.g. raw 0xA4 0xC3 doesn’t break separation */
+	xcp[ez_ctomb(xcp, tmpa)] = '\0';
+	x_uescmb(&xcp);
+	ez_ctomb(xcp, tmpb);
+	x_uescmb(&xcp);
+	/* though a ^L now re-recognises that, probably okay */
 	x_modified();
 	return (KSTD);
 }
@@ -2220,7 +2309,7 @@ x_transpose(int c MKSH_A_UNUSED)
 static int
 x_literal(int c MKSH_A_UNUSED)
 {
-	x_curprefix = -1;
+	x_curprefix = X_NOTAB;
 	return (KSTD);
 }
 
@@ -2259,7 +2348,7 @@ x_kill(int c MKSH_A_UNUSED)
 		ndel = col - narg;
 	} else
 		ndel = narg - col;
-	x_delete(x_nb2nc(ndel), true);
+	x_delete(x_nb2nc(ndel), Ja);
 	return (KSTD);
 }
 
@@ -2284,7 +2373,6 @@ x_yank(int c MKSH_A_UNUSED)
 		x_redraw('\n');
 		return (KSTD);
 	}
-	xmp = xcp;
 	x_ins(killstack[killtp]);
 	return (KSTD);
 }
@@ -2297,13 +2385,13 @@ x_meta_yank(int c MKSH_A_UNUSED)
 	if ((x_last_command != XFUNC_yank && x_last_command != XFUNC_meta_yank) ||
 	    killstack[killtp] == 0) {
 		killtp = killsp;
-		x_e_puts("\nyank something first");
+		x_e_puts(Tyankfirst);
 		x_redraw('\n');
 		return (KSTD);
 	}
 	len = strlen(killstack[killtp]);
 	x_goto(xcp - len);
-	x_delete(x_nb2nc(len), false);
+	x_delete(x_nb2nc(len), Nee);
 	do {
 		if (killtp == 0)
 			killtp = KILLSIZE - 1;
@@ -2318,18 +2406,24 @@ x_meta_yank(int c MKSH_A_UNUSED)
 static void
 x_intr(int signo, int c)
 {
-	x_vi_zotc(c);
+	uprntc(c, shl_out);
 	*xep = '\0';
 	strip_nuls(xbuf, xep - xbuf);
 	if (*xbuf)
-		histsave(&source->line, xbuf, HIST_STORE, true);
+		histsave(&source->line, xbuf, HIST_STORE, Ja);
 	xlp = xep = xcp = xbp = xbuf;
-	xlp_valid = true;
+	xdp = xbp + x_displen;
+	xlp_valid = Ja;
 	*xcp = 0;
 	x_modified();
+	if (!signo) {
+		x_putc('\r');
+		x_putc('\n');
+	}
 	x_flush();
-	trapsig(signo);
-	x_mode(false);
+	if (signo)
+		trapsig(signo);
+	x_mode(Nee);
 	unwind(LSHELL);
 }
 
@@ -2342,7 +2436,7 @@ x_abort(int c MKSH_A_UNUSED)
 static int
 x_error(int c MKSH_A_UNUSED)
 {
-	x_e_putc2(KSH_BEL);
+	x_e_putb(KSH_BEL);
 	return (KSTD);
 }
 
@@ -2359,7 +2453,7 @@ x_vt_hack(int c)
 	switch ((c = x_e_getc())) {
 	case '~':
 		x_arg = 1;
-		x_arg_defaulted = true;
+		x_arg_defaulted = Ja;
 		return (x_mv_beg(0));
 	case ';':
 		/* "interesting" sequence detected */
@@ -2397,77 +2491,65 @@ x_vt_hack(int c)
 int
 x_bind_check(void)
 {
-	return (x_tab == NULL);
+	return (x_btab == NULL);
 }
 
-static XString x_bind_show_xs;
-static char *x_bind_show_xp;
-
-static void
-x_bind_show_ch(unsigned char ch)
-{
-	Xcheck(x_bind_show_xs, x_bind_show_xp);
-	switch (ch) {
-	case ORD('^'):
-	case ORD('\\'):
-	case ORD('='):
-		*x_bind_show_xp++ = '\\';
-		*x_bind_show_xp++ = ch;
-		break;
-	default:
-		if (ksh_isctrl(ch)) {
-			*x_bind_show_xp++ = '^';
-			*x_bind_show_xp++ = ksh_unctrl(ch);
-		} else
-			*x_bind_show_xp++ = ch;
-		break;
-	}
-}
+static char *x_bind_show_s;
+static size_t x_bind_show_n;
 
 static void
-x_bind_showone(int prefix, int key)
+x_bind_showone(kui prefix, kui key)
 {
-	unsigned char f = XFUNC_VALUE(x_tab[prefix][key]);
+	kby f = XFUNC_VALUE(X_KTAB(prefix, key));
+	struct shf shf;
 
-	if (!x_bind_show_xs.areap)
-		XinitN(x_bind_show_xs, 16, AEDIT);
+	if (!x_bind_show_n)
+		x_bind_show_s = aresize(x_bind_show_s,
+		    (x_bind_show_n = 12), AEDIT);
 
-	x_bind_show_xp = Xstring(x_bind_show_xs, x_bind_show_xp);
 	shf_puts("bind ", shl_stdout);
 #ifndef MKSH_SMALL
 	if (f == XFUNC_ins_string)
 		shf_puts("-m ", shl_stdout);
 #endif
+
+	shf_sreopen(x_bind_show_s, x_bind_show_n, AEDIT, &shf);
 	switch (prefix) {
 	case 1:
-		x_bind_show_ch(CTRL_BO);
+		uprntc(CTRL_BO, &shf);
 		break;
 	case 2:
-		x_bind_show_ch(CTRL_X);
+		uprntc(CTRL_X, &shf);
 		break;
 	case 3:
-		x_bind_show_ch(0);
+		uprntc(CTRL_AT, &shf);
 		break;
 	}
-	x_bind_show_ch(key);
+	switch (key) {
+	case ORD('^'):
+	case ORD('\\'):
+	case ORD('='):
+		shf_putc('\\', &shf);
+		shf_putc(key, &shf);
+		break;
+	default:
+		uprntc(key, &shf);
+	}
 #ifndef MKSH_SMALL
-	if (x_tab[prefix][key] & 0x80)
-		*x_bind_show_xp++ = '~';
+	if (X_KTAB(prefix, key) & 0x80U)
+		shf_putc('~', &shf);
 #endif
-	*x_bind_show_xp = '\0';
-	x_bind_show_xp = Xstring(x_bind_show_xs, x_bind_show_xp);
-	print_value_quoted(shl_stdout, x_bind_show_xp);
+	x_bind_show_n = shf.wbsize;
+	x_bind_show_s = shf_sclose(&shf);
+	print_value_quoted(shl_stdout, x_bind_show_s);
 	shf_putc('=', shl_stdout);
 #ifndef MKSH_SMALL
 	if (f == XFUNC_ins_string) {
-		const unsigned char *cp = (const void *)x_atab[prefix][key];
-		unsigned char c;
-
-		while ((c = *cp++))
-			x_bind_show_ch(c);
-		*x_bind_show_xp = '\0';
-		x_bind_show_xp = Xstring(x_bind_show_xs, x_bind_show_xp);
-		print_value_quoted(shl_stdout, x_bind_show_xp);
+		shf_sreopen(x_bind_show_s, x_bind_show_n, AEDIT, &shf);
+		uprntmbs(X_MTAB(prefix, key), Ja, &shf);
+		x_bind_show_n = shf.wbsize;
+		x_bind_show_s = shf_sclose(&shf);
+		print_value_quoted(shl_stdout, x_bind_show_s);
 	} else
 #endif
 	  shf_puts(x_ftab[f].xf_name, shl_stdout);
@@ -2488,11 +2570,11 @@ x_bind_list(void)
 int
 x_bind_showall(void)
 {
-	int prefix, key;
+	kui prefix, key;
 
-	for (prefix = 0; prefix < X_NTABS; prefix++)
-		for (key = 0; key < X_TABSZ; key++)
-			switch (XFUNC_VALUE(x_tab[prefix][key])) {
+	for (prefix = 0; prefix < X_NTABS; ++prefix)
+		for (key = 0; key <= 0xFF; ++key)
+			switch (XFUNC_VALUE(X_KTAB(prefix, key))) {
 			case XFUNC_error:	/* unset */
 			case XFUNC_insert:	/* auto-insert */
 				break;
@@ -2503,57 +2585,100 @@ x_bind_showall(void)
 	return (0);
 }
 
-static unsigned int
-x_bind_getc(const char **ccpp)
+struct x_bind_getc {
+	const char *cp;
+	kby next;
+};
+
+static kui
+x_bind_getc(struct x_bind_getc *ctx)
 {
-	unsigned int ch, ec;
+	kui ch;
+	kby tmp[4];
 
-	if ((ch = ord(**ccpp)))
-		++(*ccpp);
+	if ((ch = ctx->next)) {
+		ctx->next = 0;
+		return (ch);
+	}
+	if ((ch = ord(*(ctx->cp))))
+		++(ctx->cp);
 	switch (ch) {
 	case ORD('^'):
-		ch = ksh_toctrl(**ccpp) | 0x100U;
-		if (**ccpp)
-			++(*ccpp);
+		if ((ch = ord(*(ctx->cp))))
+			++(ctx->cp);
+		switch (ch) {
+		case ORD('!'):
+			if ((ch = ord(*(ctx->cp))))
+				++(ctx->cp);
+			ch = asc2rtt((rtt2asc(ch) & 0x1FU) + 0x80U);
+			break;
+		case ORD('+'):
+			if ((ch = ord(*(ctx->cp))))
+				++(ctx->cp);
+			utf_wctomb((char *)tmp, (rtt2asc(ch) & 0x1FU) + 0x80U);
+			ch = tmp[0];
+			ctx->next = tmp[1];
+			break;
+		case ORD('?'):
+			ch = CTRL_QM;
+			break;
+		default:
+			ch = asc2rtt(rtt2asc(ch) & 0x1FU);
+			break;
+		}
 		break;
 	case ORD('\\'):
-		switch ((ec = ord(**ccpp))) {
-		case ORD('^'):
-		case ORD('\\'):
-		case ORD('='):
-			ch = ec | 0x100U;
-			++(*ccpp);
-			break;
+		if ((ch = ord(*(ctx->cp))))
+			++(ctx->cp);
+		if (ch == ORD('x') && ctype(ctx->cp[0], C_SEDEC) &&
+		    ctype(ctx->cp[1], C_SEDEC)) {
+			if (ctype(ctx->cp[0], C_DIGIT))
+				ch = ksh_numdig(ctx->cp[0]);
+			else if (ctype(ctx->cp[0], C_UPPER))
+				ch = ksh_numuc(ctx->cp[0]) + 10;
+			else
+				ch = ksh_numlc(ctx->cp[0]) + 10;
+			ch <<= 4;
+			if (ctype(ctx->cp[1], C_DIGIT))
+				ch |= ksh_numdig(ctx->cp[1]);
+			else if (ctype(ctx->cp[1], C_UPPER))
+				ch |= ksh_numuc(ctx->cp[1]) + 10;
+			else
+				ch |= ksh_numlc(ctx->cp[1]) + 10;
+			ctx->cp += 2;
 		}
+		ch |= 0x100U;
 		break;
 	}
 	return (ch);
 }
 
 int
-x_bind(const char *s SMALLP(bool macro))
+x_bind(const char *s SMALLP(Wahr macro))
 {
-	const char *ccp = s;
-	int prefix, key;
-	unsigned int c;
+	register kui t;
+	struct x_bind_getc state;
+	kui c, key, prefix;
 #ifndef MKSH_SMALL
-	bool hastilde = false;
+	Wahr hastilde = Nee;
 	char *ms = NULL;
 #endif
 
+	state.cp = s;
+	state.next = 0;
 	prefix = 0;
-	c = x_bind_getc(&ccp);
+	c = x_bind_getc(&state);
 	if (!c || c == ORD('=')) {
 		bi_errorf("no key to bind");
 		return (1);
 	}
-	key = c & 0xFF;
-	while ((c = x_bind_getc(&ccp)) != ORD('=')) {
+	key = KBI(c);
+	while ((c = x_bind_getc(&state)) != ORD('=')) {
 		if (!c) {
 			x_bind_showone(prefix, key);
 			return (0);
 		}
-		switch (XFUNC_VALUE(x_tab[prefix][key])) {
+		switch (XFUNC_VALUE(X_KTAB(prefix, key))) {
 		case XFUNC_meta1:
 			prefix = 1;
 			if (0)
@@ -2564,12 +2689,12 @@ x_bind(const char *s SMALLP(bool macro))
 				/* FALLTHROUGH */
 		case XFUNC_meta3:
 			  prefix = 3;
-			key = c & 0xFF;
+			key = KBI(c);
 			continue;
 		}
 #ifndef MKSH_SMALL
 		if (c == ORD('~')) {
-			hastilde = true;
+			hastilde = Ja;
 			continue;
 		}
 #endif
@@ -2581,41 +2706,40 @@ x_bind(const char *s SMALLP(bool macro))
 	if (macro) {
 		char *cp;
 
-		cp = ms = alloc(strlen(ccp) + 1, AEDIT);
-		while ((c = x_bind_getc(&ccp)))
+		cp = ms = alloc(strlen(state.cp) + 1, AEDIT);
+		while ((c = x_bind_getc(&state)))
 			*cp++ = c;
 		*cp = '\0';
 		c = XFUNC_ins_string;
 	} else
 #endif
-	  if (!*ccp) {
+	  if (state.cp[0] == '\0') {
 		c = XFUNC_insert;
 	} else {
 		for (c = 0; c < NELEM(x_ftab); ++c)
-			if (!strcmp(x_ftab[c].xf_name, ccp))
+			if (!strcmp(x_ftab[c].xf_name, state.cp))
 				break;
 		if (c == NELEM(x_ftab) || x_ftab[c].xf_flags & XF_NOBIND) {
-			bi_errorf("%s: no such editing command", ccp);
+			bi_errorf("%s: no such editing command", state.cp);
 			return (1);
 		}
 	}
 
+	t = X_xTABidx(prefix, key);
 #ifndef MKSH_SMALL
-	if (XFUNC_VALUE(x_tab[prefix][key]) == XFUNC_ins_string)
-		afree(x_atab[prefix][key], AEDIT);
-	x_atab[prefix][key] = ms;
+	if (XFUNC_VALUE(x_ktab[t]) == XFUNC_ins_string)
+		afree(x_mtab[t], AEDIT);
+	x_mtab[t] = ms;
 	if (hastilde)
 		c |= 0x80U;
 #endif
-	x_tab[prefix][key] = c;
+	x_ktab[t] = c;
 
-	/* track what the user has bound, so x_mode(true) won't toast things */
+	/* track what the user has bound, so x_mode(Ja) won't toast things */
 	if (c == XFUNC_insert)
-		x_bound[(prefix * X_TABSZ + key) / 8] &=
-		    ~(1 << ((prefix * X_TABSZ + key) % 8));
+		x_btab[t >> 3] &= ~BIT(t & 7);
 	else
-		x_bound[(prefix * X_TABSZ + key) / 8] |=
-		    (1 << ((prefix * X_TABSZ + key) % 8));
+		x_btab[t >> 3] |= BIT(t & 7);
 
 	return (0);
 }
@@ -2623,17 +2747,15 @@ x_bind(const char *s SMALLP(bool macro))
 static void
 bind_if_not_bound(int p, int k, int func)
 {
-	int t;
+	register kui t = X_xTABidx(p, k);
 
 	/*
 	 * Has user already bound this key?
 	 * If so, do not override it.
 	 */
-	t = p * X_TABSZ + k;
-	if (x_bound[t >> 3] & (1 << (t & 7)))
+	if (x_btab[t >> 3] & BIT(t & 7))
 		return;
-
-	x_tab[p][k] = func;
+	x_ktab[t] = func;
 }
 
 static int
@@ -2650,7 +2772,7 @@ x_kill_region(int c MKSH_A_UNUSED)
 	char *xr;
 
 	if (xmp == NULL) {
-		x_e_putc2(KSH_BEL);
+		x_e_putb(KSH_BEL);
 		return (KSTD);
 	}
 	if (xmp > xcp) {
@@ -2661,7 +2783,7 @@ x_kill_region(int c MKSH_A_UNUSED)
 		xr = xmp;
 	}
 	x_goto(xr);
-	x_delete(x_nb2nc(rsize), true);
+	x_delete(x_nb2nc(rsize), Ja);
 	xmp = xr;
 	return (KSTD);
 }
@@ -2672,7 +2794,7 @@ x_xchg_point_mark(int c MKSH_A_UNUSED)
 	char *tmp;
 
 	if (xmp == NULL) {
-		x_e_putc2(KSH_BEL);
+		x_e_putb(KSH_BEL);
 		return (KSTD);
 	}
 	tmp = xmp;
@@ -2750,17 +2872,17 @@ x_expand(int c MKSH_A_UNUSED)
 	    &start, &end, &words);
 
 	if (nwords == 0) {
-		x_e_putc2(KSH_BEL);
+		x_e_putb(KSH_BEL);
 		return (KSTD);
 	}
 	x_goto(xbuf + start);
-	x_delete(x_nb2nc(end - start), false);
+	x_delete(x_nb2nc(end - start), Nee);
 
 	i = 0;
 	while (i < nwords) {
 		if (x_escape(words[i], strlen(words[i]), x_do_ins) < 0 ||
 		    (++i < nwords && x_ins(T1space) < 0)) {
-			x_e_putc2(KSH_BEL);
+			x_e_putb(KSH_BEL);
 			return (KSTD);
 		}
 	}
@@ -2778,18 +2900,18 @@ do_complete(
 {
 	char **words;
 	int start, end, nlen, olen, nwords;
-	bool completed;
+	Wahr completed;
 
 	nwords = x_cf_glob(&flags, xbuf, xep - xbuf, xcp - xbuf,
 	    &start, &end, &words);
 	/* no match */
 	if (nwords == 0) {
-		x_e_putc2(KSH_BEL);
+		x_e_putb(KSH_BEL);
 		return;
 	}
 	if (type == CT_LIST) {
 		x_print_expansions(nwords, words,
-		    tobool(flags & XCF_IS_COMMAND));
+		    isWahr(flags & XCF_IS_COMMAND));
 		x_redraw(0);
 		x_free_words(nwords, words);
 		return;
@@ -2802,7 +2924,7 @@ do_complete(
 		 * any expansion of parameter substitution
 		 * is always at most one result, too
 		 */
-		completed = true;
+		completed = Ja;
 	} else {
 		char *unescaped;
 
@@ -2810,7 +2932,7 @@ do_complete(
 		strndupx(unescaped, xbuf + start, olen, ATEMP);
 
 		/* expand any tilde and unescape the string for comparison */
-		unescaped = x_glob_hlp_tilde_and_rem_qchar(unescaped, true);
+		unescaped = x_glob_hlp_tilde_and_rem_qchar(unescaped, Ja);
 
 		/*
 		 * match iff entire original string is part of the
@@ -2827,12 +2949,19 @@ do_complete(
 		 * just a single match
 		 */
 		x_print_expansions(nwords, words,
-		    tobool(flags & XCF_IS_COMMAND));
+		    isWahr(flags & XCF_IS_COMMAND));
 	}
 	if (completed) {
 		/* expand on the command line */
-		xmp = NULL;
 		xcp = xbuf + start;
+		if (xmp && xmp > xcp) {
+			if (xcp + olen > xmp) {
+				/* sods, within the completion prefix */
+				/* for at least some cases we could do better */
+				xmp = xcp;
+			} else
+				xmp -= olen;
+		}
 		xep -= olen;
 		memmove(xcp, xcp + olen, xep - xcp + 1);
 		x_escape(words[0], nlen, x_do_ins);
@@ -2840,11 +2969,13 @@ do_complete(
 	x_adjust();
 	/*
 	 * append a space if this is a single non-directory match
-	 * and not a parameter or homedir substitution
+	 * and not a parameter substitution, slash for homedir
 	 */
-	if (nwords == 1 && !mksh_cdirsep(words[0][nlen - 1]) &&
-	    !(flags & XCF_IS_NOSPACE)) {
-		x_ins(T1space);
+	if (nwords == 1 && !mksh_cdirsep(words[0][nlen - 1])) {
+		if (flags & XCF_IS_HOMEDIR)
+			x_ins("/");
+		else if (!(flags & XCF_IS_NOSPACE))
+			x_ins(T1space);
 	}
 
 	x_free_words(nwords, words);
@@ -2867,43 +2998,53 @@ do_complete(
 static void
 x_adjust(void)
 {
-	int col_left, n;
+	int colcur, colmax;
 
 	/* flag the fact that we were called */
 	x_adj_done++;
 
+	/* fix up xcp to just past a character end first */
+	xcp = xcp >= xep ? xep : ez_bs(xcp, xbuf);
+	/* shortcut if going to beginning of line */
+	if (xcp == (xbp = xbuf))
+		goto x_adjust_out;
+
+	/* check if the entire line fits */
+	x_displen = xx_cols - 2 - pwidth;
+	xlp_valid = Nee;
+	x_lastcp();
+	/* accept if the cursor is still in the editable area */
+	if (xcp < xdp /*|| xdp >= xep */)
+		goto x_adjust_out;
+
+	/* ok, that was a failure so we need to proceed backwards from xcp */
+	xbp = xcp;
+	/* assert xbp > xbuf */
+
 	/*
-	 * calculate the amount of columns we need to "go back"
-	 * from xcp to set xbp to (but never < xbuf) to 2/3 of
-	 * the display width; take care of pwidth though
+	 * if we have enough space left on screen, we aim to
+	 * position the cursor at 3/4 of the display width;
+	 * if not we emergency-fit just one character before…
 	 */
-	if ((col_left = xx_cols * 2 / 3) < MIN_EDIT_SPACE) {
-		/*
-		 * cowardly refuse to do anything
-		 * if the available space is too small;
-		 * fall back to dumb pdksh code
-		 */
-		if ((xbp = xcp - (x_displen / 2)) < xbuf)
-			xbp = xbuf;
-		/* elide UTF-8 fixup as penalty */
+	if ((colmax = xx_cols * 3 / 4) < MIN_EDIT_SPACE) {
+		/* one backwards though */
+		xbp = ez_bs(xbp - 1, xbuf);
+		/* go for it */
 		goto x_adjust_out;
 	}
 
-	/* fix up xbp to just past a character end first */
-	xbp = xcp >= xep ? xep : x_bs0(xcp, xbuf);
-	/* walk backwards */
-	while (xbp > xbuf && col_left > 0) {
-		xbp = x_bs0(xbp - 1, xbuf);
-		col_left -= (n = x_size2(xbp, NULL));
-	}
-	/* check if we hit the prompt */
-	if (xbp == xbuf && xcp != xbuf && col_left >= 0 && col_left < pwidth) {
-		/* so we did; force scrolling occurs */
-		xbp += utf_ptradj(xbp);
+	/* go backwards until we reached the target width */
+	colcur = 0;
+	while (xbp > xbuf && colcur < colmax) {
+		xbp = ez_bs(xbp - 1, xbuf);
+		colcur += uwidthmbT(xbp, NULL);
 	}
+	/* check if we hit the prompt and force scrolling if so */
+	if (xbp == xbuf)
+		xbp += ez_mbtoc(NULL, xbp);
 
  x_adjust_out:
-	xlp_valid = false;
+	xlp_valid = Nee;
 	x_redraw('\r');
 	x_flush();
 }
@@ -2936,42 +3077,23 @@ x_e_getc(void)
 	return (x_getc());
 }
 
+/* takes single-column single-byte characters only */
 static void
-x_e_putc2(int c)
+x_e_putb(int c)
 {
-	int width = 1;
-
-	if (ctype(c, C_CR | C_LF))
+	if (ctype(c, C_CR | C_LF)) {
+		x_putc(c);
 		x_col = 0;
-	if (x_col < xx_cols) {
-#ifndef MKSH_EBCDIC
-		if (UTFMODE && (c > 0x7F)) {
-			char utf_tmp[3];
-			size_t x;
-
-			if (c < 0xA0)
-				c = 0xFFFD;
-			x = utf_wctomb(utf_tmp, c);
-			x_putc(utf_tmp[0]);
-			if (x > 1)
-				x_putc(utf_tmp[1]);
-			if (x > 2)
-				x_putc(utf_tmp[2]);
-			width = utf_wcwidth(c);
-		} else
-#endif
-			x_putc(c);
-		switch (c) {
-		case KSH_BEL:
-			break;
-		case '\r':
-		case '\n':
+	} else if (x_col < xx_cols) {
+		x_putc(c);
+		switch (ord(c)) {
+		case ORD(KSH_BEL):
 			break;
-		case '\b':
-			x_col--;
+		case ORD('\b'):
+			--x_col;
 			break;
 		default:
-			x_col += width;
+			++x_col;
 			break;
 		}
 	}
@@ -2980,58 +3102,50 @@ x_e_putc2(int c)
 }
 
 static void
-x_e_putc3(const char **cp)
+x_e_puts(const char *s)
 {
-	int width = 1, c = **(const unsigned char **)cp;
+	unsigned int c;
+	int width;
+	size_t len;
+	kby adj = x_adj_done;
 
-	if (ctype(c, C_CR | C_LF))
-		x_col = 0;
-	if (x_col < xx_cols) {
-		if (UTFMODE && (c > 0x7F)) {
-			char *cp2;
-
-			width = utf_widthadj(*cp, (const char **)&cp2);
-			if (cp2 == *cp + 1) {
-				(*cp)++;
-#ifdef MKSH_EBCDIC
-				x_putc(asc2rtt(0xEF));
-				x_putc(asc2rtt(0xBF));
-				x_putc(asc2rtt(0xBD));
-#else
-				shf_puts("\xEF\xBF\xBD", shl_out);
-#endif
-			} else
-				while (*cp < cp2)
-					x_putcf(*(*cp)++);
-		} else {
-			(*cp)++;
+	while ((c = ord(*s)) && adj == x_adj_done) {
+		if (ctype(c, C_CR | C_LF)) {
 			x_putc(c);
+			x_col = 0;
+			++s;
+		} else if (x_col < xx_cols) {
+			if (rtt2asc(c) < 0x80U || !UTFMODE) {
+				x_putc(c);
+				switch (c) {
+				case ORD(KSH_BEL):
+					break;
+				case ORD('\b'):
+					--x_col;
+					break;
+				default:
+					++x_col;
+					break;
+				}
+				++s;
+			} else if ((len = utf_mbtowc(&c, s)) == (size_t)-1) {
+				/* substitute U+FFFD */
+				x_putcf(asc2rtt(0xEF));
+				x_putcf(asc2rtt(0xBF));
+				x_putcf(asc2rtt(0xBD));
+				++x_col;
+				++s;
+			} else {
+				/* C1 control character? C0/DEL use 1 above */
+				if ((width = utf_wcwidth(c)) < 0)
+					width = /* for consistency */ 1;
+				shf_wr_sm(s, len, shl_out);
+				x_col += width;
+			}
 		}
-		switch (c) {
-		case KSH_BEL:
-			break;
-		case '\r':
-		case '\n':
-			break;
-		case '\b':
-			x_col--;
-			break;
-		default:
-			x_col += width;
-			break;
-		}
+		if (x_adj_ok && (x_col < 0 || x_col >= (xx_cols - 2)))
+			x_adjust();
 	}
-	if (x_adj_ok && (x_col < 0 || x_col >= (xx_cols - 2)))
-		x_adjust();
-}
-
-static void
-x_e_puts(const char *s)
-{
-	int adj = x_adj_done;
-
-	while (*s && adj == x_adj_done)
-		x_e_putc3(&s);
 }
 
 /*-
@@ -3048,27 +3162,28 @@ static int
 x_set_arg(int c)
 {
 	unsigned int n = 0;
-	bool first = true;
+	Wahr first = Ja;
 
 	/* strip command prefix */
 	c &= 255;
-	while (c >= 0 && ctype(c, C_DIGIT)) {
+	/* loop to get digits */
+	while (cinttype(c, C_DIGIT)) {
 		n = n * 10 + ksh_numdig(c);
 		if (n > LINE)
 			/* upper bound for repeat */
 			goto x_set_arg_too_big;
 		c = x_e_getc();
-		first = false;
+		first = Nee;
 	}
 	if (c < 0 || first) {
  x_set_arg_too_big:
-		x_e_putc2(KSH_BEL);
+		x_e_putb(KSH_BEL);
 		x_arg = 1;
-		x_arg_defaulted = true;
+		x_arg_defaulted = Ja;
 	} else {
 		x_e_ungetc(c);
 		x_arg = n;
-		x_arg_defaulted = false;
+		x_arg_defaulted = Nee;
 	}
 	return (KSTD);
 }
@@ -3081,7 +3196,7 @@ x_comment(int c MKSH_A_UNUSED)
 	int ret = x_do_comment(xbuf, xend - xbuf, &len);
 
 	if (ret < 0)
-		x_e_putc2(KSH_BEL);
+		x_e_putb(KSH_BEL);
 	else {
 		x_modified();
 		xep = xbuf + len;
@@ -3133,7 +3248,7 @@ x_edit_line(int c MKSH_A_UNUSED)
 	if (x_arg_defaulted) {
 		if (modified) {
 			*xep = '\0';
-			histsave(&source->line, xbuf, HIST_STORE, true);
+			histsave(&source->line, xbuf, HIST_STORE, Ja);
 			x_arg = 0;
 		} else
 			x_arg = source->line - (histptr - x_histp);
@@ -3149,12 +3264,12 @@ x_edit_line(int c MKSH_A_UNUSED)
 
 /*-
  * NAME:
- *	x_prev_histword - recover word from prev command
+ *	x_prev_histword - recover bigword from prev command
  *
  * DESCRIPTION:
- *	This function recovers the last word from the previous
+ *	This function recovers the last bigword from the previous
  *	command and inserts it into the current edit line. If a
- *	numeric arg is supplied then the n'th word from the
+ *	numeric arg is supplied then the n'th bigword from the
  *	start of the previous command is used.
  *	As a side effect, trashes the mark in order to achieve
  *	being called in a repeatable fashion.
@@ -3182,7 +3297,7 @@ x_prev_histword(int c MKSH_A_UNUSED)
 		last_arg = x_arg_defaulted ? -1 : x_arg;
 	xhp = histptr - (m - 1);
 	if ((xhp < history) || !(cp = *xhp)) {
-		x_e_putc2(KSH_BEL);
+		x_e_putb(KSH_BEL);
 		x_modified();
 		return (KSTD);
 	}
@@ -3192,13 +3307,13 @@ x_prev_histword(int c MKSH_A_UNUSED)
 
 		rcp = &cp[strlen(cp) - 1];
 		/*
-		 * ignore white-space after the last word
+		 * ignore whitespace after the last bigword
 		 */
-		while (rcp > cp && ctype(*rcp, C_CFS))
+		while (rcp > cp && ctype(*rcp, C_BLANK))
 			rcp--;
-		while (rcp > cp && !ctype(*rcp, C_CFS))
+		while (rcp > cp && !ctype(*rcp, C_BLANK))
 			rcp--;
-		if (ctype(*rcp, C_CFS))
+		if (ctype(*rcp, C_BLANK))
 			rcp++;
 		x_ins(rcp);
 	} else {
@@ -3207,18 +3322,18 @@ x_prev_histword(int c MKSH_A_UNUSED)
 
 		rcp = cp;
 		/*
-		 * ignore white-space at start of line
+		 * ignore whitespace at start of line
 		 */
-		while (*rcp && ctype(*rcp, C_CFS))
+		while (*rcp && ctype(*rcp, C_BLANK))
 			rcp++;
 		while (x_arg-- > 0) {
-			while (*rcp && !ctype(*rcp, C_CFS))
+			while (*rcp && !ctype(*rcp, C_BLANK))
 				rcp++;
-			while (*rcp && ctype(*rcp, C_CFS))
+			while (*rcp && ctype(*rcp, C_BLANK))
 				rcp++;
 		}
 		cp = rcp;
-		while (*rcp && !ctype(*rcp, C_CFS))
+		while (*rcp && !ctype(*rcp, C_BLANK))
 			rcp++;
 		ch = *rcp;
 		*rcp = '\0';
@@ -3236,21 +3351,42 @@ x_prev_histword(int c MKSH_A_UNUSED)
 static int
 x_fold_upper(int c MKSH_A_UNUSED)
 {
-	return (x_fold_case('U'));
+	return (x_fold_case('U', C_MFS));
 }
 
 /* Lowercase N(1) words */
 static int
 x_fold_lower(int c MKSH_A_UNUSED)
 {
-	return (x_fold_case('L'));
+	return (x_fold_case('L', C_MFS));
 }
 
 /* Titlecase N(1) words */
 static int
 x_fold_capitalise(int c MKSH_A_UNUSED)
 {
-	return (x_fold_case('C'));
+	return (x_fold_case('C', C_MFS));
+}
+
+/* Uppercase N(1) bigwords */
+static int
+x_foldb_upper(int c MKSH_A_UNUSED)
+{
+	return (x_fold_case('U', C_BLANK));
+}
+
+/* Lowercase N(1) bigwords */
+static int
+x_foldb_lower(int c MKSH_A_UNUSED)
+{
+	return (x_fold_case('L', C_BLANK));
+}
+
+/* Titlecase N(1) bigwords */
+static int
+x_foldb_capitalise(int c MKSH_A_UNUSED)
+{
+	return (x_fold_case('C', C_BLANK));
 }
 
 /*-
@@ -3259,25 +3395,25 @@ x_fold_capitalise(int c MKSH_A_UNUSED)
  *
  * DESCRIPTION:
  *	This function is used to implement M-U/M-u, M-L/M-l, M-C/M-c
- *	to UPPER CASE, lower case or Capitalise Words.
+ *	to UPPER CASE, lower case or Capitalise words and bigwords.
  *
  * RETURN VALUE:
  *	None
  */
 static int
-x_fold_case(int c)
+x_fold_case(int c, kui separator)
 {
 	char *cp = xcp;
 
 	if (cp == xep) {
-		x_e_putc2(KSH_BEL);
+		x_e_putb(KSH_BEL);
 		return (KSTD);
 	}
 	while (x_arg--) {
 		/*
 		 * first skip over any white-space
 		 */
-		while (cp != xep && ctype(*cp, C_MFS))
+		while (cp != xep && ctype(*cp, separator))
 			cp++;
 		/*
 		 * do the first char on its own since it may be
@@ -3295,7 +3431,7 @@ x_fold_case(int c)
 		/*
 		 * now for the rest of the word
 		 */
-		while (cp != xep && !ctype(*cp, C_MFS)) {
+		while (cp != xep && !ctype(*cp, separator)) {
 			if (c == 'U')
 				/* uppercase */
 				*cp = ksh_toupper(*cp);
@@ -3318,7 +3454,7 @@ x_fold_case(int c)
  * DESCRIPTION:
  *	This function returns a pointer to that char in the
  *	edit buffer that will be the last displayed on the
- *	screen.
+ *	screen. It also updates xlp and xdp.
  */
 static char *
 x_lastcp(void)
@@ -3329,14 +3465,20 @@ x_lastcp(void)
 
 		xlp = xbp;
 		while (xlp < xep) {
-			j = x_size2(xlp, &xlp2);
-			if ((i + j) > x_displen)
-				break;
+			j = uwidthmbT(xlp, &xlp2);
+			if ((i + j) > x_displen) {
+				/* don’t add (x_displen - i) here */
+				/* can be 2-column doesn’t-fit char */
+				xdp = xlp;
+				goto xlp_longline;
+			}
 			i += j;
 			xlp = xlp2;
 		}
+		xdp = xlp + (x_displen - i);
+ xlp_longline:
+		xlp_valid = Ja;
 	}
-	xlp_valid = true;
 	return (xlp);
 }
 
@@ -3351,16 +3493,16 @@ x_lastpos(void)
 }
 
 static void
-x_mode(bool onoff)
+x_mode(Wahr onoff)
 {
-	static bool x_cur_mode;
+	static Wahr x_cur_mode;
 
 	if (x_cur_mode == onoff)
 		return;
 	x_cur_mode = onoff;
 
 	if (onoff) {
-		x_mkraw(tty_fd, NULL, false);
+		x_mkraw(tty_fd, NULL, Nee);
 
 		edchars.erase = toedchar(tty_state.c_cc[VERASE]);
 		edchars.kill = toedchar(tty_state.c_cc[VKILL]);
@@ -3424,9 +3566,9 @@ static void yank_range(int, int);
 static int bracktype(int);
 static void save_cbuf(void);
 static void restore_cbuf(void);
-static int putbuf(const char *, ssize_t, bool);
+static int putbuf(const char *, ssize_t, Wahr);
 static void del_range(int, int);
-static int findch(int, int, bool, bool) MKSH_A_PURE;
+static int findch(int, int, Wahr, Wahr);
 static int forwword(int);
 static int backword(int);
 static int endword(int);
@@ -3434,13 +3576,13 @@ static int Forwword(int);
 static int Backword(int);
 static int Endword(int);
 static int grabhist(int, int);
-static int grabsearch(const char *, int, int, bool);
-static void redraw_line(bool);
-static void refresh(bool);
+static int grabsearch(const char *, int, int, Wahr);
+static void redraw_line(Wahr);
+static void refresh(Wahr);
 static int outofwin(void);
 static void rewindow(void);
 static int newcol(unsigned char, int);
-static void display(char *, char *, bool);
+static void display(char *, char *, Wahr);
 static void ed_mov_opt(int, char *);
 static int expand_word(int);
 static int complete_word(int, int);
@@ -3449,6 +3591,7 @@ static void vi_error(void);
 static void vi_macro_reset(void);
 static int x_vi_putbuf(const char *, size_t);
 #define char_len(c) (ksh_isctrl(c) ? 2 : 1)
+#define ksh_unctrl(c) asc2rtt(rtt2asc(c) ^ 0x40U)
 
 #define vC	0x01		/* a valid command that isn't a vM, vE, vU */
 #define vM	0x02		/* movement command (h, l, etc.) */
@@ -3534,17 +3677,17 @@ static struct edstate	*vs;		/* current V
 static struct edstate	*undo;
 
 static char *ibuf;			/* input buffer */
-static bool first_insert;		/* set when starting in insert mode */
+static Wahr first_insert;		/* set when starting in insert mode */
 static int saved_inslen;		/* saved inslen for first insert */
 static int inslen;			/* length of input buffer */
 static int srchlen;			/* length of current search pattern */
 static char *ybuf;			/* yank buffer */
 static int yanklen;			/* length of yank buffer */
-static uint8_t fsavecmd = ORD(' ');	/* last find command */
+static kby fsavecmd = ORD(' ');		/* last find command */
 static int fsavech;			/* character to find */
 static char lastcmd[MAXVICMD];		/* last non-move command */
 static int lastac;			/* argcnt for lastcmd */
-static uint8_t lastsearch = ORD(' ');	/* last search command */
+static kby lastsearch = ORD(' ');	/* last search command */
 static char srchpat[SRCHLEN];		/* last search pattern */
 static int insert;			/* <>0 in insert mode */
 static int hnum;			/* position in history */
@@ -3571,7 +3714,7 @@ static enum expand_mode {
 	NONE = 0, EXPAND, COMPLETE, PRINT
 } expanded;
 
-static int
+static ssize_t
 x_vi(char *buf)
 {
 	int c;
@@ -3580,7 +3723,7 @@ x_vi(char *buf)
 	ohnum = hnum = hlast = histnum(-1) + 1;
 	insert = INSERT;
 	saved_inslen = inslen;
-	first_insert = true;
+	first_insert = Ja;
 	inslen = 0;
 	vi_macro_reset();
 
@@ -3597,7 +3740,7 @@ x_vi(char *buf)
 	vs = &ebuf;
 	undo = &undobuf;
 
-	x_init_prompt(true);
+	x_init_prompt(Ja);
 	x_col = pwidth;
 
 	if (wbuf_len != x_cols - 3 && ((wbuf_len = x_cols - 3))) {
@@ -3646,7 +3789,11 @@ x_vi(char *buf)
 			} else if (isched(c, edchars.eof) &&
 			    state != VVERSION) {
 				if (vs->linelen == 0) {
-					x_vi_zotc(c);
+					if (ksh_isctrl(c)) {
+						x_putc('^');
+						c = ksh_unctrl(c);
+					}
+					x_putc(c);
 					c = -1;
 					break;
 				}
@@ -3712,7 +3859,7 @@ vi_hook(int ch)
 			case 0:
 				if (state == VLIT) {
 					vs->cursor--;
-					refresh(false);
+					refresh(Nee);
 				} else
 					refresh(insert != 0);
 				break;
@@ -3736,17 +3883,17 @@ vi_hook(int ch)
 					vs->cursor = 0;
 					vs->linelen = 0;
 					if (putbuf(ord(ch) == ORD('/') ?
-					    "/" : "?", 1, false) != 0)
+					    "/" : "?", 1, Nee) != 0)
 						return (-1);
-					refresh(false);
+					refresh(Nee);
 				}
 				if (state == VVERSION) {
 					save_cbuf();
 					vs->cursor = 0;
 					vs->linelen = 0;
 					putbuf(KSH_VERSION,
-					    strlen(KSH_VERSION), false);
-					refresh(false);
+					    strlen(KSH_VERSION), Nee);
+					refresh(Nee);
 				}
 			}
 		}
@@ -3758,14 +3905,14 @@ vi_hook(int ch)
 			vi_error();
 		} else
 			vs->cbuf[vs->cursor++] = ch;
-		refresh(true);
+		refresh(Ja);
 		state = VNORMAL;
 		break;
 
 	case VVERSION:
 		restore_cbuf();
 		state = VNORMAL;
-		refresh(false);
+		refresh(Nee);
 		break;
 
 	case VARG1:
@@ -3829,7 +3976,7 @@ vi_hook(int ch)
 				if (!srchpat[0]) {
 					vi_error();
 					state = VNORMAL;
-					refresh(false);
+					refresh(Nee);
 					return (0);
 				}
 			} else {
@@ -3842,17 +3989,17 @@ vi_hook(int ch)
 				srchlen--;
 				vs->linelen -= char_len(locpat[srchlen]);
 				vs->cursor = vs->linelen;
-				refresh(false);
+				refresh(Nee);
 				return (0);
 			}
 			restore_cbuf();
 			state = VNORMAL;
-			refresh(false);
+			refresh(Nee);
 		} else if (isched(ch, edchars.kill)) {
 			srchlen = 0;
 			vs->linelen = 1;
 			vs->cursor = 1;
-			refresh(false);
+			refresh(Nee);
 			return (0);
 		} else if (isched(ch, edchars.werase)) {
 			unsigned int i, n;
@@ -3871,7 +4018,7 @@ vi_hook(int ch)
 				vs->linelen -= char_len(locpat[i]);
 			srchlen = (int)n;
 			vs->cursor = vs->linelen;
-			refresh(false);
+			refresh(Nee);
 			return (0);
 		} else {
 			if (srchlen == SRCHLEN - 1)
@@ -3890,7 +4037,7 @@ vi_hook(int ch)
 					vs->cbuf[vs->linelen++] = ch;
 				}
 				vs->cursor = vs->linelen;
-				refresh(false);
+				refresh(Nee);
 			}
 			return (0);
 		}
@@ -3931,7 +4078,7 @@ vi_hook(int ch)
 		switch (vi_cmd(argc1, curcmd)) {
 		case -1:
 			vi_error();
-			refresh(false);
+			refresh(Nee);
 			break;
 		case 0:
 			if (insert != 0)
@@ -3939,7 +4086,7 @@ vi_hook(int ch)
 			refresh(insert != 0);
 			break;
 		case 1:
-			refresh(false);
+			refresh(Nee);
 			return (1);
 		case 2:
 			/* back from a 'v' command - don't redraw the screen */
@@ -3954,12 +4101,12 @@ vi_hook(int ch)
 		switch (vi_cmd(lastac, lastcmd)) {
 		case -1:
 			vi_error();
-			refresh(false);
+			refresh(Nee);
 			break;
 		case 0:
 			if (insert != 0) {
 				if (lastcmd[0] == 's' ||
-				    ksh_eq(lastcmd[0], 'C', 'c')) {
+				    isCh(lastcmd[0], 'C', 'c')) {
 					if (redo_insert(1) != 0)
 						vi_error();
 				} else {
@@ -3967,10 +4114,10 @@ vi_hook(int ch)
 						vi_error();
 				}
 			}
-			refresh(false);
+			refresh(Nee);
 			break;
 		case 1:
-			refresh(false);
+			refresh(Nee);
 			return (1);
 		case 2:
 			/* back from a 'v' command - can't happen */
@@ -4080,7 +4227,7 @@ vi_insert(int ch)
 	case CTRL_BO:
 		expanded = NONE;
 		if (first_insert) {
-			first_insert = false;
+			first_insert = Nee;
 			if (inslen == 0) {
 				inslen = saved_inslen;
 				return (redo_insert(0));
@@ -4088,7 +4235,7 @@ vi_insert(int ch)
 			lastcmd[0] = 'a';
 			lastac = 1;
 		}
-		if (lastcmd[0] == 's' || ksh_eq(lastcmd[0], 'C', 'c'))
+		if (lastcmd[0] == 's' || isCh(lastcmd[0], 'C', 'c'))
 			return (redo_insert(0));
 		else
 			return (redo_insert(lastac - 1));
@@ -4137,7 +4284,7 @@ vi_cmd(int argcnt, const char *cmd)
 	int ncursor;
 	int cur, c1, c2;
 	int any;
-	bool b;
+	Wahr b;
 	struct edstate *t;
 
 	if (argcnt == 0 && !is_zerocount(*cmd))
@@ -4164,7 +4311,7 @@ vi_cmd(int argcnt, const char *cmd)
 
 		case CTRL_L:
 		case CTRL_R:
-			redraw_line(true);
+			redraw_line(Ja);
 			break;
 
 		case ORD('@'):
@@ -4185,14 +4332,10 @@ vi_cmd(int argcnt, const char *cmd)
 						if (*++p == cmd[1])
 							return (-1);
 				/* insert alias into macro buffer */
-				nlen = strlen(ap->val.s) + 1;
+				nlen = strlen(ap->val.s) + 1U;
 				olen = !macro.p ? 2 :
 				    macro.len - (macro.p - macro.buf);
-				/*
-				 * at this point, it's fairly reasonable that
-				 * nlen + olen + 2 doesn't overflow
-				 */
-				nbuf = alloc(nlen + 1 + olen, AEDIT);
+				nbuf = alloc1(nlen + 1U, olen, AEDIT);
 				memcpy(nbuf, ap->val.s, nlen);
 				nbuf[nlen++] = cmd[1];
 				if (macro.p) {
@@ -4248,7 +4391,7 @@ vi_cmd(int argcnt, const char *cmd)
 			else {
 				if ((ncursor = domove(argcnt, &cmd[1], 1)) < 0)
 					return (-1);
-				if (*cmd == 'c' && ksh_eq(cmd[1], 'W', 'w') &&
+				if (*cmd == 'c' && isCh(cmd[1], 'W', 'w') &&
 				    !ctype(vs->cbuf[vs->cursor], C_SPACE)) {
 					do {
 						--ncursor;
@@ -4283,7 +4426,7 @@ vi_cmd(int argcnt, const char *cmd)
 			hnum = hlast;
 			if (vs->linelen != 0)
 				vs->cursor++;
-			while (putbuf(ybuf, yanklen, false) == 0 &&
+			while (putbuf(ybuf, yanklen, Nee) == 0 &&
 			    --argcnt > 0)
 				;
 			if (vs->cursor != 0)
@@ -4296,7 +4439,7 @@ vi_cmd(int argcnt, const char *cmd)
 			modified = 1;
 			hnum = hlast;
 			any = 0;
-			while (putbuf(ybuf, yanklen, false) == 0 &&
+			while (putbuf(ybuf, yanklen, Nee) == 0 &&
 			    --argcnt > 0)
 				any = 1;
 			if (any && vs->cursor != 0)
@@ -4411,7 +4554,7 @@ vi_cmd(int argcnt, const char *cmd)
 				if (modified) {
 					vs->cbuf[vs->linelen] = '\0';
 					histsave(&source->line, vs->cbuf,
-					    HIST_STORE, true);
+					    HIST_STORE, Ja);
 				} else
 					argcnt = source->line + 1 -
 					    (hlast - hnum);
@@ -4486,7 +4629,7 @@ vi_cmd(int argcnt, const char *cmd)
 			if ((c2 = grabsearch(srchpat, modified, hnum, b)) < 0) {
 				if (c1) {
 					restore_cbuf();
-					refresh(false);
+					refresh(Nee);
 				}
 				return (-1);
 			} else {
@@ -4502,7 +4645,7 @@ vi_cmd(int argcnt, const char *cmd)
 			break;
 		case ORD('_'):
 			{
-				bool inspace;
+				Wahr inspace;
 				char *p, *sp;
 
 				if (histnum(-1) < 0)
@@ -4522,12 +4665,12 @@ vi_cmd(int argcnt, const char *cmd)
 					sp = p;
 				} else {
 					sp = p;
-					inspace = false;
+					inspace = Nee;
 					while (*p) {
 						if (ctype(*p, C_SPACE))
-							inspace = true;
+							inspace = Ja;
 						else if (inspace) {
-							inspace = false;
+							inspace = Nee;
 							sp = p;
 						}
 						p++;
@@ -4542,8 +4685,8 @@ vi_cmd(int argcnt, const char *cmd)
 					argcnt++;
 					p++;
 				}
-				if (putbuf(T1space, 1, false) != 0 ||
-				    putbuf(sp, argcnt, false) != 0) {
+				if (putbuf(T1space, 1, Nee) != 0 ||
+				    putbuf(sp, argcnt, Nee) != 0) {
 					if (vs->cursor != 0)
 						vs->cursor--;
 					return (-1);
@@ -4592,7 +4735,6 @@ vi_cmd(int argcnt, const char *cmd)
 			print_expansions(vs, 1);
 			break;
 
-
 		/* Nonstandard vi/ksh */
 		case CTRL_I:
 			if (!Flag(FVITABCOMPLETE))
@@ -4612,7 +4754,6 @@ vi_cmd(int argcnt, const char *cmd)
 			complete_word(1, argcnt);
 			break;
 
-
 		/* AT&T ksh */
 		case ORD('*'):
 		/* Nonstandard vi/ksh */
@@ -4620,7 +4761,6 @@ vi_cmd(int argcnt, const char *cmd)
 			expand_word(1);
 			break;
 
-
 		/* mksh: cursor movement */
 		case ORD('['):
 		case ORD('O'):
@@ -4682,12 +4822,12 @@ domove(int argcnt, const char *cmd, int
 	case ORD(';'):
 		if (fsavecmd == ORD(' '))
 			return (-1);
-		i = ksh_eq(fsavecmd, 'F', 'f');
+		i = isCh(fsavecmd, 'F', 'f');
 		t = rtt2asc(fsavecmd) > rtt2asc('a');
 		if (*cmd == ',')
 			t = !t;
-		if ((ncursor = findch(fsavech, argcnt, tobool(t),
-		    tobool(i))) < 0)
+		if ((ncursor = findch(fsavech, argcnt, isWahr(t),
+		    isWahr(i))) < 0)
 			return (-1);
 		if (sub && t)
 			ncursor++;
@@ -4795,7 +4935,7 @@ static int
 redo_insert(int count)
 {
 	while (count-- > 0)
-		if (putbuf(ibuf, inslen, tobool(insert == REPLACE)) != 0)
+		if (putbuf(ibuf, inslen, isWahr(insert == REPLACE)) != 0)
 			return (-1);
 	if (vs->cursor > 0)
 		vs->cursor--;
@@ -4898,11 +5038,11 @@ free_edstate(struct edstate *old)
 static int
 x_vi_putbuf(const char *s, size_t len)
 {
-	return (putbuf(s, len, false));
+	return (putbuf(s, len, Nee));
 }
 
 static int
-putbuf(const char *buf, ssize_t len, bool repl)
+putbuf(const char *buf, ssize_t len, Wahr repl)
 {
 	if (len == 0)
 		return (0);
@@ -4932,7 +5072,7 @@ del_range(int a, int b)
 }
 
 static int
-findch(int ch, int cnt, bool forw, bool incl)
+findch(int ch, int cnt, Wahr forw, Wahr incl)
 {
 	int ncursor;
 
@@ -5095,9 +5235,10 @@ grabhist(int save, int n)
 		ohnum = n;
 		return (0);
 	}
-	(void)histnum(n);
+	histnum(n);
 	if ((hptr = *histpos()) == NULL) {
-		internal_warningf("grabhist: bad history array");
+		kwarnf(KWF_INTERNAL | KWF_WARNING | KWF_ONEMSG | KWF_NOERRNO,
+		    "grabhist: bad history array");
 		return (-1);
 	}
 	if (save)
@@ -5111,11 +5252,11 @@ grabhist(int save, int n)
 }
 
 static int
-grabsearch(const char *pat, int save, int start, bool fwd)
+grabsearch(const char *pat, int save, int start, Wahr fwd)
 {
 	char *hptr;
 	int hist;
-	bool anchored;
+	Wahr anchored;
 
 	if ((start == 0 && !fwd) || (start >= hlast - 1 && fwd))
 		return (-1);
@@ -5123,7 +5264,7 @@ grabsearch(const char *pat, int save, in
 		start++;
 	else
 		start--;
-	anchored = *pat == '^' ? (++pat, true) : false;
+	anchored = *pat == '^' ? (++pat, Ja) : Nee;
 	if ((hist = findhist(start, pat, fwd, anchored)) < 0) {
 		/* (start != 0 && fwd && match(holdbufp, pat) >= 0) */
 		if (start != 0 && fwd && strcmp(holdbufp, pat) >= 0) {
@@ -5144,7 +5285,7 @@ grabsearch(const char *pat, int save, in
 }
 
 static void
-redraw_line(bool newl)
+redraw_line(Wahr newl)
 {
 	if (wbuf_len)
 		memset(wbuf[win], ' ', wbuf_len);
@@ -5157,7 +5298,7 @@ redraw_line(bool newl)
 }
 
 static void
-refresh(bool leftside)
+refresh(Wahr leftside)
 {
 	if (outofwin())
 		rewindow();
@@ -5214,7 +5355,7 @@ newcol(unsigned char ch, int col)
 }
 
 static void
-display(char *wb1, char *wb2, bool leftside)
+display(char *wb1, char *wb2, Wahr leftside)
 {
 	unsigned char ch;
 	char *twb1, *twb2, mc;
@@ -5318,7 +5459,6 @@ ed_mov_opt(int col, char *wb)
 	x_col = col;
 }
 
-
 /* replace word with all expansions (ie, expand word*) */
 static int
 expand_word(int cmd)
@@ -5357,7 +5497,7 @@ expand_word(int cmd)
 			rval = -1;
 			break;
 		}
-		if (++i < nwords && putbuf(T1space, 1, false) != 0) {
+		if (++i < nwords && putbuf(T1space, 1, Nee) != 0) {
 			rval = -1;
 			break;
 		}
@@ -5369,7 +5509,7 @@ expand_word(int cmd)
 	hnum = hlast;
 	insert = INSERT;
 	lastac = 0;
-	refresh(false);
+	refresh(Nee);
 	return (rval);
 }
 
@@ -5381,7 +5521,7 @@ complete_word(int cmd, int count)
 	size_t match_len;
 	char **words;
 	char *match;
-	bool is_unique;
+	Wahr is_unique;
 
 	/* Undo previous completion */
 	if (cmd == 0 && expanded == COMPLETE && buf) {
@@ -5420,9 +5560,9 @@ complete_word(int cmd, int count)
 		if (count >= nwords) {
 			vi_error();
 			x_print_expansions(nwords, words,
-			    tobool(flags & XCF_IS_COMMAND));
+			    isWahr(flags & XCF_IS_COMMAND));
 			x_free_words(nwords, words);
-			redraw_line(false);
+			redraw_line(Nee);
 			return (-1);
 		}
 		/*
@@ -5442,7 +5582,7 @@ complete_word(int cmd, int count)
 		} else
 			match = words[count];
 		match_len = strlen(match);
-		is_unique = true;
+		is_unique = Ja;
 		/* expanded = PRINT;	next call undo */
 	} else {
 		match = words[0];
@@ -5471,11 +5611,14 @@ complete_word(int cmd, int count)
 
 		/*
 		 * append a space if this is a non-directory match
-		 * and not a parameter or homedir substitution
+		 * and not a parameter substitution, slash for homedir
 		 */
-		if (match_len > 0 && !mksh_cdirsep(match[match_len - 1]) &&
-		    !(flags & XCF_IS_NOSPACE))
-			rval = putbuf(T1space, 1, false);
+		if (match_len > 0 && !mksh_cdirsep(match[match_len - 1])) {
+			if (flags & XCF_IS_HOMEDIR)
+				rval = putbuf("/", 1, Nee);
+			else if (!(flags & XCF_IS_NOSPACE))
+				rval = putbuf(T1space, 1, Nee);
+		}
 	}
 	x_free_words(nwords, words);
 
@@ -5484,7 +5627,7 @@ complete_word(int cmd, int count)
 	insert = INSERT;
 	/* prevent this from being redone... */
 	lastac = 0;
-	refresh(false);
+	refresh(Nee);
 
 	return (rval);
 }
@@ -5502,25 +5645,12 @@ print_expansions(struct edstate *est, in
 		vi_error();
 		return (-1);
 	}
-	x_print_expansions(nwords, words, tobool(i & XCF_IS_COMMAND));
+	x_print_expansions(nwords, words, isWahr(i & XCF_IS_COMMAND));
 	x_free_words(nwords, words);
-	redraw_line(false);
+	redraw_line(Nee);
 	return (0);
 }
-#endif /* !MKSH_S_NOVI */
 
-/* Similar to x_zotc(emacs.c), but no tab weirdness */
-static void
-x_vi_zotc(int c)
-{
-	if (ksh_isctrl(c)) {
-		x_putc('^');
-		c = ksh_unctrl(c);
-	}
-	x_putc(c);
-}
-
-#if !MKSH_S_NOVI
 static void
 vi_error(void)
 {
@@ -5544,7 +5674,7 @@ vi_macro_reset(void)
 void
 x_init(void)
 {
-	int i, j;
+	size_t i;
 
 	/*
 	 * set edchars to force initial binding, except we need
@@ -5561,29 +5691,32 @@ x_init(void)
 	/* initialise Emacs command line editing mode */
 	x_nextcmd = -1;
 
-	x_tab = alloc2(X_NTABS, sizeof(*x_tab), AEDIT);
-	for (j = 0; j < X_TABSZ; j++)
-		x_tab[0][j] = XFUNC_insert;
-	for (i = 1; i < X_NTABS; i++)
-		for (j = 0; j < X_TABSZ; j++)
-			x_tab[i][j] = XFUNC_error;
-	for (i = 0; i < (int)NELEM(x_defbindings); i++)
-		x_tab[x_defbindings[i].xdb_tab][x_defbindings[i].xdb_char]
-		    = x_defbindings[i].xdb_func;
+	x_ktab = alloc2(X_NTABS << 8, sizeof(kby), AEDIT);
+	i = 0;
+	while (i <= 0xFF)
+		x_ktab[i++] = XFUNC_insert;
+	while (i < (X_NTABS << 8))
+		x_ktab[i++] = XFUNC_error;
+	for (i = 0; i < NELEM(x_defbindings); ++i)
+		X_KTAB(x_defbindings[i].xdb_tab,
+		    x_defbindings[i].xdb_char) = x_defbindings[i].xdb_func;
 
 #ifndef MKSH_SMALL
-	x_atab = alloc2(X_NTABS, sizeof(*x_atab), AEDIT);
-	for (i = 1; i < X_NTABS; i++)
-		for (j = 0; j < X_TABSZ; j++)
-			x_atab[i][j] = NULL;
+	x_mtab = alloc2(X_NTABS << 8, sizeof(char *), AEDIT);
+	i = 0;
+	while (i < (X_NTABS << 8))
+		x_mtab[i++] = NULL;
 #endif
+
+	x_btab = alloc2(X_NTABS << (8 - 3), sizeof(kby), AEDIT);
+	memset(x_btab, 0, (X_NTABS << (8 - 3)) * sizeof(kby));
 }
 
 #ifdef DEBUG_LEAKS
 void
 x_done(void)
 {
-	if (x_tab != NULL)
+	if (x_btab != NULL)
 		afreeall(AEDIT);
 }
 #endif
@@ -5597,12 +5730,12 @@ x_initterm(const char *termtype)
 	switch (*termtype) {
 	case 's':
 		if (!strncmp(termtype, "screen", 6) &&
-		    (termtype[6] == '\0' || termtype[6] == '-'))
+		    (!termtype[6] || ord(termtype[6]) == ORD('-')))
 			x_term_mode = 1;
 		break;
 	case 't':
 		if (!strncmp(termtype, "tmux", 4) &&
-		    (termtype[4] == '\0' || termtype[4] == '-'))
+		    (!termtype[4] || ord(termtype[4]) == ORD('-')))
 			x_term_mode = 1;
 		break;
 	}
@@ -5652,17 +5785,17 @@ x_operate_region(char *(*helper)(const c
 		rgend = xmp;
 	}
 
-	x_e_putc2('\r');
-	x_clrtoeol(' ', false);
+	x_e_putb('\r');
+	x_clrtoeol(' ', Nee);
 	x_flush();
-	x_mode(false);
+	x_mode(Nee);
 	cp = helper(rgbeg, rgend - rgbeg);
-	x_mode(true);
+	x_mode(Ja);
 
 	if (cp == NULL) {
 		/* error return from helper */
  x_eval_region_err:
-		x_e_putc2(KSH_BEL);
+		x_e_putb(KSH_BEL);
 		x_redraw('\r');
 		return (KSTD);
 	}
@@ -5699,9 +5832,7 @@ x_quote_region_helper(const char *cmd, s
 
 	strndupx(s, cmd, len, ATEMP);
 	newlen = len < 256 ? 256 : 4096;
-	shf_sopen(alloc(newlen, AEDIT), newlen, SHF_WR | SHF_DYNAMIC, &shf);
-	shf.areap = AEDIT;
-	shf.flags |= SHF_ALLOCB;
+	shf_sreopen(alloc(newlen, AEDIT), newlen, AEDIT, &shf);
 	print_value_quoted(&shf, s);
 	afree(s, ATEMP);
 	return (shf_sclose(&shf));
@@ -5713,4 +5844,88 @@ x_quote_region(int c MKSH_A_UNUSED)
 	return (x_operate_region(x_quote_region_helper));
 }
 #endif /* !MKSH_SMALL */
+
+#ifdef DF
+/* debug code to dump the Emacs buffer state */
+#define TL() do {							\
+	tmp = ofs & 0xFU;						\
+	if (tmp) {							\
+		while (tmp != 0x10U) {					\
+			shf_puts(tmp == 0x8U ? " -   " : "   ", &to);	\
+			++tmp;						\
+		}							\
+		tmp = ofs & (size_t)~(size_t)0xFU;			\
+	} else if (ofs)							\
+		tmp = ofs - 0x10U;					\
+	shf_puts("  ", &to);						\
+	while ((tmp & 0xFU) < lbeg) {					\
+		shf_putc(' ', &to);					\
+		++tmp;							\
+	}								\
+	shf_putc('|', &to);						\
+	while (tmp < ofs) {						\
+		kby c = xbuf[tmp++];					\
+		shf_putc(ctype(c, C_PRINT) ? c : '.', &to);		\
+	}								\
+	shf_putc('|', &to);						\
+	lbeg = ofs & 0xFU;						\
+	nl = 1;								\
+} while (/* CONSTCOND */ 0)
+
+#define DP(p) do { if ((xbuf + ofs) == p) {				\
+	if (!nl) TL();							\
+	shf_fprintf(&to, nl < 2 ? "\n   ↓ = %s" : " and %s", #p);	\
+	nl = 2;								\
+} } while (/* CONSTCOND */ 0)
+
+static void
+x_emacs_DF(const char *reason)
+{
+	struct shf to;
+	kby nl;
+	size_t ofs, end, tmp, lbeg = 0;
+
+	shf_sopen(NULL, 0, SHF_WR | SHF_DYNAMIC, &to);
+	ofs = 0;
+	nl = 1;
+	if (xdp > xep)
+		end = xdp - xbuf + 1;
+	else
+		end = xep - xbuf + 1;
+	/* end is within xend + X_EXTRA */
+	while (ofs < end) {
+		DP(xbp);
+		DP(xmp);
+		DP(xcp);
+		DP(xlp);
+		DP(xdp);
+		DP(xep);
+		if (nl) {
+			shf_fprintf(&to, "\n%04zX ", ofs);
+			tmp = ofs & (size_t)~(size_t)0xFU;
+			while (tmp < ofs) {
+				shf_puts((tmp & 0xFU) == 0x8U ?
+				    " -   " : "   ", &to);
+				++tmp;
+			}
+			nl = 0;
+		}
+		shf_fprintf(&to, (ofs & 0xFU) == 0x8U ? " - %02X" : " %02X",
+		    ord(xbuf[ofs]));
+		++ofs;
+		if (!(ofs & 0xFU))
+			TL();
+	}
+	if (!nl)
+		TL();
+	DF("‣ xbuf: %s%s", reason, shf_sclose(&to));
+}
+
+static int
+x_debug_buf(int c MKSH_A_UNUSED)
+{
+	x_emacs_DF("from keyboard");
+	return (KSTD);
+}
+#endif
 #endif /* !MKSH_NO_CMDLINE_EDITING */
--- mksh-59c.orig/emacsfn.h
+++ mksh-59c/emacsfn.h
@@ -1,6 +1,6 @@
 /*-
- * Copyright (c) 2009, 2010, 2015, 2016, 2020
- *	mirabilos <m@mirbsd.org>
+ * Copyright (c) 2009, 2010, 2015, 2016, 2020, 2021
+ *	mirabilos <m$(date +%Y)@mirbsd.de>
  *
  * Provided that these terms and disclaimer and all copyright notices
  * are retained or reproduced in an accompanying document, permission
@@ -19,7 +19,7 @@
  */
 
 #if defined(EMACSFN_DEFNS)
-__RCSID("$MirOS: src/bin/mksh/emacsfn.h,v 1.11 2020/04/13 20:46:39 tg Exp $");
+__RCSID("$MirOS: src/bin/mksh/emacsfn.h,v 1.17 2025/04/25 23:14:54 tg Exp $");
 #define FN(cname,sname,flags)	static int x_##cname(int);
 #elif defined(EMACSFN_ENUMS)
 #define FN(cname,sname,flags)	XFUNC_##cname,
@@ -40,10 +40,19 @@ FN(comp_comm, "complete-command", 0)
 FN(comp_file, "complete-file", 0)
 FN(comp_list, "complete-list", 0)
 FN(complete, "complete", 0)
+#ifdef DF
+FN(debug_buf, "debug-buffer", 0)
+#endif
 FN(del_back, "delete-char-backward", XF_ARG)
 FN(del_bword, "delete-word-backward", XF_ARG)
+#ifndef MKSH_SMALL
+FN(del_bbigword, "delete-bigword-backward", XF_ARG)
+#endif
 FN(del_char, "delete-char-forward", XF_ARG)
 FN(del_fword, "delete-word-forward", XF_ARG)
+#ifndef MKSH_SMALL
+FN(del_fbigword, "delete-bigword-forward", XF_ARG)
+#endif
 FN(del_line, "kill-line", 0)
 FN(draw_line, "redraw", 0)
 #ifndef MKSH_SMALL
@@ -59,8 +68,11 @@ FN(eval_region, "evaluate-region", 0)
 #endif
 FN(expand, "expand-file", 0)
 #ifndef MKSH_SMALL
-FN(fold_capitalise, "capitalize-word", XF_ARG)
+FN(foldb_capitalise, "capitalise-bigword", XF_ARG)
+FN(fold_capitalise, "capitalise-word", XF_ARG)
+FN(foldb_lower, "downcase-bigword", XF_ARG)
 FN(fold_lower, "downcase-word", XF_ARG)
+FN(foldb_upper, "upcase-bigword", XF_ARG)
 FN(fold_upper, "upcase-word", XF_ARG)
 #endif
 FN(goto_hist, "goto-history", XF_ARG)
@@ -80,15 +92,21 @@ FN(meta_yank, "yank-pop", 0)
 FN(mv_back, "backward-char", XF_ARG)
 FN(mv_beg, "beginning-of-line", 0)
 FN(mv_bword, "backward-word", XF_ARG)
+#ifndef MKSH_SMALL
+FN(mv_bbigword, "backward-bigword", XF_ARG)
+#endif
 FN(mv_end, "end-of-line", 0)
 FN(mv_forw, "forward-char", XF_ARG)
 FN(mv_fword, "forward-word", XF_ARG)
+#ifndef MKSH_SMALL
+FN(mv_fbigword, "forward-bigword", XF_ARG)
+#endif
 FN(newline, "newline", 0)
 FN(next_com, "down-history", XF_ARG)
 FN(nl_next_com, "newline-and-next", 0)
 FN(noop, "no-op", 0)
 FN(prev_com, "up-history", XF_ARG)
-FN(prev_histword, "prev-hist-word", XF_ARG)
+FN(prev_histword, "prev-hist-bigword", XF_ARG)
 #ifndef MKSH_SMALL
 FN(quote_region, "quote-region", 0)
 #endif
--- mksh-59c.orig/eval.c
+++ mksh-59c/eval.c
@@ -3,8 +3,8 @@
 /*-
  * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
  *		 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018,
- *		 2019, 2020
- *	mirabilos <m@mirbsd.org>
+ *		 2019, 2020, 2021, 2022, 2023, 2025
+ *	mirabilos <m$(date +%Y)@mirbsd.de>
  *
  * Provided that these terms and disclaimer and all copyright notices
  * are retained or reproduced in an accompanying document, permission
@@ -24,7 +24,7 @@
 
 #include "sh.h"
 
-__RCSID("$MirOS: src/bin/mksh/eval.c,v 1.231 2020/05/05 21:34:27 tg Exp $");
+__RCSID("$MirOS: src/bin/mksh/eval.c,v 1.264 2025/12/23 20:26:00 tg Exp $");
 
 /*
  * string expansion
@@ -48,7 +48,7 @@ typedef struct {
 	/* variable in ${var...} */
 	struct tbl *var;
 	/* split "$@" / call waitlast in $() */
-	bool split;
+	Wahr split;
 } Expand;
 
 #define XBASE		0	/* scanning original string */
@@ -79,17 +79,21 @@ typedef struct {
 static int varsub(Expand *, const char *, const char *, unsigned int *, int *);
 static int comsub(Expand *, const char *, int);
 static char *valsub(struct op *, Area *);
+static void funsub(struct op *);
 static char *trimsub(char *, char *, int);
-static void glob(char *, XPtrV *, bool);
+static void glob(char *, XPtrV *, Wahr);
 static void globit(XString *, char **, char *, XPtrV *, int);
-static const char *maybe_expand_tilde(const char *, XString *, char **, bool);
+static const char *maybe_expand_tilde(const char *, XString *, char **, Wahr);
 #ifndef MKSH_NOPWNAM
 static char *homedir(char *);
 #endif
 static void alt_expand(XPtrV *, char *, char *, char *, int);
-static int utflen(const char *) MKSH_A_PURE;
+static int utflen(const char *);
 static void utfincptr(const char *, mksh_ari_t *);
 
+/* null (sh.h) */
+char null_string[4] = { 0, 0, 0, 0 };
+
 /* UTFMODE functions */
 static int
 utflen(const char *s)
@@ -99,7 +103,7 @@ utflen(const char *s)
 	if (UTFMODE) {
 		n = 0;
 		while (*s) {
-			s += utf_ptradj(s);
+			s += ez_mbtoc(NULL, s);
 			++n;
 		}
 	} else
@@ -116,7 +120,7 @@ utfincptr(const char *s, mksh_ari_t *lp)
 	const char *cp = s;
 
 	while ((*lp)--)
-		cp += utf_ptradj(cp);
+		cp += ez_mbtoc(NULL, cp);
 	*lp = cp - s;
 }
 
@@ -131,7 +135,8 @@ substitute(const char *cp, int f)
 	s->start = s->str = cp;
 	source = s;
 	if (yylex(ONEWORD) != LWORD)
-		internal_errorf(Tbadsubst);
+		kerrf(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_ONEMSG | KWF_NOERRNO,
+		    Tbadsubst);
 	source = sold;
 	afree(s, ATEMP);
 	return (evalstr(yylval.cp, f));
@@ -212,8 +217,8 @@ typedef struct SubType {
 	size_t	base;		/* start position of expanded word */
 	unsigned short stype;	/* [=+-?%#] action after expanded word */
 	short	f;		/* saved value of f (DOPAT, etc) */
-	uint8_t	quotep;		/* saved value of quote (for ${..[%#]..}) */
-	uint8_t	quotew;		/* saved value of quote (for ${..[+-=]..}) */
+	kby	quotep;		/* saved value of quote (for ${..[%#]..}) */
+	kby	quotew;		/* saved value of quote (for ${..[+-=]..}) */
 } SubType;
 
 void
@@ -248,15 +253,16 @@ expand(
 	SubType st_head, *st;
 	/* record number of trailing newlines in COMSUB */
 	int newlines = 0;
-	bool saw_eq, make_magic;
+	Wahr saw_eq, make_magic;
 	unsigned int tilde_ok;
 	size_t len;
 	char *cp;
 
 	if (ccp == NULL)
-		internal_errorf("expand(NULL)");
+		kerrf(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_ONEMSG | KWF_NOERRNO,
+		    "expand(NULL)");
 	/* for alias, readonly, set, typeset commands */
-	if ((f & DOVACHECK) && is_wdvarassign(ccp)) {
+	if ((f & DOVACHECK) && is_wdvarassign(ccp, Nee)) {
 		f &= ~(DOVACHECK | DOBLANK | DOGLOB | DOTILDE);
 		f |= DOASNTILDE | DOSCALAR;
 	}
@@ -272,11 +278,11 @@ expand(
 	type = XBASE;
 	sp = ccp;
 	fdo = 0;
-	saw_eq = false;
+	saw_eq = Nee;
 	/* must be 1/0 */
 	tilde_ok = (f & (DOTILDE | DOASNTILDE)) ? 1 : 0;
 	doblank = 0;
-	make_magic = false;
+	make_magic = Nee;
 	word = (f&DOBLANK) ? IFS_WS : IFS_WORD;
 	/* clang doesn't know OSUBST comes before CSUBST */
 	memset(&st_head, 0, sizeof(st_head));
@@ -361,16 +367,17 @@ expand(
 					}
 					*dp++ = ')'; *dp++ = ')';
 				} else {
-					struct tbl v;
+					union tbl_static v;
 
-					v.flag = DEFINED|ISSET|INTEGER;
+					v.tbl.flag = DEFINED|ISSET|INTEGER;
 					/* not default */
-					v.type = 10;
-					v.name[0] = '\0';
-					v_evaluate(&v, substitute(sp, 0),
-					    KSH_UNWIND_ERROR, true);
+					v.tbl.type = 10;
+					v.tbl.name[0] = '\0';
+					v_evaluate((struct tbl *)&v,
+					    substitute(sp, 0),
+					    KSH_UNWIND_ERROR, Ja);
 					sp = strnul(sp) + 1;
-					x.str = str_val(&v);
+					x.str = str_val((struct tbl *)&v);
 					type = XSUB;
 					if (f & DOBLANK)
 						doblank++;
@@ -386,11 +393,11 @@ expand(
 			 */
 				/* skip the { or x (}) */
 				const char *varname = ++sp;
-				unsigned int stype;
+				unsigned int stype /* for GCC */ = 0;
 				int slen = 0;
 
 				/* skip variable */
-				sp = cstrchr(sp, '\0') + 1;
+				sp = strnul(sp) + 1;
 				type = varsub(&x, varname, sp, &stype, &slen);
 				if (type < 0) {
 					char *beg, *end, *str;
@@ -398,14 +405,16 @@ expand(
 					/* restore sp */
 					sp = varname - 2;
 					beg = wdcopy(sp, ATEMP);
-					end = (wdscan(cstrchr(sp, '\0') + 1,
-					    CSUBST) - sp) + beg;
+					end = (wdscan(strnul(sp) + 1, CSUBST) -
+					    sp) + beg;
 					/* ({) the } or x is already skipped */
 					if (end < wdscan(beg, EOS))
 						*end = EOS;
 					str = snptreef(NULL, 64, Tf_S, beg);
 					afree(beg, ATEMP);
-					errorf(Tf_sD_s, str, Tbadsubst);
+					kerrf(KWF_ERR(1) | KWF_PREFIX |
+					    KWF_FILELINE | KWF_TWOMSG |
+					    KWF_NOERRNO, str, Tbadsubst);
 				}
 				if (f & DOBLANK)
 					doblank++;
@@ -443,6 +452,7 @@ expand(
 					switch (stype & STYPE_SINGLE) {
 					case ORD('#') | STYPE_AT:
 					case ORD('Q') | STYPE_AT:
+					case ORD('^') | STYPE_AT:
 						break;
 					case ORD('0'): {
 						char *beg, *mid, *end, *stg;
@@ -465,11 +475,11 @@ expand(
 							sp += end - beg - 1;
 						}
 						evaluate(substitute(stg = wdstrip(beg, 0), 0),
-						    &from, KSH_UNWIND_ERROR, true);
+						    &from, KSH_UNWIND_ERROR, Ja);
 						afree(stg, ATEMP);
 						if (end) {
 							evaluate(substitute(stg = wdstrip(mid, 0), 0),
-							    &num, KSH_UNWIND_ERROR, true);
+							    &num, KSH_UNWIND_ERROR, Ja);
 							afree(stg, ATEMP);
 						}
 						afree(beg, ATEMP);
@@ -541,7 +551,7 @@ expand(
 							goto no_repl;
 						}
 						if ((stype & STYPE_MASK) &&
-						    gmatchx(null, pat, false)) {
+						    gmatchx(null, pat, Nee)) {
 							/*
 							 * pattern matches empty
 							 * string => don't loop
@@ -568,13 +578,13 @@ expand(
 						 * this would not be necessary if gmatchx would return
 						 * the start and end values of a match found, like re*
 						 */
-						if (!gmatchx(sbeg, tpat1, false))
+						if (!gmatchx(sbeg, tpat1, Nee))
 							goto end_repl;
 						d = strnul(s);
 						/* now anchor the beginning of the match */
 						if (ord(fpat) != ORD('#'))
 							while (sbeg <= d) {
-								if (gmatchx(sbeg, tpat2, false))
+								if (gmatchx(sbeg, tpat2, Nee))
 									break;
 								else
 									sbeg++;
@@ -583,11 +593,11 @@ expand(
 						p = d;
 						if (ord(fpat) != ORD('%'))
 							while (p >= sbeg) {
-								bool gotmatch;
+								Wahr gotmatch;
 
 								c = ord(*p);
 								*p = '\0';
-								gotmatch = tobool(gmatchx(sbeg, pat, false));
+								gotmatch = isWahr(gmatchx(sbeg, pat, Nee));
 								*p = c;
 								if (gotmatch)
 									break;
@@ -703,8 +713,10 @@ expand(
 						break;
 					case ORD('?'):
 						if (*sp == CSUBST)
-							errorf("%s: parameter null or not set",
-							    st->var->name);
+							kerrf(KWF_ERR(1) | KWF_PREFIX |
+							    KWF_FILELINE | KWF_TWOMSG |
+							    KWF_NOERRNO, st->var->name,
+							    "parameter null or not set");
 						f &= ~DOBLANK;
 						f |= DOTEMP;
 						/* FALLTHROUGH */
@@ -785,9 +797,9 @@ expand(
 					 * in AT&T ksh.
 					 */
 					/*
-					 * XXX POSIX says readonly is only
+					 * XXX POSIX says read-only is only
 					 * fatal for special builtins (setstr
-					 * does readonly check).
+					 * does read-only check).
 					 */
 					len = strlen(dp) + 1;
 					setstr(st->var,
@@ -803,11 +815,13 @@ expand(
 				case ORD('?'):
 					dp = Xrestpos(ds, dp, st->base);
 
-					errorf(Tf_sD_s, st->var->name,
+					kerrf(KWF_ERR(1) | KWF_PREFIX |
+					    KWF_FILELINE | KWF_TWOMSG |
+					    KWF_NOERRNO, st->var->name,
 					    debunk(dp, dp, strlen(dp) + 1));
 					break;
 				case ORD('#') | STYPE_AT:
-					x.str = shf_smprintf("%08X",
+					x.str = shf_smprintf(Thex32,
 					    (unsigned int)hash(str_val(st->var)));
 					goto common_CSUBST;
 				case ORD('Q') | STYPE_AT: {
@@ -818,6 +832,14 @@ expand(
 					x.str = shf_sclose(&shf);
 					goto common_CSUBST;
 				    }
+				case ORD('^') | STYPE_AT: {
+					struct shf shf;
+
+					shf_sopen(NULL, 0, SHF_WR|SHF_DYNAMIC, &shf);
+					uprntmbs(str_val(st->var), Ja, &shf);
+					x.str = shf_sclose(&shf);
+					goto common_CSUBST;
+				    }
 				case ORD('0'):
 				case ORD('/') | STYPE_AT:
 				case ORD('/'):
@@ -838,19 +860,19 @@ expand(
 			case OPAT:
 				/* open pattern: *(foo|bar) */
 				/* Next char is the type of pattern */
-				make_magic = true;
+				make_magic = Ja;
 				c = ord(*sp++) | 0x80U;
 				break;
 
 			case SPAT:
 				/* pattern separator (|) */
-				make_magic = true;
+				make_magic = Ja;
 				c = ORD('|');
 				break;
 
 			case CPAT:
 				/* close pattern */
-				make_magic = true;
+				make_magic = Ja;
 				c = ORD(/*(*/ ')');
 				break;
 			}
@@ -893,7 +915,7 @@ expand(
 				if (ord(*x.str) == ORD('('/*)*/)) {
 					++x.str;
 					c |= 0x80U;
-					make_magic = true;
+					make_magic = Ja;
 				}
 				break;
 			case ORD('('):
@@ -901,7 +923,7 @@ expand(
 				/* FALLTHROUGH */
 			case ORD('|'):
 			case ORD(')'):
-				make_magic = true;
+				make_magic = Ja;
 				break;
 			}
 			break;
@@ -1005,8 +1027,8 @@ expand(
 				c = ORD('\n');
 				--newlines;
 			} else {
-				while ((c = shf_getc(x.u.shf)) == 0 ||
-				    cinttype(c, C_NL)) {
+				while (c = shf_getc(x.u.shf),
+				    cinttype(c, C_NL | C_NUL)) {
 #ifdef MKSH_WITH_TEXTMODE
 					if (c == ORD('\r')) {
 						c = shf_getc(x.u.shf);
@@ -1063,25 +1085,26 @@ expand(
 			if ((word == IFS_WORD) || (word == IFS_QUOTE) || (c &&
 			    (word == IFS_IWS || word == IFS_NWS) &&
 			    !ctype(c, C_IFSWS))) {
+				size_t dlen;
  emit_word:
 				if (f & DOHERESTR)
 					*dp++ = '\n';
 				*dp++ = '\0';
+				dlen = Xlength(ds, dp);
 				cp = Xclose(ds, dp);
 				if (fdo & DOBRACE)
 					/* also does globbing */
 					alt_expand(wp, cp, cp,
-					    cp + Xlength(ds, (dp - 1)),
+					    cp + dlen - 1,
 					    fdo | (f & DOMARKDIRS));
 				else if (fdo & DOGLOB)
-					glob(cp, wp, tobool(f & DOMARKDIRS));
+					glob(cp, wp, isWahr(f & DOMARKDIRS));
 				else if ((f & DOPAT) || !(fdo & DOMAGIC))
 					XPput(*wp, cp);
 				else
-					XPput(*wp, debunk(cp, cp,
-					    strlen(cp) + 1));
+					XPput(*wp, debunk(cp, cp, dlen));
 				fdo = 0;
-				saw_eq = false;
+				saw_eq = Nee;
 				/* must be 1/0 */
 				tilde_ok = (f & (DOTILDE | DOASNTILDE)) ? 1 : 0;
 				if (c == 0)
@@ -1143,7 +1166,7 @@ expand(
 					/* Note first unquoted = for ~ */
 					if (!(f & DOTEMP) && (!Flag(FPOSIX) ||
 					    (f & DOASNTILDE)) && !saw_eq) {
-						saw_eq = true;
+						saw_eq = Ja;
 						tilde_ok = 1;
 					}
 					break;
@@ -1168,7 +1191,7 @@ expand(
 
 						tcp = maybe_expand_tilde(sp,
 						    &ds, &tdp,
-						    tobool(f & DOASNTILDE));
+						    isWahr(f & DOASNTILDE));
 						if (tcp) {
 							if (dp != tdp)
 								word = IFS_WORD;
@@ -1184,7 +1207,7 @@ expand(
 				quote &= ~2;
 
 			if (make_magic) {
-				make_magic = false;
+				make_magic = Nee;
 				fdo |= DOMAGIC | (f & DOGLOB);
 				*dp++ = MAGIC;
 			} else if (ISMAGIC(c)) {
@@ -1198,15 +1221,15 @@ expand(
 	}
 }
 
-static bool
+static Wahr
 hasnonempty(const char **strv)
 {
 	size_t i = 0;
 
 	while (strv[i])
 		if (*strv[i++])
-			return (true);
-	return (false);
+			return (Ja);
+	return (Nee);
 }
 
 /*
@@ -1225,7 +1248,7 @@ varsub(Expand *xp, const char *sp, const
 	int slen = 0;
 	const char *p;
 	struct tbl *vp;
-	bool zero_ok = false;
+	Wahr zero_ok = Nee;
 	int sc;
 	XPtrV wv;
 
@@ -1300,7 +1323,7 @@ varsub(Expand *xp, const char *sp, const
 			if (sc & 2) {
 				stype = 0;
 				XPinit(wv, 32);
-				vp = global(arrayname(sp));
+				vp = arraybase(sp);
 				do {
 					if (vp->flag & ISSET)
 						XPput(wv, shf_smprintf(Tf_lu,
@@ -1310,12 +1333,13 @@ varsub(Expand *xp, const char *sp, const
 			}
 			xp->var = global(sp);
 			/* use saved p from above */
-			xp->str = p ? shf_smprintf("%s[%lu]", xp->var->name,
+			xp->str = p ? shf_smprintf(Tf_sSQlu, xp->var->name,
 			    arrayindex(xp->var)) : xp->var->name;
 			break;
 #ifdef DEBUG
 		default:
-			internal_errorf("stype mismatch");
+			kerrf(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_ONEMSG | KWF_NOERRNO,
+			    "stype mismatch");
 			/* NOTREACHED */
 #endif
 		case ORD('%'):
@@ -1327,13 +1351,7 @@ varsub(Expand *xp, const char *sp, const
 			/* partial utf_mbswidth reimplementation */
 			sc = 0;
 			while (*p) {
-				if (!UTFMODE ||
-				    (wv.len = utf_mbtowc(&c, p)) == (size_t)-1)
-					/* not UTFMODE or not UTF-8 */
-					c = rtt2asc(*p++);
-				else
-					/* UTFMODE and UTF-8 */
-					p += wv.len;
+				p += ez_mbtowc(&c, p);
 				/* c == char or wchar at p++ */
 				if ((slen = utf_wcwidth(c)) == -1) {
 					/* 646, 8859-1, 10646 C0/C1 */
@@ -1347,9 +1365,9 @@ varsub(Expand *xp, const char *sp, const
 		case ORD('#'):
 			  switch (sc & 3) {
 			case 3:
-				vp = global(arrayname(sp));
+				vp = arraybase(sp);
 				if (vp->flag & (ISSET|ARRAY))
-					zero_ok = true;
+					zero_ok = Ja;
 				sc = 0;
 				do {
 					if (vp->flag & ISSET)
@@ -1367,7 +1385,9 @@ varsub(Expand *xp, const char *sp, const
 			}
 			/* ${%var} also here */
 			if (Flag(FNOUNSET) && sc == 0 && !zero_ok)
-				errorf(Tf_parm, sp);
+				kerrf(KWF_ERR(1) | KWF_PREFIX |
+				    KWF_FILELINE | KWF_TWOMSG |
+				    KWF_NOERRNO, sp, Tf_parm);
 			xp->str = shf_smprintf(Tf_d, sc);
 			break;
 		}
@@ -1414,6 +1434,7 @@ varsub(Expand *xp, const char *sp, const
 		case ORD('#'):
 		case ORD('/'):
 		case ORD('Q'):
+		case ORD('^'):
 			break;
 		default:
 			return (-1);
@@ -1452,13 +1473,14 @@ varsub(Expand *xp, const char *sp, const
 		case ORD('0'):
 		case ORD('#') | STYPE_AT:
 		case ORD('Q') | STYPE_AT:
+		case ORD('^') | STYPE_AT:
 	*/	default:
 			return (-1);
 		}
 		/* do what we can */
 		if (sc & 2) {
 			XPinit(wv, 32);
-			vp = global(arrayname(sp));
+			vp = arraybase(sp);
 			do {
 				if (vp->flag & ISSET)
 					XPput(wv, str_val(vp));
@@ -1476,7 +1498,7 @@ varsub(Expand *xp, const char *sp, const
 			else
 				xp->u.strv = (const char **)e->loc->argv + 1;
 			/* POSIX 2009? */
-			zero_ok = true;
+			zero_ok = Ja;
 		}
 		/* have we got any elements? */
 		if (c) {
@@ -1487,7 +1509,7 @@ varsub(Expand *xp, const char *sp, const
 			/* yes → load first */
 			xp->str = *xp->u.strv++;
 			/* $@ or ${foo[@]} */
-			xp->split = tobool(sc & 4);
+			xp->split = isWahr(sc & 4);
 			state = XARG;
 		}
 	}
@@ -1502,12 +1524,14 @@ varsub(Expand *xp, const char *sp, const
 	    stype == (ORD('0') | STYPE_DBL) ||
 	    stype == (ORD('#') | STYPE_AT) ||
 	    stype == (ORD('Q') | STYPE_AT) ||
+	    stype == (ORD('^') | STYPE_AT) ||
 	    (stype & STYPE_CHAR) == ORD('/'))
 		/* expand word instead of variable value */
 		state = XBASE;
 	if (Flag(FNOUNSET) && xp->str == null && !zero_ok &&
 	    (ctype(c, C_SUB2) || (state != XBASE && c != ORD('+'))))
-		errorf(Tf_parm, sp);
+		kerrf(KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE | KWF_TWOMSG |
+		    KWF_NOERRNO, sp, Tf_parm);
 	*stypep = stype;
 	*slenp = slen;
 	return (state);
@@ -1522,8 +1546,8 @@ comsub(Expand *xp, const char *cp, int f
 	Source *s, *sold;
 	struct op *t;
 	struct shf *shf;
-	bool doalias = false;
-	uint8_t old_utfmode = UTFMODE;
+	Wahr doalias = Nee;
+	kby old_utfmode = UTFMODE;
 
 	switch (fn) {
 	case COMASUB:
@@ -1532,13 +1556,13 @@ comsub(Expand *xp, const char *cp, int f
 			/* FALLTHROUGH */
 	case FUNASUB:
 		  fn = FUNSUB;
-		doalias = true;
+		doalias = Ja;
 	}
 
 	s = pushs(SSTRING, ATEMP);
 	s->start = s->str = cp;
 	sold = source;
-	t = compile(s, true, doalias);
+	t = compile(s, doalias);
 	afree(s, ATEMP);
 	source = sold;
 
@@ -1548,22 +1572,27 @@ comsub(Expand *xp, const char *cp, int f
 		return (XBASE);
 
 	/* no waitlast() unless specifically enabled later */
-	xp->split = false;
+	xp->split = Nee;
 
 	if (t->type == TCOM &&
 	    *t->args == NULL && *t->vars == NULL && t->ioact != NULL) {
 		/* $(<file) */
-		struct ioword *io = *t->ioact;
+		struct ioword *io;
 		char *name;
 
+		if (t->ioact[1] != NULL) {
+			io = t->ioact[1];
+			goto funny;
+		}
+		io = *t->ioact;
 		switch (io->ioflag & IOTYPE) {
 		case IOREAD:
 			shf = shf_open(name = evalstr(io->ioname, DOTILDE),
 				O_RDONLY, 0, SHF_MAPHI | SHF_CLEXEC);
 			if (shf == NULL)
-				warningf(!Flag(FTALKING), Tf_sD_s_sD_s,
-				    name, Tcant_open, "$(<...) input",
-				    cstrerror(errno));
+				kwarnf(KWF_PREFIX | (Flag(FTALKING) ?
+				    KWF_FILELINE : 0) | KWF_TWOMSG,
+				    name, Tcant_filesub);
 			break;
 		case IOHERE:
 			if (!herein(io, &name)) {
@@ -1578,8 +1607,10 @@ comsub(Expand *xp, const char *cp, int f
 			shf = NULL;
 			break;
 		default:
-			errorf(Tf_sD_s, T_funny_command,
-			    snptreef(NULL, 32, Tft_R, io));
+ funny:
+			kerrf(KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE |
+			    KWF_TWOMSG | KWF_NOERRNO, T_funny_command,
+			    stripioact(io));
 		}
 	} else if (fn == FUNSUB) {
 		int ofd1;
@@ -1590,22 +1621,21 @@ comsub(Expand *xp, const char *cp, int f
 		 * with an shf open for reading (buffered) but yet unused
 		 */
 		maketemp(ATEMP, TT_FUNSUB, &tf);
-		if (!tf->shf) {
-			errorf(Tf_temp,
-			    Tcreate, tf->tffn, cstrerror(errno));
-		}
+		if (!tf->shf)
+			kerrf0(KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE,
+			    Tf_temp, Tcreate, tf->tffn);
 		/* extract shf from temporary file, unlink and free it */
 		shf = tf->shf;
 		unlink(tf->tffn);
 		afree(tf, ATEMP);
 		/* save stdout and let it point to the tempfile */
 		ofd1 = savefd(1);
-		ksh_dup2(shf_fileno(shf), 1, false);
+		ksh_dup2(shf_fileno(shf), 1, Nee);
 		/*
 		 * run tree, with output thrown into the tempfile,
 		 * in a new function block
 		 */
-		valsub(t, NULL);
+		funsub(t);
 		subst_exstat = exstat & 0xFF;
 		/* rewind the tempfile and restore regular stdout */
 		lseek(shf_fileno(shf), (off_t)0, SEEK_SET);
@@ -1621,14 +1651,14 @@ comsub(Expand *xp, const char *cp, int f
 		shf = shf_fdopen(pv[0], SHF_RD, NULL);
 		ofd1 = savefd(1);
 		if (pv[1] != 1) {
-			ksh_dup2(pv[1], 1, false);
+			ksh_dup2(pv[1], 1, Nee);
 			close(pv[1]);
 		}
 		execute(t, XXCOM | XPIPEO | XFORK, NULL);
 		restfd(1, ofd1);
 		startlast();
 		/* waitlast() */
-		xp->split = true;
+		xp->split = Ja;
 	}
 
 	xp->u.shf = shf;
@@ -1647,48 +1677,47 @@ trimsub(char *str, char *pat, int how)
 	switch (how & (STYPE_CHAR | STYPE_DBL)) {
 	case ORD('#'):
 		/* shortest match at beginning */
-		for (p = str; p <= end; p += utf_ptradj(p)) {
-			c = *p; *p = '\0';
-			if (gmatchx(str, pat, false)) {
+		p = str;
+		do {
+			c = *p;
+			*p = '\0';
+			if (gmatchx(str, pat, Nee)) {
 				record_match(str);
 				*p = c;
 				return (p);
 			}
 			*p = c;
-		}
+			p += ez_mbtoc(NULL, p);
+		} while (c != '\0');
 		break;
 	case ORD('#') | STYPE_DBL:
 		/* longest match at beginning */
-		for (p = end; p >= str; p--) {
-			c = *p; *p = '\0';
-			if (gmatchx(str, pat, false)) {
+		p = end;
+		while (p >= str) {
+			c = *p;
+			*p = '\0';
+			if (gmatchx(str, pat, Nee)) {
 				record_match(str);
 				*p = c;
 				return (p);
 			}
 			*p = c;
+			--p;
 		}
 		break;
 	case ORD('%'):
 		/* shortest match at end */
 		p = end;
 		while (p >= str) {
-			if (gmatchx(p, pat, false))
+			if (gmatchx(p, pat, Nee))
 				goto trimsub_match;
-			if (UTFMODE) {
-				char *op = p;
-				while ((p-- > str) && ((rtt2asc(*p) & 0xC0) == 0x80))
-					;
-				if ((p < str) || (p + utf_ptradj(p) != op))
-					p = op - 1;
-			} else
-				--p;
+			p = ez_bs(p - 1, str);
 		}
 		break;
 	case ORD('%') | STYPE_DBL:
 		/* longest match at end */
 		for (p = str; p <= end; p++)
-			if (gmatchx(p, pat, false)) {
+			if (gmatchx(p, pat, Nee)) {
  trimsub_match:
 				record_match(p);
 				strndupx(end, str, p - str, ATEMP);
@@ -1708,7 +1737,7 @@ trimsub(char *str, char *pat, int how)
 
 /* XXX cp not const 'cause slashes are temporarily replaced with NULs... */
 static void
-glob(char *cp, XPtrV *wp, bool markdirs)
+glob(char *cp, XPtrV *wp, Wahr markdirs)
 {
 	int oldsize = XPsize(*wp);
 
@@ -1729,7 +1758,7 @@ glob(char *cp, XPtrV *wp, bool markdirs)
  * the number of matches found.
  */
 int
-glob_str(char *cp, XPtrV *wp, bool markdirs)
+glob_str(char *cp, XPtrV *wp, Wahr markdirs)
 {
 	int oldsize = XPsize(*wp);
 	XString xs;
@@ -1753,6 +1782,8 @@ globit(XString *xs,	/* dest string */
 	char *xp = *xpp;
 	char *se;
 	char odirsep;
+	DIR *dirp;
+	size_t prefix_len;
 
 	/* This to allow long expansions to be interrupted */
 	intrcheck();
@@ -1811,6 +1842,7 @@ globit(XString *xs,	/* dest string */
 		Xcheck(*xs, xp);
 		*xp++ = *sp++;
 	}
+	*xp = '\0';
 	np = mksh_sdirsep(sp);
 	if (np != NULL) {
 		se = np;
@@ -1822,7 +1854,6 @@ globit(XString *xs,	/* dest string */
 		se = strnul(sp);
 	}
 
-
 	/*
 	 * Check if sp needs globbing - done to avoid pattern checks for strings
 	 * containing MAGIC characters, open [s without the matching close ],
@@ -1836,43 +1867,34 @@ globit(XString *xs,	/* dest string */
 		xp = strnul(xp);
 		*xpp = xp;
 		globit(xs, xpp, np, wp, check);
-	} else {
-		DIR *dirp;
+	} else if ((dirp = opendir((prefix_len = Xlength(*xs, xp)) ?
+	    Xstring(*xs, xp) : Tdot))) {
 		struct dirent *d;
-		char *name;
-		size_t len, prefix_len;
 
-		/* xp = *xpp;	copy_non_glob() may have re-alloc'd xs */
-		*xp = '\0';
-		prefix_len = Xlength(*xs, xp);
-		dirp = opendir(prefix_len ? Xstring(*xs, xp) : Tdot);
-		if (dirp == NULL)
-			goto Nodir;
 		while ((d = readdir(dirp)) != NULL) {
-			name = d->d_name;
-			if (name[0] == '.' &&
-			    (name[1] == 0 || (name[1] == '.' && name[2] == 0)))
+			size_t len;
+
+			if (isch(d->d_name[0], '.') && (!d->d_name[1] ||
+			    (isch(d->d_name[1], '.') && !d->d_name[2])))
 				/* always ignore . and .. */
 				continue;
-			if ((*name == '.' && *sp != '.') ||
-			    !gmatchx(name, sp, true))
+			if ((isch(d->d_name[0], '.') && !isch(*sp, '.')) ||
+			    !gmatchx(d->d_name, sp, Ja))
 				continue;
 
 			len = strlen(d->d_name) + 1;
 			XcheckN(*xs, xp, len);
-			memcpy(xp, name, len);
+			memcpy(xp, d->d_name, len);
 			*xpp = xp + len - 1;
 			globit(xs, xpp, np, wp, (check & GF_MARKDIR) |
 			    GF_GLOBBED | (np ? GF_EXCHECK : GF_NONE));
 			xp = Xstring(*xs, xp) + prefix_len;
 		}
 		closedir(dirp);
- Nodir:
-		;
 	}
 
 	if (np != NULL)
-		*--np = odirsep;
+		*(char *)(--np) = odirsep;
 }
 
 /* remove MAGIC from string */
@@ -1909,7 +1931,7 @@ debunk(char *dp, const char *sp, size_t
  * past the name, otherwise returns 0.
  */
 static const char *
-maybe_expand_tilde(const char *p, XString *dsp, char **dpp, bool isassign)
+maybe_expand_tilde(const char *p, XString *dsp, char **dpp, Wahr isassign)
 {
 	XString ts;
 	char *dp = *dpp;
@@ -1951,7 +1973,7 @@ do_tilde(char *cp)
 {
 	char *dp = null;
 #ifndef MKSH_NOPWNAM
-	bool do_simplify = true;
+	Wahr do_simplify = Ja;
 #endif
 
 	if (cp[0] == '\0')
@@ -1963,7 +1985,7 @@ do_tilde(char *cp)
 #ifndef MKSH_NOPWNAM
 	else {
 		dp = homedir(cp);
-		do_simplify = false;
+		do_simplify = Nee;
 	}
 #endif
 
@@ -2017,7 +2039,7 @@ alt_expand(XPtrV *wp, char *start, char
 	char *p = exp_start;
 
 	/* search for open brace */
-	while ((p = strchr(p, MAGIC)) && ord(p[1]) != ORD('{' /*}*/))
+	while ((p = ucstrchr(p, MAGIC)) && ord(p[1]) != ORD('{' /*}*/))
 		p += 2;
 	brace_start = p;
 
@@ -2046,7 +2068,7 @@ alt_expand(XPtrV *wp, char *start, char
 		 * expansion. }
 		 */
 		if (fdo & DOGLOB)
-			glob(start, wp, tobool(fdo & DOMARKDIRS));
+			glob(start, wp, isWahr(fdo & DOMARKDIRS));
 		else
 			XPput(*wp, debunk(start, start, end - start));
 		return;
@@ -2067,7 +2089,7 @@ alt_expand(XPtrV *wp, char *start, char
 			else if ((ord(*p) == ORD(/*{*/ '}') && --count == 0) ||
 			    (*p == ',' && count == 1)) {
 				char *news;
-				int l1, l2, l3;
+				size_t l1, l2, l3;
 
 				/*
 				 * addition safe since these operate on
@@ -2090,22 +2112,55 @@ alt_expand(XPtrV *wp, char *start, char
 	return;
 }
 
+static void
+subcpybk(struct block *l)
+{
+	/* did the valsub/funsub change $#/$*? */
+	if (e->loc->argc == l->argc &&
+	    e->loc->argv == l->argv)
+		return;
+
+	/* yes ⇒ copy back to parent Area */
+	l->argv = cpyargv(&l->argc, e->loc->argv, &l->area);
+}
+
 /* helper function due to setjmp/longjmp woes */
 static char *
 valsub(struct op *t, Area *ap)
 {
-	char * volatile cp = NULL;
-	struct tbl * volatile vp = NULL;
+	char *cp;
+	struct tbl * volatile vp;
+	struct block * volatile l;
+	int i;
 
+	l = e->loc;
 	newenv(E_FUNC);
 	newblock();
-	if (ap)
-		vp = local(TREPLY, false);
-	if (!kshsetjmp(e->jbuf))
-		execute(t, XXCOM | XERROK, NULL);
-	if (vp)
-		strdupx(cp, str_val(vp), ap);
+	vp = local(TREPLY, Nee);
+	if (!(i = kshsetjmp(e->jbuf))) {
+		execute(t, XXCOM, NULL);
+		i = LRETURN;
+	}
+	strdupx(cp, str_val(vp), ap);
+	subcpybk(l);
 	quitenv(NULL);
+	/* see CFUNC case in exec.c:comexec() */
+	if (i != LRETURN)
+		unwind(i);
 
 	return (cp);
 }
+
+static void
+funsub(struct op *t)
+{
+	struct block * volatile l;
+
+	l = e->loc;
+	newenv(E_FUNC);
+	newblock();
+	if (!kshsetjmp(e->jbuf))
+		execute(t, XXCOM | XERROK, NULL);
+	subcpybk(l);
+	quitenv(NULL);
+}
--- mksh-59c.orig/exec.c
+++ mksh-59c/exec.c
@@ -3,8 +3,8 @@
 /*-
  * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
  *		 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018,
- *		 2019, 2020
- *	mirabilos <m@mirbsd.org>
+ *		 2019, 2020, 2021, 2022, 2023, 2024, 2025
+ *	mirabilos <m$(date +%Y)@mirbsd.de>
  *
  * Provided that these terms and disclaimer and all copyright notices
  * are retained or reproduced in an accompanying document, permission
@@ -24,20 +24,21 @@
 
 #include "sh.h"
 
-__RCSID("$MirOS: src/bin/mksh/exec.c,v 1.224 2020/08/27 19:52:43 tg Exp $");
+__RCSID("$MirOS: src/bin/mksh/exec.c,v 1.256 2025/12/24 04:51:51 tg Exp $");
 
 #ifndef MKSH_DEFAULT_EXECSHELL
 #define MKSH_DEFAULT_EXECSHELL	MKSH_UNIXROOT "/bin/sh"
 #endif
 
 static int comexec(struct op *, struct tbl * volatile, const char **,
-    int volatile, volatile int *);
-static void scriptexec(struct op *, const char **) MKSH_A_NORETURN;
-static int call_builtin(struct tbl *, const char **, const char *, bool);
+    int volatile, int *);
+static int scriptexec(struct op *, const char **);
+static int call_builtin(struct tbl *, const char **, const char *, Wahr);
+static void doexfunc(struct op *);
 static int iosetup(struct ioword *, struct tbl *);
-static const char *do_selectargs(const char **, bool);
+static const char *do_selectargs(const char **, Wahr);
 static Test_op dbteste_isa(Test_env *, Test_meta);
-static const char *dbteste_getopnd(Test_env *, Test_op, bool);
+static const char *dbteste_getopnd(Test_env *, Test_op, Wahr);
 static void dbteste_error(Test_env *, int, const char *);
 /* XXX: horrible kludge to fit within the framework */
 static void plain_fmt_entry(char *, size_t, unsigned int, const void *);
@@ -50,16 +51,17 @@ int
 execute(struct op * volatile t,
     /* if XEXEC don't fork */
     volatile int flags,
-    volatile int * volatile xerrok)
+    int * volatile xerrok)
 {
 	int i;
-	volatile int rv = 0, dummy = 0;
+	volatile int rv = 0;
 	int pv[2];
 	const char ** volatile ap = NULL;
-	char ** volatile up;
+	char **up;
 	const char *s, *ccp;
 	struct ioword **iowp;
 	struct tbl *tp = NULL;
+	int dummy = 0;
 
 	if (t == NULL)
 		return (0);
@@ -68,9 +70,18 @@ execute(struct op * volatile t,
 	if (xerrok == NULL)
 		xerrok = &dummy;
 
-	if ((flags&XFORK) && !(flags&XEXEC) && t->type != TPIPE)
-		/* run in sub-process */
-		return (exchild(t, flags & ~XTIME, xerrok, -1));
+	if (flags & XFORK)
+		switch (t->type) {
+		case TPIPE:
+			break;
+		default:
+			if (flags & XEXEC)
+				break;
+			/* FALLTHROUGH */
+		case TTIME:
+			/* run in sub-process */
+			return (exchild(t, flags & ~XTIME, xerrok, -1));
+		}
 
 	newenv(E_EXEC);
 	if (trap)
@@ -99,7 +110,7 @@ execute(struct op * volatile t,
 		    /* of type "here document" (or "here string") */
 		    (t->ioact[0]->ioflag & IOTYPE) == IOHERE &&
 		    /* the variable assignment begins with a valid varname */
-		    (ccp = skip_wdvarname(t->vars[0], true)) != t->vars[0] &&
+		    (ccp = skip_wdvarname(t->vars[0], Ja)) != t->vars[0] &&
 		    /* and has no right-hand side (i.e. "varname=") */
 		    ccp[0] == CHAR && ((ccp[1] == '=' && ccp[2] == EOS) ||
 		    /* or "varname+=" */ (ccp[1] == '+' && ccp[2] == CHAR &&
@@ -124,7 +135,8 @@ execute(struct op * volatile t,
 		up = eval(t->args, t->u.evalflags | DOBLANK | DOGLOB | DOTILDE);
 		if (flags & XTIME)
 			/* Allow option parsing (bizarre, but POSIX) */
-			timex_hook(t, &up);
+			if ((rv = time_hook(t, &up)))
+				goto Break;
 		ap = (const char **)up;
 		if (ap[0])
 			tp = findcom(ap[0], FC_BI | FC_FUNC);
@@ -132,9 +144,9 @@ execute(struct op * volatile t,
 	flags &= ~XTIME;
 
 	if (t->ioact != NULL || t->type == TPIPE || t->type == TCOPROC) {
-		e->savefd = alloc2(NUFILE, sizeof(short), ATEMP);
+		e->savedfd = alloc2(NUFILE, sizeof(ksh_fdsave), ATEMP);
 		/* initialise to not redirected */
-		memset(e->savefd, 0, NUFILE * sizeof(short));
+		memset(e->savedfd, 0, NUFILE * sizeof(ksh_fdsave));
 	}
 
 	/* mark for replacement later (unless TPIPE) */
@@ -151,12 +163,15 @@ execute(struct op * volatile t,
 				 */
 				if (tp && tp->type == CSHELL &&
 				    (tp->flag & SPEC_BI))
-					errorfz();
+					kerrf(KWF_ERR(1) | KWF_PREFIX |
+					    KWF_FILELINE | KWF_ONEMSG |
+					    KWF_NOERRNO, "redirection failure");
 				/* Deal with FERREXIT, quitenv(), etc. */
 				goto Break;
 			}
 		}
 
+ reentry:
 	switch (t->type) {
 	case TCOM:
 		rv = comexec(t, tp, (const char **)ap, flags, xerrok);
@@ -169,12 +184,12 @@ execute(struct op * volatile t,
 	case TPIPE:
 		flags |= XFORK;
 		flags &= ~XEXEC;
-		e->savefd[0] = savefd(0);
-		e->savefd[1] = savefd(1);
+		FDSAVE(0, savefd(0));
+		FDSAVE(1, savefd(1));
 		while (t->type == TPIPE) {
 			openpipe(pv);
 			/* stdout of curr */
-			ksh_dup2(pv[1], 1, false);
+			ksh_dup2(pv[1], 1, Nee);
 			/**
 			 * Let exchild() close pv[0] in child
 			 * (if this isn't done, commands like
@@ -184,15 +199,15 @@ execute(struct op * volatile t,
 			exchild(t->left, flags | XPIPEO | XCCLOSE,
 			    NULL, pv[0]);
 			/* stdin of next */
-			ksh_dup2(pv[0], 0, false);
+			ksh_dup2(pv[0], 0, Nee);
 			closepipe(pv);
 			flags |= XPIPEI;
 			t = t->right;
 		}
 		/* stdout of last */
-		restfd(1, e->savefd[1]);
+		restfd(1, SAVEDFD(e, 1));
 		/* no need to re-restore this */
-		e->savefd[1] = 0;
+		e->savedfd[1] = 0;
 		/* Let exchild() close 0 in parent, after fork, before wait */
 		i = exchild(t, flags | XPCLOSE | XPIPEST, xerrok, 0);
 		if (!(flags&XBGND) && !(flags&XXCOM))
@@ -226,29 +241,31 @@ execute(struct op * volatile t,
 #endif
 		/* Already have a (live) co-process? */
 		if (coproc.job && coproc.write >= 0)
-			errorf("coprocess already exists");
+			kerrf(KWF_ERR(1) | KWF_PREFIX |
+			    KWF_FILELINE | KWF_ONEMSG |
+			    KWF_NOERRNO, "coprocess already exists");
 
 		/* Can we re-use the existing co-process pipe? */
-		coproc_cleanup(true);
+		coproc_cleanup(Ja);
 
 		/* do this before opening pipes, in case these fail */
-		e->savefd[0] = savefd(0);
-		e->savefd[1] = savefd(1);
+		FDSAVE(0, savefd(0));
+		FDSAVE(1, savefd(1));
 
 		openpipe(pv);
 		if (pv[0] != 0) {
-			ksh_dup2(pv[0], 0, false);
+			ksh_dup2(pv[0], 0, Nee);
 			close(pv[0]);
 		}
 		coproc.write = pv[1];
 		coproc.job = NULL;
 
 		if (coproc.readw >= 0)
-			ksh_dup2(coproc.readw, 1, false);
+			ksh_dup2(coproc.readw, 1, Nee);
 		else {
 			openpipe(pv);
 			coproc.read = pv[0];
-			ksh_dup2(pv[1], 1, false);
+			ksh_dup2(pv[1], 1, Nee);
 			/* closed before first read */
 			coproc.readw = pv[1];
 			coproc.njobs = 0;
@@ -316,11 +333,14 @@ execute(struct op * volatile t,
 
 	case TFOR:
 	case TSELECT: {
-		volatile bool is_first = true;
+		volatile Wahr is_first = Ja;
 
-		ap = (t->vars == NULL) ? e->loc->argv + 1 :
-		    (const char **)eval((const char **)t->vars,
-		    DOBLANK | DOGLOB | DOTILDE);
+		if (t->vars == NULL)
+			/* “for i; do” */
+			ap = cpyargv(NULL, e->loc->argv, ATEMP) + 1;
+		else
+			ap = (const char **)eval((const char **)t->vars,
+			    DOBLANK | DOGLOB | DOTILDE);
 		e->type = E_LOOP;
 		while ((i = kshsetjmp(e->jbuf))) {
 			if ((e->flags&EF_BRKCONT_PASS) ||
@@ -336,14 +356,14 @@ execute(struct op * volatile t,
 		rv = 0;
 		if (t->type == TFOR) {
 			while (*ap != NULL) {
-				setstr(global(t->str), *ap++, KSH_UNWIND_ERROR);
+				setstr(global(t->op_str), *ap++, KSH_UNWIND_ERROR);
 				rv = execute(t->left, flags & XERROK, xerrok);
 			}
 		} else {
  do_TSELECT:
 			if ((ccp = do_selectargs(ap, is_first))) {
-				is_first = false;
-				setstr(global(t->str), ccp, KSH_UNWIND_ERROR);
+				is_first = Nee;
+				setstr(global(t->op_str), ccp, KSH_UNWIND_ERROR);
 				execute(t->left, flags & XERROK, xerrok);
 				goto do_TSELECT;
 			}
@@ -383,11 +403,11 @@ execute(struct op * volatile t,
 
 	case TCASE:
 		i = 0;
-		ccp = evalstr(t->str, DOTILDE | DOSCALAR);
+		ccp = evalstr(t->op_str, DOTILDE | DOSCALAR);
 		for (t = t->left; t != NULL && t->type == TPAT; t = t->right) {
 			for (ap = (const char **)t->vars; *ap; ap++) {
 				if (i || ((s = evalstr(*ap, DOTILDE|DOPAT)) &&
-				    gmatchx(ccp, s, false))) {
+				    gmatchx(ccp, s, Nee))) {
 					record_match(ccp);
 					rv = execute(t->left, flags & XERROK,
 					    xerrok);
@@ -414,9 +434,25 @@ execute(struct op * volatile t,
 		break;
 
 	case TFUNCT:
-		rv = define(t->str, t);
+		rv = define(t->op_str, t);
 		break;
 
+	case TEXFUNC:
+#ifndef MKSH_SMALL
+		/* these make reentry not safe, should not happen */
+		i = 0;
+		if (!t->left) i |= 1;
+		if (t->left->type != TBRACE) i |= 2;
+		if (t->ioact != NULL) i |= 4;
+		if (t->left->ioact != NULL) i |= 8;
+		if (i)
+			kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,
+			    Tunexpected_type, Tfunction, "TEXFUNC", i);
+#endif
+		doexfunc(t);
+		t = t->left;
+		goto reentry;
+
 	case TTIME:
 		/*
 		 * Clear XEXEC so nested execute() call doesn't exit
@@ -433,20 +469,41 @@ execute(struct op * volatile t,
 		/* I/O redirection cleanup to be done in child process */
 		if (!Flag(FPOSIX) && !Flag(FSH) && t->left->ioact != NULL)
 			for (iowp = t->left->ioact; *iowp != NULL; iowp++)
-				if ((*iowp)->ioflag & IODUPSELF)
-					fcntl((*iowp)->unit, F_SETFD, 0);
+				if (((*iowp)->ioflag & IODUPSELF) &&
+				    fcntl((*iowp)->unit, F_SETFD, 0) == -1)
+					kwarnf0(KWF_INTERNAL | KWF_WARNING,
+					    Tcloexec_failed, "clear",
+					    (*iowp)->unit);
 		/* try to execute */
 		{
 			union mksh_ccphack cargs;
 
 			cargs.ro = t->args;
-			execve(t->str, cargs.rw, up);
+			execve(t->op_str, cargs.rw, up);
 			rv = errno;
 		}
 		if (rv == ENOEXEC)
-			scriptexec(t, (const char **)up);
+			rv = scriptexec(t, (const char **)up);
 		else
-			errorfx(126, Tf_sD_s, t->str, cstrerror(rv));
+			kwarnf(KWF_VERRNO | KWF_ERR(126) | KWF_PREFIX |
+			    KWF_FILELINE | KWF_ONEMSG, rv, t->op_str);
+		unrestoresigs();
+		switch (rv) {
+		case ENOENT:
+#ifdef ELOOP
+		case ELOOP:
+#endif
+#ifdef ENAMETOOLONG
+		case ENAMETOOLONG:
+#endif
+			exstat = 127;
+			break;
+		default:
+			exstat = 126;
+			break;
+		}
+		errno = rv;
+		unwind(Flag(FPOSIX) ? LSHELL : LEXIT);
 	}
  Break:
 	exstat = rv & 0xFF;
@@ -474,24 +531,25 @@ execute(struct op * volatile t,
 /*
  * execute simple command
  */
-
 static int
 comexec(struct op *t, struct tbl * volatile tp, const char **ap,
-    volatile int flags, volatile int *xerrok)
+    volatile int flags, int *xerrok)
 {
 	int i;
 	volatile int rv = 0;
 	const char *cp;
 	const char **lastp;
-	/* Must be static (XXX but why?) */
-	static struct op texec;
 	int type_flags;
-	bool resetspec;
+	Wahr resetspec;
 	int fcflags = FC_BI | FC_FUNC | FC_PATH;
 	struct block *l_expand, *l_assign;
 	int optc;
 	const char *exec_argv0 = NULL;
-	bool exec_clrenv = false;
+	Wahr exec_clrenv = Nee;
+	volatile kui old_inuse;
+	const char * volatile old_kshname;
+	volatile kby old_flags[FNFLAGS];
+	static struct op texec; /* static for use by child process */
 
 	/* snag the last argument for $_ */
 	if (Flag(FTALKING) && *(lastp = ap)) {
@@ -521,7 +579,7 @@ comexec(struct op *t, struct tbl * volat
 	 *	FOO=bar command			FOO is neither kept nor exported
 	 *	PATH=... foobar			use new PATH in foobar search
 	 */
-	resetspec = false;
+	resetspec = Nee;
 	while (tp && tp->type == CSHELL) {
 		/* undo effects of command */
 		fcflags = FC_BI | FC_FUNC | FC_PATH;
@@ -532,7 +590,9 @@ comexec(struct op *t, struct tbl * volat
 				break;
 			}
 			if ((tp = findcom(cp, FC_BI)) == NULL)
-				errorf(Tf_sD_sD_s, Tbuiltin, cp, Tnot_found);
+				kerrf(KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE |
+				    KWF_THREEMSG | KWF_NOERRNO, Tbuiltin, cp,
+				    Tnot_found);
 			if (tp->type == CSHELL && (tp->flag & LOW_BI))
 				break;
 			continue;
@@ -546,9 +606,9 @@ comexec(struct op *t, struct tbl * volat
 					exec_argv0 = builtin_opt.optarg;
 					break;
 				case 'c':
-					exec_clrenv = true;
+					exec_clrenv = Ja;
 					/* ensure we can actually do this */
-					resetspec = true;
+					resetspec = Ja;
 					break;
 				default:
 					rv = 2;
@@ -560,7 +620,7 @@ comexec(struct op *t, struct tbl * volat
 			if (Flag(FPOSIX))
 				fcflags = FC_PATH;
 		} else if (tp->val.f == c_command) {
-			bool saw_p = false;
+			Wahr saw_p = Nee;
 
 			/*
 			 * Ugly dealing with options in two places (here
@@ -568,7 +628,7 @@ comexec(struct op *t, struct tbl * volat
 			 */
 			ksh_getopt_reset(&builtin_opt, 0);
 			while ((optc = ksh_getopt(ap, &builtin_opt, ":p")) == 'p')
-				saw_p = true;
+				saw_p = Ja;
 			if (optc != -1)
 				/* command -vV or something */
 				break;
@@ -576,7 +636,8 @@ comexec(struct op *t, struct tbl * volat
 			fcflags = FC_BI | FC_PATH;
 			if (saw_p) {
 				if (Flag(FRESTRICTED)) {
-					warningf(true, Tf_sD_s,
+					kwarnf(KWF_PREFIX | KWF_FILELINE |
+					    KWF_TWOMSG | KWF_NOERRNO,
 					    "command -p", "restricted");
 					rv = 1;
 					goto Leave;
@@ -588,7 +649,7 @@ comexec(struct op *t, struct tbl * volat
 			 * POSIX says special builtins lose their status
 			 * if accessed using command.
 			 */
-			resetspec = true;
+			resetspec = Ja;
 			if (!ap[0]) {
 				/* ensure command with no args exits with 0 */
 				subst_exstat = 0;
@@ -633,7 +694,7 @@ comexec(struct op *t, struct tbl * volat
 	if (Flag(FEXPORT))
 		type_flags |= EXPORT;
 	if (Flag(FXTRACE))
-		change_xtrace(2, false);
+		change_xtrace(2, Nee);
 	for (i = 0; t->vars[i]; i++) {
 		/* do NOT lookup in the new var/fn block just created */
 		e->loc = l_expand;
@@ -642,7 +703,7 @@ comexec(struct op *t, struct tbl * volat
 		if (Flag(FXTRACE)) {
 			const char *ccp;
 
-			ccp = skip_varname(cp, true);
+			ccp = skip_varname(cp, Ja);
 			if (*ccp == '+')
 				++ccp;
 			if (*ccp == '=')
@@ -656,7 +717,7 @@ comexec(struct op *t, struct tbl * volat
 	}
 
 	if (Flag(FXTRACE)) {
-		change_xtrace(2, false);
+		change_xtrace(2, Nee);
 		if (ap[rv = 0]) {
  xtrace_ap_loop:
 			print_value_quoted(shl_xtrace, ap[rv]);
@@ -665,7 +726,7 @@ comexec(struct op *t, struct tbl * volat
 				goto xtrace_ap_loop;
 			}
 		}
-		change_xtrace(1, false);
+		change_xtrace(1, Nee);
 	}
 
 	if ((cp = *ap) == NULL) {
@@ -673,7 +734,8 @@ comexec(struct op *t, struct tbl * volat
 		goto Leave;
 	} else if (!tp) {
 		if (Flag(FRESTRICTED) && mksh_vdirsep(cp)) {
-			warningf(true, Tf_sD_s, cp, "restricted");
+			kwarnf(KWF_PREFIX | KWF_FILELINE | KWF_TWOMSG |
+			    KWF_NOERRNO, cp, "restricted");
 			rv = 1;
 			goto Leave;
 		}
@@ -691,25 +753,22 @@ comexec(struct op *t, struct tbl * volat
 		break;
 
 	/* function call */
-	case CFUNC: {
-		volatile uint32_t old_inuse;
-		const char * volatile old_kshname;
-		volatile uint8_t old_flags[FNFLAGS];
-
+	case CFUNC:
 		if (!(tp->flag & ISSET)) {
 			struct tbl *ftp;
 
 			if (!tp->u.fpath) {
  fpath_error:
 				rv = (tp->u2.errnov == ENOENT) ? 127 : 126;
-				warningf(true, Tf_sD_s_sD_s, cp,
-				    Tcant_find, Tfile_fd,
-				    cstrerror(tp->u2.errnov));
+				kwarnf(KWF_ERR(rv) | KWF_VERRNO |
+				    KWF_PREFIX | KWF_FILELINE | KWF_TWOMSG,
+				    tp->u2.errnov, cp,
+				    "function definition file");
 				break;
 			}
 			errno = 0;
-			if (include(tp->u.fpath, 0, NULL, false) < 0 ||
-			    !(ftp = findfunc(cp, hash(cp), false)) ||
+			if (include(tp->u.fpath, NULL, Nee) < 0 ||
+			    !(ftp = findfunc(cp, hash(cp), Nee)) ||
 			    !(ftp->flag & ISSET)) {
 				rv = errno;
 				if ((ftp = findcom(cp, FC_BI)) &&
@@ -723,7 +782,9 @@ comexec(struct op *t, struct tbl * volat
 					cp = tp->u.fpath;
 					goto fpath_error;
 				}
-				warningf(true, Tf_sD_s_s, cp,
+				kwarnf0(KWF_ERR(127) |
+				    KWF_PREFIX | KWF_FILELINE | KWF_NOERRNO,
+				    Tf_sD_s_s, cp,
 				    "function not defined by", tp->u.fpath);
 				rv = 127;
 				break;
@@ -757,7 +818,7 @@ comexec(struct op *t, struct tbl * volat
 		for (type_flags = 0; type_flags < FNFLAGS; ++type_flags)
 			old_flags[type_flags] = shell_flags[type_flags];
 		change_xtrace((Flag(FXTRACEREC) ? Flag(FXTRACE) : 0) |
-		    ((tp->flag & TRACE) ? 1 : 0), false);
+		    ((tp->flag & TRACE) ? 1 : 0), Nee);
 		old_inuse = tp->flag & FINUSE;
 		tp->flag |= FINUSE;
 
@@ -768,13 +829,22 @@ comexec(struct op *t, struct tbl * volat
 		}
 
 		kshname = old_kshname;
-		change_xtrace(old_flags[(int)FXTRACE], false);
+		change_xtrace(old_flags[(int)FXTRACE], Nee);
 #ifndef MKSH_LEGACY_MODE
 		if (tp->flag & FKSH) {
 			/* Korn style functions restore Flags on return */
 			old_flags[(int)FXTRACE] = Flag(FXTRACE);
+			/* some must not be restored / need special handling */
 			for (type_flags = 0; type_flags < FNFLAGS; ++type_flags)
-				shell_flags[type_flags] = old_flags[type_flags];
+#ifndef MKSH_UNEMPLOYED
+				if (type_flags == FMONITOR)
+					change_flag(type_flags, OF_INTERNAL,
+					    old_flags[type_flags]);
+				else
+#endif
+				  if (type_flags != FPRIVILEGED)
+					shell_flags[type_flags] =
+					    old_flags[type_flags];
 		}
 #endif
 		tp->flag = (tp->flag & ~FINUSE) | old_inuse;
@@ -796,6 +866,7 @@ comexec(struct op *t, struct tbl * volat
 		case LERREXT:
 			rv = exstat & 0xFF;
 			break;
+		case LRDERR:
 		case LINTR:
 		case LEXIT:
 		case LLEAVE:
@@ -805,10 +876,10 @@ comexec(struct op *t, struct tbl * volat
 			/* NOTREACHED */
 		default:
 			quitenv(NULL);
-			internal_errorf(Tunexpected_type, Tunwind, Tfunction, i);
+			kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,
+			    Tunexpected_type, Tunwind, Tfunction, i);
 		}
 		break;
-	}
 
 	/* executable command */
 	case CEXEC:
@@ -817,12 +888,14 @@ comexec(struct op *t, struct tbl * volat
 		if (!(tp->flag&ISSET)) {
 			if (tp->u2.errnov == ENOENT) {
 				rv = 127;
-				warningf(true, Tf_sD_s_s, cp,
-				    "inaccessible or", Tnot_found);
+				kwarnf(KWF_ERR(127) |
+				    KWF_PREFIX | KWF_FILELINE | KWF_TWOMSG |
+				    KWF_NOERRNO, cp, Tinacc_not_found);
 			} else {
 				rv = 126;
-				warningf(true, Tf_sD_sD_s, cp, "can't execute",
-				    cstrerror(tp->u2.errnov));
+				kwarnf(KWF_ERR(126) | KWF_VERRNO |
+				    KWF_PREFIX | KWF_FILELINE | KWF_TWOMSG,
+				    tp->u2.errnov, cp, "can't execute");
 			}
 			break;
 		}
@@ -836,7 +909,7 @@ comexec(struct op *t, struct tbl * volat
 		texec.type = TEXEC;
 		/* for vistree/dumptree */
 		texec.left = t;
-		texec.str = tp->val.s;
+		texec.op_str = tp->val.s;
 		texec.args = ap;
 
 		/* in this case we do not fork, of course */
@@ -844,14 +917,6 @@ comexec(struct op *t, struct tbl * volat
 			if (exec_argv0)
 				texec.args[0] = exec_argv0;
 			j_exit();
-			if (!(flags & XBGND)
-#ifndef MKSH_UNEMPLOYED
-			    || Flag(FMONITOR)
-#endif
-			    ) {
-				setexecsig(&sigtraps[SIGINT], SS_RESTORE_ORIG);
-				setexecsig(&sigtraps[SIGQUIT], SS_RESTORE_ORIG);
-			}
 		}
 
 		rv = exchild(&texec, flags, xerrok, -1);
@@ -860,12 +925,12 @@ comexec(struct op *t, struct tbl * volat
  Leave:
 	if (flags & XEXEC) {
 		exstat = rv & 0xFF;
-		unwind(LEXIT);
+		unwind(Flag(FPOSIX) ? LSHELL : LEXIT);
 	}
 	return (rv);
 }
 
-static void
+static int
 scriptexec(struct op *tp, const char **ap)
 {
 	const char *sh;
@@ -874,6 +939,7 @@ scriptexec(struct op *tp, const char **a
 	unsigned char buf[68];
 #endif
 	union mksh_ccphack args, cap;
+	int eno;
 
 	sh = str_val(global(TEXECSHELL));
 	if (sh && *sh)
@@ -881,19 +947,17 @@ scriptexec(struct op *tp, const char **a
 	if (!sh || !*sh)
 		sh = MKSH_DEFAULT_EXECSHELL;
 
-	*tp->args-- = tp->str;
+	*tp->args-- = tp->op_str;
 
 #ifndef MKSH_SMALL
-	if ((fd = binopen2(tp->str, O_RDONLY | O_MAYEXEC)) >= 0) {
+	if ((fd = binopen2(tp->op_str, O_RDONLY | O_MAYEXEC)) >= 0) {
 		unsigned char *cp;
-#ifndef MKSH_EBCDIC
 		unsigned short m;
-#endif
 		ssize_t n;
-
-#if defined(__OS2__) && defined(MKSH_WITH_TEXTMODE)
-		setmode(fd, O_TEXT);
+#ifdef __OS2__
+		const char *str;
 #endif
+
 		/* read first couple of octets from file */
 		n = read(fd, buf, sizeof(buf) - 1);
 		close(fd);
@@ -903,31 +967,32 @@ scriptexec(struct op *tp, const char **a
 		/* terminate buffer */
 		buf[n] = '\0';
 
-		/* skip UTF-8 Byte Order Mark, if present */
-		cp = buf + (n = ((buf[0] == 0xEF) && (buf[1] == 0xBB) &&
-		    (buf[2] == 0xBF)) ? 3 : 0);
-
+		/* scan for shebang magic */
+		if (ord(buf[0]) == ORD('#') && ord(buf[1]) == ORD('!'))
+			n = 2;
+#ifdef __OS2__
+		else if (n > 8 && !strncmp((char *)buf, Textproc, 7) &&
+		    ctype(buf[7], C_BLANK))
+			n = 8;
+#endif
+		else
+			goto noshebang;
 		/* scan for newline or NUL (end of buffer) */
+		cp = buf + n;
 		while (!ctype(*cp, C_NL | C_NUL))
 			++cp;
 		/* if the shebang line is longer than MAXINTERP, bail out */
-		if (!*cp)
-			goto noshebang;
+		if (!*cp) {
+			kwarnf0(KWF_ERR(126) | KWF_PREFIX | KWF_FILELINE |
+			    KWF_NOERRNO, "%s: not executable: shebang too long",
+			    tp->op_str);
+			return (ENOEXEC);
+		}
 		/* replace newline by NUL */
 		*cp = '\0';
 
-		/* restore start of shebang position (buf+0 or buf+3) */
+		/* restore start of shebang position */
 		cp = buf + n;
-		/* bail out if no shebang magic found */
-		if (cp[0] == '#' && cp[1] == '!')
-			cp += 2;
-#ifdef __OS2__
-		else if (!strncmp(cp, Textproc, 7) &&
-		    ctype(cp[7], C_BLANK))
-			cp += 8;
-#endif
-		else
-			goto noshebang;
 		/* skip whitespace before shell name */
 		while (ctype(*cp, C_BLANK))
 			++cp;
@@ -959,18 +1024,21 @@ scriptexec(struct op *tp, const char **a
 		 * search to find it.
 		 */
 		if (mksh_vdirsep(sh) && !search_path(sh, path, X_OK, NULL)) {
-			cp = search_path(_getname(sh), path, X_OK, NULL);
-			if (cp)
-				sh = cp;
+			str = search_path(_getname(sh), path, X_OK, NULL);
+			if (str)
+				sh = str;
 		}
 #endif
 		goto nomagic;
  noshebang:
-#ifndef MKSH_EBCDIC
-		m = buf[0] << 8 | buf[1];
-		if (m == 0x7F45 && buf[2] == 'L' && buf[3] == 'F')
-			errorf("%s: not executable: %d-bit ELF file", tp->str,
-			    32 * buf[4]);
+		m = ord(rtt2asc(buf[0])) << 8 | ord(rtt2asc(buf[1]));
+		if (m == 0x7F45 && ord(buf[2]) == ORD('L') &&
+		    ord(buf[3]) == ORD('F')) {
+			kwarnf0(KWF_ERR(126) | KWF_PREFIX | KWF_FILELINE |
+			    KWF_NOERRNO, "%s: not executable: %u-bit ELF file",
+			    tp->op_str, 32U * buf[4]);
+			return (ENOEXEC);
+		}
 		if ((m == /* OMAGIC */ 0407) ||
 		    (m == /* NMAGIC */ 0410) ||
 		    (m == /* ZMAGIC */ 0413) ||
@@ -978,22 +1046,35 @@ scriptexec(struct op *tp, const char **a
 		    (m == /* ECOFF_I386 */ 0x4C01) ||
 		    (m == /* ECOFF_M68K */ 0x0150 || m == 0x5001) ||
 		    (m == /* ECOFF_SH */   0x0500 || m == 0x0005) ||
-		    (m == /* bzip */ 0x425A) || (m == /* "MZ" */ 0x4D5A) ||
+		    (m == /* "MZ" */ 0x4D5A && !( /* cosmo libc APE */
+		     ord(buf[2]) == ORD('q') && ord(buf[3]) == ORD('F') &&
+		     ord(buf[4]) == ORD('p') && ord(buf[5]) == ORD('D') &&
+		     ord(buf[6]) == ORD('=') && ord(buf[7]) == ORD('\''))) ||
 		    (m == /* "NE" */ 0x4E45) || (m == /* "LX" */ 0x4C58) ||
 		    (m == /* ksh93 */ 0x0B13) || (m == /* LZIP */ 0x4C5A) ||
-		    (m == /* xz */ 0xFD37 && buf[2] == 'z' && buf[3] == 'X' &&
-		    buf[4] == 'Z') || (m == /* 7zip */ 0x377A) ||
-		    (m == /* gzip */ 0x1F8B) || (m == /* .Z */ 0x1F9D))
-			errorf("%s: not executable: magic %04X", tp->str, m);
-#endif
+		    (m == /* xz */ 0xFD37 && ord(buf[2]) == ORD('z') &&
+		     ord(buf[3]) == ORD('X') && ord(buf[4]) == ORD('Z')) ||
+		    (m == /* Zstd */ 0x28B5 && ord(rtt2asc(buf[2])) == 0x2FU &&
+		     ord(rtt2asc(buf[3])) == 0xFDU) ||
+		    (m == /* bzip */ 0x425A) || (m == /* 7zip */ 0x377A) ||
+		    (m == /* gzip */ 0x1F8B) || (m == /* .Z */ 0x1F9D) ||
+		    (m == /* UTF-8 BOM */ 0xEFBB &&
+		     ord(rtt2asc(buf[2])) == 0xBFU) ||
+		    (m == /* UCS-4, may also be general binary */ 0x0000) ||
+		    (m == /* UCS-2LE */ 0xFFFE) || (m == /* UCS-2BE */ 0xFEFF)) {
+			kwarnf0(KWF_ERR(126) | KWF_PREFIX | KWF_FILELINE |
+			    KWF_NOERRNO, "%s: not executable: magic %04X",
+			    tp->op_str, m);
+			return (ENOEXEC);
+		}
 #ifdef __OS2__
-		cp = _getext(tp->str);
-		if (cp && (!stricmp(cp, ".cmd") || !stricmp(cp, ".bat"))) {
+		str = _getext(tp->str);
+		if (str && (!stricmp(str, ".cmd") || !stricmp(str, ".bat"))) {
 			/* execute .cmd and .bat with OS2_SHELL, usually CMD.EXE */
 			sh = str_val(global("OS2_SHELL"));
 			*tp->args-- = "/c";
 			/* convert slahes to backslashes */
-			for (cp = tp->str; *cp; cp++) {
+			for (cp = (unsigned char *)tp->str; *cp; cp++) {
 				if (*cp == '/')
 					*cp = '\\';
 			}
@@ -1008,16 +1089,19 @@ scriptexec(struct op *tp, const char **a
 
 	cap.ro = ap;
 	execve(args.rw[0], args.rw, cap.rw);
+	eno = errno;
 
 	/* report both the program that was run and the bogus interpreter */
-	errorf(Tf_sD_sD_s, tp->str, sh, cstrerror(errno));
+	kwarnf(KWF_ERR(127) | KWF_PREFIX | KWF_FILELINE | KWF_TWOMSG,
+	    tp->op_str, sh);
+	return (eno);
 }
 
 /* actual 'builtin' built-in utility call is handled in comexec() */
 int
 c_builtin(const char **wp)
 {
-	return (call_builtin(get_builtin(*wp), wp, Tbuiltin, false));
+	return (call_builtin(get_builtin(*wp), wp, Tbuiltin, Nee));
 }
 
 struct tbl *
@@ -1031,7 +1115,7 @@ get_builtin(const char *s)
  * is created if none is found.
  */
 struct tbl *
-findfunc(const char *name, uint32_t h, bool create)
+findfunc(const char *name, k32 h, Wahr create)
 {
 	struct block *l;
 	struct tbl *tp = NULL;
@@ -1058,17 +1142,17 @@ findfunc(const char *name, uint32_t h, b
 int
 define(const char *name, struct op *t)
 {
-	uint32_t nhash;
+	k32 nhash;
 	struct tbl *tp;
-	bool was_set = false;
+	Wahr was_set = Nee;
 
 	nhash = hash(name);
 
 	while (/* CONSTCOND */ 1) {
-		tp = findfunc(name, nhash, true);
+		tp = findfunc(name, nhash, Ja);
 
 		if (tp->flag & ISSET)
-			was_set = true;
+			was_set = Ja;
 		/*
 		 * If this function is currently being executed, we zap
 		 * this table entry so findfunc() won't see it
@@ -1095,7 +1179,7 @@ define(const char *name, struct op *t)
 
 	tp->val.t = tcopy(t->left, tp->areap);
 	tp->flag |= (ISSET|ALLOC);
-	if (t->u.ksh_func)
+	if (t->u.charflag)
 		tp->flag |= FKSH;
 
 	return (0);
@@ -1108,7 +1192,7 @@ const char *
 builtin(const char *name, int (*func) (const char **))
 {
 	struct tbl *tp;
-	uint32_t flag = DEFINED;
+	kui flag = DEFINED;
 
 	/* see if any flags should be set for this builtin */
  flags_loop:
@@ -1165,8 +1249,8 @@ builtin(const char *name, int (*func) (c
 struct tbl *
 findcom(const char *name, int flags)
 {
-	static struct tbl temp;
-	uint32_t h = hash(name);
+	static union tbl_static temp;
+	k32 h = hash(name);
 	struct tbl *tp = NULL, *tbi;
 	/* insert if not found */
 	unsigned char insert = Flag(FTRACKALL);
@@ -1188,7 +1272,7 @@ findcom(const char *name, int flags)
 	if ((flags & FC_SPECBI) && tbi && (tbi->flag & SPEC_BI))
 		tp = tbi;
 	if (!tp && (flags & FC_FUNC)) {
-		tp = findfunc(name, h, false);
+		tp = findfunc(name, h, Nee);
 		if (tp && !(tp->flag & ISSET)) {
 			if ((fpath = str_val(global(TFPATH))) == null) {
 				tp->u.fpath = NULL;
@@ -1220,7 +1304,7 @@ findcom(const char *name, int flags)
 				tp = ktenter(&taliases, name, h);
 				tp->type = CTALIAS;
 			} else {
-				tp = &temp;
+				tp = (struct tbl *)&temp;
 				tp->type = CEXEC;
 			}
 			/* make ~ISSET */
@@ -1244,7 +1328,7 @@ findcom(const char *name, int flags)
 			 * even if the command hasn't been set up as an
 			 * autoloaded function (ie, no typeset -uf).
 			 */
-			tp = &temp;
+			tp = (struct tbl *)&temp;
 			tp->type = CFUNC;
 			/* make ~ISSET */
 			tp->flag = DEFINED;
@@ -1259,7 +1343,7 @@ findcom(const char *name, int flags)
  * (just relative or all?)
  */
 void
-flushcom(bool all)
+flushcom(Wahr all)
 {
 	struct tbl *tp;
 	struct tstate ts;
@@ -1376,27 +1460,105 @@ search_path(const char *name, const char
 }
 
 static int
-call_builtin(struct tbl *tp, const char **wp, const char *where, bool resetspec)
+call_builtin(struct tbl *tp, const char **wp, const char *where, Wahr resetspec)
 {
 	int rv;
+	Wahr old_builtin_spec;
 
 	if (!tp)
-		internal_errorf(Tf_sD_s, where, wp[0]);
+		kerrf(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_TWOMSG | KWF_NOERRNO,
+		    where, wp[0]);
 	builtin_argv0 = wp[0];
-	builtin_spec = tobool(!resetspec && (tp->flag & SPEC_BI));
+	old_builtin_spec = builtin_spec;
+	builtin_spec = isWahr(!resetspec && (tp->flag & SPEC_BI));
 	shf_reopen(1, SHF_WR, shl_stdout);
-	shl_stdout_ok = true;
+	shl_stdout_ok = Ja;
 	ksh_getopt_reset(&builtin_opt, GF_ERROR);
 	rv = (*tp->val.f)(wp);
-	shf_flush(shl_stdout);
-	shl_stdout_ok = false;
+	if (shf_flush(shl_stdout) < 0) {
+		bi_errorf(Tf_sD_s, Twrite, cstrerror(errno));
+		if (rv == 0)
+			rv = 1;
+	}
+	shl_stdout_ok = Nee;
 	builtin_argv0 = NULL;
-	builtin_spec = false;
+	builtin_spec = old_builtin_spec;
 	return (rv);
 }
 
+static void
+doexfunc(struct op *t)
+{
+	const char **ap = t->args;
+	const char *s, *p;
+	char *u;
+	struct tbl *vp;
+	struct block *l = e->loc;
+	size_t n;
+	unsigned int S = 0;
+
+	subst_exstat = 0;
+	current_lineno = t->lineno;
+
+	if (!*ap)
+		return;
+
+	if (Flag(FXTRACE)) {
+		change_xtrace(2, Nee);
+		shf_puts("local ", shl_xtrace);
+	}
+	while ((s = *ap++)) {
+		p = skip_wdvarname(s, Nee);
+		if (*p == EOS) {
+			/* mandatory argument */
+			s = wdstrip(s, 0);
+			if (l->argc < 1)
+				kerrf(KWF_ERR(2) | KWF_PREFIX | KWF_FILELINE |
+				    KWF_TWOMSG | KWF_NOERRNO,
+				    "missing argument", s);
+ take_first:
+			p = l->argv[1];
+			/* shift */
+			l->argv[1] = l->argv[0];
+			++l->argv;
+			--l->argc;
+			++S;
+		} else if (l->argc > 0) {
+			/* optional argument, present */
+			n = p + 1 - s;
+			u = memcpy(alloc(n, ATEMP), s, n);
+			u[n - 1U] = EOS;
+			s = wdstrip(u, 0);
+			goto take_first;
+		} else {
+			/* optional argument, absent */
+			u = evalstr(s, DOASNTILDE | DOSCALAR);
+			s = u;
+			u = ucstrchr(u, '=');
+			*u++ = '\0';
+			p = u;
+		}
+		if (varnamecheck(s))
+			kerrf(KWF_ERR(2) | KWF_PREFIX | KWF_FILELINE |
+			    KWF_TWOMSG | KWF_NOERRNO, s, "restricted");
+		if (Flag(FXTRACE)) {
+			shf_puts(s, shl_xtrace);
+			shf_putc('=', shl_xtrace);
+			print_value_quoted(shl_xtrace, p);
+			shf_putc(' ', shl_xtrace);
+		}
+		vp = local(s, Nee);
+		setstr(vp, p, KSH_UNWIND_ERROR);
+	}
+	if (Flag(FXTRACE)) {
+		if (S)
+			shf_fprintf(shl_xtrace, "; shift %u", S);
+		change_xtrace(1, Nee);
+	}
+}
+
 /*
- * set up redirection, saving old fds in e->savefd
+ * set up redirection, saving old fds in e->savedfd
  */
 static int
 iosetup(struct ioword *iop, struct tbl *tp)
@@ -1404,7 +1566,7 @@ iosetup(struct ioword *iop, struct tbl *
 	int u = -1;
 	char *cp = iop->ioname;
 	int iotype = iop->ioflag & IOTYPE;
-	bool do_open = true, do_close = false, do_fstat = false;
+	Wahr do_open = Ja, do_close = Nee, do_fstat = Nee;
 	int flags = 0;
 	struct ioword iotmp;
 	struct stat statb;
@@ -1418,9 +1580,9 @@ iosetup(struct ioword *iop, struct tbl *
 	iotmp.ioflag |= IONAMEXP;
 
 	if (Flag(FXTRACE)) {
-		change_xtrace(2, false);
-		fptreef(shl_xtrace, 0, Tft_R, &iotmp);
-		change_xtrace(1, false);
+		change_xtrace(2, Nee);
+		pioact(shl_xtrace, &iotmp);
+		change_xtrace(1, Nee);
 	}
 
 	switch (iotype) {
@@ -1448,7 +1610,7 @@ iosetup(struct ioword *iop, struct tbl *
 				 */
 				flags = O_WRONLY;
 				/* but check again after opening */
-				do_fstat = true;
+				do_fstat = Ja;
 			}
 		} else {
 			/* >|file or set +C */
@@ -1461,7 +1623,7 @@ iosetup(struct ioword *iop, struct tbl *
 		break;
 
 	case IOHERE:
-		do_open = false;
+		do_open = Nee;
 		/* herein() returns -2 if error has been printed */
 		u = herein(iop, NULL);
 		/* cp may have wrong name */
@@ -1470,19 +1632,16 @@ iosetup(struct ioword *iop, struct tbl *
 	case IODUP: {
 		const char *emsg;
 
-		do_open = false;
+		do_open = Nee;
 		if (ksh_isdash(cp)) {
 			/* prevent error return below */
 			u = 1009;
-			do_close = true;
+			do_close = Ja;
 		} else if ((u = check_fd(cp,
 		    X_OK | ((iop->ioflag & IORDUP) ? R_OK : W_OK),
 		    &emsg)) < 0) {
-			char *sp;
-
-			warningf(true, Tf_sD_s,
-			    (sp = snptreef(NULL, 32, Tft_R, &iotmp)), emsg);
-			afree(sp, ATEMP);
+			kwarnf(KWF_PREFIX | KWF_FILELINE | KWF_TWOMSG |
+			    KWF_NOERRNO, stripioact(&iotmp), emsg);
 			return (-1);
 		}
 		if (u == (int)iop->unit) {
@@ -1496,7 +1655,8 @@ iosetup(struct ioword *iop, struct tbl *
 
 	if (do_open) {
 		if (Flag(FRESTRICTED) && (flags & O_CREAT)) {
-			warningf(true, Tf_sD_s, cp, "restricted");
+			kwarnf(KWF_PREFIX | KWF_FILELINE | KWF_TWOMSG |
+			    KWF_NOERRNO, cp, "restricted");
 			return (-1);
 		}
 		u = binopen3(cp, flags, 0666);
@@ -1513,45 +1673,37 @@ iosetup(struct ioword *iop, struct tbl *
 	if (u < 0) {
 		/* herein() may already have printed message */
 		if (u == -1) {
-			u = errno;
-			warningf(true, Tf_cant_ss_s,
+			kwarnf(KWF_PREFIX | KWF_FILELINE | KWF_TWOMSG, cp,
+			    (iotype == IOREAD || iotype == IOHERE) ? Topen :
 #if 0
 			    /* can't happen */
 			    iotype == IODUP ? "dup" :
 #endif
-			    (iotype == IOREAD || iotype == IOHERE) ?
-			    Topen : Tcreate, cp, cstrerror(u));
+			    Tcreate);
 		}
 		return (-1);
 	}
-	/* Do not save if it has already been redirected (i.e. "cat >x >y"). */
-	if (e->savefd[iop->unit] == 0) {
-		/* If these are the same, it means unit was previously closed */
-		if (u == (int)iop->unit)
-			e->savefd[iop->unit] = -1;
-		else
-			/*
-			 * c_exec() assumes e->savefd[fd] set for any
-			 * redirections. Ask savefd() not to close iop->unit;
-			 * this allows error messages to be seen if iop->unit
-			 * is 2; also means we can't lose the fd (eg, both
-			 * dup2 below and dup2 in restfd() failing).
-			 */
-			e->savefd[iop->unit] = savefd(iop->unit);
-	}
+	/* only save if it has not yet been redirected (e.g. by "cat >x >y") */
+	if (FDSVNUM(e, iop->unit) == 0U) {
+		/* c_exec() assumes e->savedfd[fd] set for any redirection */
+		FDSAVE(iop->unit, u == (int)iop->unit ?
+		    /* previously closed (exec >&-; ls >x; print e) */ -1 :
+		    savefd(iop->unit));
+	} else
+		/* clear previous fd-was-closed flag */
+		e->savedfd[iop->unit] &= FDNUMMASK;
 
-	if (do_close)
+	if (do_close) {
 		close(iop->unit);
-	else if (u != (int)iop->unit) {
-		if (ksh_dup2(u, iop->unit, true) < 0) {
+		e->savedfd[iop->unit] |= FDICLMASK;
+	} else if (u != (int)iop->unit) {
+		if (ksh_dup2(u, iop->unit, Ja) < 0) {
 			int eno;
-			char *sp;
 
 			eno = errno;
-			warningf(true, Tf_s_sD_s, Tredirection_dup,
-			    (sp = snptreef(NULL, 32, Tft_R, &iotmp)),
-			    cstrerror(eno));
-			afree(sp, ATEMP);
+			kwarnf(KWF_VERRNO | KWF_PREFIX | KWF_FILELINE |
+			    KWF_TWOMSG, eno,
+			    stripioact(&iotmp), Tredirection_dup);
 			if (iotype != IODUP)
 				close(u);
 			return (-1);
@@ -1585,7 +1737,7 @@ iosetup(struct ioword *iop, struct tbl *
 static int
 hereinval(struct ioword *iop, int sub, char **resbuf, struct shf *shf)
 {
-	const char * volatile ccp = iop->heredoc;
+	const char *ccp;
 	struct source *s, *osource;
 
 	osource = source;
@@ -1596,6 +1748,7 @@ hereinval(struct ioword *iop, int sub, c
 		/* special to iosetup(): don't print error */
 		return (-2);
 	}
+	ccp = iop->heredoc;
 	if (iop->ioflag & IOHERESTR) {
 		ccp = evalstr(iop->delim, DOHERESTR | DOSCALAR);
 	} else if (sub) {
@@ -1604,7 +1757,8 @@ hereinval(struct ioword *iop, int sub, c
 		s->start = s->str = ccp;
 		source = s;
 		if (yylex(sub) != LWORD)
-			internal_errorf("herein: yylex");
+			kerrf(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_ONEMSG | KWF_NOERRNO,
+			    "herein: yylex");
 		source = osource;
 		ccp = evalstr(yylval.cp, DOSCALAR | DOHEREDOC);
 	}
@@ -1639,9 +1793,8 @@ herein(struct ioword *iop, char **resbuf
 	 */
 	h = maketemp(ATEMP, TT_HEREDOC_EXP, &e->temps);
 	if (!(shf = h->shf) || (fd = binopen3(h->tffn, O_RDONLY, 0)) < 0) {
-		i = errno;
-		warningf(true, Tf_temp,
-		    !shf ? Tcreate : Topen, h->tffn, cstrerror(i));
+		kwarnf0(KWF_PREFIX | KWF_FILELINE, Tf_temp,
+		    !shf ? Tcreate : Topen, h->tffn);
 		if (shf)
 			shf_close(shf);
 		/* special to iosetup(): don't print error */
@@ -1657,8 +1810,8 @@ herein(struct ioword *iop, char **resbuf
 	if (shf_close(shf) == -1) {
 		i = errno;
 		close(fd);
-		warningf(true, Tf_temp,
-		    Twrite, h->tffn, cstrerror(i));
+		kwarnf1(KWF_VERRNO | KWF_PREFIX | KWF_FILELINE, i,
+		    Tf_temp, Twrite, h->tffn);
 		/* special to iosetup(): don't print error */
 		return (-2);
 	}
@@ -1671,7 +1824,7 @@ herein(struct ioword *iop, char **resbuf
  *	print the args in column form - assuming that we can
  */
 static const char *
-do_selectargs(const char **ap, bool print_menu)
+do_selectargs(const char **ap, Wahr print_menu)
 {
 	static const char *read_args[] = {
 		Tread, Tdr, TREPLY, NULL
@@ -1691,13 +1844,12 @@ do_selectargs(const char **ap, bool prin
 		if (print_menu || !*str_val(global(TREPLY)))
 			pr_menu(ap);
 		shellf(Tf_s, str_val(global("PS3")));
-		if (call_builtin(findcom(Tread, FC_BI), read_args, Tselect,
-		    false))
+		if (call_builtin(findcom(Tread, FC_BI), read_args, Tselect, Nee))
 			return (NULL);
 		if (*(s = str_val(global(TREPLY))))
 			return ((getn(s, &i) && i >= 1 && i <= argct) ?
 			    ap[i - 1] : null);
-		print_menu = true;
+		print_menu = Ja;
 	}
 }
 
@@ -1758,7 +1910,7 @@ pr_menu(const char * const *ap)
 	smi.args = ap;
 	co.shf = shl_out;
 	co.linesep = '\n';
-	co.prefcol = co.do_last = true;
+	co.prefcol = co.do_last = Ja;
 	print_columns(&co, n, select_fmt_entry, (void *)&smi,
 	    smi.num_width + 2 + aocts, smi.num_width + 2 + acols);
 }
@@ -1802,7 +1954,7 @@ static Test_op
 dbteste_isa(Test_env *te, Test_meta meta)
 {
 	Test_op ret = TO_NONOP;
-	bool uqword;
+	Wahr uqword;
 	const char *p;
 
 	if (!*te->pos.wp)
@@ -1840,7 +1992,7 @@ dbteste_isa(Test_env *te, Test_meta meta
 }
 
 static const char *
-dbteste_getopnd(Test_env *te, Test_op op, bool do_eval)
+dbteste_getopnd(Test_env *te, Test_op op, Wahr do_eval)
 {
 	const char *s = *te->pos.wp;
 	int flags = DOTILDE | DOSCALAR;
@@ -1866,5 +2018,44 @@ static void
 dbteste_error(Test_env *te, int offset, const char *msg)
 {
 	te->flags |= TEF_ERROR;
-	internal_warningf("dbteste_error: %s (offset %d)", msg, offset);
+	kwarnf0(KWF_INTERNAL | KWF_WARNING | KWF_NOERRNO,
+	    "dbteste_error: %s (offset %d)", msg, offset);
+}
+
+const char **
+cpyargv(int *i, const char **src, Area *ap)
+{
+	size_t n;
+	const char **wp, **dst;
+
+	wp = src - 1;
+	while (*++wp != NULL)
+		/* nothing */;
+	n = wp - src;
+	if (n < 1 || notoktoadd(n, 1) ||
+	    notok2add((size_t)INT_MAX, n, 1))
+		kerrf(KWF_VERRNO | KWF_INTERNAL | KWF_ERR(0xFF) |
+		    KWF_PREFIX | KWF_FILELINE | KWF_ONEMSG,
+		    EOVERFLOW, "cpyargv");
+	if (i)
+		*i = n - /* kshname */ 1U;
+	dst = alloc2(n + /* NULL */ 1U, sizeof(const char *), ap);
+
+	wp = dst;
+	*wp++ = *src++;
+	while (--n)
+		strdupx(*wp++, *src++, ap);
+	*wp = NULL;
+	return (dst);
+}
+
+int
+varnamecheck(const char *var)
+{
+	if (!Flag(FRESTRICTED))
+		return (0);
+	if (!strcmp(var, TENV) || !strcmp(var, "HISTFILE") ||
+	    !strcmp(var, TPATH) || !strcmp(var, TSHELL))
+		return (1);
+	return (0);
 }
--- mksh-59c.orig/expr.c
+++ mksh-59c/expr.c
@@ -2,8 +2,9 @@
 
 /*-
  * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
- *		 2011, 2012, 2013, 2014, 2016, 2017, 2018, 2019
- *	mirabilos <m@mirbsd.org>
+ *		 2011, 2012, 2013, 2014, 2016, 2017, 2018, 2019,
+ *		 2021, 2022, 2023
+ *	mirabilos <m$(date +%Y)@mirbsd.de>
  *
  * Provided that these terms and disclaimer and all copyright notices
  * are retained or reproduced in an accompanying document, permission
@@ -21,9 +22,10 @@
  * of said person's immediate fault when using the work as intended.
  */
 
+#define MKSH_DO_MBI_CTAS
 #include "sh.h"
 
-__RCSID("$MirOS: src/bin/mksh/expr.c,v 1.108 2020/06/20 02:27:50 tg Exp $");
+__RCSID("$MirOS: src/bin/mksh/expr.c,v 1.129 2025/12/24 04:51:52 tg Exp $");
 
 #define EXPRTOK_DEFNS
 #include "exprtok.h"
@@ -56,12 +58,12 @@ static const char opname[][4] = {
 #include "exprtok.h"
 };
 
-static const uint8_t oplen[] = {
+static const kby oplen[] = {
 #define EXPRTOK_LEN
 #include "exprtok.h"
 };
 
-static const uint8_t opprec[] = {
+static const kby opprec[] = {
 #define EXPRTOK_PREC
 #include "exprtok.h"
 };
@@ -78,11 +80,11 @@ typedef struct expr_state {
 	/* token from token() */
 	enum token tok;
 	/* don't do assignments (for ?:, &&, ||) */
-	uint8_t noassign;
+	kby noassign;
 	/* evaluating an $(()) expression? */
-	bool arith;
+	Wahr arith;
 	/* unsigned arithmetic calculation */
-	bool natural;
+	Wahr natural;
 } Expr_state;
 
 enum error_type {
@@ -94,7 +96,7 @@ static void evalerr(Expr_state *, enum e
     MKSH_A_NORETURN;
 static struct tbl *evalexpr(Expr_state *, unsigned int);
 static void exprtoken(Expr_state *);
-static struct tbl *do_ppmm(Expr_state *, enum token, struct tbl *, bool);
+static struct tbl *do_ppmm(Expr_state *, enum token, struct tbl *, Wahr);
 static void assign_check(Expr_state *, enum token, struct tbl *);
 static struct tbl *intvar(Expr_state *, struct tbl *);
 
@@ -102,15 +104,15 @@ static struct tbl *intvar(Expr_state *,
  * parse and evaluate expression
  */
 int
-evaluate(const char *expr, mksh_ari_t *rval, int error_ok, bool arith)
+evaluate(const char *expr, mksh_ari_t *rval, int error_ok, Wahr arith)
 {
-	struct tbl v;
+	union tbl_static v;
 	int ret;
 
-	v.flag = DEFINED | INTEGER;
-	v.type = 0;
-	ret = v_evaluate(&v, expr, error_ok, arith);
-	*rval = v.val.i;
+	v.tbl.flag = DEFINED | INTEGER;
+	v.tbl.type = 0;
+	ret = v_evaluate((struct tbl *)&v, expr, error_ok, arith);
+	*rval = v.tbl.val.i;
 	return (ret);
 }
 
@@ -118,8 +120,7 @@ evaluate(const char *expr, mksh_ari_t *r
  * parse and evaluate expression, storing result in vp.
  */
 int
-v_evaluate(struct tbl *vp, const char *expr, volatile int error_ok,
-    bool arith)
+v_evaluate(struct tbl *vp, const char *expr, int error_ok, Wahr arith)
 {
 	struct tbl *v;
 	Expr_state curstate;
@@ -141,7 +142,11 @@ v_evaluate(struct tbl *vp, const char *e
 		if (i == LAEXPR) {
 			if (error_ok == KSH_RETURN_ERROR)
 				return (0);
-			errorfz();
+			/* error already printed */
+			/* (cf. syn.c for why) */
+			exstat = 1;
+			shl_stdout_ok = Nee;
+			i = LERROR;
 		}
 		unwind(i);
 		/* NOTREACHED */
@@ -162,7 +167,7 @@ v_evaluate(struct tbl *vp, const char *e
 	if (vp->flag & INTEGER)
 		setint_v(vp, v, es->arith);
 	else
-		/* can fail if readonly */
+		/* can fail if read-only */
 		setstr(vp, str_val(v), error_ok);
 
 	quitenv(NULL);
@@ -176,7 +181,7 @@ evalerr(Expr_state *es, enum error_type
 	char tbuf[2];
 	const char *s;
 
-	es->arith = false;
+	es->arith = Nee;
 	switch (type) {
 	case ET_UNEXPECTED:
 		switch (es->tok) {
@@ -197,33 +202,41 @@ evalerr(Expr_state *es, enum error_type
 		default:
 			s = opname[(int)es->tok];
 		}
-		warningf(true, Tf_sD_s_qs, es->expression,
-		    Tunexpected, s);
+		kwarnf0(KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE | KWF_NOERRNO,
+		    Tf_sD_s_qs, es->expression, Tunexpected, s);
 		break;
 
 	case ET_BADLIT:
-		warningf(true, Tf_sD_s_qs, es->expression,
-		    Tbadnum, str);
+		if (!strcmp(es->expression, str))
+			kwarnf0(KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE |
+			    KWF_TWOMSG, es->expression, Tbadnum);
+		else
+			kwarnf0(KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE,
+			    Tf_sD_s_qs, es->expression, Tbadnum, str);
 		break;
 
 	case ET_RECURSIVE:
-		warningf(true, Tf_sD_s_qs, es->expression,
-		    "expression recurses on parameter", str);
+		kwarnf0(KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE | KWF_NOERRNO,
+		    Tf_sD_s_qs,
+		    es->expression, "expression recurses on parameter", str);
 		break;
 
 	case ET_LVALUE:
-		warningf(true, Tf_sD_s_s,
+		kwarnf0(KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE | KWF_NOERRNO,
+		    Tf_sD_s_s,
 		    es->expression, str, "requires lvalue");
 		break;
 
 	case ET_RDONLY:
-		warningf(true, Tf_sD_s_s,
+		kwarnf0(KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE | KWF_NOERRNO,
+		    Tf_sD_s_s,
 		    es->expression, str, "applied to read-only variable");
 		break;
 
 	default: /* keep gcc happy */
 	case ET_STR:
-		warningf(true, Tf_sD_s, es->expression, str);
+		kwarnf(KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE | KWF_NOERRNO |
+		    KWF_TWOMSG, es->expression, str);
 		break;
 	}
 	unwind(LAEXPR);
@@ -231,7 +244,7 @@ evalerr(Expr_state *es, enum error_type
 
 /* do a ++ or -- operation */
 static struct tbl *
-do_ppmm(Expr_state *es, enum token op, struct tbl *vasn, bool is_prefix)
+do_ppmm(Expr_state *es, enum token op, struct tbl *vasn, Wahr is_prefix)
 {
 	struct tbl *vl;
 	mksh_uari_t oval;
@@ -262,7 +275,7 @@ evalexpr(Expr_state *es, unsigned int pr
 {
 	struct tbl *vl, *vr = NULL, *vasn;
 	enum token op;
-	mksh_uari_t res = 0, t1, t2, t3;
+	mksh_uari_t res = 0;
 
 	if (prec == P_PRIMARY) {
 		switch ((int)(op = es->tok)) {
@@ -299,7 +312,7 @@ evalexpr(Expr_state *es, unsigned int pr
 		case O_PLUSPLUS:
 		case O_MINUSMINUS:
 			exprtoken(es);
-			vl = do_ppmm(es, op, es->val, true);
+			vl = do_ppmm(es, op, es->val, Ja);
 			exprtoken(es);
 			break;
 
@@ -315,7 +328,7 @@ evalexpr(Expr_state *es, unsigned int pr
 		}
 
 		if (es->tok == O_PLUSPLUS || es->tok == O_MINUSMINUS) {
-			vl = do_ppmm(es, es->tok, vl, false);
+			vl = do_ppmm(es, es->tok, vl, Nee);
 			exprtoken(es);
 		}
 
@@ -344,7 +357,7 @@ evalexpr(Expr_state *es, unsigned int pr
 				assign_check(es, op, vasn);
 			vr = intvar(es, evalexpr(es, P_ASSIGN));
 		} else if (op == O_TERN) {
-			bool ev = vl->val.u != 0;
+			Wahr ev = vl->val.u != 0;
 
 			if (!ev)
 				es->noassign++;
@@ -365,118 +378,91 @@ evalexpr(Expr_state *es, unsigned int pr
 		} else if (op != O_LAND && op != O_LOR)
 			vr = intvar(es, evalexpr(es, prec - 1));
 
-		/* common ops setup */
+		/* op calculation */
+#ifndef MKSH_LEGACY_MODE
+#define ariop(op)	(vl->val.u op vr->val.u)
+#define cmpop(op)	(es->natural ?			\
+	(mksh_uari_t)(vl->val.u op vr->val.u) :		\
+	(mksh_uari_t)mbiKcmp(mksh_uari_t, KUA_HM,	\
+	    vl->val.u, op, vr->val.u))
+#else
+#define ariop(op)	(es->natural ?			\
+	(mksh_uari_t)(vl->val.u op vr->val.u) :		\
+	(mksh_uari_t)(vl->val.i op vr->val.i))
+#define cmpop(op)	ariop(op)
+#endif
 		switch ((int)op) {
+		case O_PLUS:
+		case O_PLUSASN:
+			res = ariop(+);
+			break;
+		case O_MINUS:
+		case O_MINUSASN:
+			res = ariop(-);
+			break;
+		case O_TIMES:
+		case O_TIMESASN:
+			res = ariop(*);
+			break;
 		case O_DIV:
 		case O_DIVASN:
-		case O_MOD:
-		case O_MODASN:
-			if (vr->val.u == 0) {
+			if (vr->val.i == 0) {
 				if (!es->noassign)
 					evalerr(es, ET_STR, "zero divisor");
-				vr->val.u = 1;
+				res = vl->val.u; /* dummy value, could be 1 */
+				break;
 			}
-			/* calculate the absolute values */
-			t1 = vl->val.i < 0 ? -vl->val.u : vl->val.u;
-			t2 = vr->val.i < 0 ? -vr->val.u : vr->val.u;
-			break;
 #ifndef MKSH_LEGACY_MODE
-		case O_LSHIFT:
-		case O_LSHIFTASN:
-		case O_RSHIFT:
-		case O_RSHIFTASN:
-		case O_ROL:
-		case O_ROLASN:
-		case O_ROR:
-		case O_RORASN:
-			t1 = vl->val.u;
-			t2 = vr->val.u & 31;
-			break;
+			if (!es->natural)
+				res = mbiKdiv(mksh_uari_t, KUA_HM,
+				    vl->val.u, vr->val.u);
+			else
 #endif
-		case O_LAND:
-		case O_LOR:
-			t1 = vl->val.u;
-			t2 = 0;	/* gcc */
-			break;
-		default:
-			t1 = vl->val.u;
-			t2 = vr->val.u;
-			break;
-		}
-
-#define cmpop(op)	(es->natural ?			\
-	(mksh_uari_t)(vl->val.u op vr->val.u) :		\
-	(mksh_uari_t)(vl->val.i op vr->val.i)		\
-)
-
-		/* op calculation */
-		switch ((int)op) {
-		case O_TIMES:
-		case O_TIMESASN:
-			res = t1 * t2;
+				res = ariop(/);
 			break;
 		case O_MOD:
 		case O_MODASN:
-			if (es->natural) {
-				res = vl->val.u % vr->val.u;
-				break;
-			}
-			goto signed_division;
-		case O_DIV:
-		case O_DIVASN:
-			if (es->natural) {
-				res = vl->val.u / vr->val.u;
+			if (vr->val.i == 0) {
+				if (!es->noassign)
+					evalerr(es, ET_STR, "zero divisor");
+				res = vl->val.u; /* dummy value, could be 1 */
 				break;
 			}
- signed_division:
-			/*
-			 * a / b = abs(a) / abs(b) * sgn((u)a^(u)b)
-			 */
-			t3 = t1 / t2;
 #ifndef MKSH_LEGACY_MODE
-			res = ((vl->val.u ^ vr->val.u) & 0x80000000) ? -t3 : t3;
-#else
-			res = ((t1 == vl->val.u ? 0 : 1) ^
-			    (t2 == vr->val.u ? 0 : 1)) ? -t3 : t3;
+			if (!es->natural)
+				res = mbiKrem(mksh_uari_t, KUA_HM,
+				    vl->val.u, vr->val.u);
+			else
 #endif
-			if (op == O_MOD || op == O_MODASN) {
-				/*
-				 * primitive modulo, to get the sign of
-				 * the result correct:
-				 * (a % b) = a - ((a / b) * b)
-				 * the subtraction and multiplication
-				 * are, amazingly enough, sign ignorant
-				 */
-				res = vl->val.u - (res * vr->val.u);
-			}
-			break;
-		case O_PLUS:
-		case O_PLUSASN:
-			res = t1 + t2;
-			break;
-		case O_MINUS:
-		case O_MINUSASN:
-			res = t1 - t2;
+				res = ariop(%);
 			break;
 #ifndef MKSH_LEGACY_MODE
 		case O_ROL:
 		case O_ROLASN:
-			res = (t1 << t2) | (t1 >> (32 - t2));
+			res = mbiKrol(mksh_uari_t, vl->val.u, vr->val.u);
 			break;
 		case O_ROR:
 		case O_RORASN:
-			res = (t1 >> t2) | (t1 << (32 - t2));
+			res = mbiKror(mksh_uari_t, vl->val.u, vr->val.u);
 			break;
 #endif
 		case O_LSHIFT:
 		case O_LSHIFTASN:
-			res = t1 << t2;
+#ifndef MKSH_LEGACY_MODE
+			res = mbiKshl(mksh_uari_t, vl->val.u, vr->val.u);
+#else
+			res = ariop(<<);
+#endif
 			break;
 		case O_RSHIFT:
 		case O_RSHIFTASN:
-			res = es->natural || vl->val.i >= 0 ?
-			    t1 >> t2 :
-			    ~(~t1 >> t2);
+#ifndef MKSH_LEGACY_MODE
+			res = mbiKsar(mksh_uari_t,
+			    !es->natural && vl->val.i < 0,
+			    vl->val.u, vr->val.u);
+#else
+			res = ariop(>>);
+#endif
 			break;
 		case O_LT:
 			res = cmpop(<);
@@ -491,47 +477,47 @@ evalexpr(Expr_state *es, unsigned int pr
 			res = cmpop(>=);
 			break;
 		case O_EQ:
-			res = t1 == t2;
+			res = ariop(==);
 			break;
 		case O_NE:
-			res = t1 != t2;
+			res = ariop(!=);
 			break;
 		case O_BAND:
 		case O_BANDASN:
-			res = t1 & t2;
+			res = ariop(&);
 			break;
 		case O_BXOR:
 		case O_BXORASN:
-			res = t1 ^ t2;
+			res = ariop(^);
 			break;
 		case O_BOR:
 		case O_BORASN:
-			res = t1 | t2;
+			res = ariop(|);
 			break;
 		case O_LAND:
-			if (!t1)
+			if (!vl->val.u)
 				es->noassign++;
 			exprtoken(es);
 			vr = intvar(es, evalexpr(es, prec - 1));
-			res = t1 && vr->val.u;
-			if (!t1)
+			res = vl->val.u && vr->val.u;
+			if (!vl->val.u)
 				es->noassign--;
 			break;
 		case O_LOR:
-			if (t1)
+			if (vl->val.u)
 				es->noassign++;
 			exprtoken(es);
 			vr = intvar(es, evalexpr(es, prec - 1));
-			res = t1 || vr->val.u;
-			if (t1)
+			res = vl->val.u || vr->val.u;
+			if (vl->val.u)
 				es->noassign--;
 			break;
 		case O_ASN:
 		case O_COMMA:
-			res = t2;
+			res = vr->val.u;
 			break;
 		}
-
+#undef ariop
 #undef cmpop
 
 		if (IS_ASSIGNOP(op)) {
@@ -565,7 +551,7 @@ exprtoken(Expr_state *es)
 	if (es->tokp == es->expression && (unsigned int)c == ORD('#')) {
 		/* expression begins with # */
 		/* switch to unsigned */
-		es->natural = true;
+		es->natural = Ja;
 		++cp;
 		goto skip_spaces;
 	}
@@ -597,7 +583,7 @@ exprtoken(Expr_state *es)
 	} else if (c == '1' && cp[1] == '#') {
 		cp += 2;
 		if (*cp)
-			cp += utf_ptradj(cp);
+			cp += ez_mbtoc(NULL, cp);
 		strndupx(tvar, es->tokp, cp - es->tokp, ATEMP);
 		goto process_tvar;
 #ifndef MKSH_SMALL
@@ -606,7 +592,7 @@ exprtoken(Expr_state *es)
 			es->tok = END;
 			evalerr(es, ET_UNEXPECTED, NULL);
 		}
-		cp += utf_ptradj(cp);
+		cp += ez_mbtoc(NULL, cp);
 		if (*cp++ != '\'')
 			evalerr(es, ET_STR,
 			    "multi-character character constant");
@@ -664,8 +650,9 @@ tempvar(const char *vname)
 	struct tbl *vp;
 	size_t vsize;
 
-	vsize = strlen(vname) + 1;
-	vp = alloc(offsetof(struct tbl, name[0]) + vsize, ATEMP);
+	/* vname is either "" or vtemp->name which maxes at 12 */
+	vsize = strlen(vname) + 1U;
+	vp = alloc(mbccFAMsz(struct tbl, name, vsize), ATEMP);
 	memcpy(vp->name, vname, vsize);
 	vp->flag = ISSET|INTEGER;
 	vp->type = 0;
@@ -699,11 +686,30 @@ intvar(Expr_state *es, struct tbl *vp)
 	return (vq);
 }
 
-
 /*
  * UTF-8 support code: high-level functions
  */
 
+char *
+ez_bs(char *cp, char *lower_bound)
+{
+	if (UTFMODE) {
+		char *bp = cp;
+		size_t n;
+
+		/* skip backwards knowing the UTF-8 encoding */
+		while (bp > lower_bound && (rtt2asc(*bp) & 0xC0U) == 0x80U)
+			--bp;
+		/* ensure we arrive back at the original point */
+		n = ez_mbtoc(NULL, bp);
+		/* back where we started? if so, this was indeed UTF-8 */
+		if (bp + n - 1 == cp)
+			return (bp);
+		/* no so some raw octet is at *cp */
+	}
+	return (cp);
+}
+
 int
 utf_widthadj(const char *src, const char **dst)
 {
@@ -711,15 +717,12 @@ utf_widthadj(const char *src, const char
 	unsigned int wc;
 	int width;
 
-	if (!UTFMODE || (len = utf_mbtowc(&wc, src)) == (size_t)-1 ||
-	    wc == 0)
+	if (!UTFMODE || !*src || (len = utf_mbtowc(&wc, src)) == (size_t)-1)
 		len = width = 1;
 	else if ((width = utf_wcwidth(wc)) < 0)
-		/* XXX use 2 for x_zotc3 here? */
 		width = 1;
 
-	if (dst)
-		*dst = src + len;
+	*dst = src + len;
 	return (width);
 }
 
@@ -745,41 +748,6 @@ utf_mbswidth(const char *s)
 	return (width);
 }
 
-const char *
-utf_skipcols(const char *p, int cols, int *colp)
-{
-	int c = 0;
-	const char *q;
-
-	while (c < cols) {
-		if (!*p) {
-			/* end of input; special handling for edit.c */
-			if (!colp)
-				return (p + cols - c);
-			*colp = c;
-			return (p);
-		}
-		c += utf_widthadj(p, &p);
-	}
-	if (UTFMODE)
-		while (utf_widthadj(p, &q) == 0)
-			p = q;
-	if (colp)
-		*colp = c;
-	return (p);
-}
-
-size_t
-utf_ptradj(const char *src)
-{
-	register size_t n;
-
-	if (!UTFMODE || rtt2asc(*src) < 0xC2 ||
-	    (n = utf_mbtowc(NULL, src)) == (size_t)-1)
-		n = 1;
-	return (n);
-}
-
 /*
  * UTF-8 support code: low-level functions
  */
@@ -850,6 +818,54 @@ utf_wctomb(char *dst, unsigned int wc)
 	return ((char *)d - dst);
 }
 
+/* “give me that character right now” */
+
+#if defined(MKSH_EBCDIC) || defined(MKSH_FAUX_EBCDIC)
+/* as UCS codepoint; dst must not be NULL */
+size_t
+ez_mbtowc(unsigned int *dst, const char *src)
+{
+	size_t n;
+
+	if (UTFMODE) {
+		if ((n = utf_mbtowc(dst, src)) != (size_t)-1)
+			return (n);
+		*dst = OPTUMKRAW(rtt2asc(*src));
+	} else
+		*dst = ord(rtt2asc(*src));
+	return (*src ? 1 : 0);
+}
+/* identical to ez_mbtoc, unless EBCDIC… */
+#endif
+
+/* as kby if !UTFMODE, UCS codepoint or OPTURAW otherwise */
+size_t
+ez_mbtoc(unsigned int *dst, const char *src)
+{
+	size_t n;
+
+	if (UTFMODE) {
+		if ((n = utf_mbtowc(dst, src)) != (size_t)-1)
+			return (n);
+		if (dst)
+			*dst = OPTUMKRAW(rtt2asc(*src));
+	} else if (dst)
+		*dst = ord(*src);
+	return (*src ? 1 : 0);
+}
+
+size_t
+ez_ctomb(char *dst, unsigned int wc)
+{
+	if (!UTFMODE)
+		*dst = (kby)wc;
+	else if (OPTUISRAW(wc))
+		*dst = asc2rtt((kby)wc);
+	else
+		return (utf_wctomb(dst, wc));
+	return (1);
+}
+
 /*
  * Wrapper around access(2) because it says root can execute everything
  * on some operating systems. Does not set errno, no user needs it. Use
@@ -875,7 +891,7 @@ ksh_access(const char *fn, int mode)
 }
 
 #ifndef MIRBSD_BOOTFLOPPY
-/* From: X11/xc/programs/xterm/wcwidth.c,v 1.10 */
+/* From: X11/xc/programs/xterm/wcwidth.c,v 1.17 */
 
 struct mb_ucsrange {
 	unsigned short beg;
@@ -883,17 +899,17 @@ struct mb_ucsrange {
 };
 
 static int mb_ucsbsearch(const struct mb_ucsrange arr[], size_t elems,
-    unsigned int val) MKSH_A_PURE;
+    unsigned int val);
 
 /*
- * Generated from the UCD 13.0.0 - see /usr/share/doc/legal/LICENCE-BSD - by
+ * Generated from the UCD 15.0.0 - see /usr/share/doc/legal/LICENCE-BSD - by
  * MirOS: contrib/code/Snippets/eawparse,v 1.15 2020/06/15 20:31:13 tg Exp $
  */
 
 /*-
- * Parts Copyright © 1991–2020 Unicode, Inc. All rights reserved.
- * Distributed under the Terms of Use in
- *     https://www.unicode.org/copyright.html.
+ * Parts Copyright © 1991–2022 Unicode, Inc. All rights reserved.
+ * Distributed under the Terms of Use in:
+ *	https://www.unicode.org/copyright.html
  *
  * Permission is hereby granted, free of charge, to any person obtaining
  * a copy of the Unicode data files and any associated documentation
@@ -951,7 +967,8 @@ static const struct mb_ucsrange mb_ucs_c
 	{ 0x0825, 0x0827 },
 	{ 0x0829, 0x082D },
 	{ 0x0859, 0x085B },
-	{ 0x08D3, 0x08E1 },
+	{ 0x0898, 0x089F },
+	{ 0x08CA, 0x08E1 },
 	{ 0x08E3, 0x0902 },
 	{ 0x093A, 0x093A },
 	{ 0x093C, 0x093C },
@@ -992,6 +1009,7 @@ static const struct mb_ucsrange mb_ucs_c
 	{ 0x0BCD, 0x0BCD },
 	{ 0x0C00, 0x0C00 },
 	{ 0x0C04, 0x0C04 },
+	{ 0x0C3C, 0x0C3C },
 	{ 0x0C3E, 0x0C40 },
 	{ 0x0C46, 0x0C48 },
 	{ 0x0C4A, 0x0C4D },
@@ -1017,7 +1035,7 @@ static const struct mb_ucsrange mb_ucs_c
 	{ 0x0E47, 0x0E4E },
 	{ 0x0EB1, 0x0EB1 },
 	{ 0x0EB4, 0x0EBC },
-	{ 0x0EC8, 0x0ECD },
+	{ 0x0EC8, 0x0ECE },
 	{ 0x0F18, 0x0F19 },
 	{ 0x0F35, 0x0F35 },
 	{ 0x0F37, 0x0F37 },
@@ -1042,7 +1060,7 @@ static const struct mb_ucsrange mb_ucs_c
 	{ 0x1160, 0x11FF },
 	{ 0x135D, 0x135F },
 	{ 0x1712, 0x1714 },
-	{ 0x1732, 0x1734 },
+	{ 0x1732, 0x1733 },
 	{ 0x1752, 0x1753 },
 	{ 0x1772, 0x1773 },
 	{ 0x17B4, 0x17B5 },
@@ -1050,7 +1068,7 @@ static const struct mb_ucsrange mb_ucs_c
 	{ 0x17C6, 0x17C6 },
 	{ 0x17C9, 0x17D3 },
 	{ 0x17DD, 0x17DD },
-	{ 0x180B, 0x180E },
+	{ 0x180B, 0x180F },
 	{ 0x1885, 0x1886 },
 	{ 0x18A9, 0x18A9 },
 	{ 0x1920, 0x1922 },
@@ -1066,7 +1084,7 @@ static const struct mb_ucsrange mb_ucs_c
 	{ 0x1A65, 0x1A6C },
 	{ 0x1A73, 0x1A7C },
 	{ 0x1A7F, 0x1A7F },
-	{ 0x1AB0, 0x1AC0 },
+	{ 0x1AB0, 0x1ACE },
 	{ 0x1B00, 0x1B03 },
 	{ 0x1B34, 0x1B34 },
 	{ 0x1B36, 0x1B3A },
@@ -1089,8 +1107,7 @@ static const struct mb_ucsrange mb_ucs_c
 	{ 0x1CED, 0x1CED },
 	{ 0x1CF4, 0x1CF4 },
 	{ 0x1CF8, 0x1CF9 },
-	{ 0x1DC0, 0x1DF9 },
-	{ 0x1DFB, 0x1DFF },
+	{ 0x1DC0, 0x1DFF },
 	{ 0x200B, 0x200F },
 	{ 0x202A, 0x202E },
 	{ 0x2060, 0x2064 },
@@ -1220,8 +1237,12 @@ int
 utf_wcwidth(unsigned int wc)
 {
 	/* except NUL, C0/C1 control characters and DEL yield -1 */
-	if (wc < 0x20 || (wc >= 0x7F && wc < 0xA0))
+	if (wc < 0x20)
 		return (wc ? -1 : 0);
+	if (wc < 0x7F)
+		return (1);
+	if (wc < 0xA0)
+		return (-1);
 
 	/* combining characters use 0 screen columns */
 	if (mb_ucsbsearch(mb_ucs_combining, NELEM(mb_ucs_combining), wc))
--- mksh-59c.orig/exprtok.h
+++ mksh-59c/exprtok.h
@@ -1,6 +1,6 @@
 /*-
  * Copyright (c) 2016, 2020
- *	mirabilos <m@mirbsd.org>
+ *	mirabilos <m$(date +%Y)@mirbsd.de>
  *
  * Provided that these terms and disclaimer and all copyright notices
  * are retained or reproduced in an accompanying document, permission
@@ -19,7 +19,7 @@
  */
 
 #if defined(EXPRTOK_DEFNS)
-__RCSID("$MirOS: src/bin/mksh/exprtok.h,v 1.4 2020/04/07 11:56:46 tg Exp $");
+__RCSID("$MirOS: src/bin/mksh/exprtok.h,v 1.5 2025/04/25 23:14:55 tg Exp $");
 /* see range comment below */
 #define IS_ASSIGNOP(op) ((int)(op) >= (int)O_ASN && (int)(op) <= (int)O_BORASN)
 #define FN(name,len,prec,enum)		/* nothing */
--- mksh-59c.orig/funcs.c
+++ mksh-59c/funcs.c
@@ -5,8 +5,8 @@
 /*-
  * Copyright (c) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
  *		 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017,
- *		 2019, 2020
- *	mirabilos <m@mirbsd.org>
+ *		 2019, 2020, 2021, 2022, 2023, 2024, 2025
+ *	mirabilos <m$(date +%Y)@mirbsd.de>
  *
  * Provided that these terms and disclaimer and all copyright notices
  * are retained or reproduced in an accompanying document, permission
@@ -26,19 +26,7 @@
 
 #include "sh.h"
 
-#if HAVE_SELECT
-#if HAVE_SYS_BSDTYPES_H
-#include <sys/bsdtypes.h>
-#endif
-#if HAVE_SYS_SELECT_H
-#include <sys/select.h>
-#endif
-#if HAVE_BSTRING_H
-#include <bstring.h>
-#endif
-#endif
-
-__RCSID("$MirOS: src/bin/mksh/funcs.c,v 1.379 2020/08/27 19:52:44 tg Exp $");
+__RCSID("$MirOS: src/bin/mksh/funcs.c,v 1.422 2025/12/24 04:51:52 tg Exp $");
 
 #if HAVE_KILLPG
 /*
@@ -59,7 +47,8 @@ __RCSID("$MirOS: src/bin/mksh/funcs.c,v
 static int c_suspend(const char **);
 #endif
 
-static int do_whence(const char **, int, bool, bool);
+static int do_whence(const char **, int, Wahr, Wahr);
+static int do_evalcmd(const char **);
 
 /* getn() that prints error */
 static int
@@ -87,7 +76,9 @@ c_false(const char **wp MKSH_A_UNUSED)
 /*
  * A leading = means assignments before command are kept.
  * A leading * means a POSIX special builtin.
- * A leading ^ means declaration utility, - forwarder.
+ * A leading ^ means declaration utility, - declaration forwarder.
+ * A leading ~ means external utilities override this, ! with flags only.
+ * A leading # means is set or shift (for argc/argv bookkeeping).
  */
 const struct builtin mkshbuiltins[] = {
 	{Tsgdot, c_dot},
@@ -98,7 +89,6 @@ const struct builtin mkshbuiltins[] = {
 	{Tsgbreak, c_brkcont},
 	{T__builtin, c_builtin},
 	{Tbuiltin, c_builtin},
-	{Tbcat, c_cat},
 	{Tcd, c_cd},
 	/* dash compatibility hack */
 	{"chdir", c_cd},
@@ -120,7 +110,9 @@ const struct builtin mkshbuiltins[] = {
 	{Tread, c_read},
 	{Tdsgreadonly, c_typeset},
 	{"!realpath", c_realpath},
+#if HAVE_RENAME
 	{"~rename", c_rename},
+#endif
 	{"*=return", c_exitreturn},
 	{Tsghset, c_set},
 	{"*=#shift", c_shift},
@@ -129,6 +121,8 @@ const struct builtin mkshbuiltins[] = {
 	{Tsuspend, c_suspend},
 #endif
 	{"test", c_test},
+	/* normally a syntax element but as_builtin or 'x=y time foo' do: */
+	{Ttime, do_evalcmd},
 	{"*=times", c_times},
 	{"*=trap", c_trap},
 	{Ttrue, c_true},
@@ -152,13 +146,6 @@ const struct builtin mkshbuiltins[] = {
 #ifdef MKSH_PRINTF_BUILTIN
 	{"~printf", c_printf},
 #endif
-#if HAVE_SELECT
-	{"sleep", c_sleep},
-#endif
-#ifdef __MirBSD__
-	/* alias to "true" for historical reasons */
-	{"domainname", c_true},
-#endif
 #ifdef __OS2__
 	{Textproc, c_true},
 #endif
@@ -173,7 +160,7 @@ struct kill_info {
 const struct t_op u_ops[] = {
 /* 0*/	{"-a",	TO_FILAXST },
 	{"-b",	TO_FILBDEV },
-	{"-c",	TO_FILCDEV },
+/* 2*/	{"-c",	TO_FILCDEV },
 	{"-d",	TO_FILID },
 	{"-e",	TO_FILEXST },
 	{"-f",	TO_FILREG },
@@ -186,7 +173,7 @@ const struct t_op u_ops[] = {
 /*12*/	{"-n",	TO_STNZE },
 	{"-O",	TO_FILUID },
 /*14*/	{"-o",	TO_OPTION },
-	{"-p",	TO_FILFIFO },
+/*15*/	{"-p",	TO_FILFIFO },
 /*16*/	{"-r",	TO_FILRD },
 	{"-S",	TO_FILSOCK },
 	{"-s",	TO_FILGZ },
@@ -198,7 +185,9 @@ const struct t_op u_ops[] = {
 	{"-z",	TO_STZER },
 	{"",	TO_NONOP }
 };
-cta(u_ops_size, NELEM(u_ops) == 26);
+mbCTA_BEG(funcs_c);
+	mbCTA(u_ops_size, NELEM(u_ops) == 26);
+mbCTA_END(funcs_c);
 const struct t_op b_ops[] = {
 	{"=",	TO_STEQL },
 	{"==",	TO_STEQL },
@@ -217,31 +206,30 @@ const struct t_op b_ops[] = {
 	{"",	TO_NONOP }
 };
 
-static int test_oexpr(Test_env *, bool);
-static int test_aexpr(Test_env *, bool);
-static int test_nexpr(Test_env *, bool);
-static int test_primary(Test_env *, bool);
+static int test_oexpr(Test_env *, Wahr);
+static int test_aexpr(Test_env *, Wahr);
+static int test_nexpr(Test_env *, Wahr);
+static int test_primary(Test_env *, Wahr);
 static Test_op ptest_isa(Test_env *, Test_meta);
-static const char *ptest_getopnd(Test_env *, Test_op, bool);
+static const char *ptest_getopnd(Test_env *, Test_op, Wahr);
 static void ptest_error(Test_env *, int, const char *);
 static void kill_fmt_entry(char *, size_t, unsigned int, const void *);
-static void p_time(struct shf *, bool, long, int, int,
-    const char *, const char *);
 
 int
 c_pwd(const char **wp)
 {
 	int optc;
-	bool physical = tobool(Flag(FPHYSICAL));
-	char *p, *allocd = NULL;
+	Wahr physical = isWahr(Flag(FPHYSICAL));
+	const char *p;
+	char *allocd = NULL;
 
 	while ((optc = ksh_getopt(wp, &builtin_opt, "LP")) != -1)
 		switch (optc) {
 		case 'L':
-			physical = false;
+			physical = Nee;
 			break;
 		case 'P':
-			physical = true;
+			physical = Ja;
 			break;
 		case '?':
 			return (1);
@@ -257,7 +245,7 @@ c_pwd(const char **wp)
 	/* LINTED use of access */
 	if (p && access(p, R_OK) < 0)
 		p = NULL;
-	if (!p && !(p = allocd = ksh_get_wd())) {
+	if (!p && !(p = ksh_getwd())) {
 		bi_errorf(Tf_sD_s, "can't determine current directory",
 		    cstrerror(errno));
 		return (1);
@@ -285,32 +273,30 @@ c_print(const char **wp)
 		mksh_ari_t wc;
 		/* output file descriptor (if any) */
 		int fd;
-		/* temporary storage for a multibyte character */
-		char ts[4];
 		/* output word separator */
 		char ws;
 		/* output line separator */
 		char ls;
 		/* output a trailing line separator? */
-		bool nl;
+		Wahr nl;
 		/* expand backslash sequences? */
-		bool exp;
+		Wahr exp;
 		/* columnise output? */
-		bool col;
+		Wahr col;
 		/* print to history instead of file descriptor / stdout? */
-		bool hist;
+		Wahr hist;
 		/* print words as wide characters? */
-		bool chars;
+		Wahr chars;
 		/* writing to a coprocess (SIGPIPE blocked)? */
-		bool coproc;
-		bool copipe;
+		Wahr coproc;
+		Wahr copipe;
 	} po;
 
 	memset(&po, 0, sizeof(po));
 	po.fd = 1;
 	po.ws = ' ';
 	po.ls = '\n';
-	po.nl = true;
+	po.nl = Ja;
 
 	if (wp[0][0] == 'e') {
 		/* "echo" builtin */
@@ -323,12 +309,12 @@ c_print(const char **wp)
 			++wp;
  bsd_echo:
 			if (*wp && !strcmp(*wp, Tdn)) {
-				po.nl = false;
+				po.nl = Nee;
 				++wp;
 			}
-			po.exp = false;
+			po.exp = Nee;
 		} else {
-			bool new_exp, new_nl = true;
+			Wahr new_exp, new_nl = Ja;
 
 			/*-
 			 * compromise between various historic echos: only
@@ -338,11 +324,11 @@ c_print(const char **wp)
 #ifdef MKSH_MIDNIGHTBSD01ASH_COMPAT
 			/* MidnightBSD /bin/sh needs -e supported but off */
 			if (Flag(FSH))
-				new_exp = false;
+				new_exp = Nee;
 			else
 #endif
 			/* otherwise compromise on -e enabled by default */
-			  new_exp = true;
+			  new_exp = Ja;
 			goto print_tradparse_beg;
 
  print_tradparse_arg:
@@ -350,13 +336,13 @@ c_print(const char **wp)
  print_tradparse_ch:
 				switch ((c = *s++)) {
 				case 'E':
-					new_exp = false;
+					new_exp = Nee;
 					goto print_tradparse_ch;
 				case 'e':
-					new_exp = true;
+					new_exp = Ja;
 					goto print_tradparse_ch;
 				case 'n':
-					new_nl = false;
+					new_nl = Nee;
 					goto print_tradparse_ch;
 				case '\0':
  print_tradparse_beg:
@@ -372,18 +358,18 @@ c_print(const char **wp)
 		const char *opts = "AcelNnpRrsu,";
 		const char *emsg;
 
-		po.exp = true;
+		po.exp = Ja;
 
 		while ((c = ksh_getopt(wp, &builtin_opt, opts)) != -1)
 			switch (c) {
 			case 'A':
-				po.chars = true;
+				po.chars = Ja;
 				break;
 			case 'c':
-				po.col = true;
+				po.col = Ja;
 				break;
 			case 'e':
-				po.exp = true;
+				po.exp = Ja;
 				break;
 			case 'l':
 				po.ws = '\n';
@@ -393,11 +379,11 @@ c_print(const char **wp)
 				po.ls = '\0';
 				break;
 			case 'n':
-				po.nl = false;
+				po.nl = Nee;
 				break;
 			case 'p':
 				if ((po.fd = coproc_getfd(W_OK, &emsg)) < 0) {
-					bi_errorf(Tf_coproc, emsg);
+					bi_errorf("%s: %s", Tdp, emsg);
 					return (1);
 				}
 				break;
@@ -406,10 +392,10 @@ c_print(const char **wp)
 				wp += builtin_opt.optind;
 				goto bsd_echo;
 			case 'r':
-				po.exp = false;
+				po.exp = Nee;
 				break;
 			case 's':
-				po.hist = true;
+				po.hist = Ja;
 				break;
 			case 'u':
 				if (!*(s = builtin_opt.optarg))
@@ -449,31 +435,24 @@ c_print(const char **wp)
 			s = *wp++;
 			if (*s == '\0')
 				break;
-			if (!evaluate(s, &po.wc, KSH_RETURN_ERROR, true))
+			if (!evaluate(s, &po.wc, KSH_RETURN_ERROR, Ja))
 				return (1);
-			Xcheck(xs, xp);
-			if (UTFMODE) {
-				po.ts[utf_wctomb(po.ts, po.wc)] = 0;
-				c = 0;
-				do {
-					Xput(xs, xp, po.ts[c]);
-				} while (po.ts[++c]);
-			} else
-				Xput(xs, xp, po.wc & 0xFF);
+			XcheckN(xs, xp, 4);
+			xp += ez_ctomb(xp, po.wc);
 		}
 	} else {
 		s = *wp++;
 		while ((c = *s++) != '\0') {
-			Xcheck(xs, xp);
+			XcheckN(xs, xp, 4);
 			if (po.exp && c == '\\') {
 				s_ptr = s;
-				c = unbksl(false, s_get, s_put);
+				c = unbksl(Nee, s_get, s_put);
 				s = s_ptr;
 				if (c == -1) {
 					/* rejected by generic function */
 					switch ((c = *s++)) {
 					case 'c':
-						po.nl = false;
+						po.nl = Nee;
 						/* AT&T brain damage */
 						continue;
 					case '\0':
@@ -485,11 +464,7 @@ c_print(const char **wp)
 					}
 				} else if ((unsigned int)c > 0xFF) {
 					/* generic function returned UCS */
-					po.ts[utf_wctomb(po.ts, c - 0x100)] = 0;
-					c = 0;
-					do {
-						Xput(xs, xp, po.ts[c]);
-					} while (po.ts[++c]);
+					xp += utf_wctomb(xp, c - 0x100);
 					continue;
 				}
 			}
@@ -513,7 +488,7 @@ c_print(const char **wp)
 		XPput(po.words, NULL);
 		co.shf = shf_sopen(NULL, 128, SHF_WR | SHF_DYNAMIC, NULL);
 		co.linesep = po.ls;
-		co.prefcol = co.do_last = false;
+		co.prefcol = co.do_last = Nee;
 		pr_list(&co, (char **)XPptrv(po.words));
 		while (w--)
 			afree(XPptrv(po.words)[w], ATEMP);
@@ -531,7 +506,7 @@ c_print(const char **wp)
 	c = 0;
 	if (po.hist) {
 		Xput(xs, xp, '\0');
-		histsave(&source->line, Xstring(xs, xp), HIST_STORE, false);
+		histsave(&source->line, Xstring(xs, xp), HIST_STORE, Nee);
 	} else {
 		size_t len = Xlength(xs, xp);
 
@@ -542,10 +517,10 @@ c_print(const char **wp)
 		 * not enough).
 		 */
 		if (coproc.write >= 0 && coproc.write == po.fd) {
-			po.coproc = true;
+			po.coproc = Ja;
 			po.copipe = block_pipe();
 		} else
-			po.coproc = po.copipe = false;
+			po.coproc = po.copipe = Nee;
 
 		s = Xstring(xs, xp);
 		while (len > 0) {
@@ -562,6 +537,7 @@ c_print(const char **wp)
 						po.copipe = block_pipe();
 					continue;
 				}
+				bi_errorf(Tf_sD_s, Twrite, cstrerror(errno));
 				c = 1;
 				break;
 			}
@@ -592,15 +568,15 @@ int
 c_whence(const char **wp)
 {
 	int optc;
-	bool pflag = false, vflag = false;
+	Wahr pflag = Nee, vflag = Nee;
 
 	while ((optc = ksh_getopt(wp, &builtin_opt, Tpv)) != -1)
 		switch (optc) {
 		case 'p':
-			pflag = true;
+			pflag = Ja;
 			break;
 		case 'v':
-			vflag = true;
+			vflag = Ja;
 			break;
 		case '?':
 			return (1);
@@ -608,7 +584,7 @@ c_whence(const char **wp)
 	wp += builtin_opt.optind;
 
 	return (do_whence(wp, pflag ? FC_PATH :
-	    FC_BI | FC_FUNC | FC_PATH | FC_WHENCE, vflag, false));
+	    FC_BI | FC_FUNC | FC_PATH | FC_WHENCE, vflag, Nee));
 }
 
 /* note: command without -vV is dealt with in comexec() */
@@ -616,7 +592,7 @@ int
 c_command(const char **wp)
 {
 	int optc, fcflags = FC_BI | FC_FUNC | FC_PATH | FC_WHENCE;
-	bool vflag = false;
+	Wahr vflag = Nee;
 
 	while ((optc = ksh_getopt(wp, &builtin_opt, TpVv)) != -1)
 		switch (optc) {
@@ -624,23 +600,23 @@ c_command(const char **wp)
 			fcflags |= FC_DEFPATH;
 			break;
 		case 'V':
-			vflag = true;
+			vflag = Ja;
 			break;
 		case 'v':
-			vflag = false;
+			vflag = Nee;
 			break;
 		case '?':
 			return (1);
 		}
 	wp += builtin_opt.optind;
 
-	return (do_whence(wp, fcflags, vflag, true));
+	return (do_whence(wp, fcflags, vflag, Ja));
 }
 
 static int
-do_whence(const char **wp, int fcflags, bool vflag, bool iscommand)
+do_whence(const char **wp, int fcflags, Wahr vflag, Wahr iscommand)
 {
-	uint32_t h;
+	k32 h;
 	int rv = 0;
 	struct tbl *tp;
 	const char *id;
@@ -692,9 +668,11 @@ do_whence(const char **wp, int fcflags,
 			break;
 		case CEXEC:
 		case CTALIAS:
+			if (vflag)
+				shf_puts(id, shl_stdout);
 			if (tp->flag & ISSET) {
 				if (vflag) {
-					shprintf("%s is ", id);
+					shf_puts(" is ", shl_stdout);
 					if (tp->type == CTALIAS)
 						shprintf("a tracked %s%s for ",
 						    (tp->flag & EXPORT) ?
@@ -703,10 +681,10 @@ do_whence(const char **wp, int fcflags,
 				}
 				if (!mksh_abspath(tp->val.s)) {
 					const char *xcwd = current_wd[0] ?
-					    current_wd : ".";
+					    current_wd : Tdot;
 					size_t xlen = strlen(xcwd);
 					size_t clen = strlen(tp->val.s) + 1;
-					char *xp = alloc(xlen + 1 + clen, ATEMP);
+					char *xp = alloc1(xlen + 1U, clen, ATEMP);
 
 					memcpy(xp, xcwd, xlen);
 					if (mksh_cdirsep(xp[xlen - 1]))
@@ -720,7 +698,7 @@ do_whence(const char **wp, int fcflags,
 					shf_puts(tp->val.s, shl_stdout);
 			} else {
 				if (vflag)
-					shprintf(Tnot_found_s, id);
+					shf_puts(Tsp_not_found, shl_stdout);
 				rv = 1;
 			}
 			break;
@@ -753,24 +731,24 @@ do_whence(const char **wp, int fcflags,
 	return (rv);
 }
 
-bool
+Wahr
 valid_alias_name(const char *cp)
 {
 	switch (ord(*cp)) {
 	case ORD('+'):
 	case ORD('-'):
-		return (false);
+		return (Nee);
 	case ORD('['):
 		if (ord(cp[1]) == ORD('[') && !cp[2])
-			return (false);
+			return (Nee);
 		break;
 	}
 	while (*cp)
 		if (ctype(*cp, C_ALIAS))
 			++cp;
 		else
-			return (false);
-	return (true);
+			return (Nee);
+	return (Ja);
 }
 
 int
@@ -778,8 +756,8 @@ c_alias(const char **wp)
 {
 	struct table *t = &aliases;
 	int rv = 0, prefix = 0;
-	bool rflag = false, tflag, Uflag = false, pflag = false, chkalias;
-	uint32_t xflag = 0;
+	Wahr rflag = Nee, tflag, Uflag = Nee, pflag = Nee, chkalias;
+	kui xflag = 0;
 	int optc;
 
 	builtin_opt.flags |= GF_PLUSOPT;
@@ -794,10 +772,10 @@ c_alias(const char **wp)
 #endif
 			break;
 		case 'p':
-			pflag = true;
+			pflag = Ja;
 			break;
 		case 'r':
-			rflag = true;
+			rflag = Ja;
 			break;
 		case 't':
 			t = &taliases;
@@ -807,7 +785,7 @@ c_alias(const char **wp)
 			 * kludge for tracked alias initialization
 			 * (don't do a path search, just make an entry)
 			 */
-			Uflag = true;
+			Uflag = Ja;
 			break;
 		case 'x':
 			xflag = EXPORT;
@@ -866,7 +844,7 @@ c_alias(const char **wp)
 		const char *alias = *wp, *val, *newval;
 		char *xalias = NULL;
 		struct tbl *ap;
-		uint32_t h;
+		k32 h;
 
 		if ((val = cstrchr(alias, '='))) {
 			strndupx(xalias, alias, val++ - alias, ATEMP);
@@ -930,12 +908,12 @@ c_unalias(const char **wp)
 	struct table *t = &aliases;
 	struct tbl *ap;
 	int optc, rv = 0;
-	bool all = false;
+	Wahr all = Nee;
 
 	while ((optc = ksh_getopt(wp, &builtin_opt, "adt")) != -1)
 		switch (optc) {
 		case 'a':
-			all = true;
+			all = Ja;
 			break;
 		case 'd':
 #ifdef MKSH_NOPWNAM
@@ -997,7 +975,7 @@ c_let(const char **wp)
 		bi_errorf(Tno_args);
 	else
 		for (wp++; *wp; wp++)
-			if (!evaluate(*wp, &val, KSH_RETURN_ERROR, true)) {
+			if (!evaluate(*wp, &val, KSH_RETURN_ERROR, Ja)) {
 				/* distinguish error from zero result */
 				rv = 2;
 				break;
@@ -1045,7 +1023,7 @@ c_jobs(const char **wp)
 int
 c_fgbg(const char **wp)
 {
-	bool bg = strcmp(*wp, Tbg) == 0;
+	Wahr bg = strcmp(*wp, Tbg) == 0;
 	int rv = 0;
 
 	if (!Flag(FMONITOR)) {
@@ -1083,13 +1061,15 @@ c_kill(const char **wp)
 {
 	Trap *t = NULL;
 	const char *p;
-	bool lflag = false;
+	Wahr lflag = Nee;
 	int i, n, rv, sig;
 
 	/* assume old style options if -digits or -UPPERCASE */
-	if ((p = wp[1]) && *p == '-' && ctype(p[1], C_DIGIT | C_UPPER)) {
-		if (!(t = gettrap(p + 1, false, false))) {
-			bi_errorf(Tbad_sig_s, p + 1);
+	if ((p = wp[1]) && isch(*p, '-') && ctype(p[1], C_DIGIT | C_UPPER)) {
+		++p;
+		if (!(t = gettrap(p, Nee, Nee))) {
+			kwarnf(KWF_BIERR | KWF_TWOMSG | KWF_NOERRNO,
+			    Tbad_sig, p);
 			return (1);
 		}
 		i = (wp[2] && strcmp(wp[2], "--") == 0) ? 3 : 2;
@@ -1099,12 +1079,13 @@ c_kill(const char **wp)
 		while ((optc = ksh_getopt(wp, &builtin_opt, "ls:")) != -1)
 			switch (optc) {
 			case 'l':
-				lflag = true;
+				lflag = Ja;
 				break;
 			case 's':
 				if (!(t = gettrap(builtin_opt.optarg,
-				    true, false))) {
-					bi_errorf(Tbad_sig_s,
+				    Ja, Nee))) {
+					kwarnf(KWF_BIERR | KWF_TWOMSG |
+					    KWF_NOERRNO, Tbad_sig,
 					    builtin_opt.optarg);
 					return (1);
 				}
@@ -1120,7 +1101,7 @@ c_kill(const char **wp)
 		    " { job | pid | pgrp } ...\n"
 		    "\tkill -l [exit_status ...]\n", shl_out);
 #endif
-		bi_errorfz();
+		bi_unwind(1);
 		return (1);
 	}
 
@@ -1142,7 +1123,8 @@ c_kill(const char **wp)
 			n = 1;
 			while (n < ksh_NSIG) {
 				shf_puts(sigtraps[n].name, shl_stdout);
-				shf_putc(++n == ksh_NSIG ? '\n' : ' ',
+				++n;
+				shf_putc(n == ksh_NSIG ? '\n' : ' ',
 				    shl_stdout);
 			}
 		} else {
@@ -1169,7 +1151,7 @@ c_kill(const char **wp)
 
 			co.shf = shl_stdout;
 			co.linesep = '\n';
-			co.prefcol = co.do_last = true;
+			co.prefcol = co.do_last = Ja;
 
 			print_columns(&co, (unsigned int)(ksh_NSIG - 1),
 			    kill_fmt_entry, (void *)&ki,
@@ -1231,13 +1213,14 @@ c_getopts(const char **wp)
 		bi_errorf(Tf_sD_s, Tname, Tno_args);
 		return (1);
 	}
-	if (!*var || *skip_varname(var, true)) {
+	if (not_varname(var, Ja)) {
 		bi_errorf(Tf_sD_s, var, Tnot_ident);
 		return (1);
 	}
 
 	if (e->loc->next == NULL) {
-		internal_warningf(Tf_sD_s, Tgetopts, Tno_args);
+		kwarnf(KWF_INTERNAL | KWF_WARNING | KWF_TWOMSG | KWF_NOERRNO,
+		    Tgetopts, Tno_args);
 		return (1);
 	}
 	/* Which arguments are we parsing... */
@@ -1305,7 +1288,7 @@ c_bind(const char **wp)
 {
 	int optc, rv = 0;
 #ifndef MKSH_SMALL
-	bool macro = false;
+	Wahr macro = Nee;
 #endif
 
 	if (x_bind_check()) {
@@ -1319,7 +1302,7 @@ c_bind(const char **wp)
 			return (x_bind_list());
 #ifndef MKSH_SMALL
 		case 'm':
-			macro = true;
+			macro = Ja;
 			break;
 #endif
 		default:
@@ -1359,9 +1342,9 @@ c_shift(const char **wp)
 
 	if (!arg)
 		n = 1;
-	else if (!evaluate(arg, &val, KSH_RETURN_ERROR, false)) {
+	else if (!evaluate(arg, &val, KSH_RETURN_ERROR, Nee)) {
 		/* error already printed */
-		bi_errorfz();
+		bi_unwind(1);
 		return (1);
 	} else if (!(n = val)) {
 		/* nothing to do */
@@ -1386,13 +1369,13 @@ c_umask(const char **wp)
 {
 	int i, optc;
 	const char *cp;
-	bool symbolic = false;
+	Wahr symbolic = Nee;
 	mode_t old_umask;
 
 	while ((optc = ksh_getopt(wp, &builtin_opt, "S")) != -1)
 		switch (optc) {
 		case 'S':
-			symbolic = true;
+			symbolic = Ja;
 			break;
 		case '?':
 			return (1);
@@ -1521,7 +1504,7 @@ int
 c_dot(const char **wp)
 {
 	const char *file, *cp, **argv;
-	int argc, rv, errcode;
+	int rv, errcode;
 
 	if (ksh_getopt(wp, &builtin_opt, null) == '?')
 		return (1);
@@ -1544,17 +1527,18 @@ c_dot(const char **wp)
 		argv = wp + builtin_opt.optind;
 		/* preserve $0 */
 		argv[0] = e->loc->argv[0];
-		for (argc = 0; argv[argc + 1]; argc++)
-			;
-	} else {
-		argc = 0;
+	} else
 		argv = NULL;
-	}
 	/* SUSv4: OR with a high value never written otherwise */
 	exstat |= 0x4000;
-	if ((rv = include(file, argc, argv, false)) < 0) {
-		/* should not happen */
-		bi_errorf(Tf_sD_s, cp, cstrerror(errno));
+	if ((rv = include(file, argv, Nee)) < 0) {
+		if (__predict_true(rv == -2)) {
+			/* error already printed */
+			bi_unwind(1);
+		} else {
+			/* should not happen */
+			kwarnf(KWF_BIERR | KWF_ONEMSG, cp);
+		}
 		return (1);
 	}
 	if (exstat & 0x4000)
@@ -1590,11 +1574,11 @@ c_read(const char **wp)
 {
 #define is_ifsws(c) (ctype((c), C_IFS) && ctype((c), C_IFSWS))
 	int c, fd = 0, rv = 0;
-	bool savehist = false, intoarray = false, aschars = false;
-	bool rawmode = false, expanding = false;
-	bool lastparmmode = false, lastparmused = false;
+	Wahr savehist = Nee, intoarray = Nee, aschars = Nee;
+	Wahr rawmode = Nee, expanding = Nee;
+	Wahr lastparmmode = Nee, lastparmused = Nee;
 	enum { LINES, BYTES, UPTO, READALL } readmode = LINES;
-	char delim = '\n';
+	kby delim = ORD('\n');
 	size_t bytesleft = 128, bytesread;
 	struct tbl *vp /* FU gcc */ = NULL, *vq = NULL;
 	char *cp, *allocd = NULL, *xp;
@@ -1602,11 +1586,12 @@ c_read(const char **wp)
 	XString xs;
 	size_t xsave = 0;
 	mksh_ttyst tios;
-	bool restore_tios = false;
+	Wahr restore_tios = Nee;
 	/* to catch read -aN2 foo[i] */
-	bool subarray = false;
+	Wahr subarray = Nee;
+	k32 idx = 0;
 #if HAVE_SELECT
-	bool hastimeout = false;
+	Wahr hastimeout = Nee;
 	struct timeval tv, tvlim;
 #define c_read_opts "Aad:N:n:prst:u,"
 #else
@@ -1618,19 +1603,22 @@ c_read(const char **wp)
 #endif
 
 	while ((c = ksh_getopt(wp, &builtin_opt, c_read_opts)) != -1)
-	switch (c) {
-	case 'a':
-		aschars = true;
+	switch (ord(c)) {
+	case ORD('a'):
+		aschars = Ja;
 		/* FALLTHROUGH */
-	case 'A':
-		intoarray = true;
+	case ORD('A'):
+		intoarray = Ja;
 		break;
-	case 'd':
-		delim = builtin_opt.optarg[0];
+	case ORD('d'):
+		delim = ord(builtin_opt.optarg[0]);
 		break;
-	case 'N':
-	case 'n':
-		readmode = c == 'N' ? BYTES : UPTO;
+	case ORD('N'):
+		readmode = BYTES;
+		if (0)
+			/* FALLTHROUGH */
+	case ORD('n'):
+		  readmode = UPTO;
 		if (!bi_getn(builtin_opt.optarg, &c))
 			return (2);
 		if (c == -1) {
@@ -1641,31 +1629,36 @@ c_read(const char **wp)
 		break;
 	case 'p':
 		if ((fd = coproc_getfd(R_OK, &ccp)) < 0) {
-			bi_errorf(Tf_coproc, ccp);
+			kwarnf(KWF_ERR(2) | KWF_PREFIX | KWF_FILELINE |
+			    KWF_BUILTIN | KWF_TWOMSG | KWF_NOERRNO,
+			    Tdp, ccp);
 			return (2);
 		}
 		break;
 	case 'r':
-		rawmode = true;
+		rawmode = Ja;
 		break;
 	case 's':
-		savehist = true;
+		savehist = Ja;
 		break;
 #if HAVE_SELECT
 	case 't':
 		if (parse_usec(builtin_opt.optarg, &tv)) {
-			bi_errorf(Tf_sD_s_qs, Tsynerr, cstrerror(errno),
-			    builtin_opt.optarg);
+			kwarnf(KWF_ERR(2) | KWF_PREFIX | KWF_FILELINE |
+			    KWF_BUILTIN | KWF_THREEMSG,
+			    builtin_opt.optarg, Tsynerr);
 			return (2);
 		}
-		hastimeout = true;
+		hastimeout = Ja;
 		break;
 #endif
 	case 'u':
 		if (!builtin_opt.optarg[0])
 			fd = 0;
 		else if ((fd = check_fd(builtin_opt.optarg, R_OK, &ccp)) < 0) {
-			bi_errorf(Tf_sD_sD_s, Tdu, builtin_opt.optarg, ccp);
+			kwarnf(KWF_ERR(2) | KWF_PREFIX | KWF_FILELINE |
+			    KWF_BUILTIN | KWF_NOERRNO, "-u%s: %s",
+			    builtin_opt.optarg, ccp);
 			return (2);
 		}
 		break;
@@ -1677,13 +1670,14 @@ c_read(const char **wp)
 		*--wp = TREPLY;
 
 	if (intoarray && wp[1] != NULL) {
-		bi_errorf(Ttoo_many_args);
+		kwarnf(KWF_ERR(2) | KWF_PREFIX | KWF_FILELINE |
+		    KWF_BUILTIN | KWF_ONEMSG | KWF_NOERRNO,
+		    Ttoo_many_args);
 		return (2);
 	}
 
 	if ((ccp = cstrchr(*wp, '?')) != NULL) {
-		strdupx(allocd, *wp, ATEMP);
-		allocd[ccp - *wp] = '\0';
+		strndupx(allocd, *wp, ccp - *wp, ATEMP);
 		*wp = allocd;
 		if (isatty(fd)) {
 			/*
@@ -1702,8 +1696,8 @@ c_read(const char **wp)
 	if (readmode == LINES)
 		bytesleft = 1;
 	else if (isatty(fd)) {
-		x_mkraw(fd, &tios, true);
-		restore_tios = true;
+		x_mkraw(fd, &tios, Ja);
+		restore_tios = Ja;
 	}
 
 #if HAVE_SELECT
@@ -1721,12 +1715,12 @@ c_read(const char **wp)
 		FD_ZERO(&fdset);
 		FD_SET((unsigned int)fd, &fdset);
 		mksh_TIME(tv);
-		timersub(&tvlim, &tv, &tv);
-		if (tv.tv_sec < 0) {
+		if (timercmp(&tvlim, &tv, <)) {
 			/* timeout expired globally */
 			rv = 3;
 			goto c_read_out;
 		}
+		timersub(&tvlim, &tv, &tv);
 
 		switch (select(fd + 1, &fdset, NULL, NULL, &tv)) {
 		case 1:
@@ -1737,7 +1731,8 @@ c_read(const char **wp)
 			rv = 3;
 			goto c_read_readdone;
 		default:
-			bi_errorf(Tf_sD_s, Tselect, cstrerror(errno));
+			kwarnf(KWF_ERR(2) | KWF_PREFIX | KWF_FILELINE |
+			    KWF_BUILTIN | KWF_ONEMSG, Tselect);
 			rv = 2;
 			goto c_read_out;
 		}
@@ -1762,7 +1757,8 @@ c_read(const char **wp)
 			/* pretend the read was killed */
 		} else {
 			/* unexpected error */
-			bi_errorf(Tf_s, cstrerror(errno));
+			kwarnf(KWF_ERR(2) | KWF_PREFIX | KWF_FILELINE |
+			    KWF_ONEMSG, Tread);
 		}
 		rv = 2;
 		goto c_read_out;
@@ -1806,13 +1802,13 @@ c_read(const char **wp)
 			rv = 1;
 			goto c_read_readdone;
 		}
-		if ((c = *xp) == '\0' && !aschars && delim != '\0') {
+		if ((c = ord(*xp)) == '\0' && !aschars && delim != '\0') {
 			/* skip any read NULs unless delimiter */
 			break;
 		}
 		if (expanding) {
-			expanding = false;
-			if (c == delim) {
+			expanding = Nee;
+			if (ord(c) == ord(delim)) {
 				if (Flag(FTALKING_I) && isatty(fd)) {
 					/*
 					 * set prompt in case this is
@@ -1826,10 +1822,10 @@ c_read(const char **wp)
 				/* and the delimiter */
 				break;
 			}
-		} else if (c == delim) {
+		} else if (ord(c) == ord(delim)) {
 			goto c_read_readdone;
-		} else if (!rawmode && c == '\\') {
-			expanding = true;
+		} else if (!rawmode && ord(c) == ORD('\\')) {
+			expanding = Ja;
 		}
 		Xcheck(xs, xp);
 		++xp;
@@ -1856,24 +1852,34 @@ c_read(const char **wp)
 	}
 
 	if (savehist)
-		histsave(&source->line, Xstring(xs, xp), HIST_STORE, false);
+		histsave(&source->line, Xstring(xs, xp), HIST_STORE, Nee);
 
 	ccp = cp = Xclose(xs, xp);
-	expanding = false;
+	expanding = Nee;
 	XinitN(xs, 128, ATEMP);
 	if (intoarray) {
+		if (not_varname(*wp, Nee)) {
+ c_read_badvar:
+			kwarnf(KWF_ERR(2) | KWF_PREFIX | KWF_FILELINE |
+			    KWF_BUILTIN | KWF_TWOMSG | KWF_NOERRNO,
+			    *wp, Tnot_ident);
+			goto c_read_spliterr;
+		}
 		vp = global(*wp);
 		subarray = last_lookup_was_array;
 		if (vp->flag & RDONLY) {
  c_read_splitro:
-			bi_errorf(Tf_ro, *wp);
+			kwarnf(KWF_ERR(2) | KWF_PREFIX | KWF_FILELINE |
+			    KWF_BUILTIN | KWF_TWOMSG | KWF_NOERRNO,
+			    *wp, Tread_only);
  c_read_spliterr:
 			rv = 2;
 			afree(cp, ATEMP);
 			goto c_read_out;
 		}
 		/* counter for array index */
-		c = subarray ? arrayindex(vp) : 0;
+		if (subarray)
+			idx = arrayindex(vp);
 		/* exporting an array is currently pointless */
 		unset(vp, subarray ? 0 : 1);
 	}
@@ -1899,23 +1905,28 @@ c_read(const char **wp)
 		goto c_read_gotword;
 	}
 	if (aschars) {
+		bytesleft = ez_mbtoc(NULL, ccp);
+		if (!bytesleft) {
+			/* got a NUL byte */
+			Xput(xs, xp, '2');
+			Xput(xs, xp, '#');
+			Xput(xs, xp, '0');
+			++ccp;
+			--bytesread;
+			goto c_read_gotword;
+		}
 		Xput(xs, xp, '1');
 		Xput(xs, xp, '#');
-		bytesleft = utf_ptradj(ccp);
 		while (bytesleft && bytesread) {
 			*xp++ = *ccp++;
 			--bytesleft;
 			--bytesread;
 		}
-		if (xp[-1] == '\0') {
-			xp[-1] = '0';
-			xp[-3] = '2';
-		}
 		goto c_read_gotword;
 	}
 
 	if (!intoarray && wp[1] == NULL)
-		lastparmmode = true;
+		lastparmmode = Ja;
 
  c_read_splitlast:
 	/* copy until IFS character */
@@ -1924,12 +1935,12 @@ c_read(const char **wp)
 
 		ch = *ccp;
 		if (expanding) {
-			expanding = false;
+			expanding = Nee;
 			goto c_read_splitcopy;
 		} else if (ctype(ch, C_IFS)) {
 			break;
 		} else if (!rawmode && ch == '\\') {
-			expanding = true;
+			expanding = Ja;
 		} else {
  c_read_splitcopy:
 			Xcheck(xs, xp);
@@ -1940,7 +1951,7 @@ c_read(const char **wp)
 	}
 	xsave = Xsavepos(xs, xp);
 	/* copy word delimiter: IFSWS+IFS,IFSWS */
-	expanding = false;
+	expanding = Nee;
 	while (bytesread) {
 		char ch;
 
@@ -1948,7 +1959,7 @@ c_read(const char **wp)
 		if (!ctype(ch, C_IFS))
 			break;
 		if (lastparmmode && !expanding && !rawmode && ch == '\\') {
-			expanding = true;
+			expanding = Ja;
 		} else {
 			Xcheck(xs, xp);
 			Xput(xs, xp, ch);
@@ -1968,7 +1979,7 @@ c_read(const char **wp)
 	}
 	/* if no more parameters, rinse and repeat */
 	if (lastparmmode && bytesread) {
-		lastparmused = true;
+		lastparmused = Ja;
 		goto c_read_splitlast;
 	}
 	/* get rid of the delimiter unless we pack the rest */
@@ -1980,16 +1991,22 @@ c_read(const char **wp)
 		if (subarray) {
 			/* array element passed, accept first read */
 			if (vq) {
-				bi_errorf("nested arrays not yet supported");
+				kwarnf(KWF_ERR(2) | KWF_PREFIX | KWF_FILELINE |
+				    KWF_BUILTIN | KWF_ONEMSG | KWF_NOERRNO,
+				    "nested arrays not yet supported");
 				goto c_read_spliterr;
 			}
 			vq = vp;
-			if (c)
+			if (idx)
 				/* [0] doesn't */
 				vq->flag |= AINDEX;
-		} else
-			vq = arraysearch(vp, c++);
+		} else {
+			vq = arraysearch(vp, idx);
+			idx = mbiMO(k32, K32_FM, idx, +, 1U);
+		}
 	} else {
+		if (not_varname(*wp, Nee))
+			goto c_read_badvar;
 		vq = global(*wp);
 		/* must be checked before exporting */
 		if (vq->flag & RDONLY)
@@ -2000,7 +2017,7 @@ c_read(const char **wp)
 	if (!setstr(vq, Xstring(xs, xp), KSH_RETURN_ERROR))
 		goto c_read_spliterr;
 	if (aschars) {
-		setint_v(vq, vq, false);
+		setint_v(vq, vq, Nee);
 		/* protect from UTFMODE changes */
 		vq->type = 0;
 	}
@@ -2023,13 +2040,19 @@ c_read(const char **wp)
 int
 c_eval(const char **wp)
 {
+	if (ksh_getopt(wp, &builtin_opt, null) == '?')
+		return (1);
+	return (do_evalcmd(wp + builtin_opt.optind));
+}
+
+static int
+do_evalcmd(const char **wp)
+{
 	struct source *s, *saves = source;
 	int rv;
 
-	if (ksh_getopt(wp, &builtin_opt, null) == '?')
-		return (1);
 	s = pushs(SWORDS, ATEMP);
-	s->u.strv = wp + builtin_opt.optind;
+	s->u.strv = wp;
 	s->line = current_lineno;
 
 	/*-
@@ -2075,30 +2098,62 @@ c_eval(const char **wp)
 	return (rv);
 }
 
+static void
+print_trap(Trap *p)
+{
+	shf_puts("trap -- ", shl_stdout);
+	if (p->trap)
+		print_value_quoted(shl_stdout, p->trap);
+	else {
+		Wahr isIGN;
+
+		if (p->signal == ksh_SIGEXIT || p->signal == ksh_SIGERR)
+			isIGN = Nee;
+		else if (!(p->flags & (TF_ORIG_IGN|TF_ORIG_DFL))) {
+			sig_t ohandler;
+
+			if ((ohandler = ksh_sigget(p->signal)) == SIG_ERR &&
+			    errno != EINVAL /* signals 32, 33 on GNU/Linux again */)
+				kwarnf0(KWF_PREFIX, Tsigerr, Tget, p->name);
+			isIGN = isWahr(ohandler == SIG_IGN);
+		} else
+			isIGN = isWahr(p->flags & TF_ORIG_IGN);
+		shf_puts(isIGN ? "-" : "''", shl_stdout);
+	}
+	shprintf(Tf__sN, p->name);
+}
+
 int
 c_trap(const char **wp)
 {
 	Trap *p = sigtraps;
 	int i = ksh_NSIG;
-	const char *s;
+	const char *s = NULL;
+	Wahr dashp = Nee;
+	int optc;
 
-	if (ksh_getopt(wp, &builtin_opt, null) == '?')
-		return (1);
+	while ((optc = ksh_getopt(wp, &builtin_opt, "p")) != -1)
+		switch (optc) {
+		case 'p':
+			dashp = Ja;
+			break;
+		case '?':
+			return (1);
+		}
 	wp += builtin_opt.optind;
 
 	if (*wp == NULL) {
 		do {
-			if (p->trap) {
-				shf_puts("trap -- ", shl_stdout);
-				print_value_quoted(shl_stdout, p->trap);
-				shprintf(Tf__sN, p->name);
-			}
+			if (p->trap || dashp)
+				print_trap(p);
 			++p;
 		} while (i--);
 		return (0);
 	}
 
-	if (getn(*wp, &i)) {
+	if (dashp) {
+		/* print */
+	} else if (getn(*wp, &i)) {
 		/* first argument is a signal number, reset them all */
 		s = NULL;
 	} else {
@@ -2112,10 +2167,13 @@ c_trap(const char **wp)
 	/* set/clear the traps */
 	i = 0;
 	while (*wp)
-		if (!(p = gettrap(*wp++, true, true))) {
-			warningf(true, Tbad_sig_ss, builtin_argv0, wp[-1]);
+		if (!(p = gettrap(*wp++, Ja, Ja))) {
+			kwarnf(KWF_PREFIX | KWF_FILELINE | KWF_BUILTIN |
+			    KWF_TWOMSG | KWF_NOERRNO, Tbad_sig, wp[-1]);
 			i = 1;
-		} else
+		} else if (dashp)
+			print_trap(p);
+		else
 			settrap(p, s);
 	return (i);
 }
@@ -2148,7 +2206,7 @@ c_exitreturn(const char **wp)
 	}
 
 	if (how == LEXIT && !really_exit && j_stopped_running()) {
-		really_exit = true;
+		really_exit = Ja;
 		how = LSHELL;
 	}
 
@@ -2201,7 +2259,8 @@ c_brkcont(const char **wp)
 		 * scripts, but don't generate an error (ie, keep going).
 		 */
 		if ((unsigned int)n == quit) {
-			warningf(true, Tf_cant_s, wp[0], wp[0]);
+			kwarnf0(KWF_PREFIX | KWF_FILELINE | KWF_NOERRNO,
+			    Tf_cant_s, wp[0], wp[0]);
 			return (0);
 		}
 		/*
@@ -2211,7 +2270,8 @@ c_brkcont(const char **wp)
 		 */
 		if (last_ep)
 			last_ep->flags &= ~EF_BRKCONT_PASS;
-		warningf(true, "%s: can only %s %u level(s)",
+		kwarnf0(KWF_PREFIX | KWF_FILELINE | KWF_NOERRNO,
+		    "%s: can only %s %u level(s)",
 		    wp[0], wp[0], (unsigned int)n - quit);
 	}
 
@@ -2226,7 +2286,7 @@ int
 c_set(const char **wp)
 {
 	int argi;
-	bool setargs;
+	Wahr setargs;
 	struct block *l = e->loc;
 
 	if ((l->flags & BF_RESETSPEC)) {
@@ -2245,18 +2305,10 @@ c_set(const char **wp)
 		return (2);
 	/* set $# and $* */
 	if (setargs) {
-		const char **owp;
-
 		wp += argi - 1;
-		owp = wp;
 		/* save $0 */
 		wp[0] = l->argv[0];
-		while (*++wp != NULL)
-			strdupx(*wp, *wp, &l->area);
-		l->argc = wp - owp - 1;
-		l->argv = alloc2(l->argc + 2, sizeof(char *), &l->area);
-		for (wp = l->argv; (*wp++ = *owp++) != NULL; )
-			;
+		l->argv = cpyargv(&l->argc, wp, &l->area);
 	}
 	/*-
 	 * POSIX says set exit status is 0, but old scripts that use
@@ -2280,18 +2332,18 @@ c_unset(const char **wp)
 {
 	const char *id;
 	int optc, rv = 0;
-	bool unset_var = true;
+	Wahr unset_var = Ja;
 
 	while ((optc = ksh_getopt(wp, &builtin_opt, "fv")) != -1)
 		switch (optc) {
 		case 'f':
-			unset_var = false;
+			unset_var = Nee;
 			break;
 		case 'v':
-			unset_var = true;
+			unset_var = Ja;
 			break;
 		case '?':
-			/*XXX not reached due to GF_ERROR */
+			/*XXX not reached due to GF_ERROR in spec_bi */
 			return (2);
 		}
 	wp += builtin_opt.optind;
@@ -2316,7 +2368,8 @@ c_unset(const char **wp)
 			afree(cp, ATEMP);
 
 			if ((vp->flag&RDONLY)) {
-				warningf(true, Tf_ro, vp->name);
+				kwarnf(KWF_PREFIX | KWF_FILELINE | KWF_TWOMSG |
+				    KWF_NOERRNO, vp->name, Tread_only);
 				rv = 1;
 			} else
 				unset(vp, optc);
@@ -2327,54 +2380,68 @@ c_unset(const char **wp)
 }
 
 static void
-p_time(struct shf *shf, bool posix, long tv_sec, int tv_usec, int width,
-    const char *prefix, const char *suffix)
+c_times_i(int what)
 {
-	tv_usec /= 10000;
-	if (posix)
-		shf_fprintf(shf, "%s%*ld.%02d%s", prefix, width,
-		    tv_sec, tv_usec, suffix);
-	else
-		shf_fprintf(shf, "%s%*ldm%02d.%02ds%s", prefix, width,
-		    tv_sec / 60, (int)(tv_sec % 60), tv_usec, suffix);
+	struct rusage usage;
+
+	if (ksh_getrusage(what, &usage))
+		kwarnf(KWF_BIERR | KWF_ONEMSG, "getrusage");
+	shf_fprintf(shl_stdout,
+	    "%ldm%02d.%02ds %ldm%02d.%02ds\n",
+	    (long)(usage.ru_utime.tv_sec / 60),
+	    (int)(usage.ru_utime.tv_sec % 60),
+	    (int)(usage.ru_utime.tv_usec / 10000),
+	    (long)(usage.ru_stime.tv_sec / 60),
+	    (int)(usage.ru_stime.tv_sec % 60),
+	    (int)(usage.ru_stime.tv_usec / 10000));
 }
 
 int
 c_times(const char **wp MKSH_A_UNUSED)
 {
-	struct rusage usage;
+	c_times_i(RUSAGE_SELF);
+	c_times_i(RUSAGE_CHILDREN);
+	return (0);
+}
 
-	getrusage(RUSAGE_SELF, &usage);
-	p_time(shl_stdout, false, usage.ru_utime.tv_sec,
-	    usage.ru_utime.tv_usec, 0, null, T1space);
-	p_time(shl_stdout, false, usage.ru_stime.tv_sec,
-	    usage.ru_stime.tv_usec, 0, null, "\n");
-
-	getrusage(RUSAGE_CHILDREN, &usage);
-	p_time(shl_stdout, false, usage.ru_utime.tv_sec,
-	    usage.ru_utime.tv_usec, 0, null, T1space);
-	p_time(shl_stdout, false, usage.ru_stime.tv_sec,
-	    usage.ru_stime.tv_usec, 0, null, "\n");
+static void
+p_time_psx(struct timeval *tv, const char *prefix)
+{
+	shf_fprintf(shl_out, "%s%ld.%02d\n", prefix,
+	    (long)(tv->tv_sec),
+	    (int)(tv->tv_usec / 10000));
+}
 
-	return (0);
+static void
+p_time_ksh(struct timeval *tv, const char *suffix)
+{
+	shf_fprintf(shl_out, "%5ldm%02d.%02ds%s",
+	    (long)(tv->tv_sec / 60),
+	    (int)(tv->tv_sec % 60),
+	    (int)(tv->tv_usec / 10000), suffix);
 }
 
 /*
  * time pipeline (really a statement, not a built-in command)
  */
 int
-timex(struct op *t, int f, volatile int *xerrok)
+timex(struct op *t, int f, int *xerrok)
 {
-#define TF_NOARGS	BIT(0)
-#define TF_NOREAL	BIT(1)		/* don't report real time */
-#define TF_POSIX	BIT(2)		/* report in POSIX format */
+#define TMX_NOARGS	BIT(0)
+#define TMX_NOREAL	BIT(1)		/* don't report real time */
+#define TMX_POSIX	BIT(2)		/* report in POSIX format */
+#define TMX_FAILED	BIT(3)		/* user syntax error or so */
 	int rv = 0, tf = 0;
 	struct rusage ru0, ru1, cru0, cru1;
 	struct timeval usrtime, systime, tv0, tv1;
 
 	mksh_TIME(tv0);
-	getrusage(RUSAGE_SELF, &ru0);
-	getrusage(RUSAGE_CHILDREN, &cru0);
+	if (ksh_getrusage(RUSAGE_SELF, &ru0) ||
+	    ksh_getrusage(RUSAGE_CHILDREN, &cru0)) {
+		kwarnf(KWF_PREFIX | KWF_FILELINE | KWF_ONEMSG,
+		    Ttime_getrusage);
+		return (125);
+	}
 	if (t->left) {
 		/*
 		 * Two ways of getting cpu usage of a command: just use t0
@@ -2388,16 +2455,22 @@ timex(struct op *t, int f, volatile int
 		timerclear(&j_systime);
 		rv = execute(t->left, f | XTIME, xerrok);
 		if (t->left->type == TCOM)
-			tf |= t->left->str[0];
+			tf |= t->left->op_flag;
+		if (tf & TMX_FAILED)
+			return (rv);
 		mksh_TIME(tv1);
-		getrusage(RUSAGE_SELF, &ru1);
-		getrusage(RUSAGE_CHILDREN, &cru1);
+		if (ksh_getrusage(RUSAGE_SELF, &ru1) ||
+		    ksh_getrusage(RUSAGE_CHILDREN, &cru1)) {
+			kwarnf(KWF_PREFIX | KWF_FILELINE | KWF_ONEMSG,
+			    Ttime_getrusage);
+			return (rv);
+		}
 	} else
-		tf = TF_NOARGS;
+		tf = TMX_NOARGS;
 
-	if (tf & TF_NOARGS) {
+	if (tf & TMX_NOARGS) {
 		/* ksh93 - report shell times (shell+kids) */
-		tf |= TF_NOREAL;
+		tf |= TMX_NOREAL;
 		timeradd(&ru0.ru_utime, &cru0.ru_utime, &usrtime);
 		timeradd(&ru0.ru_stime, &cru0.ru_stime, &systime);
 	} else {
@@ -2407,34 +2480,29 @@ timex(struct op *t, int f, volatile int
 		timeradd(&systime, &j_systime, &systime);
 	}
 
-	if (!(tf & TF_NOREAL)) {
-		timersub(&tv1, &tv0, &tv1);
-		if (tf & TF_POSIX)
-			p_time(shl_out, true, tv1.tv_sec, tv1.tv_usec,
-			    5, Treal_sp1, "\n");
-		else
-			p_time(shl_out, false, tv1.tv_sec, tv1.tv_usec,
-			    5, null, Treal_sp2);
+	if (tf & TMX_POSIX) {
+		if (!(tf & TMX_NOREAL)) {
+			timersub(&tv1, &tv0, &tv1);
+			p_time_psx(&tv1, Treal_sp1);
+		}
+		p_time_psx(&usrtime, Tuser_sp1);
+		p_time_psx(&systime, "sys ");
+	} else {
+		if (!(tf & TMX_NOREAL)) {
+			timersub(&tv1, &tv0, &tv1);
+			p_time_ksh(&tv1, Treal_sp2);
+		}
+		p_time_ksh(&usrtime, Tuser_sp2);
+		p_time_ksh(&systime, " system\n");
 	}
-	if (tf & TF_POSIX)
-		p_time(shl_out, true, usrtime.tv_sec, usrtime.tv_usec,
-		    5, Tuser_sp1, "\n");
-	else
-		p_time(shl_out, false, usrtime.tv_sec, usrtime.tv_usec,
-		    5, null, Tuser_sp2);
-	if (tf & TF_POSIX)
-		p_time(shl_out, true, systime.tv_sec, systime.tv_usec,
-		    5, "sys  ", "\n");
-	else
-		p_time(shl_out, false, systime.tv_sec, systime.tv_usec,
-		    5, null, " system\n");
 	shf_flush(shl_out);
 
 	return (rv);
 }
 
-void
-timex_hook(struct op *t, char **volatile *app)
+/* option parsing for the time statement/builtin */
+int
+time_hook(struct op *t, char ***app)
 {
 	char **wp = *app;
 	int optc, i, j;
@@ -2446,14 +2514,18 @@ timex_hook(struct op *t, char **volatile
 	while ((optc = ksh_getopt((const char **)wp, &opt, ":p")) != -1)
 		switch (optc) {
 		case 'p':
-			t->str[0] |= TF_POSIX;
+			t->op_flag |= TMX_POSIX;
 			break;
 		case '?':
-			errorf(Tf_optfoo, Ttime, Tcolsp,
-			    opt.optarg[0], Tunknown_option);
+			ksh_getopt_opterr(opt.optarg[0], Ttime,
+			    Tunknown_option);
+			t->op_flag |= TMX_FAILED;
+			return (1);
 		case ':':
-			errorf(Tf_optfoo, Ttime, Tcolsp,
-			    opt.optarg[0], Treq_arg);
+			ksh_getopt_opterr(opt.optarg[0], Ttime,
+			    Treq_arg);
+			t->op_flag |= TMX_FAILED;
+			return (1);
 		}
 	/* Copy command words down over options. */
 	if (opt.optind != 0) {
@@ -2463,8 +2535,9 @@ timex_hook(struct op *t, char **volatile
 			;
 	}
 	if (!wp[0])
-		t->str[0] |= TF_NOARGS;
+		t->op_flag |= TMX_NOARGS;
 	*app = wp;
+	return (0);
 }
 
 /* exec with no args - args case is taken care of in comexec() */
@@ -2472,22 +2545,35 @@ int
 c_exec(const char **wp MKSH_A_UNUSED)
 {
 	int i;
+	kui sfd;
+
+	if (e->savedfd == NULL)
+		return (0);
 
 	/* make sure redirects stay in place */
-	if (e->savefd != NULL) {
+
+	/* for ksh, keep file descriptors private (except stdin/out/err)… */
+	if (!Flag(FPOSIX) && !Flag(FSH)) {
 		for (i = 0; i < NUFILE; i++) {
-			if (e->savefd[i] > 0)
-				close(e->savefd[i]);
-			/*
-			 * keep all file descriptors > 2 private for ksh,
-			 * but not for POSIX or legacy/kludge sh
-			 */
-			if (!Flag(FPOSIX) && !Flag(FSH) && i > 2 &&
-			    e->savefd[i])
-				fcntl(i, F_SETFD, FD_CLOEXEC);
+			if (!(sfd = FDSVNUM(e, i)))
+				continue;
+			if (sfd > (kui)FDBASE)
+				close((int)sfd);
+			if (i > 2 && !(e->savedfd[i] & FDICLMASK) &&
+			    fcntl(i, F_SETFD, FD_CLOEXEC) == -1)
+				kwarnf0(KWF_INTERNAL | KWF_WARNING,
+				    Tcloexec_failed, Tset, i);
+		}
+	} else {
+		/* … but not for POSIX or legacy/kludge sh */
+		for (i = 0; i < NUFILE; i++) {
+			sfd = FDSVNUM(e, i);
+			if (sfd > (kui)FDBASE)
+				close((int)sfd);
 		}
-		e->savefd = NULL;
 	}
+
+	e->savedfd = NULL;
 	return (0);
 }
 
@@ -2496,7 +2582,7 @@ int
 c_mknod(const char **wp)
 {
 	int argc, optc, rv = 0;
-	bool ismkfifo = false;
+	Wahr ismkfifo = Nee;
 	const char **argv;
 	void *set = NULL;
 	mode_t mode = 0, oldmode = 0;
@@ -2522,7 +2608,7 @@ c_mknod(const char **wp)
 	for (argc = 0; argv[argc]; argc++)
 		;
 	if (argc == 2 && argv[1][0] == 'p')
-		ismkfifo = true;
+		ismkfifo = Ja;
 	else if (argc != 4 || (argv[1][0] != 'b' && argv[1][0] != 'c'))
 		goto c_mknod_usage;
 
@@ -2541,21 +2627,21 @@ c_mknod(const char **wp)
 
 		majnum = strtoul(argv[2], &c, 0);
 		if ((c == argv[2]) || (*c != '\0')) {
-			bi_errorf(Tf_nonnum, "device", "major", argv[2]);
+			bi_errorf("%s: %s: %s", "major", "non-numeric", argv[2]);
 			goto c_mknod_err;
 		}
 		minnum = strtoul(argv[3], &c, 0);
 		if ((c == argv[3]) || (*c != '\0')) {
-			bi_errorf(Tf_nonnum, "device", "minor", argv[3]);
+			bi_errorf("%s: %s: %s", "minor", "non-numeric", argv[3]);
 			goto c_mknod_err;
 		}
 		dv = makedev(majnum, minnum);
 		if ((unsigned long)(major(dv)) != majnum) {
-			bi_errorf(Tf_toolarge, "device", "major", majnum);
+			bi_errorf(Tf_toolarge, "major", majnum);
 			goto c_mknod_err;
 		}
 		if ((unsigned long)(minor(dv)) != minnum) {
-			bi_errorf(Tf_toolarge, "device", "minor", minnum);
+			bi_errorf(Tf_toolarge, "minor", minnum);
 			goto c_mknod_err;
 		}
 		if (mknod(argv[0], mode, dv))
@@ -2650,7 +2736,7 @@ c_test(const char **wp)
 		}
 		if ((op = ptest_isa(&te, TM_UNOP))) {
  ptest_unary:
-			rv = test_eval(&te, op, *te.pos.wp++, NULL, true);
+			rv = test_eval(&te, op, *te.pos.wp++, NULL, Ja);
  ptest_out:
 			if (te.flags & TEF_ERROR)
 				return (T_ERR_EXIT);
@@ -2665,13 +2751,13 @@ c_test(const char **wp)
 		lhs = *te.pos.wp++;
 		if ((op = ptest_isa(&te, TM_BINOP))) {
 			/* test lhs op rhs */
-			rv = test_eval(&te, op, lhs, *te.pos.wp++, true);
+			rv = test_eval(&te, op, lhs, *te.pos.wp++, Ja);
 			goto ptest_out;
 		}
 		if (ptest_isa(&te, tm = TM_AND) || ptest_isa(&te, tm = TM_OR)) {
 			/* XSI */
-			argc = test_eval(&te, TO_STNZE, lhs, NULL, true);
-			rv = test_eval(&te, TO_STNZE, *te.pos.wp++, NULL, true);
+			argc = test_eval(&te, TO_STNZE, lhs, NULL, Ja);
+			rv = test_eval(&te, TO_STNZE, *te.pos.wp++, NULL, Ja);
 			if (tm == TM_AND)
 				rv = argc && rv;
 			else
@@ -2757,11 +2843,6 @@ test_isop(Test_meta meta, const char *s)
 #define test_lstat(name,buffer)	lstat((name), (buffer))
 #endif
 
-#if HAVE_ST_MTIM
-#undef st_mtimensec
-#define st_mtimensec st_mtim.tv_nsec
-#endif
-
 static int
 mtimecmp(const struct stat *sb1, const struct stat *sb2)
 {
@@ -2769,7 +2850,7 @@ mtimecmp(const struct stat *sb1, const s
 		return (-1);
 	if (sb1->st_mtime > sb2->st_mtime)
 		return (1);
-#if (HAVE_ST_MTIMENSEC || HAVE_ST_MTIM)
+#if HAVE_ST_MTIMENSEC
 	if (sb1->st_mtimensec < sb2->st_mtimensec)
 		return (-1);
 	if (sb1->st_mtimensec > sb2->st_mtimensec)
@@ -2780,7 +2861,7 @@ mtimecmp(const struct stat *sb1, const s
 
 int
 test_eval(Test_env *te, Test_op op, const char *opnd1, const char *opnd2,
-    bool do_eval)
+    Wahr do_eval)
 {
 	int i, s;
 	size_t k;
@@ -2835,7 +2916,7 @@ test_eval(Test_env *te, Test_op op, cons
 
 	/* -v */
 	case TO_ISSET:
-		return ((vp = isglobal(opnd1, false)) && (vp->flag & ISSET));
+		return ((vp = isglobal(opnd1, Nee)) && (vp->flag & ISSET));
 
 	/* -o */
 	case TO_OPTION:
@@ -2972,7 +3053,7 @@ test_eval(Test_env *te, Test_op op, cons
 	/* =, == */
 	case TO_STEQL:
 		if (te->flags & TEF_DBRACKET) {
-			if ((i = gmatchx(opnd1, opnd2, false)))
+			if ((i = gmatchx(opnd1, opnd2, Nee)))
 				record_match(opnd1);
 			return (i);
 		}
@@ -2981,7 +3062,7 @@ test_eval(Test_env *te, Test_op op, cons
 	/* != */
 	case TO_STNEQ:
 		if (te->flags & TEF_DBRACKET) {
-			if ((i = gmatchx(opnd1, opnd2, false)))
+			if ((i = gmatchx(opnd1, opnd2, Nee)))
 				record_match(opnd1);
 			return (!i);
 		}
@@ -3039,8 +3120,8 @@ test_eval(Test_env *te, Test_op op, cons
 	case TO_INTLE:
 	/* -lt */
 	case TO_INTLT:
-		if (!evaluate(opnd1, &v1, KSH_RETURN_ERROR, false) ||
-		    !evaluate(opnd2, &v2, KSH_RETURN_ERROR, false)) {
+		if (!evaluate(opnd1, &v1, KSH_RETURN_ERROR, Nee) ||
+		    !evaluate(opnd2, &v2, KSH_RETURN_ERROR, Nee)) {
 			/* error already printed.. */
 			te->flags |= TEF_ERROR;
 			return (1);
@@ -3082,31 +3163,31 @@ test_parse(Test_env *te)
 }
 
 static int
-test_oexpr(Test_env *te, bool do_eval)
+test_oexpr(Test_env *te, Wahr do_eval)
 {
 	int rv;
 
 	if ((rv = test_aexpr(te, do_eval)))
-		do_eval = false;
+		do_eval = Nee;
 	if (!(te->flags & TEF_ERROR) && (*te->isa)(te, TM_OR))
 		return (test_oexpr(te, do_eval) || rv);
 	return (rv);
 }
 
 static int
-test_aexpr(Test_env *te, bool do_eval)
+test_aexpr(Test_env *te, Wahr do_eval)
 {
 	int rv;
 
 	if (!(rv = test_nexpr(te, do_eval)))
-		do_eval = false;
+		do_eval = Nee;
 	if (!(te->flags & TEF_ERROR) && (*te->isa)(te, TM_AND))
 		return (test_aexpr(te, do_eval) && rv);
 	return (rv);
 }
 
 static int
-test_nexpr(Test_env *te, bool do_eval)
+test_nexpr(Test_env *te, Wahr do_eval)
 {
 	if (!(te->flags & TEF_ERROR) && (*te->isa)(te, TM_NOT))
 		return (!test_nexpr(te, do_eval));
@@ -3114,7 +3195,7 @@ test_nexpr(Test_env *te, bool do_eval)
 }
 
 static int
-test_primary(Test_env *te, bool do_eval)
+test_primary(Test_env *te, Wahr do_eval)
 {
 	const char *opnd1, *opnd2;
 	int rv;
@@ -3204,7 +3285,7 @@ ptest_isa(Test_env *te, Test_meta meta)
 }
 
 static const char *
-ptest_getopnd(Test_env *te, Test_op op, bool do_eval MKSH_A_UNUSED)
+ptest_getopnd(Test_env *te, Test_op op, Wahr do_eval MKSH_A_UNUSED)
 {
 	if (te->pos.wp >= te->wp_end)
 		return (op == TO_FILTT ? "1" : NULL);
@@ -3223,6 +3304,7 @@ ptest_error(Test_env *te, int ofs, const
 		bi_errorf(Tf_s, msg);
 }
 
+#if HAVE_RENAME
 int
 c_rename(const char **wp)
 {
@@ -3246,6 +3328,7 @@ c_rename(const char **wp)
 
 	return (rv);
 }
+#endif
 
 int
 c_realpath(const char **wp)
@@ -3276,167 +3359,6 @@ c_realpath(const char **wp)
 	return (rv);
 }
 
-int
-c_cat(const char **wp)
-{
-	int fd = 0, rv;
-	ssize_t n, w;
-	const char *fn = "<stdin>";
-	char *buf, *cp;
-	bool opipe;
-#define MKSH_CAT_BUFSIZ 4096
-
-	/* parse options: POSIX demands we support "-u" as no-op */
-	while ((rv = ksh_getopt(wp, &builtin_opt, Tu)) != -1) {
-		switch (rv) {
-		case 'u':
-			/* we already operate unbuffered */
-			break;
-		default:
-			bi_errorf(Tsynerr);
-			return (1);
-		}
-	}
-	wp += builtin_opt.optind;
-	rv = 0;
-
-	if ((buf = malloc_osfunc(MKSH_CAT_BUFSIZ)) == NULL) {
-		bi_errorf(Toomem, (size_t)MKSH_CAT_BUFSIZ);
-		return (1);
-	}
-
-	/* catch SIGPIPE */
-	opipe = block_pipe();
-
-	do {
-		if (*wp) {
-			fn = *wp++;
-			if (ksh_isdash(fn))
-				fd = 0;
-			else if ((fd = binopen2(fn, O_RDONLY)) < 0) {
-				bi_errorf(Tf_sD_s, fn, cstrerror(errno));
-				rv = 1;
-				continue;
-			}
-		}
-		while (/* CONSTCOND */ 1) {
-			if ((n = blocking_read(fd, (cp = buf),
-			    MKSH_CAT_BUFSIZ)) == -1) {
-				if (errno == EINTR) {
-					if (opipe)
-						restore_pipe();
-					/* give the user a chance to ^C out */
-					intrcheck();
-					/* interrupted, try again */
-					opipe = block_pipe();
-					continue;
-				}
-				/* an error occurred during reading */
-				bi_errorf(Tf_sD_s, fn, cstrerror(errno));
-				rv = 1;
-				break;
-			} else if (n == 0)
-				/* end of file reached */
-				break;
-			while (n) {
-				if (intrsig)
-					goto has_intrsig;
-				if ((w = write(1, cp, n)) != -1) {
-					n -= w;
-					cp += w;
-					continue;
-				}
-				if (errno == EINTR) {
- has_intrsig:
-					if (opipe)
-						restore_pipe();
-					/* give the user a chance to ^C out */
-					intrcheck();
-					/* interrupted, try again */
-					opipe = block_pipe();
-					continue;
-				}
-				if (errno == EPIPE) {
-					/* fake receiving signal */
-					rv = ksh_sigmask(SIGPIPE);
-				} else {
-					/* an error occurred during writing */
-					bi_errorf(Tf_sD_s, "<stdout>",
-					    cstrerror(errno));
-					rv = 1;
-				}
-				if (fd != 0)
-					close(fd);
-				goto out;
-			}
-		}
-		if (fd != 0)
-			close(fd);
-	} while (*wp);
-
- out:
-	if (opipe)
-		restore_pipe();
-	free_osfunc(buf);
-	return (rv);
-}
-
-#if HAVE_SELECT
-int
-c_sleep(const char **wp)
-{
-	struct timeval tv;
-	int rv = 1;
-
-	/* skip argv[0] */
-	++wp;
-	if (wp[0] && !strcmp(wp[0], "--"))
-		/* skip "--" (options separator) */
-		++wp;
-
-	if (!wp[0] || wp[1])
-		bi_errorf(Tsynerr);
-	else if (parse_usec(wp[0], &tv))
-		bi_errorf(Tf_sD_s_qs, Tsynerr, cstrerror(errno), wp[0]);
-	else {
-#ifndef MKSH_NOPROSPECTOFWORK
-		sigset_t omask, bmask;
-
-		/* block a number of signals from interrupting us, though */
-		(void)sigemptyset(&bmask);
-		(void)sigaddset(&bmask, SIGPIPE);
-		(void)sigaddset(&bmask, SIGCHLD);
-#ifdef SIGWINCH
-		(void)sigaddset(&bmask, SIGWINCH);
-#endif
-#ifdef SIGINFO
-		(void)sigaddset(&bmask, SIGINFO);
-#endif
-#ifdef SIGUSR1
-		(void)sigaddset(&bmask, SIGUSR1);
-#endif
-#ifdef SIGUSR2
-		(void)sigaddset(&bmask, SIGUSR2);
-#endif
-		sigprocmask(SIG_BLOCK, &bmask, &omask);
-#endif
-		if (select(1, NULL, NULL, NULL, &tv) == 0 || errno == EINTR)
-			/*
-			 * strictly speaking only for SIGALRM, but the
-			 * execution may be interrupted by other signals
-			 */
-			rv = 0;
-		else
-			bi_errorf(Tf_sD_s, Tselect, cstrerror(errno));
-#ifndef MKSH_NOPROSPECTOFWORK
-		/* this will re-schedule signal delivery */
-		sigprocmask(SIG_SETMASK, &omask, NULL);
-#endif
-	}
-	return (rv);
-}
-#endif
-
 #if !defined(MKSH_UNEMPLOYED) && HAVE_GETSID
 static int
 c_suspend(const char **wp)
--- mksh-59c.orig/histrap.c
+++ mksh-59c/histrap.c
@@ -3,8 +3,9 @@
 
 /*-
  * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
- *		 2011, 2012, 2014, 2015, 2016, 2017, 2018, 2019
- *	mirabilos <m@mirbsd.org>
+ *		 2011, 2012, 2014, 2015, 2016, 2017, 2018, 2019,
+ *		 2021, 2022, 2023, 2025
+ *	mirabilos <m$(date +%Y)@mirbsd.de>
  *
  * Provided that these terms and disclaimer and all copyright notices
  * are retained or reproduced in an accompanying document, permission
@@ -23,14 +24,11 @@
  */
 
 #include "sh.h"
-#if HAVE_SYS_FILE_H
-#include <sys/file.h>
-#endif
+#include "mirhash.h"
 
-__RCSID("$MirOS: src/bin/mksh/histrap.c,v 1.170 2020/10/01 22:53:20 tg Exp $");
+__RCSID("$MirOS: src/bin/mksh/histrap.c,v 1.192 2025/05/22 17:07:46 tg Exp $");
 
 Trap sigtraps[ksh_NSIG + 1];
-static struct sigaction Sigact_ign;
 
 #if HAVE_PERSISTENT_HISTORY
 static int histload(Source *, unsigned char *, size_t);
@@ -39,10 +37,10 @@ static void writehistfile(int, const cha
 #endif
 
 static int hist_execute(char *, Area *);
-static char **hist_get(const char *, bool, bool);
+static char **hist_get(const char *, Wahr, Wahr);
 static char **hist_get_oldest(void);
 
-static bool hstarted;		/* set after hist_init() called */
+static Wahr hstarted;		/* set after hist_init() called */
 static Source *hist_source;
 
 #if HAVE_PERSISTENT_HISTORY
@@ -86,8 +84,7 @@ c_fc(const char **wp)
 {
 	struct shf *shf;
 	struct temp *tf;
-	bool gflag = false, lflag = false, nflag = false, rflag = false,
-	    sflag = false;
+	Wahr gflag = Nee, lflag = Nee, nflag = Nee, rflag = Nee, sflag = Nee;
 	int optc;
 	const char *p, *first = NULL, *last = NULL;
 	char **hfirst, **hlast, **hp, *editor = NULL;
@@ -104,37 +101,37 @@ c_fc(const char **wp)
 		case 'e':
 			p = builtin_opt.optarg;
 			if (ksh_isdash(p))
-				sflag = true;
+				sflag = Ja;
 			else {
 				size_t len = strlen(p);
 
 				/* almost certainly not overflowing */
-				editor = alloc(len + 4, ATEMP);
+				editor = alloc(len + 6U, ATEMP);
 				memcpy(editor, p, len);
-				memcpy(editor + len, Tspdollaru, 4);
+				memcpy(editor + len, Tspdollaru, 6U);
 			}
 			break;
 
 		/* non-AT&T ksh */
 		case 'g':
-			gflag = true;
+			gflag = Ja;
 			break;
 
 		case 'l':
-			lflag = true;
+			lflag = Ja;
 			break;
 
 		case 'n':
-			nflag = true;
+			nflag = Ja;
 			break;
 
 		case 'r':
-			rflag = true;
+			rflag = Ja;
 			break;
 
 		/* POSIX version of -e - */
 		case 's':
-			sflag = true;
+			sflag = Ja;
 			break;
 
 		/* kludge city - accept -num as -- -num (kind of) */
@@ -181,8 +178,7 @@ c_fc(const char **wp)
 			return (1);
 		}
 
-		hp = first ? hist_get(first, false, false) :
-		    hist_get_newest(false);
+		hp = first ? hist_get(first, Nee, Nee) : hist_get_newest(Nee);
 		if (!hp)
 			return (1);
 		/* hist_replace */
@@ -193,14 +189,14 @@ c_fc(const char **wp)
 			size_t len, pat_len, rep_len;
 			XString xs;
 			char *xp;
-			bool any_subst = false;
+			Wahr any_subst = Nee;
 
 			pat_len = strlen(pat);
 			rep_len = strlen(rep);
 			Xinit(xs, xp, 128, ATEMP);
-			for (s = *hp; (s1 = strstr(s, pat)) &&
+			for (s = *hp; (s1 = ucstrstr(s, pat)) &&
 			    (!any_subst || gflag); s = s1 + pat_len) {
-				any_subst = true;
+				any_subst = Ja;
 				len = s1 - s;
 				XcheckN(xs, xp, len + rep_len);
 				/*; first part */
@@ -237,23 +233,22 @@ c_fc(const char **wp)
 		return (1);
 	}
 	if (!first) {
-		hfirst = lflag ? hist_get("-16", true, true) :
-		    hist_get_newest(false);
+		hfirst = lflag ? hist_get("-16", Ja, Ja) : hist_get_newest(Nee);
 		if (!hfirst)
 			return (1);
 		/* can't fail if hfirst didn't fail */
-		hlast = hist_get_newest(false);
+		hlast = hist_get_newest(Nee);
 	} else {
 		/*
 		 * POSIX says not an error if first/last out of bounds
 		 * when range is specified; AT&T ksh and pdksh allow out
 		 * of bounds for -l as well.
 		 */
-		hfirst = hist_get(first, tobool(lflag || last), lflag);
+		hfirst = hist_get(first, isWahr(lflag || last), lflag);
 		if (!hfirst)
 			return (1);
-		hlast = last ? hist_get(last, true, lflag) :
-		    (lflag ? hist_get_newest(false) : hfirst);
+		hlast = last ? hist_get(last, Ja, lflag) :
+		    (lflag ? hist_get_newest(Nee) : hfirst);
 		if (!hlast)
 			return (1);
 	}
@@ -278,7 +273,7 @@ c_fc(const char **wp)
 			shf_putc('\t', shl_stdout);
 			/* print multi-line commands correctly */
 			s = *hp;
-			while ((t = strchr(s, '\n'))) {
+			while ((t = ucstrchr(s, '\n'))) {
 				*t = '\0';
 				shf_fprintf(shl_stdout, "%s\n\t", s);
 				*t++ = '\n';
@@ -294,19 +289,19 @@ c_fc(const char **wp)
 
 	tf = maketemp(ATEMP, TT_HIST_EDIT, &e->temps);
 	if (!(shf = tf->shf)) {
-		bi_errorf(Tf_temp, Tcreate, tf->tffn, cstrerror(errno));
+		kwarnf0(KWF_BIERR, Tf_temp, Tcreate, tf->tffn);
 		return (1);
 	}
 	for (hp = rflag ? hlast : hfirst;
 	    hp >= hfirst && hp <= hlast; hp += rflag ? -1 : 1)
 		shf_fprintf(shf, Tf_sN, *hp);
 	if (shf_close(shf) == -1) {
-		bi_errorf(Tf_temp, Twrite, tf->tffn, cstrerror(errno));
+		kwarnf0(KWF_BIERR, Tf_temp, Twrite, tf->tffn);
 		return (1);
 	}
 
 	/* Ignore setstr errors here (arbitrary) */
-	setstr(local("_", false), tf->tffn, KSH_RETURN_ERROR);
+	setstr(local("_", Nee), tf->tffn, KSH_RETURN_ERROR);
 
 	if ((optc = command(editor ? editor : TFCEDIT_dollaru, 0)))
 		return (optc);
@@ -318,15 +313,15 @@ c_fc(const char **wp)
 		ssize_t n;
 
 		if (!(shf = shf_open(tf->tffn, O_RDONLY, 0, 0))) {
-			bi_errorf(Tf_temp, Topen, tf->tffn, cstrerror(errno));
+			kwarnf0(KWF_BIERR, Tf_temp, Topen, tf->tffn);
 			return (1);
 		}
 
 		if (stat(tf->tffn, &statb) < 0)
 			n = 128;
 		else if ((off_t)statb.st_size > MKSH_MAXHISTFSIZE) {
-			bi_errorf(Tf_toolarge, Thistory,
-			    Tfile, (unsigned long)statb.st_size);
+			bi_errorf(Tf_toolarge, Tfile,
+			    (unsigned long)statb.st_size);
 			goto errout;
 		} else
 			n = (size_t)statb.st_size + 1;
@@ -337,8 +332,8 @@ c_fc(const char **wp)
 				XcheckN(xs, xp, Xlength(xs, xp));
 		}
 		if (n < 0) {
-			bi_errorf(Tf_temp, Tread, tf->tffn,
-			    cstrerror(shf_errno(shf)));
+			kwarnf1(KWF_VERRNO | KWF_BIERR, shf_errno(shf),
+			    Tf_temp, Tread, tf->tffn);
  errout:
 			shf_close(shf);
 			return (1);
@@ -364,7 +359,7 @@ hist_execute(char *cmd, Area *areap)
 		last_line = hist_source->line;
 	}
 
-	histsave(&hist_source->line, cmd, HIST_STORE, true);
+	histsave(&hist_source->line, cmd, HIST_STORE, Ja);
 	/* now *histptr == cmd without all trailing newlines */
 	afree(cmd, areap);
 	cmd = *histptr;
@@ -386,7 +381,7 @@ hist_execute(char *cmd, Area *areap)
  * pattern is a number or string
  */
 static char **
-hist_get(const char *str, bool approx, bool allow_cur)
+hist_get(const char *str, Wahr approx, Wahr allow_cur)
 {
 	char **hp = NULL;
 	int n;
@@ -412,11 +407,10 @@ hist_get(const char *str, bool approx, b
 			hp = NULL;
 		}
 	} else {
-		bool anchored = *str == '?' ? (++str, false) : true;
+		Wahr anchd = *str == '?' ? (++str, Nee) : Ja;
 
 		/* the -1 is to avoid the current fc command */
-		if ((n = findhist(histptr - history - 1, str, false,
-		    anchored)) < 0)
+		if ((n = findhist(histptr - history - 1, str, Nee, anchd)) < 0)
 			bi_errorf(Tf_sD_s, str, Tnot_in_history);
 		else
 			hp = &history[n];
@@ -426,7 +420,7 @@ hist_get(const char *str, bool approx, b
 
 /* Return a pointer to the newest command in the history */
 char **
-hist_get_newest(bool allow_cur)
+hist_get_newest(Wahr allow_cur)
 {
 	if (histptr < history || (!allow_cur && histptr == history)) {
 		bi_errorf("no history (yet)");
@@ -480,7 +474,7 @@ histnum(int n)
  * direction.
  */
 int
-findhist(int start, const char *str, bool fwd, bool anchored)
+findhist(int start, const char *str, Wahr fwd, Wahr anchored)
 {
 	char **hp;
 	int maxhist = histptr - history;
@@ -493,7 +487,7 @@ findhist(int start, const char *str, boo
 	hp = &history[start];
 	for (; hp >= history && hp <= histptr; hp += incr)
 		if ((anchored && strncmp(*hp, str, len) == 0) ||
-		    (!anchored && strstr(*hp, str)))
+		    (!anchored && vstrstr(*hp, str)))
 			return (hp - history);
 
 	return (-1);
@@ -532,7 +526,7 @@ void
 sethistfile(const char *name)
 {
 	/* if not started then nothing to do */
-	if (hstarted == false)
+	if (!hstarted)
 		return;
 
 	/* if the name is the same as the name we have */
@@ -544,13 +538,13 @@ sethistfile(const char *name)
 	 */
 	if (histfd != -1) {
 		/* yes the file is open */
-		(void)close(histfd);
+		close(histfd);
 		histfd = -1;
 		histfsize = 0;
 		afree(hname, APERM);
 		hname = NULL;
 		/* let's reset the history */
-		histsave(NULL, NULL, HIST_DISCARD, true);
+		histsave(NULL, NULL, HIST_DISCARD, Ja);
 		histptr = history - 1;
 		hist_source->line = 0;
 	}
@@ -573,17 +567,16 @@ init_histvec(void)
 	}
 }
 
-
 /*
  * It turns out that there is a lot of ghastly hackery here
  */
 
 #if !defined(MKSH_SMALL) && HAVE_PERSISTENT_HISTORY
 /* do not save command in history but possibly sync */
-bool
+Wahr
 histsync(void)
 {
-	bool changed = false;
+	Wahr changed = Nee;
 
 	/* called by histsave(), may not HIST_DISCARD, caller should flush */
 
@@ -595,7 +588,7 @@ histsync(void)
 		hist_source->line--;
 
 		if (lno != hist_source->line)
-			changed = true;
+			changed = Ja;
 	}
 
 	return (changed);
@@ -606,7 +599,7 @@ histsync(void)
  * save command in history
  */
 void
-histsave(int *lnp, const char *cmd, int svmode, bool ignoredups)
+histsave(int *lnp, const char *cmd, int svmode, Wahr ignoredups)
 {
 	static char *enqueued = NULL;
 	char **hp, *c;
@@ -625,7 +618,7 @@ histsave(int *lnp, const char *cmd, int
 		c = enqueued;
 		enqueued = NULL;
 		--*lnp;
-		histsave(lnp, c, HIST_STORE, true);
+		histsave(lnp, c, HIST_STORE, Ja);
 		afree(c, APERM);
 	}
 
@@ -669,7 +662,7 @@ histsave(int *lnp, const char *cmd, int
 
 		nenq = strlen(enqueued);
 		ncmd = strlen(c);
-		enqueued = aresize(enqueued, nenq + 1 + ncmd + 1, APERM);
+		enqueued = aresize1(enqueued, nenq + 1, ncmd + 1, APERM);
 		enqueued[nenq] = '\n';
 		memcpy(enqueued + nenq + 1, c, ncmd + 1);
 		afree(c, APERM);
@@ -788,8 +781,10 @@ hist_persist_init(void)
 	/* we have a file and are interactive */
 	if ((fd = binopen3(hname, O_RDWR | O_CREAT | O_APPEND, 0600)) < 0)
 		return;
-	if ((histfd = savefd(fd)) < 0)
+	if ((histfd = savefd(fd)) < 0) {
+		close(fd);
 		return;
+	}
 	if (histfd != fd)
 		close(fd);
 
@@ -827,7 +822,7 @@ hist_persist_init(void)
 				goto hist_trunc_dont;
 			}
 			if (fstat(histfd, &sb) >= 0 &&
-			    chown(nhname, sb.st_uid, sb.st_gid)) {
+			    fchown(fd, sb.st_uid, sb.st_gid)) {
 				/* abort the truncation then, meh. */
 				goto hist_trunc_abort;
 			}
@@ -870,7 +865,7 @@ hist_persist_init(void)
 			goto retry;
 		}
 		if (hs != hist_init_retry)
-			bi_errorf(Tf_cant_ss_s,
+			bi_errorf("can't %s %s: %s",
 			    "unlink HISTFILE", hname, cstrerror(errno));
 		histfsize = 0;
 		return;
@@ -892,12 +887,12 @@ hist_persist_init(void)
 void
 hist_init(Source *s)
 {
-	histsave(NULL, NULL, HIST_DISCARD, true);
+	histsave(NULL, NULL, HIST_DISCARD, Ja);
 
 	if (Flag(FTALKING) == 0)
 		return;
 
-	hstarted = true;
+	hstarted = Ja;
 	hist_source = s;
 
 #if HAVE_PERSISTENT_HISTORY
@@ -941,7 +936,7 @@ histload(Source *s, unsigned char *base,
 		}
 	} else {
 		s->line = lno--;
-		histsave(&lno, (char *)(base + 4), HIST_NOTE, false);
+		histsave(&lno, (char *)(base + 4), HIST_NOTE, Nee);
 	}
 	/* advance base pointer past NUL */
 	bytes -= ++cp - base;
@@ -1028,14 +1023,15 @@ hist_finish(void)
 {
 	if (histfd >= 0) {
 		mksh_unlkfd(histfd);
-		(void)close(histfd);
+		close(histfd);
 	}
 	histfd = -1;
 }
 #endif
 
+/* +++ signals +++ */
 
-#if !HAVE_SYS_SIGNAME
+#if !HAVE_SIGABBREV_NP && !HAVE_SYS_SIGNAME
 static const struct mksh_sigpair {
 	const char * const name;
 	int nr;
@@ -1045,18 +1041,12 @@ static const struct mksh_sigpair {
 };
 #endif
 
-#if HAVE_SYS_SIGLIST
-#if !HAVE_SYS_SIGLIST_DECL
-extern const char * const sys_siglist[];
-#endif
-#endif
-
 void
 inittraps(void)
 {
 	int i;
 	const char *cs;
-#if !HAVE_SYS_SIGNAME
+#if !HAVE_SIGABBREV_NP && !HAVE_SYS_SIGNAME
 	const struct mksh_sigpair *pair;
 #endif
 
@@ -1065,7 +1055,9 @@ inittraps(void)
 	/* populate sigtraps based on sys_signame and sys_siglist */
 	for (i = 1; i < ksh_NSIG; i++) {
 		sigtraps[i].signal = i;
-#if HAVE_SYS_SIGNAME
+#if HAVE_SIGABBREV_NP
+		cs = sigabbrev_np(i);
+#elif HAVE_SYS_SIGNAME
 		cs = sys_signame[i];
 #else
 		pair = mksh_sigpairs;
@@ -1080,9 +1072,9 @@ inittraps(void)
 			char *s;
 
 			/* this is not optimal, what about SIGSIG1? */
-			if (ksh_eq(cs[0], 'S', 's') &&
-			    ksh_eq(cs[1], 'I', 'i') &&
-			    ksh_eq(cs[2], 'G', 'g') &&
+			if (isCh(cs[0], 'S', 's') &&
+			    isCh(cs[1], 'I', 'i') &&
+			    isCh(cs[2], 'G', 'g') &&
 			    cs[3] != '\0') {
 				/* skip leading "SIG" */
 				cs += 3;
@@ -1095,23 +1087,16 @@ inittraps(void)
 			if (!strcmp(sigtraps[i].name, "EXIT") ||
 			    !strcmp(sigtraps[i].name, "ERR")) {
 #ifndef MKSH_SMALL
-				internal_warningf(Tinvname, sigtraps[i].name,
-				    "signal");
+				kwarnf0(KWF_INTERNAL | KWF_WARNING | KWF_NOERRNO,
+				    Tinvname, sigtraps[i].name, "signal");
 #endif
 				sigtraps[i].name = null;
 			}
 		}
 		if (sigtraps[i].name == null)
 			sigtraps[i].name = shf_smprintf(Tf_d, i);
-#if HAVE_SYS_SIGLIST
-		sigtraps[i].mess = sys_siglist[i];
-#elif HAVE_STRSIGNAL
-		sigtraps[i].mess = strsignal(i);
-#else
-		sigtraps[i].mess = NULL;
-#endif
-		if ((sigtraps[i].mess == NULL) ||
-		    (sigtraps[i].mess[0] == '\0'))
+		sigtraps[i].mess = ksh_sigmess(i);
+		if (ksh_sigmessf(sigtraps[i].mess))
 			sigtraps[i].mess = shf_smprintf(Tf_sd,
 			    "Signal", i);
 	}
@@ -1122,10 +1107,6 @@ inittraps(void)
 	sigtraps[ksh_SIGERR].name = "ERR";
 	sigtraps[ksh_SIGERR].mess = "Error handler";
 
-	(void)sigemptyset(&Sigact_ign.sa_mask);
-	Sigact_ign.sa_flags = 0; /* interruptible */
-	Sigact_ign.sa_handler = SIG_IGN;
-
 	sigtraps[SIGINT].flags |= TF_DFL_INTR | TF_TTY_INTR;
 	sigtraps[SIGQUIT].flags |= TF_DFL_INTR | TF_TTY_INTR;
 	/* SIGTERM is not fatal for interactive */
@@ -1168,7 +1149,7 @@ alarm_catcher(int sig MKSH_A_UNUSED)
 }
 
 Trap *
-gettrap(const char *cs, bool igncase, bool allsigs)
+gettrap(const char *cs, Wahr igncase, Wahr allsigs)
 {
 	int i;
 	Trap *p;
@@ -1183,9 +1164,9 @@ gettrap(const char *cs, bool igncase, bo
 	/* do a lookup by name then */
 
 	/* this breaks SIGSIG1, but we do that above anyway */
-	if (ksh_eq(cs[0], 'S', 's') &&
-	    ksh_eq(cs[1], 'I', 'i') &&
-	    ksh_eq(cs[2], 'G', 'g') &&
+	if (isCh(cs[0], 'S', 's') &&
+	    isCh(cs[1], 'I', 'i') &&
+	    isCh(cs[2], 'G', 'g') &&
 	    cs[3] != '\0') {
 		/* skip leading "SIG" */
 		cs += 3;
@@ -1222,15 +1203,48 @@ gettrap(const char *cs, bool igncase, bo
 	return (p);
 }
 
+static k32
+traphash(int signo, int extra)
+{
+	register k32 h;
+	static volatile k32 state;
+	k32 o;
+	struct {
+		struct timeval tv;
+		void *sp;
+		int i;
+		int j;
+	} z;
+
+	memset(&z, 0, sizeof(z));
+	mksh_TIME(z.tv);
+	z.sp = &z;
+	z.i = signo;
+	z.j = extra;
+
+	o = state;
+	h = o ? o : (k32)1U;
+	BAFHUpdateMem(h, &z, sizeof(z));
+	while (state != o) {
+		o = state;
+		BAFHUpdateMem(h, &o, sizeof(o));
+	}
+	state = h;
+	return (h);
+}
+
 /*
  * trap signal handler
  */
 void
 trapsig(int i)
 {
-	Trap *p = &sigtraps[i];
-	int eno = errno;
+	Trap *p;
+	int eno;
 
+	eno = errno;
+	traphash(i, eno);
+	p = &sigtraps[i];
 	trap = p->set = 1;
 	if (p->flags & TF_DFL_INTR)
 		intrsig = 1;
@@ -1303,10 +1317,15 @@ runtraps(int flag)
 {
 	Trap *p = sigtraps;
 	int i = ksh_NSIG + 1;
+	k32 h;
+
+	h = traphash(-666, (int)ksh_tmout_state);
+	rndpush(&h, sizeof(h));
 
 	if (ksh_tmout_state == TMOUT_LEAVING) {
 		ksh_tmout_state = TMOUT_EXECUTING;
-		warningf(false, "timed out waiting for input");
+		kwarnf(KWF_PREFIX | KWF_ONEMSG | KWF_NOERRNO,
+		    "timed out waiting for input");
 		unwind(LEXIT);
 	} else
 		/*
@@ -1324,15 +1343,15 @@ runtraps(int flag)
 	do {
 		if (p->set && (!flag ||
 		    ((p->flags & flag) && p->trap == NULL)))
-			runtrap(p, false);
+			runtrap(p, Nee);
 		++p;
 	} while (--i);
 	if (!--trap_nested)
-		runtrap(NULL, true);
+		runtrap(NULL, Ja);
 }
 
 void
-runtrap(Trap *p, bool is_last)
+runtrap(Trap *p, Wahr is_last)
 {
 	int old_changed = 0, i;
 	char *trapstr;
@@ -1418,6 +1437,7 @@ restoresigs(void)
 	int i = ksh_NSIG + 1;
 
 	do {
+		p->touched = 0;
 		if (p->flags & (TF_EXEC_IGN|TF_EXEC_DFL))
 			setsig(p, (p->flags & TF_EXEC_IGN) ? SIG_IGN : SIG_DFL,
 			    SS_RESTORE_CURR|SS_FORCE);
@@ -1425,6 +1445,40 @@ restoresigs(void)
 	} while (--i);
 }
 
+/* un-restore signals after a failed exec(2) for interactive shells */
+void
+unrestoresigs(void)
+{
+	Trap *p = sigtraps;
+	int i = ksh_NSIG + 1;
+
+	do {
+#if defined(ESTALE)
+		errno = ESTALE;
+#elif defined(EDEADLK)
+		errno = EDEADLK;
+#else
+		errno = 0;
+#endif
+		switch (p->touched) {
+		case 0:
+			break;
+		case 1:
+			p->flags = p->oflags;
+			p->shtrap = p->oshtrap;
+			if (!ksh_sigrestore(p->signal, &(p->prev))) {
+				p->cursig = ksh_sighandler(&(p->prev));
+				break;
+			}
+			/* FALLTHROUGH */
+		default:
+			kwarnf0(KWF_PREFIX, Tsigerr, Trestore, p->name);
+			break;
+		}
+		++p;
+	} while (--i);
+}
+
 void
 settrap(Trap *p, const char *s)
 {
@@ -1464,20 +1518,20 @@ settrap(Trap *p, const char *s)
  * called by c_print() when writing to a co-process to ensure
  * SIGPIPE won't kill shell (unless user catches it and exits)
  */
-bool
+Wahr
 block_pipe(void)
 {
-	bool restore_dfl = false;
+	Wahr restore_dfl = Nee;
 	Trap *p = &sigtraps[SIGPIPE];
 
 	if (!(p->flags & (TF_ORIG_IGN|TF_ORIG_DFL))) {
 		setsig(p, SIG_IGN, SS_RESTORE_CURR);
 		if (p->flags & TF_ORIG_DFL)
-			restore_dfl = true;
+			restore_dfl = Ja;
 	} else if (p->cursig == SIG_DFL) {
 		setsig(p, SIG_IGN, SS_RESTORE_CURR);
 		/* restore to SIG_DFL */
-		restore_dfl = true;
+		restore_dfl = Ja;
 	}
 	return (restore_dfl);
 }
@@ -1496,22 +1550,33 @@ restore_pipe(void)
 int
 setsig(Trap *p, sig_t f, int flags)
 {
-	struct sigaction sigact;
+	ksh_sigsaved *old;
+	Wahr warned = Nee;
 
 	if (p->signal == ksh_SIGEXIT || p->signal == ksh_SIGERR)
 		return (1);
 
-	memset(&sigact, 0, sizeof(sigact));
+	/* craziness sponsored by 2024 POSIX */
+	p->oflags = p->flags;
+	p->oshtrap = p->shtrap;
+	old = &(p->prev);
 
 	/*
 	 * First time setting this signal? If so, get and note the current
 	 * setting.
 	 */
 	if (!(p->flags & (TF_ORIG_IGN|TF_ORIG_DFL))) {
-		sigaction(p->signal, &Sigact_ign, &sigact);
-		p->flags |= sigact.sa_handler == SIG_IGN ?
+		if (ksh_sigset(p->signal, SIG_IGN, old)) {
+			if (errno != EINVAL) {
+				kwarnf0(KWF_PREFIX, Tsigerr, Tset, p->name);
+				warned = Ja;
+			}
+		} else
+			++p->touched;
+		p->flags |= ksh_sighandler(old) == SIG_IGN ?
 		    TF_ORIG_IGN : TF_ORIG_DFL;
 		p->cursig = SIG_IGN;
+		old = NULL;
 	}
 
 	/*-
@@ -1540,11 +1605,11 @@ setsig(Trap *p, sig_t f, int flags)
 
 	if (p->cursig != f) {
 		p->cursig = f;
-		(void)sigemptyset(&sigact.sa_mask);
-		/* interruptible */
-		sigact.sa_flags = 0;
-		sigact.sa_handler = f;
-		sigaction(p->signal, &sigact, NULL);
+		if (ksh_sigset(p->signal, f, old)) {
+			if (!warned && errno != EINVAL)
+				kwarnf0(KWF_PREFIX, Tsigerr, Tset, p->name);
+		} else if (old != NULL)
+			++p->touched;
 	}
 
 	return (1);
@@ -1556,8 +1621,8 @@ setexecsig(Trap *p, int restore)
 {
 	/* XXX debugging */
 	if (!(p->flags & (TF_ORIG_IGN|TF_ORIG_DFL)))
-		internal_errorf("setexecsig: unset signal %d(%s)",
-		    p->signal, p->name);
+		kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,
+		    "setexecsig: unset signal %d(%s)", p->signal, p->name);
 
 	/* restore original value for exec'd kids */
 	p->flags &= ~(TF_EXEC_IGN|TF_EXEC_DFL);
@@ -1590,7 +1655,7 @@ mksh_lockfd(int fd)
 {
 #if defined(__OpenBSD__)
 	/* flock is not interrupted by signals */
-	(void)flock(fd, LOCK_EX);
+	flock(fd, LOCK_EX);
 #elif HAVE_FLOCK
 	int rv;
 
@@ -1615,7 +1680,7 @@ mksh_lockfd(int fd)
 void
 mksh_unlkfd(int fd)
 {
-	(void)flock(fd, LOCK_UN);
+	flock(fd, LOCK_UN);
 }
 #elif HAVE_LOCK_FCNTL
 void
@@ -1625,7 +1690,117 @@ mksh_unlkfd(int fd)
 
 	memset(&lks, 0, sizeof(lks));
 	lks.l_type = F_UNLCK;
-	(void)fcntl(fd, F_SETLKW, &lks);
+	fcntl(fd, F_SETLKW, &lks);
+}
+#endif
+#endif
+
+/*
+ * On handling errors when setting signals
+ *
+ * The signal management calls fail with:
+ * - EFAULT: (sigaction only) &sa or old point to invalid memory,
+ *   which is not bloody likely
+ * - E?????: (sigaction only) if SA_SIGINFO is set and […]
+ *   but we don’t ever set SA_SIGINFO
+ * - EINVAL: on invalid signal number; operating on uncatchable
+ *   respectively unignorable signals (SIGKILL, SIGSTOP)
+ *
+ * The signal number is already verified in higher-up code.
+ * POSIX documents attempts to trap SIGKILL/SIGSTOP as undefined;
+ * e.g. startx on Debian does it; we could warn, but GNU/Linux also
+ * throws EINVAL for signals 32 and 33, and “trap -p” must work,
+ * so EINVAL does not emit diagnostics :/
+ */
+
+#if HAVE_SIGACTION
+#ifdef NEED_KSH_SIGERR
+void
+ksh_sigerr(int sig MKSH_A_UNUSED)
+{
 }
 #endif
+
+sig_t
+ksh_sigget(int sig)
+{
+	struct sigaction sa;
+
+	if (sigaction(sig, NULL, &sa))
+		return (SIG_ERR);
+	return (sa.sa_handler);
+}
+
+/* masks the signal, does not (may) restart, not oneshot */
+int
+ksh_sigset(int sig, sig_t act, ksh_sigsaved *old)
+{
+	int rv;
+
+	if (act == SIG_ERR) {
+		errno = EOVERFLOW;
+		rv = -1;
+	} else {
+		struct sigaction sa;
+
+		memset(&sa, '\0', sizeof(sa));
+		sigemptyset(&sa.sa_mask);
+		sa.sa_handler = act;
+		rv = sigaction(sig, &sa, old);
+	}
+	if (rv && old) {
+		/* no memset: retain errno */
+		old->sa_handler = SIG_ERR;
+		old->sa_flags = 0;
+	}
+	return (rv);
+}
+
+int
+ksh_sigrestore(int sig, ksh_sigsaved *savedp)
+{
+	if (ksh_sighandler(savedp) == SIG_ERR) {
+		errno = EOVERFLOW;
+		return (1);
+	}
+	return (sigaction(sig, savedp, NULL));
+}
+#elif defined(MKSH_USABLE_SIGNALFUNC)
+/* masks the signal, may (probably will, not always) restart, not oneshot */
+int
+ksh_sigset(int sig, sig_t act, ksh_sigsaved *old)
+{
+	sig_t res;
+
+	if (act == SIG_ERR) {
+		errno = EOVERFLOW;
+		res = SIG_ERR;
+	} else
+		res = MKSH_USABLE_SIGNALFUNC(sig, act);
+	if (old)
+		*old = res;
+	return (res == SIG_ERR ? -1 : 0);
+}
+
+int
+ksh_sigrestore(int sig, ksh_sigsaved *savedp)
+{
+	if (ksh_sighandler(savedp) == SIG_ERR) {
+		errno = EOVERFLOW;
+		return (1);
+	}
+	return (MKSH_USABLE_SIGNALFUNC(sig, *savedp) == SIG_ERR ? -1 : 0);
+}
+
+sig_t
+ksh_sigget(int sig)
+{
+	sig_t ohandler;
+
+	if ((ohandler = MKSH_USABLE_SIGNALFUNC(sig, SIG_DFL)) != SIG_ERR &&
+	    MKSH_USABLE_SIGNALFUNC(sig, ohandler) == SIG_ERR)
+		kwarnf0(KWF_INTERNAL | KWF_PREFIX, Tsigerr, Trestore,
+		    sigtraps[sig].name);
+	return (ohandler);
+}
 #endif
--- mksh-59c.orig/jobs.c
+++ mksh-59c/jobs.c
@@ -2,8 +2,9 @@
 
 /*-
  * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2011,
- *		 2012, 2013, 2014, 2015, 2016, 2018, 2019
- *	mirabilos <m@mirbsd.org>
+ *		 2012, 2013, 2014, 2015, 2016, 2018, 2019, 2021,
+ *		 2022, 2023
+ *	mirabilos <m$(date +%Y)@mirbsd.de>
  *
  * Provided that these terms and disclaimer and all copyright notices
  * are retained or reproduced in an accompanying document, permission
@@ -23,7 +24,7 @@
 
 #include "sh.h"
 
-__RCSID("$MirOS: src/bin/mksh/jobs.c,v 1.128 2019/12/11 19:46:20 tg Exp $");
+__RCSID("$MirOS: src/bin/mksh/jobs.c,v 1.165 2025/12/24 04:51:53 tg Exp $");
 
 #if HAVE_KILLPG
 #define mksh_killpg		killpg
@@ -38,28 +39,30 @@ __RCSID("$MirOS: src/bin/mksh/jobs.c,v 1
 #define PSIGNALLED	2
 #define PSTOPPED	3
 
+#define PROC_TGTSZ	256U
+
 typedef struct proc Proc;
 /* to take alignment into consideration */
 struct proc_dummy {
 	Proc *next;
-	pid_t pid;
 	int state;
 	int status;
-	char command[128];
+	pid_t pid;
+	char command[PROC_TGTSZ - (ALLOC_OVERHEAD + 14U)];
 };
+#define PROC_OFS (offsetof(struct proc_dummy, command))
 /* real structure */
 struct proc {
 	/* next process in pipeline (if any) */
 	Proc *next;
-	/* process id of this Unix process in the job */
-	pid_t pid;
 	/* one of the four P… above */
 	int state;
 	/* wait status */
 	int status;
+	/* process ID of this Unix process in the job */
+	pid_t pid;
 	/* process command string from vistree */
-	char command[256 - (ALLOC_OVERHEAD +
-	    offsetof(struct proc_dummy, command[0]))];
+	char command[PROC_TGTSZ - (ALLOC_OVERHEAD + PROC_OFS)];
 };
 
 /* Notify/print flag - j_print() argument */
@@ -120,6 +123,8 @@ struct job {
 #define JL_AMBIG	1	/* %foo or %?foo is ambiguous */
 #define JL_INVALID	2	/* non-pid, non-% job id */
 
+const char Tpipest[] = "PIPESTATUS";
+
 static const char * const lookup_msgs[] = {
 	"no such job",
 	"ambiguous",
@@ -145,7 +150,7 @@ static volatile sig_atomic_t held_sigchl
 
 #ifndef MKSH_UNEMPLOYED
 static struct shf	*shl_j;
-static bool		ttypgrp_ok;	/* set if can use tty pgrps */
+static Wahr		ttypgrp_ok;	/* set if can use tty pgrps */
 static pid_t		restore_ttypgrp = -1;
 static int const	tt_sigs[] = { SIGTSTP, SIGTTIN, SIGTTOU };
 #endif
@@ -166,16 +171,19 @@ static int		kill_job(Job *, int);
 static void tty_init_talking(void);
 static void tty_init_state(void);
 
+static void vistree(char *, size_t, struct op *)
+    MKSH_A_BOUNDED(__string__, 1, 2);
+
 /* initialise job control */
 void
 j_init(void)
 {
 #ifndef MKSH_NOPROSPECTOFWORK
-	(void)sigemptyset(&sm_default);
+	sigemptyset(&sm_default);
 	sigprocmask(SIG_SETMASK, &sm_default, NULL);
 
-	(void)sigemptyset(&sm_sigchld);
-	(void)sigaddset(&sm_sigchld, SIGCHLD);
+	sigemptyset(&sm_sigchld);
+	sigaddset(&sm_sigchld, SIGCHLD);
 
 	setsig(&sigtraps[SIGCHLD], j_sigchld,
 	    SS_RESTORE_ORIG|SS_FORCE|SS_SHTRAP);
@@ -227,6 +235,7 @@ proc_errorlevel(Proc *p)
 	case PEXITED:
 		return ((WEXITSTATUS(p->status)) & 255);
 	case PSIGNALLED:
+		/* coverity[result_independent_of_operands : SUPPRESS] */
 		return (ksh_sigmask(WTERMSIG(p->status)));
 	default:
 		return (0);
@@ -238,7 +247,7 @@ proc_errorlevel(Proc *p)
 void
 j_suspend(void)
 {
-	struct sigaction sa, osa;
+	ksh_sigsaved ohandler;
 
 	/* Restore tty and pgrp. */
 	if (ttypgrp_ok) {
@@ -246,34 +255,33 @@ j_suspend(void)
 			mksh_tcset(tty_fd, &tty_state);
 		if (restore_ttypgrp >= 0) {
 			if (tcsetpgrp(tty_fd, restore_ttypgrp) < 0) {
-				warningf(false, Tf_ssfaileds,
-				    Tj_suspend, "tcsetpgrp", cstrerror(errno));
+				kwarnf0(KWF_PREFIX, Tf_ssfailed,
+				    Tj_suspend, "tcsetpgrp");
 			} else if (setpgid(0, restore_ttypgrp) < 0) {
-				warningf(false, Tf_ssfaileds,
-				    Tj_suspend, "setpgid", cstrerror(errno));
+				kwarnf0(KWF_PREFIX, Tf_ssfailed,
+				    Tj_suspend, "setpgid");
 			}
 		}
 	}
 
 	/* Suspend the shell. */
-	memset(&sa, 0, sizeof(sa));
-	sigemptyset(&sa.sa_mask);
-	sa.sa_handler = SIG_DFL;
-	sigaction(SIGTSTP, &sa, &osa);
+	if (ksh_sigset(SIGTSTP, SIG_DFL, &ohandler))
+		kwarnf0(KWF_PREFIX, Tsigerr, Tset, "TSTP");
 	kill(0, SIGTSTP);
 
 	/* Back from suspend, reset signals, pgrp and tty. */
-	sigaction(SIGTSTP, &osa, NULL);
+	if (ksh_sigrestore(SIGTSTP, &ohandler))
+		kwarnf0(KWF_PREFIX, Tsigerr, Trestore, "TSTP");
 	if (ttypgrp_ok) {
 		if (restore_ttypgrp >= 0) {
 			if (setpgid(0, kshpid) < 0) {
-				warningf(false, Tf_ssfaileds,
-				    Tj_suspend, "setpgid", cstrerror(errno));
-				ttypgrp_ok = false;
+				kwarnf0(KWF_PREFIX, Tf_ssfailed,
+				    Tj_suspend, "setpgid");
+				ttypgrp_ok = Nee;
 			} else if (tcsetpgrp(tty_fd, kshpid) < 0) {
-				warningf(false, Tf_ssfaileds,
-				    Tj_suspend, "tcsetpgrp", cstrerror(errno));
-				ttypgrp_ok = false;
+				kwarnf0(KWF_PREFIX, Tf_ssfailed,
+				    Tj_suspend, "tcsetpgrp");
+				ttypgrp_ok = Nee;
 			}
 		}
 		tty_init_state();
@@ -287,7 +295,7 @@ j_exit(void)
 {
 	/* kill stopped, and possibly running, jobs */
 	Job *j;
-	bool killed = false;
+	Wahr killed = Nee;
 
 	for (j = job_list; j != NULL; j = j->next) {
 		if (j->ppid == procpid &&
@@ -295,7 +303,7 @@ j_exit(void)
 		    (j->state == PRUNNING &&
 		    ((j->flags & JF_FG) ||
 		    (Flag(FLOGIN) && !Flag(FNOHUP) && procpid == kshpid))))) {
-			killed = true;
+			killed = Ja;
 			if (j->pgrp == 0)
 				kill_job(j, SIGHUP);
 			else
@@ -342,14 +350,13 @@ j_change(void)
 	int i;
 
 	if (Flag(FMONITOR)) {
-		bool use_tty = Flag(FTALKING);
-
 		/* don't call mksh_tcget until we own the tty process group */
-		if (use_tty)
+		if (Flag(FTALKING))
 			tty_init_talking();
 
 		/* no controlling tty, no SIGT* */
-		if ((ttypgrp_ok = (use_tty && tty_fd >= 0 && tty_devtty))) {
+		ttypgrp_ok = (Flag(FTALKING) && tty_fd >= 0 && tty_devtty);
+		if (ttypgrp_ok) {
 			setsig(&sigtraps[SIGTTIN], SIG_DFL,
 			    SS_RESTORE_ORIG|SS_FORCE);
 			/* wait to be given tty (POSIX.1, B.2, job control) */
@@ -357,10 +364,9 @@ j_change(void)
 				pid_t ttypgrp;
 
 				if ((ttypgrp = tcgetpgrp(tty_fd)) < 0) {
-					warningf(false, Tf_ssfaileds,
-					    "j_init", "tcgetpgrp",
-					    cstrerror(errno));
-					ttypgrp_ok = false;
+					kwarnf0(KWF_PREFIX, Tf_ssfailed,
+					    "j_init", "tcgetpgrp");
+					ttypgrp_ok = Nee;
 					break;
 				}
 				if (ttypgrp == kshpgrp)
@@ -373,27 +379,26 @@ j_change(void)
 			    SS_RESTORE_DFL|SS_FORCE);
 		if (ttypgrp_ok && kshpgrp != kshpid) {
 			if (setpgid(0, kshpid) < 0) {
-				warningf(false, Tf_ssfaileds,
-				    "j_init", "setpgid", cstrerror(errno));
-				ttypgrp_ok = false;
+				kwarnf0(KWF_PREFIX, Tf_ssfailed,
+				    "j_init", "setpgid");
+				ttypgrp_ok = Nee;
 			} else {
 				if (tcsetpgrp(tty_fd, kshpid) < 0) {
-					warningf(false, Tf_ssfaileds,
-					    "j_init", "tcsetpgrp",
-					    cstrerror(errno));
-					ttypgrp_ok = false;
+					kwarnf0(KWF_PREFIX, Tf_ssfailed,
+					    "j_init", "tcsetpgrp");
+					ttypgrp_ok = Nee;
 				} else
 					restore_ttypgrp = kshpgrp;
 				kshpgrp = kshpid;
 			}
 		}
 #ifndef MKSH_DISABLE_TTY_WARNING
-		if (use_tty && !ttypgrp_ok)
-			warningf(false, Tf_sD_s, "warning",
+		if (Flag(FTALKING) && !ttypgrp_ok)
+			kwarnf(KWF_PREFIX | KWF_ONEMSG | KWF_NOERRNO,
 			    "won't have full job control");
 #endif
 	} else {
-		ttypgrp_ok = false;
+		ttypgrp_ok = Nee;
 		if (Flag(FTALKING))
 			for (i = NELEM(tt_sigs); --i >= 0; )
 				setsig(&sigtraps[tt_sigs[i]], SIG_IGN,
@@ -408,7 +413,10 @@ j_change(void)
 					    SS_RESTORE_ORIG|SS_FORCE);
 			}
 	}
-	tty_init_state();
+	if (Flag(FTALKING))
+		tty_init_state();
+	else
+		tty_hasstate = Nee;
 }
 #endif
 
@@ -423,9 +431,9 @@ ksh_nice(int ness)
 	errno = 0;
 	/* this is gonna annoy users; complain to your distro, people! */
 	if (nice(ness) == -1 && (eno = errno) != 0)
-		warningf(false, Tf_sD_s, "bgnice", cstrerror(eno));
+		kwarnf(KWF_VERRNO | KWF_PREFIX | KWF_ONEMSG, eno, "bgnice");
 #else
-	(void)nice(ness);
+	nice(ness);
 #endif
 }
 #endif
@@ -433,7 +441,7 @@ ksh_nice(int ness)
 /* execute tree in child subprocess */
 int
 exchild(struct op *t, int flags,
-    volatile int *xerrok,
+    int *xerrok,
     /* used if XPCLOSE or XCCLOSE */
     int close_fd)
 {
@@ -441,6 +449,7 @@ exchild(struct op *t, int flags,
 	static Proc *last_proc;
 
 	int rv = 0, forksleep, jwflags = JW_NONE;
+	int eno = /* stupid GCC */ 0;
 #ifndef MKSH_NOPROSPECTOFWORK
 	sigset_t omask;
 #endif
@@ -475,8 +484,9 @@ exchild(struct op *t, int flags,
 	if (flags & XPIPEI) {
 		/* continuing with a pipe */
 		if (!last_job)
-			internal_errorf("exchild: XPIPEI and no last_job - pid %d",
-			    (int)procpid);
+			kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,
+			    "exchild: XPIPEI and no last_job - pid %ld",
+			    (long)procpid);
 		j = last_job;
 		if (last_proc)
 			last_proc->next = p;
@@ -507,15 +517,14 @@ exchild(struct op *t, int flags,
 
 	/* create child process */
 	forksleep = 1;
-	while ((cldpid = fork()) < 0 && errno == EAGAIN && forksleep < 32) {
+	while ((cldpid = fork()) < 0 && (eno = errno) == EAGAIN &&
+	    forksleep < 32) {
 		if (intrsig)
 			/* allow user to ^C out... */
 			break;
 		sleep(forksleep);
 		forksleep <<= 1;
 	}
-	/* ensure $RANDOM changes between parent and child */
-	rndset((unsigned long)cldpid);
 	/* fork failed? */
 	if (cldpid < 0) {
 		kill_job(j, SIGKILL);
@@ -523,19 +532,22 @@ exchild(struct op *t, int flags,
 #ifndef MKSH_NOPROSPECTOFWORK
 		sigprocmask(SIG_SETMASK, &omask, NULL);
 #endif
-		errorf("can't fork - try again");
+		kerrf(KWF_VERRNO | KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE |
+		    KWF_ONEMSG, eno, "can't fork - try again");
 	}
 	p->pid = cldpid ? cldpid : (procpid = getpid());
+	/* ensure $RANDOM changes between parent and child */
+	rndset((unsigned long)cldpid);
 
 #ifndef MKSH_UNEMPLOYED
 	/* job control set up */
 	if (Flag(FMONITOR) && !(flags&XXCOM)) {
-		bool dotty = false;
+		Wahr dotty = Nee;
 
 		if (j->pgrp == 0) {
 			/* First process */
 			j->pgrp = p->pid;
-			dotty = true;
+			dotty = Ja;
 		}
 
 		/*
@@ -557,7 +569,7 @@ exchild(struct op *t, int flags,
 
 		/* Do this before restoring signal */
 		if (flags & XCOPROC)
-			coproc_cleanup(false);
+			coproc_cleanup(Nee);
 		cleanup_parents_env();
 #ifndef MKSH_UNEMPLOYED
 		/*
@@ -585,8 +597,8 @@ exchild(struct op *t, int flags,
 			setsig(&sigtraps[SIGQUIT], SIG_IGN,
 			    SS_RESTORE_IGN|SS_FORCE);
 			if ((!(flags & (XPIPEI | XCOPROC))) &&
-			    ((forksleep = open("/dev/null", 0)) > 0)) {
-				(void)ksh_dup2(forksleep, 0, true);
+			    ((forksleep = open("/dev/null", 0, 0)) > 0)) {
+				ksh_dup2(forksleep, 0, Ja);
 				close(forksleep);
 			}
 		}
@@ -598,7 +610,7 @@ exchild(struct op *t, int flags,
 #endif
 		nzombie = 0;
 #ifndef MKSH_UNEMPLOYED
-		ttypgrp_ok = false;
+		ttypgrp_ok = Nee;
 		Flag(FMONITOR) = 0;
 #endif
 		Flag(FTALKING) = 0;
@@ -608,7 +620,8 @@ exchild(struct op *t, int flags,
 #ifndef MKSH_SMALL
 		if (t->type == TPIPE)
 			unwind(LLEAVE);
-		internal_warningf("%s: execute() returned", "exchild");
+		kwarnf(KWF_INTERNAL | KWF_WARNING | KWF_TWOMSG,
+		    "exchild", "execute() returned");
 		fptreef(shl_out, 8, "%s: tried to execute {\n\t%T\n}\n",
 		    "exchild", t);
 		shf_flush(shl_out);
@@ -635,7 +648,7 @@ exchild(struct op *t, int flags,
 				for (p = j->proc_list; p; p = p->next)
 					shf_fprintf(shl_out, Tf__d,
 					    (int)p->pid);
-				shf_putchar('\n', shl_out);
+				shf_putc('\n', shl_out);
 				shf_flush(shl_out);
 			}
 		} else
@@ -685,9 +698,11 @@ waitlast(void)
 	j = last_job;
 	if (!j || !(j->flags & JF_STARTED)) {
 		if (!j)
-			warningf(true, Tf_sD_s, "waitlast", "no last job");
+			kwarnf(KWF_PREFIX | KWF_FILELINE | KWF_TWOMSG |
+			    KWF_NOERRNO, "waitlast", "no last job");
 		else
-			internal_warningf(Tf_sD_s, "waitlast", Tnot_started);
+			kwarnf(KWF_INTERNAL | KWF_WARNING | KWF_TWOMSG | KWF_NOERRNO,
+			    "waitlast", Tnot_started);
 #ifndef MKSH_NOPROSPECTOFWORK
 		sigprocmask(SIG_SETMASK, &omask, NULL);
 #endif
@@ -817,7 +832,7 @@ j_resume(const char *cp, int bg)
 	Job *j;
 	Proc *p;
 	int ecode, rv = 0;
-	bool running;
+	Wahr running;
 	sigset_t omask;
 
 	sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
@@ -834,19 +849,21 @@ j_resume(const char *cp, int bg)
 		return (1);
 	}
 
-	if (bg)
-		shprintf("[%d] ", j->job);
+	if (bg) {
+		shprintf("[%d]", j->job);
+		shf_putc(' ', shl_stdout);
+	}
 
-	running = false;
+	running = Nee;
 	for (p = j->proc_list; p != NULL; p = p->next) {
 		if (p->state == PSTOPPED) {
 			p->state = PRUNNING;
 			p->status = 0;
-			running = true;
+			running = Ja;
 		}
 		shf_puts(p->command, shl_stdout);
 		if (p->next)
-			shf_puts("| ", shl_stdout);
+			shf_puts(" | ", shl_stdout);
 	}
 	shf_putc('\n', shl_stdout);
 	shf_flush(shl_stdout);
@@ -869,11 +886,10 @@ j_resume(const char *cp, int bg)
 				if (j->flags & JF_SAVEDTTY)
 					mksh_tcset(tty_fd, &tty_state);
 				sigprocmask(SIG_SETMASK, &omask, NULL);
-				bi_errorf(Tf_ldfailed,
-				    "fg: 1st", "tcsetpgrp", tty_fd,
+				kwarnf1(KWF_VERRNO | KWF_BIERR, rv,
+				    Tf_ldfailed, Tfirst, tty_fd,
 				    (long)((j->flags & JF_SAVEDTTYPGRP) ?
-				    j->saved_ttypgrp : j->pgrp),
-				    cstrerror(rv));
+				    j->saved_ttypgrp : j->pgrp));
 				return (1);
 			}
 		}
@@ -891,9 +907,9 @@ j_resume(const char *cp, int bg)
 			if (ttypgrp_ok && (j->flags & JF_SAVEDTTY))
 				mksh_tcset(tty_fd, &tty_state);
 			if (ttypgrp_ok && tcsetpgrp(tty_fd, kshpgrp) < 0)
-				warningf(true, Tf_ldfailed,
-				    "fg: 2nd", "tcsetpgrp", tty_fd,
-				    (long)kshpgrp, cstrerror(errno));
+				kwarnf0(KWF_PREFIX | KWF_FILELINE,
+				    Tf_ldfailed, "second", tty_fd,
+				    (long)kshpgrp);
 		}
 		sigprocmask(SIG_SETMASK, &omask, NULL);
 		bi_errorf(Tf_s_sD_s, "can't continue job",
@@ -938,7 +954,6 @@ j_stopped_running(void)
 	return (0);
 }
 
-
 /* list jobs for jobs built-in */
 int
 j_jobs(const char *cp, int slp,
@@ -1065,7 +1080,8 @@ j_set_async(Job *j)
 	if (async_job && (async_job->flags & (JF_KNOWN|JF_ZOMBIE)) == JF_ZOMBIE)
 		remove_job(async_job, "async");
 	if (!(j->flags & JF_STARTED)) {
-		internal_warningf(Tf_sD_s, "j_async", Tjob_not_started);
+		kwarnf(KWF_INTERNAL | KWF_WARNING | KWF_TWOMSG | KWF_NOERRNO,
+		    "j_async", Tjob_not_started);
 		return;
 	}
 	async_job = j;
@@ -1077,10 +1093,11 @@ j_set_async(Job *j)
 			    (!oldest || jl->age < oldest->age))
 				oldest = jl;
 		if (!oldest) {
-			/* XXX debugging */
 			if (!(async_job->flags & JF_ZOMBIE) || nzombie != 1) {
-				internal_warningf("%s: bad nzombie (%d)",
-				    "j_async", nzombie);
+#ifdef DEBUG
+				kwarnf0(KWF_INTERNAL | KWF_WARNING | KWF_NOERRNO,
+				    "%s: bad nzombie (%d)", "j_async", nzombie);
+#endif
 				nzombie = 0;
 			}
 			break;
@@ -1126,7 +1143,7 @@ j_waitj(Job *j,
 {
 	Proc *p;
 	int rv;
-#ifdef MKSH_NO_SIGSUSPEND
+#if !defined(MKSH_NOPROSPECTOFWORK) && defined(MKSH_NO_SIGSUSPEND)
 	sigset_t omask;
 #endif
 
@@ -1147,7 +1164,11 @@ j_waitj(Job *j,
 #ifndef MKSH_NOPROSPECTOFWORK
 #ifdef MKSH_NO_SIGSUSPEND
 		sigprocmask(SIG_SETMASK, &sm_default, &omask);
+#ifdef MKSH_POLL_FOR_PAUSE
+		poll(NULL, 0, -1);
+#else
 		pause();
+#endif
 		/* note that handlers may run here so they need to know */
 		sigprocmask(SIG_SETMASK, &omask, NULL);
 #else
@@ -1189,9 +1210,9 @@ j_waitj(Job *j,
 			    (j->saved_ttypgrp = tcgetpgrp(tty_fd)) >= 0)
 				j->flags |= JF_SAVEDTTYPGRP;
 			if (tcsetpgrp(tty_fd, kshpgrp) < 0)
-				warningf(true, Tf_ldfailed,
-				    "j_waitj:", "tcsetpgrp", tty_fd,
-				    (long)kshpgrp, cstrerror(errno));
+				kwarnf0(KWF_PREFIX | KWF_FILELINE,
+				    Tf_ldfailed, "wait", tty_fd,
+				    (long)kshpgrp);
 			if (j->state == PSTOPPED) {
 				j->flags |= JF_SAVEDTTY;
 				mksh_tcget(tty_fd, &j->ttystat);
@@ -1255,8 +1276,9 @@ j_waitj(Job *j,
 	if (!(p = j->proc_list)) {
 		;	/* nothing */
 	} else if (flags & JW_PIPEST) {
-		uint32_t num = 0;
+		k32 num = 0;
 		struct tbl *vp;
+		kby *vt;
 
 		unset(vp_pipest, 1);
 		vp = vp_pipest;
@@ -1264,19 +1286,15 @@ j_waitj(Job *j,
 		goto got_array;
 
 		while (p != NULL) {
-			{
-				struct tbl *vq;
-
-				/* strlen(vp_pipest->name) == 10 */
-				vq = alloc(offsetof(struct tbl, name[0]) + 11,
-				    vp_pipest->areap);
-				memset(vq, 0, offsetof(struct tbl, name[0]));
-				memcpy(vq->name, vp_pipest->name, 11);
-				vp->u.array = vq;
-				vp = vq;
-			}
+			vt = alloc(mbccFAMSZ(struct tbl, name,
+			    sizeof(Tpipest)), vp_pipest->areap);
+			memset(vt, 0, offsetof(struct tbl, name));
+			memcpy(vt + offsetof(struct tbl, name),
+			    Tpipest, sizeof(Tpipest));
+			vp->u.array = (void *)vt;
+			vp = (void *)vt;
 			vp->areap = vp_pipest->areap;
-			vp->ua.index = ++num;
+			vp->ua.index = num = mbiMO(k32, K32_FM, num, +, 1U);
 			vp->flag = DEFINED | ISSET | INTEGER | RDONLY |
 			    ARRAY | INT_U | AINDEX;
  got_array:
@@ -1327,7 +1345,7 @@ j_sigchld(int sig MKSH_A_UNUSED)
 	pid_t pid;
 	int status;
 	struct rusage ru0, ru1;
-#ifdef MKSH_NO_SIGSUSPEND
+#if !defined(MKSH_NOPROSPECTOFWORK) && defined(MKSH_NO_SIGSUSPEND)
 	sigset_t omask;
 
 	/* this handler can run while SIGCHLD is not blocked, so block it now */
@@ -1348,7 +1366,8 @@ j_sigchld(int sig MKSH_A_UNUSED)
 		}
 #endif
 
-	getrusage(RUSAGE_CHILDREN, &ru0);
+	if (ksh_getrusage(RUSAGE_CHILDREN, &ru0))
+		kwarnf(KWF_PREFIX | KWF_FILELINE | KWF_ONEMSG, Tgetrusage);
 	do {
 #ifndef MKSH_NOPROSPECTOFWORK
 		pid = waitpid(-1, &status, (WNOHANG |
@@ -1367,7 +1386,9 @@ j_sigchld(int sig MKSH_A_UNUSED)
 		if (pid <= 0)
 			goto j_sigchld_out;
 
-		getrusage(RUSAGE_CHILDREN, &ru1);
+		if (ksh_getrusage(RUSAGE_CHILDREN, &ru1))
+			kwarnf(KWF_PREFIX | KWF_FILELINE | KWF_ONEMSG,
+			    Tgetrusage);
 
 		/* find job and process structures for this pid */
 		for (j = job_list; j != NULL; j = j->next)
@@ -1377,8 +1398,8 @@ j_sigchld(int sig MKSH_A_UNUSED)
  found:
 		if (j == NULL) {
 			/* Can occur if process has kids, then execs shell
-			warningf(true, "bad process waited for (pid = %d)",
-				pid);
+			kwarnf0(KWF_PREFIX | KWF_FILELINE | KWF_NOERRNO,
+			    "bad process waited for (pid = %d)", pid);
 			 */
 			ru0 = ru1;
 			continue;
@@ -1417,7 +1438,7 @@ j_sigchld(int sig MKSH_A_UNUSED)
 #endif
 
  j_sigchld_out:
-#ifdef MKSH_NO_SIGSUSPEND
+#if !defined(MKSH_NOPROSPECTOFWORK) && defined(MKSH_NO_SIGSUSPEND)
 	sigprocmask(SIG_SETMASK, &omask, NULL);
 #endif
 	errno = saved_errno;
@@ -1439,7 +1460,8 @@ check_job(Job *j)
 
 	/* XXX debugging (nasty - interrupt routine using shl_out) */
 	if (!(j->flags & JF_STARTED)) {
-		internal_warningf("check_job: job started (flags 0x%X)",
+		kwarnf0(KWF_INTERNAL | KWF_WARNING | KWF_NOERRNO,
+		    "check_job: job started (flags 0x%X)",
 		    (unsigned int)j->flags);
 		return;
 	}
@@ -1492,16 +1514,17 @@ check_job(Job *j)
 			put_job(j, PJ_ON_FRONT);
 		if (Flag(FNOTIFY) &&
 		    (j->flags & (JF_WAITING|JF_W_ASYNCNOTIFY)) != JF_WAITING) {
-			/* Look for the real file descriptor 2 */
-			{
-				struct env *ep;
-				int fd = 2;
-
-				for (ep = e; ep; ep = ep->oenv)
-					if (ep->savefd && ep->savefd[2])
-						fd = ep->savefd[2];
-				shf_reopen(fd, SHF_WR, shl_j);
+			struct env *ep = e;
+			int fd = 2, nfd;
+
+			/* look for the real file descriptor 2 */
+			while (ep) {
+				if (ep->savedfd && (nfd = SAVEDFD(ep, 2)))
+					fd = nfd;
+				ep = ep->oenv;
 			}
+			shf_reopen(fd, SHF_WR, shl_j);
+
 			/*
 			 * Can't call j_notify() as it removes jobs. The job
 			 * must stay in the job list as j_waitj() may be
@@ -1541,12 +1564,13 @@ j_print(Job *j, int how, struct shf *shf
 	int state;
 	int status;
 #ifdef WCOREDUMP
-	bool coredumped;
+	Wahr coredumped;
 #endif
-	char jobchar = ' ';
-	char buf[64];
+	char jobchar;
+	Wahr output = Nee;
+	const char *msg;
 	const char *filler;
-	int output = 0;
+	char msgbuf[sizeof("Done (255)")];
 
 	if (how == JP_PGRP) {
 		/*
@@ -1558,108 +1582,110 @@ j_print(Job *j, int how, struct shf *shf
 		    (j->last_proc ? j->last_proc->pid : 0)));
 		return;
 	}
+	/* how is one of JP_SHORT, JP_MEDIUM, JP_LONG from here */
 	j->flags &= ~JF_CHANGED;
 	filler = j->job > 10 ? "\n       " : "\n      ";
 	if (j == job_list)
 		jobchar = '+';
 	else if (j == job_list->next)
 		jobchar = '-';
+	else
+		jobchar = ' ';
 
 	for (p = j->proc_list; p != NULL;) {
 #ifdef WCOREDUMP
-		coredumped = false;
+		coredumped = Nee;
 #endif
 		switch (p->state) {
 		case PRUNNING:
-			memcpy(buf, "Running", 8);
+			msg = "Running";
 			break;
-		case PSTOPPED: {
-			int stopsig = WSTOPSIG(p->status);
-
-			strlcpy(buf, stopsig > 0 && stopsig < ksh_NSIG ?
-			    sigtraps[stopsig].mess : "Stopped", sizeof(buf));
+		case PSTOPPED:
+			status = WSTOPSIG(p->status);
+			msg = status > 0 && status < ksh_NSIG ?
+			    sigtraps[status].mess : "Stopped";
 			break;
-		}
-		case PEXITED: {
-			int exitstatus = (WEXITSTATUS(p->status)) & 255;
-
+		case PEXITED:
 			if (how == JP_SHORT)
-				buf[0] = '\0';
-			else if (exitstatus == 0)
-				memcpy(buf, "Done", 5);
-			else
-				shf_snprintf(buf, sizeof(buf), "Done (%d)",
-				    exitstatus);
+				msg = null;
+			else if ((status = (WEXITSTATUS(p->status)) & 255) == 0)
+				msg = "Done";
+			else {
+				shf_snprintf(msgbuf, sizeof(msgbuf),
+				    TDone, status);
+				msg = msgbuf;
+			}
 			break;
-		}
-		case PSIGNALLED: {
-			int termsig = WTERMSIG(p->status);
+		case PSIGNALLED:
 #ifdef WCOREDUMP
 			if (WCOREDUMP(p->status))
-				coredumped = true;
+				coredumped = Ja;
 #endif
-			/*
-			 * kludge for not reporting 'normal termination
-			 * signals' (i.e. SIGINT, SIGPIPE)
-			 */
-			if (how == JP_SHORT &&
+			status = WTERMSIG(p->status);
+			/* only report “abnormal” termination signals short */
+			if (how != JP_SHORT ||
 #ifdef WCOREDUMP
-			    !coredumped &&
+			    coredumped ||
 #endif
-			    (termsig == SIGINT || termsig == SIGPIPE)) {
-				buf[0] = '\0';
-			} else
-				strlcpy(buf, termsig > 0 && termsig < ksh_NSIG ?
-				    sigtraps[termsig].mess : "Signalled",
-				    sizeof(buf));
-			break;
-		}
+			    (status != SIGINT && status != SIGPIPE)) {
+				msg = status > 0 && status < ksh_NSIG ?
+				    sigtraps[status].mess : "Signalled";
+				break;
+			}
+			/* FALLTHROUGH */
 		default:
-			buf[0] = '\0';
+			msg = null;
 		}
 
-		if (how != JP_SHORT) {
-			if (p == j->proc_list)
-				shf_fprintf(shf, "[%d] %c ", j->job, jobchar);
-			else
-				shf_puts(filler, shf);
-		}
-
-		if (how == JP_LONG)
-			shf_fprintf(shf, "%5d ", (int)p->pid);
-
 		if (how == JP_SHORT) {
-			if (buf[0]) {
-				output = 1;
+			if (msg[0]) {
+				output = Ja;
+				shf_puts(msg, shf);
 #ifdef WCOREDUMP
-				shf_fprintf(shf, "%s%s ",
-				    buf, coredumped ? " (core dumped)" : null);
-#else
-				shf_puts(buf, shf);
-				shf_putchar(' ', shf);
+				if (coredumped)
+					shf_puts(" (core dumped)", shf);
 #endif
+				shf_putc(' ', shf);
 			}
 		} else {
-			output = 1;
-			shf_fprintf(shf, "%-20s %s%s%s", buf, p->command,
-			    p->next ? "|" : null,
+			/* JP_MEDIUM or JP_LONG */
+			if (p == j->proc_list)
+				shf_fprintf(shf, "[%d] %c ", j->job, jobchar);
+			else
+				shf_puts(filler, shf);
+			if (how == JP_LONG)
+				shf_fprintf(shf, "%5d ", (int)p->pid);
+			output = Ja;
+			shf_fprintf(shf, "%-20s %s", msg, p->command);
+			if (p->next) {
+				shf_putc(' ', shf);
+				shf_putc('|', shf);
+			}
 #ifdef WCOREDUMP
-			    coredumped ? " (core dumped)" :
+			if (coredumped)
+				shf_puts(" (core dumped)", shf);
 #endif
-			     null);
 		}
 
 		state = p->state;
 		status = p->status;
 		p = p->next;
 		while (p && p->state == state && p->status == status) {
-			if (how == JP_LONG)
-				shf_fprintf(shf, "%s%5d %-20s %s%s", filler,
-				    (int)p->pid, T1space, p->command,
-				    p->next ? "|" : null);
-			else if (how == JP_MEDIUM)
-				shf_fprintf(shf, Tf__ss, p->command,
-				    p->next ? "|" : null);
+			switch (how) {
+			case JP_LONG:
+				shf_puts(filler, shf);
+				shf_fprintf(shf, "%5d %-20s",
+				    (int)p->pid, T1space);
+				/* FALLTHROUGH */
+			case JP_MEDIUM:
+				shf_putc(' ', shf);
+				shf_puts(p->command, shf);
+				if (p->next) {
+					shf_putc(' ', shf);
+					shf_putc('|', shf);
+				}
+				break;
+			}
 			p = p->next;
 		}
 	}
@@ -1727,7 +1753,7 @@ j_lookup(const char *cp, int *ecodep)
 		last_match = NULL;
 		for (j = job_list; j != NULL; j = j->next)
 			for (p = j->proc_list; p != NULL; p = p->next)
-				if (strstr(p->command, cp+1) != NULL) {
+				if (vstrstr(p->command, cp + 1)) {
 					if (last_match) {
 						if (ecodep)
 							*ecodep = JL_AMBIG;
@@ -1842,7 +1868,8 @@ remove_job(Job *j, const char *where)
 		curr = *prev;
 	}
 	if (curr != j) {
-		internal_warningf("remove_job: job %s (%s)", Tnot_found, where);
+		kwarnf0(KWF_INTERNAL | KWF_WARNING | KWF_NOERRNO,
+		    "remove_job: job %s (%s)", Tnot_found, where);
 		return;
 	}
 	*prev = curr->next;
@@ -1931,23 +1958,21 @@ tty_init_talking(void)
 		break;
 	case 1:
 #ifndef MKSH_DISABLE_TTY_WARNING
-		warningf(false, Tf_sD_s_sD_s,
-		    "No controlling tty", Topen, T_devtty, cstrerror(errno));
+		kwarnf(KWF_PREFIX | KWF_ONEMSG, "can't find controlling tty");
 #endif
 		break;
 	case 2:
 #ifndef MKSH_DISABLE_TTY_WARNING
-		warningf(false, Tf_s_sD_s, Tcant_find, Ttty_fd,
-		    cstrerror(errno));
+		kwarnf(KWF_PREFIX | KWF_ONEMSG, "can't find tty fd");
 #endif
 		break;
 	case 3:
-		warningf(false, Tf_ssfaileds, "j_ttyinit",
-		    Ttty_fd_dupof, cstrerror(errno));
+		kwarnf0(KWF_PREFIX, Tf_ssfailed,
+		    "j_ttyinit", "dup of tty fd");
 		break;
 	case 4:
-		warningf(false, Tf_sD_sD_s, "j_ttyinit",
-		    "can't set close-on-exec flag", cstrerror(errno));
+		kwarnf(KWF_PREFIX | KWF_TWOMSG, "j_ttyinit",
+		    "can't set close-on-exec flag");
 		break;
 	}
 }
@@ -1957,6 +1982,20 @@ tty_init_state(void)
 {
 	if (tty_fd >= 0) {
 		mksh_tcget(tty_fd, &tty_state);
-		tty_hasstate = true;
+		tty_hasstate = Ja;
 	}
 }
+
+static void
+vistree(char *dst, size_t sz, struct op *t)
+{
+	char buf[PROC_TGTSZ - 12];
+	struct shf shf;
+
+	snptreef(buf, sizeof(buf), Tf_T, t);
+	shf_sopen(dst, sz, SHF_WR, &shf);
+	uprntmbs(buf, Nee, &shf);
+	while ((char *)shf.wp > dst && ctype(shf.wp[-1], C_IFSWS))
+		--shf.wp;
+	shf_sclose(&shf);
+}
--- mksh-59c.orig/lalloc.c
+++ mksh-59c/lalloc.c
@@ -1,6 +1,6 @@
 /*-
- * Copyright (c) 2009, 2010, 2011, 2013, 2014, 2016
- *	mirabilos <m@mirbsd.org>
+ * Copyright (c) 2009, 2010, 2011, 2013, 2014, 2016, 2021, 2022
+ *	mirabilos <m$(date +%Y)@mirbsd.de>
  *
  * Provided that these terms and disclaimer and all copyright notices
  * are retained or reproduced in an accompanying document, permission
@@ -18,12 +18,12 @@
  * of said person's immediate fault when using the work as intended.
  */
 
-#include "sh.h"
 #ifdef MKSH_ALLOC_CATCH_UNDERRUNS
 #include <err.h>
 #endif
+#include "sh.h"
 
-__RCSID("$MirOS: src/bin/mksh/lalloc.c,v 1.26 2016/02/26 21:53:36 tg Exp $");
+__RCSID("$MirOS: src/bin/mksh/lalloc.c,v 1.36 2025/04/25 23:14:57 tg Exp $");
 
 /* build with CPPFLAGS+= -DUSE_REALLOC_MALLOC=0 on ancient systems */
 #if defined(USE_REALLOC_MALLOC) && (USE_REALLOC_MALLOC == 0)
@@ -32,7 +32,6 @@ __RCSID("$MirOS: src/bin/mksh/lalloc.c,v
 #define remalloc(p,n)	realloc_osi((p), (n))
 #endif
 
-
 static struct lalloc_common *findptr(struct lalloc_common **, char *, Area *);
 
 #ifndef MKSH_ALLOC_CATCH_UNDERRUNS
@@ -56,7 +55,7 @@ remalloc(void *ptr, size_t size)
 {
 	struct lalloc_item *lp, *lold = ptr;
 
-	size = (size + 4095) & ~(size_t)4095;
+	size = (size_t)(size + 4095U) & (size_t)~(size_t)4095U;
 
 	if (lold && lold->len >= size)
 		return (ptr);
@@ -81,6 +80,7 @@ remalloc(void *ptr, size_t size)
 }
 #endif
 
+/* pre-initio() */
 void
 ainit(Area *ap)
 {
@@ -100,6 +100,9 @@ static struct lalloc_common *
 findptr(struct lalloc_common **lpp, char *ptr, Area *ap)
 {
 	void *lp;
+#ifdef DEBUG
+	Area *oap = ap;
+#endif
 
 #ifndef MKSH_SMALL
 	if (ALLOC_ISUNALIGNED(ptr))
@@ -118,31 +121,43 @@ findptr(struct lalloc_common **lpp, char
  fail:
 #endif
 #ifdef DEBUG
-			internal_warningf("rogue pointer %zX in ap %zX",
-			    (size_t)ptr, (size_t)ap);
+			kwarnf0(KWF_INTERNAL | KWF_WARNING | KWF_NOERRNO,
+			    "rogue pointer %zX in ap %zX",
+			    (size_t)ptr, (size_t)oap);
 			/* try to get a coredump */
 			abort();
 #else
-			internal_errorf("rogue pointer %zX", (size_t)ptr);
+			kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,
+			    "rogue pointer %zX", (size_t)ptr);
 #endif
 		}
 	return (ap);
 }
 
 void *
+aresize1(void *ptr, size_t len1, size_t len2, Area *ap)
+{
+	checkoktoadd(len1, len2);
+	return (aresize(ptr, len1 + len2, ap));
+}
+
+/* pre-initio() */
+void *
 aresize2(void *ptr, size_t fac1, size_t fac2, Area *ap)
 {
 	if (notoktomul(fac1, fac2))
-		internal_errorf(Tintovfl, fac1, '*', fac2);
+		kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,
+		    Tintovfl, fac1, '*', fac2);
 	return (aresize(ptr, fac1 * fac2, ap));
 }
 
+/* pre-initio() ptr=NULL */
 void *
 aresize(void *ptr, size_t numb, Area *ap)
 {
 	struct lalloc_common *lp = NULL;
 
-	/* resizing (true) or newly allocating? */
+	/* resizing or newly allocating? */
 	if (ptr != NULL) {
 		struct lalloc_common *pp;
 
@@ -150,14 +165,29 @@ aresize(void *ptr, size_t numb, Area *ap
 		pp->next = lp->next;
 	}
 
-	if (notoktoadd(numb, sizeof(ALLOC_ITEM)) ||
-	    (lp = remalloc(lp, numb + sizeof(ALLOC_ITEM))) == NULL
+	if (notoktoadd(numb, sizeof(ALLOC_ITEM))) {
+		errno = E2BIG;
+ alloc_fail:
+		if (!initio_done) {
+			SHIKATANAI write(2, SC("mksh: out of memory early\n"));
+			exit(255);
+		}
+		kerrf0(KWF_INTERNAL | KWF_ERR(0xFF),
+		    "can't allocate %zu data bytes", numb);
+	}
+	if ((lp = remalloc(lp, numb + sizeof(ALLOC_ITEM))) == NULL)
+		goto alloc_fail;
 #ifndef MKSH_SMALL
-	    || ALLOC_ISUNALIGNED(lp)
+	if (ALLOC_ISUNALIGNED(lp)) {
+#ifdef EPROTO
+		errno = EPROTO;
 #endif
-	    )
-		internal_errorf(Toomem, numb);
+		goto alloc_fail;
+	}
+#endif
+
 	/* area pointer and items share struct lalloc_common */
+	/*XXX C99 §6.5(6) and footnote 72 may dislike this? */
 	lp->next = ap->next;
 	ap->next = lp;
 	/* return user item address */
--- mksh-59c.orig/lex.c
+++ mksh-59c/lex.c
@@ -2,8 +2,9 @@
 
 /*-
  * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
- *		 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018
- *	mirabilos <m@mirbsd.org>
+ *		 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018,
+ *		 2021, 2022, 2023, 2025
+ *	mirabilos <m$(date +%Y)@mirbsd.de>
  *
  * Provided that these terms and disclaimer and all copyright notices
  * are retained or reproduced in an accompanying document, permission
@@ -23,7 +24,7 @@
 
 #include "sh.h"
 
-__RCSID("$MirOS: src/bin/mksh/lex.c,v 1.251 2020/03/10 23:48:40 tg Exp $");
+__RCSID("$MirOS: src/bin/mksh/lex.c,v 1.270 2025/12/24 04:51:54 tg Exp $");
 
 /*
  * states while lexing word
@@ -62,9 +63,9 @@ typedef struct lex_state {
 		struct lex_state *base;
 		/* marks start of state output in output string */
 		size_t start;
-		/* SBQUOTE: true if in double quotes: "`...`" */
+		/* SBQUOTE: Ja if in double quotes: "`...`" */
 		/* SEQUOTE: got NUL, ignore rest of string */
-		bool abool;
+		Wahr sxqflag;
 		/* SADELIM information */
 		struct {
 			/* character to search for */
@@ -76,13 +77,13 @@ typedef struct lex_state {
 	/* count open parentheses */
 	short nparen;
 	/* type of this state */
-	uint8_t type;
+	kby type;
 	/* extra flags */
-	uint8_t ls_flags;
+	kby ls_flags;
 } Lex_state;
 #define ls_base		u.base
 #define ls_start	u.start
-#define ls_bool		u.abool
+#define ls_flag		u.sxqflag
 #define ls_adelim	u.adelim
 
 /* ls_flags */
@@ -101,7 +102,7 @@ static void getsc_line(Source *);
 static int getsc_bn(void);
 static int getsc_i(void);
 static char *get_brace_var(XString *, char *);
-static bool arraysub(char **);
+static Wahr arraysub(char **);
 static void gethere(void);
 static Lex_state *push_state_i(State_info *, Lex_state *);
 static Lex_state *pop_state_i(State_info *, Lex_state *);
@@ -152,7 +153,7 @@ getsc_r(int c)
 #define STATE_BSIZE	8
 
 #define PUSH_STATE(s)	do {					\
-	uint8_t state_flags = statep->ls_flags;			\
+	kby state_flags = statep->ls_flags;			\
 	if (++statep == state_info.end)				\
 		statep = push_state_i(&state_info, statep);	\
 	state = statep->type = (s);				\
@@ -193,7 +194,6 @@ getsc_r(int c)
  * for example, "${var:-${PWD}}", and "$(size $(whence ksh))".
  * hence the state stack. Note "$(...)" are now parsed recursively.
  */
-
 int
 yylex(int cf)
 {
@@ -252,13 +252,18 @@ yylex(int cf)
 	statep->ls_flags = (cf & HEREDOC) ? LS_HEREDOC : 0;
 
 	/* collect non-special or quoted characters to form word */
-	while (!((c = getsc()) == 0 ||
-	    ((state == SBASE || state == SHEREDELIM) && ctype(c, C_LEX1)))) {
-		if (state == SBASE &&
-		    subshell_nesting_type == ORD(/*{*/ '}') &&
-		    (unsigned int)c == ORD(/*{*/ '}'))
-			/* possibly end ${ :;} */
+	while ((c = getsc())) {
+		switch (state) {
+		case SBASE:
+			/* possibly end "${ :;}" */
+			if ((unsigned int)c == subshell_nesting_type)
+				goto Done;
+			/* FALLTHROUGH */
+		case SHEREDELIM:
+			if (ctype(c, C_LEX1))
+				goto Done;
 			break;
+		}
 		Xcheck(ws, wp);
 		switch (state) {
 		case SADELIM:
@@ -283,7 +288,7 @@ yylex(int cf)
 			if ((unsigned int)c == ORD('[') && (cf & CMDASN)) {
 				/* temporary */
 				*wp = EOS;
-				if (is_wdvarname(Xstring(ws, wp), false)) {
+				if (is_wdvarname(Xstring(ws, wp), Nee)) {
 					char *p, *tmp;
 
 					if (arraysub(&tmp)) {
@@ -552,15 +557,15 @@ yylex(int cf)
 				 * "…`…\"…`…" because, unlike for COMSUBs, the
 				 * outer double quoteing changes the backslash
 				 * meaning for the inside. For more details:
-				 * http://austingroupbugs.net/view.php?id=1015
+				 * https://www.austingroupbugs.net/view.php?id=1015
 				 */
-				statep->ls_bool = false;
+				statep->ls_flag = Nee;
 				s2 = statep;
 				base = state_info.base;
 				while (/* CONSTCOND */ 1) {
 					for (; s2 != base; s2--) {
 						if (s2->type == SDQUOTE) {
-							statep->ls_bool = true;
+							statep->ls_flag = Ja;
 							break;
 						}
 					}
@@ -591,27 +596,26 @@ yylex(int cf)
 				*wp++ = CQUOTE;
 				ignore_backslash_newline--;
 			} else if ((unsigned int)c == ORD('\\')) {
-				if ((c2 = unbksl(true, getsc_i, ungetsc)) == -1)
+				if ((c2 = unbksl(Ja, getsc_i, ungetsc)) == -1)
 					c2 = getsc();
 				if (c2 == 0)
-					statep->ls_bool = true;
-				if (!statep->ls_bool) {
-					char ts[4];
-
+					statep->ls_flag = Ja;
+				if (!statep->ls_flag) {
 					if ((unsigned int)c2 < 0x100) {
 						*wp++ = QCHAR;
 						*wp++ = c2;
 					} else {
+						char ts[4];
+
 						cz = utf_wctomb(ts, c2 - 0x100);
-						ts[cz] = 0;
-						cz = 0;
-						do {
+						c2 = 0;
+						while ((size_t)c2 < cz) {
 							*wp++ = QCHAR;
-							*wp++ = ts[cz];
-						} while (ts[++cz]);
+							*wp++ = ts[c2++];
+						}
 					}
 				}
-			} else if (!statep->ls_bool) {
+			} else if (!statep->ls_flag) {
 				*wp++ = QCHAR;
 				*wp++ = c;
 			}
@@ -752,7 +756,7 @@ yylex(int cf)
 					*wp++ = c;
 					break;
 				case ORD('"'):
-					if (statep->ls_bool) {
+					if (statep->ls_flag) {
 						*wp++ = c;
 						break;
 					}
@@ -830,7 +834,7 @@ yylex(int cf)
 					*wp++ = OQUOTE;
 					ignore_backslash_newline++;
 					PUSH_STATE(SEQUOTE);
-					statep->ls_bool = false;
+					statep->ls_flag = Nee;
 					break;
 				} else if ((unsigned int)c2 == ORD('"')) {
 					/* FALLTHROUGH */
@@ -1041,7 +1045,7 @@ yylex(int cf)
 
 	if (*ident != '\0' && (cf & (KEYWORD | ALIAS))) {
 		struct tbl *p;
-		uint32_t h = hash(ident);
+		k32 h = hash(ident);
 
 		if ((cf & KEYWORD) && (p = ktsearch(&keywords, ident, h)) &&
 		    (!(cf & ESACONLY) || p->val.i == ESAC ||
@@ -1098,7 +1102,7 @@ yylex(int cf)
 	} else if (*ident == '\0') {
 		/* retain typeset et al. even when quoted */
 		struct tbl *tt = get_builtin((dp = wdstrip(yylval.cp, 0)));
-		uint32_t flag = tt ? tt->flag : 0;
+		kui flag = tt ? tt->flag : 0U;
 
 		if (flag & (DECL_UTIL | DECL_FWDR))
 			strlcpy(ident, dp, sizeof(ident));
@@ -1122,7 +1126,6 @@ gethere(void)
 /*
  * read "<<word" text into temp file
  */
-
 static void
 readhere(struct ioword *iop)
 {
@@ -1157,7 +1160,7 @@ readhere(struct ioword *iop)
 		/* end of here document marker, what to do? */
 		switch (c) {
 		case ORD(/*(*/ ')'):
-			if (!subshell_nesting_type)
+			if (subshell_nesting_type != ORD(/*(*/ ')'))
 				/*-
 				 * not allowed outside $(...) or (...)
 				 * => mismatch
@@ -1209,29 +1212,9 @@ readhere(struct ioword *iop)
 		ignore_backslash_newline--;
 }
 
-void
-yyerror(const char *fmt, ...)
-{
-	va_list va;
-
-	/* pop aliases and re-reads */
-	while (source->type == SALIAS || source->type == SREREAD)
-		source = source->next;
-	/* zap pending input */
-	source->str = null;
-
-	error_prefix(true);
-	va_start(va, fmt);
-	shf_vfprintf(shl_out, fmt, va);
-	shf_putc('\n', shl_out);
-	va_end(va);
-	errorfz();
-}
-
 /*
  * input for yylex with alias expansion
  */
-
 Source *
 pushs(int type, Area *areap)
 {
@@ -1357,8 +1340,8 @@ static void
 getsc_line(Source *s)
 {
 	char *xp = Xstring(s->xs, xp), *cp;
-	bool interactive = Flag(FTALKING) && s->type == SSTDIN;
-	bool have_tty = interactive && (s->flags & SF_TTY) && tty_hasstate;
+	Wahr interactive = Flag(FTALKING) && s->type == SSTDIN;
+	Wahr have_tty = interactive && (s->flags & SF_TTY) && tty_hasstate;
 
 	/* Done here to ensure nothing odd happens when a timeout occurs */
 	XcheckN(s->xs, xp, LINE);
@@ -1371,7 +1354,7 @@ getsc_line(Source *s)
 	}
 	if (interactive) {
 		if (cur_prompt == PS1)
-			histsave(&s->line, NULL, HIST_FLUSH, true);
+			histsave(&s->line, NULL, HIST_FLUSH, Ja);
 		change_winsz();
 	}
 #ifndef MKSH_NO_CMDLINE_EDITING
@@ -1380,14 +1363,8 @@ getsc_line(Source *s)
 	    Flag(FVI) ||
 #endif
 	    Flag(FEMACS) || Flag(FGMACS))) {
-		int nread;
-
-		nread = x_read(xp);
-		if (nread < 0)
-			/* read error */
-			nread = 0;
-		xp[nread] = '\0';
-		xp += nread;
+		xp = x_read(xp);
+		*xp = '\0';
 	} else
 #endif
 	  {
@@ -1399,12 +1376,17 @@ getsc_line(Source *s)
 		while (/* CONSTCOND */ 1) {
 			char *p = shf_getse(xp, Xnleft(s->xs, xp), s->u.shf);
 
-			if (!p && shf_error(s->u.shf) &&
-			    shf_errno(s->u.shf) == EINTR) {
-				shf_clearerr(s->u.shf);
-				if (trap)
-					runtraps(0);
-				continue;
+			if (!p && shf_error(s->u.shf)) {
+				if (shf_errno(s->u.shf) == EINTR) {
+					shf_clearerr(s->u.shf);
+					if (trap)
+						runtraps(0);
+					continue;
+				}
+				kwarnf(KWF_ERR(128) | KWF_VERRNO | KWF_PREFIX |
+				    KWF_FILELINE | KWF_BUILTIN | KWF_ONEMSG |
+				    KWF_BIUNWIND, shf_errno(s->u.shf), Trderr);
+				unwind(LRDERR);
 			}
 			if (!p || (xp = p, xp[-1] == '\n'))
 				break;
@@ -1435,7 +1417,6 @@ getsc_line(Source *s)
 		alarm(0);
 	}
 	cp = Xstring(s->xs, xp);
-	rndpush(cp);
 	s->start = s->str = cp;
 	strip_nuls(Xstring(s->xs, xp), Xlength(s->xs, xp));
 	/* Note: if input is all nulls, this is not eof */
@@ -1446,9 +1427,9 @@ getsc_line(Source *s)
 		s->str = NULL;
 	} else if (interactive && *s->str) {
 		if (cur_prompt != PS1)
-			histsave(&s->line, s->str, HIST_APPEND, true);
+			histsave(&s->line, s->str, HIST_APPEND, Ja);
 		else if (!ctype(*s->str, C_IFS | C_IFSWS))
-			histsave(&s->line, s->str, HIST_QUEUE, true);
+			histsave(&s->line, s->str, HIST_QUEUE, Ja);
 #if !defined(MKSH_SMALL) && HAVE_PERSISTENT_HISTORY
 		else
 			goto check_for_sole_return;
@@ -1458,7 +1439,7 @@ getsc_line(Source *s)
 		while (ctype(*cp, C_IFSWS))
 			++cp;
 		if (!*cp) {
-			histsave(&s->line, NULL, HIST_FLUSH, true);
+			histsave(&s->line, NULL, HIST_FLUSH, Ja);
 			histsync();
 		}
 #endif
@@ -1467,10 +1448,32 @@ getsc_line(Source *s)
 		set_prompt(PS2, NULL);
 }
 
+static void
+sjsetprompt(Area *saved_atemp, char *ps1, int saved_lineno)
+{
+	char *cp;
+
+	if (kshsetjmp(e->jbuf)) {
+		prompt = safe_prompt;
+		/*
+		 * Don't print an error - assume it has already been
+		 * printed. Reason is we may have forked to run a
+		 * command and the child may be unwinding its stack
+		 * through this code as it exits.
+		 */
+	} else {
+		cp = substitute(ps1, 0);
+		strdupx(prompt, cp, saved_atemp);
+	}
+	current_lineno = saved_lineno;
+	/* frees everything in post-newenv ATEMP */
+	quitenv(NULL);
+}
+
 void
 set_prompt(int to, Source *s)
 {
-	cur_prompt = (uint8_t)to;
+	cur_prompt = (kby)to;
 
 	switch (to) {
 	/* command */
@@ -1482,41 +1485,31 @@ set_prompt(int to, Source *s)
 		 * substitutions, POSIX doesn't say which is to be done.
 		 */
 		{
+			char ch;
 			struct shf *shf;
-			char * volatile ps1;
+			char *ps1;
 			Area *saved_atemp;
 			int saved_lineno;
 
+			saved_atemp = ATEMP;
+			newenv(E_ERRH);
 			ps1 = str_val(global("PS1"));
 			shf = shf_sopen(NULL, strlen(ps1) * 2,
 			    SHF_WR | SHF_DYNAMIC, NULL);
-			while (*ps1)
-				if (*ps1 != '!' || *++ps1 == '!')
-					shf_putchar(*ps1++, shf);
-				else
+			while ((ch = *ps1++))
+				if (ch != '!' || *ps1++ == '!')
+					shf_putc(ch, shf);
+				else {
+					--ps1;
 					shf_fprintf(shf, Tf_lu, s ?
 					    (unsigned long)s->line + 1 : 0UL);
+				}
 			ps1 = shf_sclose(shf);
 			saved_lineno = current_lineno;
 			if (s)
 				current_lineno = s->line + 1;
-			saved_atemp = ATEMP;
-			newenv(E_ERRH);
-			if (kshsetjmp(e->jbuf)) {
-				prompt = safe_prompt;
-				/*
-				 * Don't print an error - assume it has already
-				 * been printed. Reason is we may have forked
-				 * to run a command and the child may be
-				 * unwinding its stack through this code as it
-				 * exits.
-				 */
-			} else {
-				char *cp = substitute(ps1, 0);
-				strdupx(prompt, cp, saved_atemp);
-			}
-			current_lineno = saved_lineno;
-			quitenv(NULL);
+			sjsetprompt(saved_atemp, ps1, saved_lineno);
+			/* includes quitenv */
 		}
 		break;
 	/* command continuation */
@@ -1530,8 +1523,8 @@ int
 pprompt(const char *cp, int ntruncate)
 {
 	char delimiter = 0;
-	bool doprint = (ntruncate != -1);
-	bool indelimit = false;
+	Wahr doprint = (ntruncate != -1);
+	Wahr indelimit = Nee;
 	int columns = 0, lines = 0;
 
 	/*
@@ -1545,7 +1538,7 @@ pprompt(const char *cp, int ntruncate)
 		delimiter = *cp;
 		cp += 2;
 	}
-	for (; *cp; cp++) {
+	while (*cp) {
 		if (indelimit && *cp != delimiter)
 			;
 		else if (ctype(*cp, C_CR | C_LF)) {
@@ -1560,17 +1553,19 @@ pprompt(const char *cp, int ntruncate)
 			indelimit = !indelimit;
 		else if (UTFMODE && (rtt2asc(*cp) > 0x7F)) {
 			const char *cp2;
+
 			columns += utf_widthadj(cp, &cp2);
 			if (doprint && (indelimit ||
 			    (ntruncate < (x_cols * lines + columns))))
 				shf_write(cp, cp2 - cp, shl_out);
-			cp = cp2 - /* loop increment */ 1;
+			cp = cp2;
 			continue;
 		} else
 			columns++;
 		if (doprint && (*cp != delimiter) &&
 		    (indelimit || (ntruncate < (x_cols * lines + columns))))
 			shf_putc(*cp, shl_out);
+		++cp;
 	}
 	if (doprint)
 		shf_flush(shl_out);
@@ -1600,10 +1595,8 @@ get_brace_var(XString *wsp, char *wp)
 
 				c2 = getsc();
 				ungetsc(c2);
-				if (ord(c2) != ORD(/*{*/ '}')) {
-					ungetsc(c);
+				if (ord(c2) != ORD(/*{*/ '}'))
 					goto out;
-				}
 			}
 			goto ps_common;
 		case PS_SAW_BANG:
@@ -1678,11 +1671,11 @@ get_brace_var(XString *wsp, char *wp)
 }
 
 /*
- * Save an array subscript - returns true if matching bracket found, false
- * if eof or newline was found.
- * (Returned string double null terminated)
+ * Save an array subscript
+ * Returns Ja if matching bracket found, Nee if EOF or newline was found.
+ * (Returned string is double-NUL-terminated.)
  */
-static bool
+static Wahr
 arraysub(char **strp)
 {
 	XString ws;
@@ -1705,7 +1698,7 @@ arraysub(char **strp)
 	*wp++ = '\0';
 	*strp = Xclose(ws, wp);
 
-	return (tobool(depth == 0));
+	return (isWahr(depth == 0));
 }
 
 /* Unget a char: handles case when we are already at the start of the buffer */
@@ -1742,7 +1735,6 @@ ungetsc_i(int c)
 	}
 }
 
-
 /* Called to get a char that isn't a \newline sequence. */
 static int
 getsc_bn(void)
@@ -1772,29 +1764,6 @@ getsc_bn(void)
 	}
 }
 
-void
-yyskiputf8bom(void)
-{
-	int c;
-
-	if (rtt2asc((c = o_getsc_u())) != 0xEF) {
-		ungetsc_i(c);
-		return;
-	}
-	if (rtt2asc((c = o_getsc_u())) != 0xBB) {
-		ungetsc_i(c);
-		ungetsc_i(asc2rtt(0xEF));
-		return;
-	}
-	if (rtt2asc((c = o_getsc_u())) != 0xBF) {
-		ungetsc_i(c);
-		ungetsc_i(asc2rtt(0xBB));
-		ungetsc_i(asc2rtt(0xEF));
-		return;
-	}
-	UTFMODE |= 8;
-}
-
 static Lex_state *
 push_state_i(State_info *si, Lex_state *old_end)
 {
--- mksh-59c.orig/lksh.1
+++ mksh-59c/lksh.1
@@ -1,7 +1,8 @@
-.\" $MirOS: src/bin/mksh/lksh.1,v 1.26 2020/09/04 22:37:01 tg Exp $
+.\" $MirOS: src/bin/mksh/lksh.1,v 1.37 2025/06/20 17:32:06 tg Exp $
 .\"-
-.\" Copyright (c) 2008, 2009, 2010, 2012, 2013, 2015, 2016, 2017, 2018
-.\"	mirabilos <m@mirbsd.org>
+.\" Copyright © 2008, 2009, 2010, 2012, 2013, 2015, 2016, 2017,
+.\"		2018, 2023
+.\"	mirabilos <m$(date +%Y)@mirbsd.de>
 .\"
 .\" Provided that these terms and disclaimer and all copyright notices
 .\" are retained or reproduced in an accompanying document, permission
@@ -18,7 +19,15 @@
 .\" damage or existence of a defect, except proven that it results out
 .\" of said person’s immediate fault when using the work as intended.
 .\"-
-.\" Try to make GNU groff and AT&T nroff more compatible
+.\" $miros: contrib/samples/portmdoc,v 1.27 2025/06/20 17:30:44 tg Exp $
+.\"-
+.\" Copyright © 2008, 2009, 2010, 2016, 2018, 2020, 2023, 2025
+.\"	mirabilos <m$(date +%Y)@mirbsd.de>
+.\" Copyright © 1991, 1993
+.\"	The Regents of the University of California. (Ⓕ 3-clause BSD)
+.\" All rights reserved.
+.\"
+.\" Glue GNU groff (BSD and GNU mdoc both) to AT&T nroff (UCB mdoc).
 .\" * ` generates ‘ in gnroff, so use \`
 .\" * ' generates ’ in gnroff, \' generates ´, so use \*(aq
 .\" * - generates ‐ in gnroff, \- generates −, so .tr it to -
@@ -26,23 +35,41 @@
 .\" * ~ is size-reduced and placed atop in groff, so use \*(TI
 .\" * ^ is size-reduced and placed atop in groff, so use \*(ha
 .\" * \(en does not work in nroff, so use \*(en for a solo en dash
-.\" *   and \*(EM for a correctly spaced em dash
+.\" *   and \*(EM for a correctly spaced em dash (omit space around!)
 .\" * <>| are problematic, so redefine and use \*(Lt\*(Gt\*(Ba
 .\" Also make sure to use \& *before* a punctuation char that is to not
 .\" be interpreted as punctuation, and especially with two-letter words
 .\" but also (after) a period that does not end a sentence (“e.g.\&”).
-.\" The section after the "doc" macropackage has been loaded contains
-.\" additional code to convene between the UCB mdoc macropackage (and
-.\" its variant as BSD mdoc in groff) and the GNU mdoc macropackage.
+.\"-
+.\"
+.\" Implement .Dd with the Mdocdate RCS keyword
+.\"
+.rn Dd xD
+.de Dd
+.ie \\$1$Mdocdate: \{\
+.	xD \\$2 \\$3, \\$4
+.\}
+.el .xD \\$1 \\$2 \\$3
+..
+.\"
+.\" .Dd must come before most everything, because when called
+.\" with -mandoc it loads -mdoc via .so in .Dd (first macro).
+.\"
+.Dd $Mdocdate: June 20 2025 $
+.\"
+.\" Check which macro package we use, and do other -mdoc setup.
 .\"
 .ie \n(.g \{\
+.	if n .ss \n[.ss] 0
 .	if \*[.T]ascii .tr \-\N'45'
 .	if \*[.T]latin1 .tr \-\N'45'
 .	if \*[.T]utf8 .tr \-\N'45'
-.	ds <= \[<=]
-.	ds >= \[>=]
-.	ds Rq \[rq]
-.	ds Lq \[lq]
+.	if \*[.T]utf8 .tr \(la\*(Lt
+.	if \*[.T]utf8 .tr \(ra\*(Gt
+.	ds <= \(<=
+.	ds >= \(>=
+.	ds Rq \(rq
+.	ds Lq \(lq
 .	ds sL \(aq
 .	ds sR \(aq
 .	if \*[.T]utf8 .ds sL `
@@ -53,56 +80,36 @@
 .	ds TI \(ti
 .	ds ha \(ha
 .	ds en \(en
+.	ie d volume-ds-1 .ds tT gnu
+.	el .ie d doc-volume-ds-1 .ds tT gnp
+.	el .ds tT bsd
 .\}
 .el \{\
 .	ds aq '
 .	ds TI ~
 .	ds ha ^
 .	ds en \(em
+.	ds tT ucb
 .\}
 .ie n \{\
-.	ds EM \ \*(en\ \&
+.	ds EM \ \(em\ \&
 .\}
 .el \{\
-.	ds EM \f(TR\^\(em\^\fP
-.\}
-.\"
-.\" Implement .Dd with the Mdocdate RCS keyword
-.\"
-.rn Dd xD
-.de Dd
-.ie \\$1$Mdocdate: \{\
-.	xD \\$2 \\$3, \\$4
-.\}
-.el .xD \\$1 \\$2 \\$3 \\$4 \\$5 \\$6 \\$7 \\$8
-..
-.\"
-.\" .Dd must come before definition of .Mx, because when called
-.\" with -mandoc, it might implement .Mx itself, but we want to
-.\" use our own definition. And .Dd must come *first*, always.
-.\"
-.Dd $Mdocdate: September 4 2020 $
-.\"
-.\" Check which macro package we use, and do other -mdoc setup.
-.\"
-.ie \n(.g \{\
-.	if \*[.T]utf8 .tr \[la]\*(Lt
-.	if \*[.T]utf8 .tr \[ra]\*(Gt
-.	ie d volume-ds-1 .ds tT gnu
-.	el .ie d doc-volume-ds-1 .ds tT gnp
-.	el .ds tT bsd
+.	ds EM \f(TR\|\(em\|\fP\&
 .\}
-.el .ds tT ucb
 .\"
+.\" Add UCB mdoc compatibility to GNU mdoc
 .\" Implement .Mx (MirBSD)
 .\"
 .ie "\*(tT"gnu" \{\
+.	ds sP \s0
+.	ds tN \*[Tn-font-size]
 .	eo
 .	de Mx
 .	nr curr-font \n[.f]
 .	nr curr-size \n[.ps]
 .	ds str-Mx \f[\n[curr-font]]\s[\n[curr-size]u]
-.	ds str-Mx1 \*[Tn-font-size]\%MirBSD\*[str-Mx]
+.	ds str-Mx1 \*(tN\%MirBSD\*[str-Mx]
 .	if !\n[arg-limit] \
 .	if \n[.$] \{\
 .	ds macro-name Mx
@@ -111,7 +118,7 @@
 .	if (\n[arg-limit] > \n[arg-ptr]) \{\
 .	nr arg-ptr +1
 .	ie (\n[type\n[arg-ptr]] == 2) \
-.	as str-Mx1 \~\*[arg\n[arg-ptr]]
+.	ds str-Mx1 \*(tN\%MirBSD\~#\*[arg\n[arg-ptr]]\*[str-Mx]
 .	el \
 .	nr arg-ptr -1
 .	\}
@@ -124,17 +131,31 @@
 .	parse-space-vector
 .	print-recursive
 ..
+.	de Aq
+.	if !\n[arg-limit] \
+.	ds macro-name Aq
+.	ie \n[in-authors-section] \{\
+.		ds quote-left \*(Lt
+.		ds quote-right \*(Gt
+.	\}
+.	el \{\
+.		ds quote-left \[la]
+.		ds quote-right \[ra]
+.	\}
+.	enclose-string \$@
+..
 .	ec
-.	ds sP \s0
-.	ds tN \*[Tn-font-size]
 .\}
 .el .ie "\*(tT"gnp" \{\
+.	ds sP \s0
+.	ie t .ds tN \s[(\n[.ps]u-1z)]
+.	el .ds tN
 .	eo
 .	de Mx
 .	nr doc-curr-font \n[.f]
 .	nr doc-curr-size \n[.ps]
 .	ds doc-str-Mx \f[\n[doc-curr-font]]\s[\n[doc-curr-size]u]
-.	ds doc-str-Mx1 \*[doc-Tn-font-size]\%MirBSD\*[doc-str-Mx]
+.	ds doc-str-Mx1 \*(tN\%MirBSD\*[doc-str-Mx]
 .	if !\n[doc-arg-limit] \
 .	if \n[.$] \{\
 .	ds doc-macro-name Mx
@@ -143,7 +164,7 @@
 .	if (\n[doc-arg-limit] > \n[doc-arg-ptr]) \{\
 .	nr doc-arg-ptr +1
 .	ie (\n[doc-type\n[doc-arg-ptr]] == 2) \
-.	as doc-str-Mx1 \~\*[doc-arg\n[doc-arg-ptr]]
+.	ds doc-str-Mx1 \*(tN\%MirBSD\~#\*[doc-arg\n[doc-arg-ptr]]\*[doc-str-Mx]
 .	el \
 .	nr doc-arg-ptr -1
 .	\}
@@ -156,9 +177,13 @@
 .	doc-parse-space-vector
 .	doc-print-recursive
 ..
+.	am1 Sh
+.	if d doc-sec-head .if !"\*[doc-sec-head]"" \{\
+.		if "\*[doc-sec-head]"\*[doc-section-synopsis]" .na
+.		if "\*[doc-sec-head]"\*[doc-section-see-also]" .na
+.	\}
+..
 .	ec
-.	ds sP \s0
-.	ds tN \*[doc-Tn-font-size]
 .\}
 .el \{\
 .	de Mx
@@ -166,13 +191,18 @@
 .	nr cZ \\n(.s
 .	ds aa \&\f\\n(cF\s\\n(cZ
 .	if \\n(aC==0 \{\
-.		ie \\n(.$==0 \&MirBSD\\*(aa
+.		ie \\n(.$==0 \&\\*(tNMirBSD\\*(aa
 .		el .aV \\$1 \\$2 \\$3 \\$4 \\$5 \\$6 \\$7 \\$8 \\$9
 .	\}
 .	if \\n(aC>\\n(aP \{\
 .		nr aP \\n(aP+1
 .		ie \\n(C\\n(aP==2 \{\
-.			as b1 \&MirBSD\ #\&\\*(A\\n(aP\\*(aa
+.			nr xX 0
+.			nr xX 1+\\*(A\\n(aP
+.			as b1 \&\\*(tNMirBSD\ \&
+.			if \\n(xX>0 .as b1 #\&
+.			as b1 \&\\*(A\\n(aP\\*(aa
+.			rr xX
 .			ie \\n(aC>\\n(aP \{\
 .				nr aP \\n(aP+1
 .				nR
@@ -180,12 +210,13 @@
 .			el .aZ
 .		\}
 .		el \{\
-.			as b1 \&MirBSD\\*(aa
+.			as b1 \&\\*(tNMirBSD\\*(aa
 .			nR
 .		\}
 .	\}
 ..
 .\}
+.\" </MirCVS://contrib/samples/portmdoc>
 .\"-
 .Dt LKSH 1
 .Os MirBSD
@@ -344,18 +375,12 @@ is not exactly specified.
 .Pp
 Talk to the
 .Mx
-development team and users using the mailing list at
-.Aq Mt miros\-mksh@mirbsd.org
-(please note the EU-DSGVO/GDPR notice on
-.Pa http://www.mirbsd.org/rss.htm#lists
-and in the SMTP banner!) or the
+development team and users in the
 .Li \&#\&!/bin/mksh
-.Pq or Li \&#ksh
-IRC channel at
-.Pa irc.freenode.net
-.Pq Port 6697 SSL, 6667 unencrypted
-if you need any further quirks or assistance,
-and consider migrating your legacy scripts to work with
+IRC channel; mind the infos from
+.Pa http://www.mirbsd.org/mksh\-faq.htm#contact
+for either.
+Consider migrating your legacy scripts to work with
 .Nm mksh
 instead of requiring
 .Nm .
--- mksh-59c.orig/main.c
+++ mksh-59c/main.c
@@ -6,8 +6,8 @@
 /*-
  * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
  *		 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018,
- *		 2019, 2020
- *	mirabilos <m@mirbsd.org>
+ *		 2019, 2020, 2021, 2022, 2023, 2025
+ *	mirabilos <m$(date +%Y)@mirbsd.de>
  *
  * Provided that these terms and disclaimer and all copyright notices
  * are retained or reproduced in an accompanying document, permission
@@ -28,14 +28,10 @@
 #define EXTERN
 #include "sh.h"
 
-#if HAVE_LANGINFO_CODESET
-#include <langinfo.h>
-#endif
-#if HAVE_SETLOCALE_CTYPE
-#include <locale.h>
-#endif
-
-__RCSID("$MirOS: src/bin/mksh/main.c,v 1.374 2020/10/01 20:28:54 tg Exp $");
+__RCSID("$MirOS: src/bin/mksh/main.c,v 1.447 2025/12/23 19:26:16 tg Exp $");
+__IDSTRING(mbsdcc_h_rcsid, SYSKERN_MBSDCC_H);
+__IDSTRING(mbsdint_h_rcsid, SYSKERN_MBSDINT_H);
+__IDSTRING(sh_h_rcsid, MKSH_SH_H_ID);
 
 #ifndef MKSHRC_PATH
 #define MKSHRC_PATH	"~/.mkshrc"
@@ -45,17 +41,34 @@ __RCSID("$MirOS: src/bin/mksh/main.c,v 1
 #define MKSH_DEFAULT_TMPDIR	MKSH_UNIXROOT "/tmp"
 #endif
 
-static uint8_t isuc(const char *);
-static int main_init(int, const char *[], Source **, struct block **);
+#if !HAVE_POSIX_UTF8_LOCALE
+/* this is the “implementation-defined default locale” */
+#ifdef MKSH_DEFAULT_UTFLOC
+#define MKSH_DEFAULT_LOCALE	"UTF-8"
+#else
+#define MKSH_DEFAULT_LOCALE	"C"
+#endif
+#endif
+
+static void main_init(int, const char *[], Source **);
 void chvt_reinit(void);
 static void reclaim(void);
 static void remove_temps(struct temp *);
-static mksh_uari_t rndsetup(void);
+static void rndsetup(void);
 static void init_environ(void);
 #ifdef SIGWINCH
 static void x_sigwinch(int);
 #endif
 
+#ifdef DEBUG
+#define D_M_UNPARSE	0x0001U
+static unsigned int debug_mode;
+
+static void reclim_trace(void);
+#else
+#define reclim_trace() /* nothing */
+#endif
+
 static const char initsubs[] =
     "${PS2=> }"
     "${PS3=#? }"
@@ -84,75 +97,80 @@ static const char *initcoms[] = {
 	NULL,
 	 /* this is what AT&T ksh seems to track, with the addition of emacs */
 	Talias, "-tU",
-	Tcat, "cc", "chmod", "cp", "date", "ed", "emacs", "grep", "ls",
+	"cat", "cc", "chmod", "cp", "date", "ed", "emacs", "grep", "ls",
 	"make", "mv", "pr", "rm", "sed", Tsh, "vi", "who", NULL,
 	NULL
 };
 
 static const char *restr_com[] = {
-	Ttypeset, Tdr, TPATH, TENV, TSHELL, NULL
+	Ttypeset, Tdr, TENV, "HISTFILE", TPATH, TSHELL, NULL
 };
 
-static bool initio_done;
+extern const char Tpipest[];
 
 /* top-level parsing and execution environment */
 static struct env env;
 struct env *e = &env;
 
-/* compile-time assertions */
+/* buffer */
+#if !HAVE_GET_CURRENT_DIR_NAME
+static size_t getwd_bufsz = 448U;
+#endif
+static char *getwd_bufp = NULL;
+
+/* many compile-time assertions */
+mbCTA_BEG(main_c);
+
+ /* require char to be 8 bit long */
+ mbCTA(char_8bit, (CHAR_BIT) == 8 &&
+    (((unsigned int)(unsigned char)255U) == 255U) &&
+    (((unsigned int)(unsigned char)256U) == 0U) &&
+    mbiTYPE_UBITS(unsigned char) == 8U &&
+    mbiMASK_BITS(SCHAR_MAX) == 7U);
+
+ /* the next assertion is probably not really needed */
+ mbCTA(short_is_2_char, sizeof(short) == 2);
+ /* the next assertion is probably not really needed */
+ mbCTA(int_is_4_char, sizeof(int) == 4);
 
-/* this one should be defined by the standard */
-cta(char_is_1_char, (sizeof(char) == 1) && (sizeof(signed char) == 1) &&
-    (sizeof(unsigned char) == 1));
-cta(char_is_8_bits, ((CHAR_BIT) == 8) && ((int)(unsigned char)0xFF == 0xFF) &&
-    ((int)(unsigned char)0x100 == 0) && ((int)(unsigned char)(int)-1 == 0xFF));
-/* the next assertion is probably not really needed */
-cta(short_is_2_char, sizeof(short) == 2);
-cta(short_size_no_matter_of_signedness, sizeof(short) == sizeof(unsigned short));
-/* the next assertion is probably not really needed */
-cta(int_is_4_char, sizeof(int) == 4);
-cta(int_size_no_matter_of_signedness, sizeof(int) == sizeof(unsigned int));
+#ifndef MKSH_LEGACY_MODE
+ /* using (u)int as exactly-32-bit-wide type */
+ mbiCTA_TYPE_MBIT(sari, mksh_ari_t);
+ mbiCTA_TYPE_MBIT(uari, mksh_uari_t);
+ mbCTA(basic_int32_ari,
+    mbiTYPE_UMAX(mksh_uari_t) == (UINT_MAX) &&
+    /* require two’s complement */
+    ((INT_MIN)+1 == -(INT_MAX)));
+ /* the next assertion is probably not really needed */
+ mbCTA(ari_is_4_char, sizeof(mksh_ari_t) == 4);
+ /* but this is */
+ mbCTA(ari_has_31_bit, mbiMASK_BITS(INT_MAX) == 31);
+ /* the next assertion is probably not really needed */
+ mbCTA(uari_is_4_char, sizeof(mksh_uari_t) == 4);
+ mbCTA(uari_is_32_bit, mbiTYPE_UBITS(mksh_uari_t) == 32);
+#else
+ mbCTA(long_complement, (LONG_MIN)+1 == -(LONG_MAX));
+#endif
+ /* these are always required */
+ mbCTA(ari_is_signed, !mbiTYPE_ISU(mksh_ari_t));
+ mbCTA(uari_is_unsigned, mbiTYPE_ISU(mksh_uari_t));
+ /* we require these to have the precisely same size and assume 2s complement */
+ mbCTA(ari_size_no_matter_of_signedness,
+    sizeof(mksh_ari_t) == sizeof(mksh_uari_t));
 
-cta(long_ge_int, sizeof(long) >= sizeof(int));
-cta(long_size_no_matter_of_signedness, sizeof(long) == sizeof(unsigned long));
+ /* our formatting routines assume this */
+ mbCTA(ari_fits_in_long, sizeof(mksh_ari_t) <= sizeof(long));
 
-#ifndef MKSH_LEGACY_MODE
-/* the next assertion is probably not really needed */
-cta(ari_is_4_char, sizeof(mksh_ari_t) == 4);
-/* but this is */
-cta(ari_has_31_bit, 0 < (mksh_ari_t)(((((mksh_ari_t)1 << 15) << 15) - 1) * 2 + 1));
-/* the next assertion is probably not really needed */
-cta(uari_is_4_char, sizeof(mksh_uari_t) == 4);
-/* but the next three are; we REQUIRE unsigned integer wraparound */
-cta(uari_has_31_bit, 0 < (mksh_uari_t)(((((mksh_uari_t)1 << 15) << 15) - 1) * 2 + 1));
-cta(uari_has_32_bit, 0 < (mksh_uari_t)(((((mksh_uari_t)1 << 15) << 15) - 1) * 4 + 3));
-cta(uari_wrap_32_bit,
-    (mksh_uari_t)(((((mksh_uari_t)1 << 15) << 15) - 1) * 4 + 3) >
-    (mksh_uari_t)(((((mksh_uari_t)1 << 15) << 15) - 1) * 4 + 4));
-#endif
-/* these are always required */
-cta(ari_is_signed, (mksh_ari_t)-1 < (mksh_ari_t)0);
-cta(uari_is_unsigned, (mksh_uari_t)-1 > (mksh_uari_t)0);
-/* we require these to have the precisely same size and assume 2s complement */
-cta(ari_size_no_matter_of_signedness, sizeof(mksh_ari_t) == sizeof(mksh_uari_t));
-
-cta(sizet_size_no_matter_of_signedness, sizeof(ssize_t) == sizeof(size_t));
-cta(sizet_voidptr_same_size, sizeof(size_t) == sizeof(void *));
-cta(sizet_funcptr_same_size, sizeof(size_t) == sizeof(void (*)(void)));
-/* our formatting routines assume this */
-cta(ptr_fits_in_long, sizeof(size_t) <= sizeof(long));
-cta(ari_fits_in_long, sizeof(mksh_ari_t) <= sizeof(long));
+mbCTA_END(main_c);
+/* end of compile-time asserts */
 
-static mksh_uari_t
+static void
 rndsetup(void)
 {
-	register uint32_t h;
 	struct {
 		ALLOC_ITEM alloc_INT;
-		void *dataptr, *stkptr, *mallocptr;
-#if defined(__GLIBC__) && (__GLIBC__ >= 2)
-		sigjmp_buf jbuf;
-#endif
+		void *bssptr, *dataptr, *stkptr, *mallocptr;
+		kshjmp_buf jbuf;
 		struct timeval tv;
 	} *bufptr;
 	char *cp;
@@ -163,27 +181,29 @@ rndsetup(void)
 	/* undo what alloc() did to the malloc result address */
 	bufptr = (void *)(cp - sizeof(ALLOC_ITEM));
 	/* PIE or something similar provides us with deltas here */
-	bufptr->dataptr = &rndsetupstate;
+	bufptr->bssptr = &rndsetupstate;
+	bufptr->dataptr = &e;
 	/* ASLR in at least Windows, Linux, some BSDs */
 	bufptr->stkptr = &bufptr;
 	/* randomised malloc in BSD (and possibly others) */
 	bufptr->mallocptr = bufptr;
-#if defined(__GLIBC__) && (__GLIBC__ >= 2)
 	/* glibc pointer guard */
+#ifdef MKSH_NO_SIGSETJMP
+	setjmp(bufptr->jbuf);
+#else
 	sigsetjmp(bufptr->jbuf, 1);
 #endif
-	/* introduce variation (and yes, second arg MBZ for portability) */
+	/* introduce variation (cannot use gettimeofday *tzp portably) */
 	mksh_TIME(bufptr->tv);
 
 #ifdef MKSH_ALLOC_CATCH_UNDERRUNS
 	mprotect(((char *)bufptr) + 4096, 4096, PROT_READ | PROT_WRITE);
 #endif
-	h = chvt_rndsetup(bufptr, sizeof(*bufptr));
-
+	chvt_rndsetup(bufptr, sizeof(*bufptr));
 	afree(cp, APERM);
-	return ((mksh_uari_t)h);
 }
 
+/* pre-initio() */
 void
 chvt_reinit(void)
 {
@@ -197,35 +217,58 @@ static const char *empty_argv[] = {
 	Tmksh, NULL
 };
 
-static uint8_t
+#ifndef MKSH_EARLY_LOCALE_TRACKING
+static kby
 isuc(const char *cx) {
-	char *cp, *x;
-	uint8_t rv = 0;
+	const char *cp;
 
 	if (!cx || !*cx)
 		return (0);
 
-	/* uppercase a string duplicate */
-	strdupx(x, cx, ATEMP);
-	cp = x;
-	while ((*cp = ksh_toupper(*cp)))
+	if ((cp = cstrchr(cx, '.')))
 		++cp;
+	else
+		cp = cx;
+	if (!isCh(cp[0], 'U', 'u') ||
+	    !isCh(cp[1], 'T', 't') ||
+	    !isCh(cp[2], 'F', 'f'))
+		return (0);
+	cp += isch(cp[3], '-') ? 4 : 3;
+	return (isch(*cp, '8') && (isch(cp[1], '@') || !cp[1]));
+}
+#endif
 
-	/* check for UTF-8 */
-	if (strstr(x, "UTF-8") || strstr(x, "UTF8"))
-		rv = 1;
+kby
+kshname_islogin(const char **kshbasenamep)
+{
+	const char *cp;
+	size_t o;
+	kby rv;
 
-	/* free copy and out */
-	afree(x, ATEMP);
+	/* determine the basename (without '-' or path) of the executable */
+	cp = kshname;
+	o = 0;
+	while ((rv = cp[o++])) {
+		if (mksh_cdirsep(rv)) {
+			cp += o;
+			o = 0;
+		}
+	}
+	rv = isch(*cp, '-') || isch(*kshname, '-');
+	if (isch(*cp, '-'))
+		++cp;
+	if (!*cp)
+		cp = empty_argv[0];
+	*kshbasenamep = cp;
 	return (rv);
 }
 
-static int
-main_init(int argc, const char *argv[], Source **sp, struct block **lp)
+/* pre-initio() */
+static void
+main_init(int argc, const char *argv[], Source **sp)
 {
-	int argi, i;
+	int argi = 1, i;
 	Source *s = NULL;
-	struct block *l;
 	unsigned char restricted_shell = 0, errexit, utf_flag;
 	char *cp;
 	const char *ccp, **wp;
@@ -236,6 +279,7 @@ main_init(int argc, const char *argv[],
 #endif
 
 #if defined(MKSH_EBCDIC) || defined(MKSH_FAUX_EBCDIC)
+	/* this must come *really* early due to locale use */
 	ebcdic_init();
 #endif
 	set_ifs(TC_IFSWS);
@@ -257,10 +301,21 @@ main_init(int argc, const char *argv[],
 	}
 	kshname = argv[0];
 
+#ifdef DEBUG
+	if (!strcmp(kshname, "--unparse")) {
+		debug_mode |= D_M_UNPARSE;
+		kshname = argv[0] = empty_argv[0];
+	}
+#endif
+
 	/* initialise permanent Area */
 	ainit(&aperm);
 	/* max. name length: -2147483648 = 11 (+ NUL) */
-	vtemp = alloc(offsetof(struct tbl, name[0]) + 12, APERM);
+	vtemp = alloc(mbccFAMSZ(struct tbl, name, 12), APERM);
+#if !HAVE_GET_CURRENT_DIR_NAME
+	getwd_bufp = alloc(getwd_bufsz + 1U, APERM);
+	getwd_bufp[getwd_bufsz] = '\0';
+#endif
 
 	/* set up base environment */
 	env.type = E_NONE;
@@ -268,24 +323,11 @@ main_init(int argc, const char *argv[],
 	/* set up global l->vars and l->funs */
 	newblock();
 
-	/* Do this first so output routines (eg, errorf, shellf) can work */
+	/* Do this first so output routines (eg. kwarnf, shellf) can work */
 	initio();
 
-	/* determine the basename (without '-' or path) of the executable */
-	ccp = kshname;
-	goto begin_parsing_kshname;
-	while ((i = ccp[argi++])) {
-		if (mksh_cdirsep(i)) {
-			ccp += argi;
- begin_parsing_kshname:
-			argi = 0;
-		}
-	}
-	Flag(FLOGIN) = (ord(*ccp) == ORD('-')) || (ord(*kshname) == ORD('-'));
-	if (ord(*ccp) == ORD('-'))
-		++ccp;
-	if (!*ccp)
-		ccp = empty_argv[0];
+	/* check kshname: leading dash, determine basename */
+	Flag(FLOGIN) = kshname_islogin(&ccp);
 
 	/*
 	 * Turn on nohup by default. (AT&T ksh does not have a nohup
@@ -306,7 +348,7 @@ main_init(int argc, const char *argv[],
 
 	/* define built-in commands and see if we were called as one */
 	ktinit(APERM, &builtins,
-	    /* currently up to 52 builtins: 75% of 128 = 2^7 */
+	    /* currently up to 50 builtins: 75% of 128 = 2^7 */
 	    7);
 	for (i = 0; mkshbuiltins[i].name != NULL; ++i) {
 		const char *builtin_name;
@@ -316,7 +358,7 @@ main_init(int argc, const char *argv[],
 		if (!builtin_name_cmp(ccp, builtin_name)) {
 			/* canonicalise argv[0] */
 			ccp = builtin_name;
-			as_builtin = true;
+			as_builtin = Ja;
 		}
 	}
 
@@ -324,24 +366,24 @@ main_init(int argc, const char *argv[],
 		/* check for -T option early */
 		argi = parse_args(argv, OF_FIRSTTIME, NULL);
 		if (argi < 0)
-			return (1);
+			unwind(LERROR);
 		/* called as rsh, rmksh, -rsh, RKSH.EXE, etc.? */
-		if (ksh_eq(*ccp, 'R', 'r')) {
+		if (isCh(*ccp, 'R', 'r')) {
 			++ccp;
 			++restricted_shell;
 		}
 #if defined(MKSH_BINSHPOSIX) || defined(MKSH_BINSHREDUCED)
 		/* are we called as -rsh or /bin/sh or SH.EXE or so? */
-		if (ksh_eq(ccp[0], 'S', 's') &&
-		    ksh_eq(ccp[1], 'H', 'h')) {
+		if (isCh(ccp[0], 'S', 's') &&
+		    isCh(ccp[1], 'H', 'h')) {
 			/* either also turns off braceexpand */
 #ifdef MKSH_BINSHPOSIX
 			/* enable better POSIX conformance */
-			change_flag(FPOSIX, OF_FIRSTTIME, true);
+			change_flag(FPOSIX, OF_FIRSTTIME, Ja);
 #endif
 #ifdef MKSH_BINSHREDUCED
 			/* enable kludge/compat mode */
-			change_flag(FSH, OF_FIRSTTIME, true);
+			change_flag(FSH, OF_FIRSTTIME, Ja);
 #endif
 		}
 #endif
@@ -393,7 +435,8 @@ main_init(int argc, const char *argv[],
 
 	/*
 	 * Set PATH to def_path (will set the path global variable).
-	 * (import of environment below will probably change this setting).
+	 * Import of environment below will probably change this setting;
+	 * the EXPORT flag is only added via initcoms for this to work.
 	 */
 	vp = global(TPATH);
 	/* setstr can't fail here */
@@ -405,7 +448,7 @@ main_init(int argc, const char *argv[],
 	 * by the environment or the user. Also, we want tab completion
 	 * on in vi by default.
 	 */
-	change_flag(FEMACS, OF_SPECIAL, true);
+	change_flag(FEMACS, OF_INTERNAL, Ja);
 #if !MKSH_S_NOVI
 	Flag(FVITABCOMPLETE) = 1;
 #endif
@@ -426,7 +469,7 @@ main_init(int argc, const char *argv[],
 	cp = str_val(vp);
 	/* Try to use existing $PWD if it is valid */
 	set_current_wd((mksh_abspath(cp) && test_eval(NULL, TO_FILEQ, cp,
-	    Tdot, true)) ? cp : NULL);
+	    Tdot, Ja)) ? cp : NULL);
 	if (current_wd[0])
 		simplify_path(current_wd);
 	/* Only set pwd if we know where we are or if it had a bogus value */
@@ -444,14 +487,16 @@ main_init(int argc, const char *argv[],
 	kshuid = getuid();
 	kshgid = getgid();
 	kshegid = getegid();
+	rndsetup();
 
 	safe_prompt = ksheuid ? "$ " : "# ";
 	vp = global("PS1");
 	/* Set PS1 if unset or we are root and prompt doesn't contain a # */
 	if (!(vp->flag & ISSET) ||
-	    (!ksheuid && !strchr(str_val(vp), '#')))
+	    (!ksheuid && !vstrchr(str_val(vp), '#')))
 		/* setstr can't fail here */
 		setstr(vp, safe_prompt, KSH_RETURN_ERROR);
+	/* ensure several variables will be (unsigned) integers */
 	setint_n((vp = global("BASHPID")), 0, 10);
 	vp->flag |= INT_U;
 	setint_n((vp = global("PGRP")), (mksh_uari_t)kshpgrp, 10);
@@ -466,9 +511,13 @@ main_init(int argc, const char *argv[],
 	vp->flag |= INT_U;
 	setint_n((vp = global("KSHGID")), (mksh_uari_t)kshgid, 10);
 	vp->flag |= INT_U;
-	setint_n((vp = global("RANDOM")), rndsetup(), 10);
-	vp->flag |= INT_U;
-	setint_n((vp_pipest = global("PIPESTATUS")), 0, 10);
+	/* this is needed globally */
+	setint_n((vp_pipest = global(Tpipest)), 0, 10);
+	/* unsigned integer, but avoid rndset call: done farther below */
+	vp = global("RANDOM");
+	vp->flag &= ~SPECIAL;
+	setint_n(vp, 0, 10);
+	vp->flag |= SPECIAL | INT_U;
 
 	/* Set this before parsing arguments */
 	Flag(FPRIVILEGED) = (kshuid != ksheuid || kshgid != kshegid) ? 2 : 0;
@@ -478,14 +527,17 @@ main_init(int argc, const char *argv[],
 	Flag(FMONITOR) = 127;
 #endif
 	/* this to note if utf-8 mode is set on command line (see below) */
+/*XXX this and the below can probably go away */
+/*XXX UTFMODE should be set from env here if locale tracking, just keep it */
 	UTFMODE = 2;
 
 	if (!as_builtin) {
 		argi = parse_args(argv, OF_CMDLINE, NULL);
 		if (argi < 0)
-			return (1);
+			unwind(LERROR);
 	}
 
+/*XXX drop this and the entire cases below */
 	/* process this later only, default to off (hysterical raisins) */
 	utf_flag = UTFMODE;
 	UTFMODE = 0;
@@ -496,7 +548,8 @@ main_init(int argc, const char *argv[],
 	} else if (Flag(FCOMMAND)) {
 		s = pushs(SSTRINGCMDLINE, ATEMP);
 		if (!(s->start = s->str = argv[argi++]))
-			errorf(Tf_optfoo, "", "", 'c', Treq_arg);
+			kerrf(KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE |
+			    KWF_TWOMSG | KWF_NOERRNO, Tdc, Treq_arg);
 		while (*s->str) {
 			if (ctype(*s->str, C_QUOTE))
 				break;
@@ -532,10 +585,9 @@ main_init(int argc, const char *argv[],
 		s->u.shf = shf_open(s->file, O_RDONLY | O_MAYEXEC, 0,
 		    SHF_MAPHI | SHF_CLEXEC);
 		if (s->u.shf == NULL) {
-			shl_stdout_ok = false;
-			warningf(true, Tf_sD_s, s->file, cstrerror(errno));
-			/* mandated by SUSv4 */
-			exstat = 127;
+			shl_stdout_ok = Nee;
+			kwarnf(KWF_ERR(127) |
+			    KWF_PREFIX | KWF_FILELINE | KWF_ONEMSG, s->file);
 			unwind(LERROR);
 		}
 		kshname = s->file;
@@ -556,7 +608,7 @@ main_init(int argc, const char *argv[],
 
 	/* this bizarreness is mandated by POSIX */
 	if (Flag(FTALKING) && fstat(0, &s_stdin) >= 0 &&
-	    S_ISCHR(s_stdin.st_mode))
+	    (S_ISCHR(s_stdin.st_mode) || S_ISFIFO(s_stdin.st_mode)))
 		reset_nonblock(0);
 
 	/* initialise job control */
@@ -587,45 +639,48 @@ main_init(int argc, const char *argv[],
 	    SS_RESTORE_ORIG|SS_FORCE|SS_SHTRAP);
 #endif
 
-	l = e->loc;
-	if (as_builtin) {
-		l->argc = argc;
-		l->argv = argv;
-		l->argv[0] = ccp;
-	} else {
-		l->argc = argc - argi;
-		/*
-		 * allocate a new array because otherwise, when we modify
-		 * it in-place, ps(1) output changes; the meaning of argc
-		 * here is slightly different as it excludes kshname, and
-		 * we add a trailing NULL sentinel as well
-		 */
-		l->argv = alloc2(l->argc + 2, sizeof(void *), APERM);
-		l->argv[0] = kshname;
-		memcpy(&l->argv[1], &argv[argi], l->argc * sizeof(void *));
-		l->argv[l->argc + 1] = NULL;
+	/*
+	 * allocate a new array because otherwise, when we modify
+	 * it in-place, ps(1) output changes; the meaning of argc
+	 * here is slightly different as it excludes kshname, and
+	 * we add a trailing NULL sentinel as well
+	 */
+	e->loc->argc = argc - argi;
+	e->loc->argv = alloc2(e->loc->argc + 2, sizeof(char *), APERM);
+	memcpy(&e->loc->argv[1], &argv[argi], e->loc->argc * sizeof(char *));
+	e->loc->argv[e->loc->argc + 1] = NULL;
+	if (as_builtin)
+		e->loc->argv[0] = ccp;
+	else {
+		e->loc->argv[0] = kshname;
 		getopts_reset(1);
 	}
 
+/*XXX to go away entirely with locale tracking */
 	/* divine the initial state of the utf8-mode Flag */
 	ccp = null;
 	switch (utf_flag) {
 
+#ifdef MKSH_EARLY_LOCALE_TRACKING
+	/* not set on command line, not FTALKING */
+	case 2:
+#endif
 	/* auto-detect from locale or environment */
 	case 4:
-#if HAVE_SETLOCALE_CTYPE
+#ifndef MKSH_EARLY_LOCALE_TRACKING
+#if HAVE_POSIX_UTF8_LOCALE
 		ccp = setlocale(LC_CTYPE, "");
-#if HAVE_LANGINFO_CODESET
 		if (!isuc(ccp))
 			ccp = nl_langinfo(CODESET);
-#endif
 		if (!isuc(ccp))
 			ccp = null;
 #endif
+#endif
 		/* FALLTHROUGH */
 
 	/* auto-detect from environment */
 	case 3:
+#ifndef MKSH_EARLY_LOCALE_TRACKING
 		/* these were imported from environ earlier */
 		if (ccp == null)
 			ccp = str_val(global("LC_ALL"));
@@ -634,10 +689,15 @@ main_init(int argc, const char *argv[],
 		if (ccp == null)
 			ccp = str_val(global("LANG"));
 		UTFMODE = isuc(ccp);
+#else
+		recheck_ctype(); /*XXX probably unnecessary here */
+#endif
 		break;
 
+#ifndef MKSH_EARLY_LOCALE_TRACKING
 	/* not set on command line, not FTALKING */
 	case 2:
+#endif
 	/* unknown values */
 	default:
 		utf_flag = 0;
@@ -668,6 +728,8 @@ main_init(int argc, const char *argv[],
 	/* mark as initialised */
 	baseline_flags[(int)FNFLAGS] = 1;
 #endif
+	rndpush(shell_flags, sizeof(shell_flags));
+	rndset(hash(/*=current_wd*/ cp) ^ hash(argv[0]));
 	if (as_builtin)
 		goto skip_startup_files;
 
@@ -676,28 +738,29 @@ main_init(int argc, const char *argv[],
 	 * user will know why things broke.
 	 */
 	if (!current_wd[0] && Flag(FTALKING))
-		warningf(false, "can't determine current directory");
+		kwarnf(KWF_PREFIX | KWF_ONEMSG | KWF_NOERRNO,
+		    "can't determine current directory");
 
 	if (Flag(FLOGIN))
-		include(MKSH_SYSTEM_PROFILE, 0, NULL, true);
+		include(MKSH_SYSTEM_PROFILE, NULL, Ja);
 	if (Flag(FPRIVILEGED)) {
-		include(MKSH_SUID_PROFILE, 0, NULL, true);
+		include(MKSH_SUID_PROFILE, NULL, Ja);
 		/* note whether -p was enabled during startup */
 		if (Flag(FPRIVILEGED) == 1)
 			/* allow set -p to setuid() later */
 			Flag(FPRIVILEGED) = 3;
 		else
 			/* turn off -p if not set explicitly */
-			change_flag(FPRIVILEGED, OF_INTERNAL, false);
+			change_flag(FPRIVILEGED, OF_INTERNAL, Nee);
 		/* track shell-imposed changes */
 		baseline_flags[(int)FPRIVILEGED] = Flag(FPRIVILEGED);
 	} else {
 		if (Flag(FLOGIN))
-			include(substitute("$HOME/.profile", 0), 0, NULL, true);
+			include(substitute("$HOME/.profile", 0), NULL, Ja);
 		if (Flag(FTALKING)) {
 			cp = substitute("${ENV:-" MKSHRC_PATH "}", DOTILDE);
 			if (cp[0] != '\0')
-				include(cp, 0, NULL, true);
+				include(cp, NULL, Ja);
 		}
 	}
 	if (restricted_shell) {
@@ -722,8 +785,6 @@ main_init(int argc, const char *argv[],
 	alarm_init();
 
 	*sp = s;
-	*lp = l;
-	return (0);
 }
 
 /* this indirection barrier reduces stack usage during normal operation */
@@ -733,21 +794,22 @@ main(int argc, const char *argv[])
 {
 	int rv;
 	Source *s;
-	struct block *l;
 
-	if ((rv = main_init(argc, argv, &s, &l)) == 0) {
-		if (as_builtin) {
-			rv = c_builtin(l->argv);
-		} else {
-			shell(s, 0);
-			/* NOTREACHED */
-		}
+	main_init(argc, argv, &s);
+	if (as_builtin) {
+		rv = c_builtin(e->loc->argv) & 0xFF;
+		exstat = rv;
+		unwind(LEXIT);
+		/* NOTREACHED */
+	} else {
+		rv = shell(s, 0) & 0xFF;
+		/* NOTREACHED */
 	}
 	return (rv);
 }
 
 int
-include(const char *name, int argc, const char **argv, bool intr_ok)
+include(const char *name, const char **argv, Wahr intr_ok)
 {
 	Source *volatile s = NULL;
 	struct shf *shf;
@@ -774,6 +836,8 @@ include(const char *name, int argc, cons
 			e->loc->argc = old_argc;
 		}
 		switch (i) {
+		case LRDERR:
+			return (-2);
 		case LRETURN:
 		case LERROR:
 		case LERREXT:
@@ -793,13 +857,16 @@ include(const char *name, int argc, cons
 			unwind(i);
 			/* NOTREACHED */
 		default:
-			internal_errorf(Tunexpected_type, Tunwind, Tsource, i);
+			kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,
+			    Tunexpected_type, Tunwind, Tsource, i);
 			/* NOTREACHED */
 		}
 	}
 	if (argv) {
 		e->loc->argv = argv;
-		e->loc->argc = argc;
+		e->loc->argc = 0;
+		while (argv[e->loc->argc + 1])
+			++e->loc->argc;
 	}
 	s = pushs(SFILE, ATEMP);
 	s->u.shf = shf;
@@ -810,7 +877,7 @@ include(const char *name, int argc, cons
 		e->loc->argv = old_argv;
 		e->loc->argc = old_argc;
 	}
-	/* & 0xff to ensure value not -1 */
+	/* & 0xFF to ensure value not -1 */
 	return (i & 0xFF);
 }
 
@@ -836,10 +903,9 @@ int
 shell(Source * volatile s, volatile int level)
 {
 	struct op *t;
-	volatile bool wastty = tobool(s->flags & SF_TTY);
-	volatile uint8_t attempts = 13;
-	volatile bool interactive = (level == 0) && Flag(FTALKING);
-	volatile bool sfirst = true;
+	volatile Wahr wastty = isWahr(s->flags & SF_TTY);
+	volatile kby attempts = 13;
+	volatile Wahr interactive = (level == 0) && Flag(FTALKING);
 	Source *volatile old_source = source;
 	int i;
 
@@ -847,13 +913,13 @@ shell(Source * volatile s, volatile int
 	if (level == 2)
 		e->flags |= EF_IN_EVAL;
 	if (interactive)
-		really_exit = false;
+		really_exit = Nee;
 	switch ((i = kshsetjmp(e->jbuf))) {
 	case 0:
 		break;
 	case LBREAK:
 	case LCONTIN:
-		/* assert: interactive == false */
+		/* assert: interactive == Nee */
 		source = old_source;
 		quitenv(NULL);
 		if (level == 2) {
@@ -861,9 +927,14 @@ shell(Source * volatile s, volatile int
 			unwind(i);
 			/* NOTREACHED */
 		}
-		internal_errorf(Tf_cant_s, Tshell,
-		    i == LBREAK ? Tbreak : Tcontinue);
+		kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,
+		    Tf_cant_s, Tshell, i == LBREAK ? Tbreak : Tcontinue);
 		/* NOTREACHED */
+	case LRDERR:
+		if (level == 0)
+			/* run exit traps */
+			unwind(LEXIT);
+		/* FALLTHROUGH */
 	case LINTR:
 		/* we get here if SIGINT not caught or ignored */
 	case LERROR:
@@ -871,7 +942,7 @@ shell(Source * volatile s, volatile int
 	case LSHELL:
 		if (interactive) {
 			if (i == LINTR)
-				shellf("\n");
+				shellf(Tnl);
 			/*
 			 * Reset any eof that was read as part of a
 			 * multiline command.
@@ -886,12 +957,14 @@ shell(Source * volatile s, volatile int
 			 * needs FMONITOR set (not FTALKING/SF_TTY)...
 			 */
 			/* toss any input we have so far */
-			yyrecursive_pop(true);
+			yyrecursive_pop(Ja);
 			s->start = s->str = null;
 			retrace_info = NULL;
 			herep = heres;
 			break;
-		}
+		} else if (i == LSHELL && level == 0)
+			/* run exit traps */
+			unwind(LEXIT);
 		/* FALLTHROUGH */
 	case LEXIT:
 	case LLEAVE:
@@ -906,7 +979,8 @@ shell(Source * volatile s, volatile int
 	default:
 		source = old_source;
 		quitenv(NULL);
-		internal_errorf(Tunexpected_type, Tunwind, Tshell, i);
+		kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,
+		    Tunexpected_type, Tunwind, Tshell, i);
 		/* NOTREACHED */
 	}
 	while (/* CONSTCOND */ 1) {
@@ -923,10 +997,9 @@ shell(Source * volatile s, volatile int
 			j_notify();
 			set_prompt(PS1, s);
 		}
-		t = compile(s, sfirst, true);
+		t = compile(s, Ja);
 		if (interactive)
-			histsave(&s->line, NULL, HIST_FLUSH, true);
-		sfirst = false;
+			histsave(&s->line, NULL, HIST_FLUSH, Ja);
 		if (!t)
 			goto source_no_tree;
 		if (t->type == TEOF) {
@@ -935,7 +1008,7 @@ shell(Source * volatile s, volatile int
 				s->type = SSTDIN;
 			} else if (wastty && !really_exit &&
 			    j_stopped_running()) {
-				really_exit = true;
+				really_exit = Ja;
 				s->type = SSTDIN;
 			} else {
 				/*
@@ -950,11 +1023,15 @@ shell(Source * volatile s, volatile int
 			}
 		} else if ((s->flags & SF_MAYEXEC) && t->type == TCOM)
 			t->u.evalflags |= DOTCOMEXEC;
+#ifdef DEBUG
+		if ((debug_mode & D_M_UNPARSE))
+			dumptree(shl_out, t);
+#endif
 		if (!Flag(FNOEXEC) || (s->flags & SF_TTY))
 			exstat = execute(t, 0, NULL) & 0xFF;
 
 		if (t->type != TEOF && interactive && really_exit)
-			really_exit = false;
+			really_exit = Nee;
 
  source_no_tree:
 		reclaim();
@@ -1015,6 +1092,7 @@ newenv(int type)
 	struct env *ep;
 	char *cp;
 
+	reclim_trace();
 	/*
 	 * struct env includes ALLOC_ITEM for alignment constraints
 	 * so first get the actually used memory, then assign it
@@ -1026,7 +1104,7 @@ newenv(int type)
 	ainit(&ep->area);
 	ep->oenv = e;
 	ep->loc = e->loc;
-	ep->savefd = NULL;
+	ep->savedfd = NULL;
 	ep->temps = NULL;
 	ep->yyrecursive_statep = NULL;
 	ep->type = type;
@@ -1039,29 +1117,28 @@ quitenv(struct shf *shf)
 {
 	struct env *ep = e;
 	char *cp;
-	int fd;
+	int fd, i;
 
-	yyrecursive_pop(true);
+	yyrecursive_pop(Ja);
 	while (ep->oenv && ep->oenv->loc != ep->loc)
 		popblock();
-	if (ep->savefd != NULL) {
+	if (ep->savedfd != NULL) {
 		for (fd = 0; fd < NUFILE; fd++)
-			/* if ep->savefd[fd] < 0, means fd was closed */
-			if (ep->savefd[fd])
-				restfd(fd, ep->savefd[fd]);
-		if (ep->savefd[2])
+			if ((i = SAVEDFD(ep, fd)))
+				restfd(fd, i);
+		if (SAVEDFD(ep, 2))
 			/* Clear any write errors */
 			shf_reopen(2, SHF_WR, shl_out);
 	}
+	if (ep->type == E_EXEC) {
+		/* could be set, would be reclaim()ed below */
+		builtin_argv0 = NULL;
+	}
 	/*
 	 * Bottom of the stack.
 	 * Either main shell is exiting or cleanup_parents_env() was called.
 	 */
 	if (ep->oenv == NULL) {
-#ifdef DEBUG_LEAKS
-		int i;
-#endif
-
 		if (ep->type == E_NONE) {
 			/* Main shell exiting? */
 #if HAVE_PERSISTENT_HISTORY
@@ -1098,6 +1175,9 @@ quitenv(struct shf *shf)
 		sigprocmask(SIG_BLOCK, &sm_sigchld, NULL);
 #endif
 		afreeall(APERM);
+#if HAVE_GET_CURRENT_DIR_NAME
+		free_gnu_gcdn(getwd_bufp);
+#endif
 		for (fd = 3; fd < NUFILE; fd++)
 			if ((i = fcntl(fd, F_GETFD, 0)) != -1 &&
 			    (i & FD_CLOEXEC))
@@ -1132,14 +1212,14 @@ cleanup_parents_env(void)
 	 * anywhere.
 	 */
 
-	/* close all file descriptors hiding in savefd */
+	/* close all file descriptors hiding in savedfd */
 	for (ep = e; ep; ep = ep->oenv) {
-		if (ep->savefd) {
+		if (ep->savedfd) {
 			for (fd = 0; fd < NUFILE; fd++)
-				if (ep->savefd[fd] > 0)
-					close(ep->savefd[fd]);
-			afree(ep->savefd, &ep->area);
-			ep->savefd = NULL;
+				if (FDSVNUM(ep, fd) > (kui)FDBASE)
+					close((int)FDSVNUM(ep, fd));
+			afree(ep->savedfd, &ep->area);
+			ep->savedfd = NULL;
 		}
 #ifdef DEBUG_LEAKS
 		if (ep->type != E_NONE)
@@ -1157,8 +1237,10 @@ cleanup_proc_env(void)
 {
 	struct env *ep;
 
-	for (ep = e; ep; ep = ep->oenv)
+	for (ep = e; ep; ep = ep->oenv) {
 		remove_temps(ep->temps);
+		ep->temps = NULL;
+	}
 }
 
 /* remove temp files and free ATEMP Area */
@@ -1182,6 +1264,7 @@ reclaim(void)
 	 */
 	if (source && source->areap == &e->area)
 		source = NULL;
+	retrace_info = NULL;
 	afreeall(&e->area);
 }
 
@@ -1211,7 +1294,7 @@ int
 tty_init_fd(void)
 {
 	int fd, rv, eno = 0;
-	bool do_close = false, is_devtty = true;
+	Wahr do_close = Nee, is_devtty = Ja;
 
 	if (tty_devtty) {
 		/* already got a tty which is /dev/tty */
@@ -1226,8 +1309,8 @@ tty_init_fd(void)
 		goto got_fd;
 	}
 #endif
-	if ((fd = open(T_devtty, O_RDWR, 0)) >= 0) {
-		do_close = true;
+	if ((fd = open("/dev/tty", O_RDWR, 0)) >= 0) {
+		do_close = Ja;
 		goto got_fd;
 	}
 	eno = errno;
@@ -1237,13 +1320,13 @@ tty_init_fd(void)
 		rv = 1;
 		goto out;
 	}
-	is_devtty = false;
+	is_devtty = Nee;
 
 	if (isatty((fd = 0)) || isatty((fd = 2)))
 		goto got_fd;
 	/* cannot find one */
 	rv = 2;
-	/* assert: do_close == false */
+	/* assert: do_close == Nee */
 	goto out;
 
  got_fd:
@@ -1268,186 +1351,12 @@ tty_init_fd(void)
 	return (rv);
 }
 
-/* A shell error occurred (eg, syntax error, etc.) */
-
-#define VWARNINGF_ERRORPREFIX	1
-#define VWARNINGF_FILELINE	2
-#define VWARNINGF_BUILTIN	4
-#define VWARNINGF_INTERNAL	8
-
-static void vwarningf(unsigned int, const char *, va_list)
-    MKSH_A_FORMAT(__printf__, 2, 0);
-
-static void
-vwarningf(unsigned int flags, const char *fmt, va_list ap)
-{
-	if (fmt) {
-		if (flags & VWARNINGF_INTERNAL)
-			shf_fprintf(shl_out, Tf_sD_, "internal error");
-		if (flags & VWARNINGF_ERRORPREFIX)
-			error_prefix(tobool(flags & VWARNINGF_FILELINE));
-		if ((flags & VWARNINGF_BUILTIN) &&
-		    /* not set when main() calls parse_args() */
-		    builtin_argv0 && builtin_argv0 != kshname)
-			shf_fprintf(shl_out, Tf_sD_, builtin_argv0);
-		shf_vfprintf(shl_out, fmt, ap);
-		shf_putchar('\n', shl_out);
-	}
-	shf_flush(shl_out);
-}
-
-void
-errorfx(int rc, const char *fmt, ...)
-{
-	va_list va;
-
-	exstat = rc;
-
-	/* debugging: note that stdout not valid */
-	shl_stdout_ok = false;
-
-	va_start(va, fmt);
-	vwarningf(VWARNINGF_ERRORPREFIX | VWARNINGF_FILELINE, fmt, va);
-	va_end(va);
-	unwind(LERROR);
-}
-
-void
-errorf(const char *fmt, ...)
-{
-	va_list va;
-
-	exstat = 1;
-
-	/* debugging: note that stdout not valid */
-	shl_stdout_ok = false;
-
-	va_start(va, fmt);
-	vwarningf(VWARNINGF_ERRORPREFIX | VWARNINGF_FILELINE, fmt, va);
-	va_end(va);
-	unwind(LERROR);
-}
-
-/* like errorf(), but no unwind is done */
-void
-warningf(bool fileline, const char *fmt, ...)
-{
-	va_list va;
-
-	va_start(va, fmt);
-	vwarningf(VWARNINGF_ERRORPREFIX | (fileline ? VWARNINGF_FILELINE : 0),
-	    fmt, va);
-	va_end(va);
-}
-
-/*
- * Used by built-in utilities to prefix shell and utility name to message
- * (also unwinds environments for special builtins).
- */
-void
-bi_errorf(const char *fmt, ...)
-{
-	va_list va;
-
-	/* debugging: note that stdout not valid */
-	shl_stdout_ok = false;
-
-	exstat = 1;
-
-	va_start(va, fmt);
-	vwarningf(VWARNINGF_ERRORPREFIX | VWARNINGF_FILELINE |
-	    VWARNINGF_BUILTIN, fmt, va);
-	va_end(va);
-
-	/* POSIX special builtins cause non-interactive shells to exit */
-	if (builtin_spec) {
-		builtin_argv0 = NULL;
-		/* may not want to use LERROR here */
-		unwind(LERROR);
-	}
-}
-
-/*
- * Used by functions called by builtins and not:
- * identical to errorfx if first argument is nil,
- * like bi_errorf storing the errorlevel into it otherwise
- */
-void
-maybe_errorf(int *ep, int rc, const char *fmt, ...)
-{
-	va_list va;
-
-	/* debugging: note that stdout not valid */
-	shl_stdout_ok = false;
-
-	exstat = rc;
-
-	va_start(va, fmt);
-	vwarningf(VWARNINGF_ERRORPREFIX | VWARNINGF_FILELINE |
-	    (ep ? VWARNINGF_BUILTIN : 0), fmt, va);
-	va_end(va);
-
-	if (!ep)
-		goto and_out;
-	*ep = rc;
-
-	/* POSIX special builtins cause non-interactive shells to exit */
-	if (builtin_spec) {
-		builtin_argv0 = NULL;
-		/* may not want to use LERROR here */
- and_out:
-		unwind(LERROR);
-	}
-}
-
-/* Called when something that shouldn't happen does */
-void
-internal_errorf(const char *fmt, ...)
-{
-	va_list va;
-
-	va_start(va, fmt);
-	vwarningf(VWARNINGF_INTERNAL, fmt, va);
-	va_end(va);
-	unwind(LERROR);
-}
-
-void
-internal_warningf(const char *fmt, ...)
-{
-	va_list va;
-
-	va_start(va, fmt);
-	vwarningf(VWARNINGF_INTERNAL, fmt, va);
-	va_end(va);
-}
-
-/* used by error reporting functions to print "ksh: .kshrc[25]: " */
-void
-error_prefix(bool fileline)
-{
-	/* Avoid foo: foo[2]: ... */
-	if (!fileline || !source || !source->file ||
-	    strcmp(source->file, kshname) != 0)
-		shf_fprintf(shl_out, Tf_sD_, kshname +
-		    (*kshname == '-' ? 1 : 0));
-	if (fileline && source && source->file != NULL) {
-		shf_fprintf(shl_out, "%s[%lu]: ", source->file,
-		    (unsigned long)(source->errline ?
-		    source->errline : source->line));
-		source->errline = 0;
-	}
-}
-
 /* printf to shl_out (stderr) with flush */
 void
 shellf(const char *fmt, ...)
 {
 	va_list va;
 
-	if (!initio_done)
-		/* shl_out may not be set up yet... */
-		return;
 	va_start(va, fmt);
 	shf_vfprintf(shl_out, fmt, va);
 	va_end(va);
@@ -1461,7 +1370,8 @@ shprintf(const char *fmt, ...)
 	va_list va;
 
 	if (!shl_stdout_ok)
-		internal_errorf("shl_stdout not valid");
+		kerrf(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_ONEMSG | KWF_NOERRNO,
+		    "shl_stdout not valid");
 	va_start(va, fmt);
 	shf_vfprintf(shl_stdout, fmt, va);
 	va_end(va);
@@ -1485,6 +1395,7 @@ int shl_dbg_fd;
 #endif
 struct shf shf_iob[NSHF_IOB];
 
+/* pre-initio() */
 void
 initio(void)
 {
@@ -1496,38 +1407,43 @@ initio(void)
 	shf_fdopen(1, SHF_WR, shl_stdout);
 	shf_fdopen(2, SHF_WR, shl_out);
 	shf_fdopen(2, SHF_WR, shl_xtrace);
+	initio_done = Ja;
 #ifdef DF
 	if ((lfp = getenv("SDMKSH_PATH")) == NULL) {
 		if ((lfp = getenv("HOME")) == NULL || !mksh_abspath(lfp))
-			errorf("can't get home directory");
+			kerrf(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_ONEMSG |
+			    KWF_NOERRNO, "can't get home directory");
 		strpathx(lfp, lfp, "mksh-dbg.txt", 1);
 	}
 
 	if ((shl_dbg_fd = open(lfp, O_WRONLY | O_APPEND | O_CREAT, 0600)) < 0)
-		errorf("can't open debug output file %s", lfp);
+		kerrf(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_TWOMSG,
+		    lfp, "can't open debug output file");
 	if (shl_dbg_fd < FDBASE) {
 		int nfd;
 
-		nfd = fcntl(shl_dbg_fd, F_DUPFD, FDBASE);
+		if ((nfd = fcntl(shl_dbg_fd, F_DUPFD, FDBASE)) == -1)
+			kerrf(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_ONEMSG,
+			    "can't dup debug output file");
 		close(shl_dbg_fd);
-		if ((shl_dbg_fd = nfd) == -1)
-			errorf("can't dup debug output file");
+		shl_dbg_fd = nfd;
 	}
 	fcntl(shl_dbg_fd, F_SETFD, FD_CLOEXEC);
 	shf_fdopen(shl_dbg_fd, SHF_WR, shl_dbg);
 	DF("=== open ===");
+	initio_done = 2;
 #endif
-	initio_done = true;
 }
 
 /* A dup2() with error checking */
 int
-ksh_dup2(int ofd, int nfd, bool errok)
+ksh_dup2(int ofd, int nfd, Wahr errok)
 {
 	int rv;
 
 	if (((rv = dup2(ofd, nfd)) < 0) && !errok && (errno != EBADF))
-		errorf(Ttoo_many_files);
+		kerrf0(KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE,
+		    Ttoo_many_files, ofd, nfd);
 
 #ifdef __ultrix
 	/*XXX imake style */
@@ -1539,21 +1455,25 @@ ksh_dup2(int ofd, int nfd, bool errok)
 }
 
 /*
- * Move fd from user space (0 <= fd < 10) to shell space (fd >= 10),
- * set close-on-exec flag. See FDBASE in sh.h, maybe 24 not 10 here.
+ * Move fd from user space (0 <= fd < FDBASE) to shell space (fd >= FDBASE)
+ * set moved fd’s close-on-exec flag (see sh.h for FDBASE).
  */
-short
+int
 savefd(int fd)
 {
 	int nfd = fd;
 
+	errno = 0;
 	if (fd < FDBASE && (nfd = fcntl(fd, F_DUPFD, FDBASE)) < 0 &&
 	    (errno == EBADF || errno == EPERM))
 		return (-1);
-	if (nfd < 0 || nfd > SHRT_MAX)
-		errorf(Ttoo_many_files);
-	fcntl(nfd, F_SETFD, FD_CLOEXEC);
-	return ((short)nfd);
+	if (nfd < FDBASE || nfd > (int)(kui)FDMAXNUM)
+		kerrf0(KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE,
+		    Ttoo_many_files, fd, nfd);
+	if (fcntl(nfd, F_SETFD, FD_CLOEXEC) == -1)
+		kwarnf0(KWF_INTERNAL | KWF_WARNING, Tcloexec_failed,
+		    Tset, nfd);
+	return (nfd);
 }
 
 void
@@ -1566,7 +1486,7 @@ restfd(int fd, int ofd)
 		close(fd);
 	else if (fd != ofd) {
 		/*XXX: what to do if this dup fails? */
-		ksh_dup2(ofd, fd, true);
+		ksh_dup2(ofd, fd, Ja);
 		close(ofd);
 	}
 }
@@ -1577,7 +1497,8 @@ openpipe(int *pv)
 	int lpv[2];
 
 	if (pipe(lpv) < 0)
-		errorf("can't create pipe - try again");
+		kerrf(KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE | KWF_ONEMSG,
+		    "pipe");
 	pv[0] = savefd(lpv[0]);
 	if (pv[0] != lpv[0])
 		close(lpv[0]);
@@ -1614,6 +1535,7 @@ check_fd(const char *name, int mode, con
  illegal_fd_name:
 		if (emsgp)
 			*emsgp = "illegal file descriptor name";
+		errno = EINVAL;
 		return (-1);
 	}
 
@@ -1635,6 +1557,11 @@ check_fd(const char *name, int mode, con
 			*emsgp = (fl == O_WRONLY) ?
 			    "fd not open for reading" :
 			    "fd not open for writing";
+#ifdef ENXIO
+		errno = ENXIO;
+#else
+		errno = EBADF;
+#endif
 		return (-1);
 	}
 	return (fd);
@@ -1699,6 +1626,7 @@ coproc_getfd(int mode, const char **emsg
 		return (fd);
 	if (emsgp)
 		*emsgp = "no coprocess";
+	errno = EBADF;
 	return (-1);
 }
 
@@ -1726,6 +1654,8 @@ coproc_cleanup(int reuse)
 	}
 }
 
+static const char temp_tpl[] = "/shXXXXXX.tmp";
+
 struct temp *
 maketemp(Area *ap, Temp_type type, struct temp **tlist)
 {
@@ -1739,23 +1669,21 @@ maketemp(Area *ap, Temp_type type, struc
 	dir = tmpdir ? tmpdir : MKSH_DEFAULT_TMPDIR;
 	/* add "/shXXXXXX.tmp" plus NUL */
 	len = strlen(dir);
-	checkoktoadd(len, offsetof(struct temp, tffn[0]) + 14);
-	tp = alloc(offsetof(struct temp, tffn[0]) + 14 + len, ap);
+	cp = alloc1(mbccFAMSZ(struct temp, tffn, sizeof(temp_tpl)), len, ap);
 
+	tp = (void *)cp;
 	tp->shf = NULL;
 	tp->pid = procpid;
 	tp->type = type;
 
-	if (stat(dir, &sb) || !S_ISDIR(sb.st_mode)) {
-		tp->tffn[0] = '\0';
-		goto maketemp_out;
-	}
-
-	cp = (void *)tp;
-	cp += offsetof(struct temp, tffn[0]);
+	cp += offsetof(struct temp, tffn);
 	memcpy(cp, dir, len);
 	cp += len;
-	memcpy(cp, "/shXXXXXX.tmp", 14);
+	memstr(cp, temp_tpl);
+
+	if (stat(dir, &sb) || !S_ISDIR(sb.st_mode))
+		goto maketemp_out;
+
 	/* point to the first of six Xes */
 	cp += 3;
 
@@ -1805,6 +1733,7 @@ maketemp(Area *ap, Temp_type type, struc
 static void tgrow(struct table *);
 static int tnamecmp(const void *, const void *);
 
+/* pre-initio() tp->tbls=NULL tp->tshift=INIT_TBLSHIFT-1 */
 static void
 tgrow(struct table *tp)
 {
@@ -1813,7 +1742,8 @@ tgrow(struct table *tp)
 	struct tbl **ntblp, **otblp = tp->tbls;
 
 	if (tp->tshift > 29)
-		internal_errorf("hash table size limit reached");
+		kerrf(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_ONEMSG | KWF_NOERRNO,
+		    "hash table size limit reached");
 
 	/* calculate old size, new shift and new size */
 	osize = (size_t)1 << (tp->tshift++);
@@ -1855,8 +1785,9 @@ tgrow(struct table *tp)
 	afree(otblp, tp->areap);
 }
 
+/* pre-initio() initshift=0 */
 void
-ktinit(Area *ap, struct table *tp, uint8_t initshift)
+ktinit(Area *ap, struct table *tp, kby initshift)
 {
 	tp->areap = ap;
 	tp->tbls = NULL;
@@ -1867,7 +1798,7 @@ ktinit(Area *ap, struct table *tp, uint8
 
 /* table, name (key) to search for, hash(name), rv pointer to tbl ptr */
 struct tbl *
-ktscan(struct table *tp, const char *name, uint32_t h, struct tbl ***ppp)
+ktscan(struct table *tp, const char *name, k32 h, struct tbl ***ppp)
 {
 	size_t j, perturb, mask;
 	struct tbl **pp, *p;
@@ -1892,7 +1823,7 @@ ktscan(struct table *tp, const char *nam
 
 /* table, name (key) to enter, hash(n) */
 struct tbl *
-ktenter(struct table *tp, const char *n, uint32_t h)
+ktenter(struct table *tp, const char *n, k32 h)
 {
 	struct tbl **pp, *p;
 	size_t len;
@@ -1908,9 +1839,8 @@ ktenter(struct table *tp, const char *n,
 	}
 
 	/* create new tbl entry */
-	len = strlen(n);
-	checkoktoadd(len, offsetof(struct tbl, name[0]) + 1);
-	p = alloc(offsetof(struct tbl, name[0]) + ++len, tp->areap);
+	len = strlen(n) + 1U;
+	p = alloc(mbccFAMsz(struct tbl, name, len), tp->areap);
 	p->flag = 0;
 	p->type = 0;
 	p->areap = tp->areap;
@@ -1997,8 +1927,8 @@ DF(const char *fmt, ...)
 	mksh_TIME(tv);
 	timet2mjd(&mjd, tv.tv_sec);
 	shf_fprintf(shl_dbg, "[%02u:%02u:%02u (%u) %u.%06u] ",
-	    (unsigned)mjd.sec / 3600, ((unsigned)mjd.sec / 60) % 60,
-	    (unsigned)mjd.sec % 60, (unsigned)getpid(),
+	    (unsigned)mjd.sec / 3600U, ((unsigned)mjd.sec / 60U) % 60U,
+	    (unsigned)mjd.sec % 60U, (unsigned)getpid(),
 	    (unsigned)tv.tv_sec, (unsigned)tv.tv_usec);
 	va_start(args, fmt);
 	shf_vfprintf(shl_dbg, fmt, args);
@@ -2010,7 +1940,7 @@ DF(const char *fmt, ...)
 #endif
 
 void
-x_mkraw(int fd, mksh_ttyst *ocb, bool forread)
+x_mkraw(int fd, mksh_ttyst *ocb, Wahr forread)
 {
 	mksh_ttyst cb;
 
@@ -2018,22 +1948,24 @@ x_mkraw(int fd, mksh_ttyst *ocb, bool fo
 		mksh_tcget(fd, ocb);
 	else
 		ocb = &tty_state;
+#ifdef FLUSHO
+	ocb->c_lflag &= ~(FLUSHO);
+#endif
 
 	cb = *ocb;
-	if (forread) {
-		cb.c_iflag &= ~(ISTRIP);
-		cb.c_lflag &= ~(ICANON) | ECHO;
-	} else {
-		cb.c_iflag &= ~(INLCR | ICRNL | ISTRIP);
+	cb.c_iflag &= ~(IGNPAR | PARMRK | INLCR | IGNCR | ICRNL | ISTRIP);
+	cb.c_iflag |= BRKINT;
+	if (forread)
+		cb.c_lflag &= ~(ICANON);
+	else
 		cb.c_lflag &= ~(ISIG | ICANON | ECHO);
-	}
-#if defined(VLNEXT) && defined(_POSIX_VDISABLE)
+#if defined(VLNEXT)
 	/* OSF/1 processes lnext when ~icanon */
-	cb.c_cc[VLNEXT] = _POSIX_VDISABLE;
+	KSH_DOVDIS(cb.c_cc[VLNEXT]);
 #endif
 	/* SunOS 4.1.x and OSF/1 process discard(flush) when ~icanon */
-#if defined(VDISCARD) && defined(_POSIX_VDISABLE)
-	cb.c_cc[VDISCARD] = _POSIX_VDISABLE;
+#if defined(VDISCARD)
+	KSH_DOVDIS(cb.c_cc[VDISCARD]);
 #endif
 	cb.c_cc[VTIME] = 0;
 	cb.c_cc[VMIN] = 1;
@@ -2042,6 +1974,9 @@ x_mkraw(int fd, mksh_ttyst *ocb, bool fo
 }
 
 #ifdef MKSH_ENVDIR
+#if HAVE_POSIX_UTF8_LOCALE
+# error MKSH_ENVDIR has not been adapted to work with POSIX locale!
+#else
 static void
 init_environ(void)
 {
@@ -2053,21 +1988,19 @@ init_environ(void)
 	struct dirent *dent;
 
 	if ((dirp = opendir(MKSH_ENVDIR)) == NULL) {
-		warningf(false, "cannot read environment from %s: %s",
-		    MKSH_ENVDIR, cstrerror(errno));
+		kwarnf(KWF_PREFIX | KWF_TWOMSG, MKSH_ENVDIR,
+		    "can't read environment");
 		return;
 	}
 	XinitN(xs, 256, ATEMP);
  read_envfile:
 	errno = 0;
 	if ((dent = readdir(dirp)) != NULL) {
-		if (skip_varname(dent->d_name, true)[0] == '\0') {
+		if (!not_varname(dent->d_name, Ja)) {
 			strpathx(xp, MKSH_ENVDIR, dent->d_name, 1);
 			if (!(shf = shf_open(xp, O_RDONLY, 0, 0))) {
-				warningf(false,
-				    "cannot read environment %s from %s: %s",
-				    dent->d_name, MKSH_ENVDIR,
-				    cstrerror(errno));
+				kwarnf(KWF_PREFIX | KWF_THREEMSG, MKSH_ENVDIR,
+				    dent->d_name, "can't read environment");
 				goto read_envfile;
 			}
 			afree(xp, ATEMP);
@@ -2080,28 +2013,28 @@ init_environ(void)
 			while ((n = shf_read(xp, Xnleft(xs, xp), shf)) > 0) {
 				xp += n;
 				if (Xnleft(xs, xp) <= 0)
-					XcheckN(xs, xp, Xlength(xs, xp));
+					XcheckN(xs, xp, 128);
 			}
 			if (n < 0) {
-				warningf(false,
-				    "cannot read environment %s from %s: %s",
-				    dent->d_name, MKSH_ENVDIR,
-				    cstrerror(shf_errno(shf)));
+				kwarnf(KWF_VERRNO | KWF_PREFIX | KWF_THREEMSG,
+				    shf_errno(shf), MKSH_ENVDIR,
+				    dent->d_name, "can't read environment");
 			} else {
 				*xp = '\0';
+				rndpush(Xstring(xs, xp), Xlength(xs, xp));
 				xp = Xstring(xs, xp);
-				rndpush(xp);
 				typeset(xp, IMPORT | EXPORT, 0, 0, 0);
 			}
 			shf_close(shf);
 		}
 		goto read_envfile;
 	} else if (errno)
-		warningf(false, "cannot read environment from %s: %s",
-		    MKSH_ENVDIR, cstrerror(errno));
+		kwarnf(KWF_PREFIX | KWF_TWOMSG, MKSH_ENVDIR,
+		    "can't read environment");
 	closedir(dirp);
 	Xfree(xs, xp);
 }
+#endif
 #else
 extern char **environ;
 
@@ -2115,9 +2048,25 @@ init_environ(void)
 
 	wp = (const char **)environ;
 	while (*wp != NULL) {
-		rndpush(*wp);
+		rndpush(*wp, strlen(*wp));
 		typeset(*wp, IMPORT | EXPORT, 0, 0, 0);
+#ifdef MKSH_EARLY_LOCALE_TRACKING
+		if (isch((*wp)[0], 'L') && (
+		    (isch((*wp)[1], 'C') && isch((*wp)[2], '_')) ||
+		    !strcmp(*wp, "LANG"))) {
+			const char **P;
+
+			/* remove LC_* / LANG from own environment */
+			P = wp;
+			while ((*P = *(P + 1)))
+				++P;
+			/* now setlocale with "" will use the default locale */
+			/* matching the user expectation wrt passed-in vars */
+		} else
+			++wp;
+#else
 		++wp;
+#endif
 	}
 }
 #endif
@@ -2127,25 +2076,194 @@ void
 recheck_ctype(void)
 {
 	const char *ccp;
-	uint8_t old_utfmode = UTFMODE;
+#if !HAVE_POSIX_UTF8_LOCALE
+	const char *cdp;
+#endif
 
+	/* determine active LC_CTYPE value */
 	ccp = str_val(global("LC_ALL"));
-	if (ccp == null)
+	if (!*ccp)
 		ccp = str_val(global("LC_CTYPE"));
-	if (ccp == null)
+	if (!*ccp)
 		ccp = str_val(global("LANG"));
-	UTFMODE = isuc(ccp);
-#if HAVE_SETLOCALE_CTYPE
-	ccp = setlocale(LC_CTYPE, ccp);
-#if HAVE_LANGINFO_CODESET
-	if (!isuc(ccp))
-		ccp = nl_langinfo(CODESET);
+#if !HAVE_POSIX_UTF8_LOCALE
+	if (!*ccp)
+		ccp = MKSH_DEFAULT_LOCALE;
+#endif
+
+	/* determine codeset used */
+#if HAVE_POSIX_UTF8_LOCALE
+	errno = EINVAL;
+	if (!setlocale(LC_CTYPE, ccp)) {
+		kwarnf(KWF_PREFIX | KWF_FILELINE | KWF_ONEMSG, "could not set locale");
+		return;
+	}
+	ccp = nl_langinfo(CODESET);
+#else
+	/* tacked on to a locale name or just a codeset? */
+	if ((cdp = cstrchr(ccp, '.')))
+		ccp = cdp + 1;
 #endif
-	if (isuc(ccp))
-		UTFMODE = 1;
+
+	/* see whether it’s UTF-8 */
+	UTFMODE = 0;
+	if (!isCh(ccp[0], 'U', 'u') ||
+	    !isCh(ccp[1], 'T', 't') ||
+	    !isCh(ccp[2], 'F', 'f'))
+		return;
+	ccp += isch(ccp[3], '-') ? 4 : 3;
+	if (!isch(*ccp, '8'))
+		return;
+	++ccp;
+	/* verify nothing untoward trails the string */
+#if !HAVE_POSIX_UTF8_LOCALE
+	if (cdp) {
+		/* tacked onto a locale name */
+		if (*ccp && !isch(*ccp, '@'))
+			return;
+	} else
+	  /* OSX has a "UTF-8" locale… */
 #endif
+	/* just a codeset so require EOS */
+	  if (*ccp != '\0')
+		return;
+	/* positively identified as UTF-8 */
+	UTFMODE = 1;
+}
+#endif
+
+#if !HAVE_MEMMOVE
+void *
+rpl_memmove(void *dst, const void *src, size_t len)
+{
+	const unsigned char *s = src;
+	unsigned char *d = dst;
 
-	if (Flag(FPOSIX) && UTFMODE && !old_utfmode)
-		warningf(true, "early locale tracking enabled UTF-8 mode while in POSIX mode, you are now noncompliant");
+	if (len) {
+		if (src < dst) {
+			s += len;
+			d += len;
+			while (len--)
+				*--d = *--s;
+		} else
+			while (len--)
+				*d++ = *s++;
+	}
+	return (dst);
 }
 #endif
+
+const char *
+ksh_getwd(void)
+{
+#if HAVE_GET_CURRENT_DIR_NAME
+	free_gnu_gcdn(getwd_bufp);
+	getwd_bufp = get_current_dir_name();
+	if (getwd_bufp && !mksh_abspath(getwd_bufp)) {
+		free_gnu_gcdn(getwd_bufp);
+		getwd_bufp = NULL;
+		errno = EACCES;
+	}
+#else
+ redo:
+	if (getcwd(getwd_bufp, getwd_bufsz)) {
+		if (mksh_abspath(getwd_bufp))
+			goto done;
+		errno = EACCES;
+		return (NULL);
+	}
+	if (errno == ERANGE) {
+		if (notoktomul(getwd_bufsz, 2U)) {
+			errno = ENAMETOOLONG;
+			return (NULL);
+		}
+		getwd_bufsz <<= 1;
+		getwd_bufp = aresize(getwd_bufp, getwd_bufsz + 1U, APERM);
+		getwd_bufp[getwd_bufsz] = '\0';
+		goto redo;
+	}
+	return (NULL);
+ done:
+#endif
+	return (getwd_bufp);
+}
+
+#ifdef DEBUG
+#if 1 /* enforce, 0 to find out */
+static void
+reclim_trace(void)
+{
+	struct env *ep = e;
+	unsigned int nenv = 0;
+
+ count:
+	if (++nenv == 128U) {
+		kerrf(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_PREFIX |
+		    KWF_FILELINE | KWF_ONEMSG | KWF_NOERRNO,
+		    "\"mksh/Build.sh -g\" recursion limit exceeded");
+	} else if (ep) {
+		ep = ep->oenv;
+		goto count;
+	}
+}
+#elif defined(SIG_ATOMIC_MAX) && (SIG_ATOMIC_MAX >= 0x7FFF)
+#include <syslog.h>
+static void reclim_atexit(void);
+
+static volatile sig_atomic_t reclim_v = 0;
+static kby reclim_warned = 0;
+
+static void
+reclim_trace(void)
+{
+	struct env *ep = e;
+	unsigned int nenv = 0;
+
+	if (!reclim_v)
+		atexit(reclim_atexit);
+ count:
+	if (nenv == SIG_ATOMIC_MAX) {
+		syslog(LOG_WARNING, "reclim_trace: SIG_ATOMIC_MAX reached");
+		reclim_v = SIG_ATOMIC_MAX;
+		return;
+	}
+	if (!++nenv) {
+		--nenv;
+		if (!reclim_warned) {
+			syslog(LOG_WARNING, "reclim_trace: %s reached",
+			    "UINT_MAX");
+			reclim_warned = 1;
+		}
+	} else if (ep) {
+		ep = ep->oenv;
+		goto count;
+	}
+
+	if ((mbiHUGE_U)nenv >= (mbiHUGE_U)(SIG_ATOMIC_MAX)) {
+		if (!reclim_warned) {
+			syslog(LOG_WARNING, "reclim_trace: %s reached",
+			    "SIG_ATOMIC_MAX");
+			reclim_warned = 1;
+		}
+		reclim_v = SIG_ATOMIC_MAX;
+		return;
+	}
+	if ((sig_atomic_t)nenv > reclim_v)
+		reclim_v = (sig_atomic_t)nenv;
+}
+
+static void
+reclim_atexit(void)
+{
+	unsigned int nenv = (unsigned int)reclim_v;
+
+	if (nenv > 32U)
+		syslog(LOG_DEBUG, "max recursion limit: %u", nenv);
+}
+#else /* missing suitable large sig_atomic_t */
+static void
+reclim_trace(void)
+{
+}
+#endif /* missing suitable large sig_atomic_t */
+#endif /* DEBUG */
--- /dev/null
+++ mksh-59c/mbsdcc.h
@@ -0,0 +1,258 @@
+/*-
+ * MirBSD ISO C compiler toolkit (macros for mbsdint.h and others)
+ *
+ * © mirabilos Ⓕ CC0 or The MirOS Licence (MirBSD)
+ */
+
+#ifndef SYSKERN_MBSDCC_H
+#define SYSKERN_MBSDCC_H "$MirOS: src/bin/mksh/mbsdcc.h,v 1.15 2025/12/08 01:25:11 tg Exp $"
+
+/*
+ * Note: this header uses the SIZE_MAX (or similar) definitions
+ * from <basetsd.h> or <limits.h> if present, so either include
+ * these before this header or include "mbsdint.h", which fixes
+ * up the corresponding definition.
+ *
+ * Place the inclusion of this after <sys/cdefs.h> or something
+ * that pulls it, for example <sys/types.h>.
+ *
+ * Furthermore, either include <stdlib.h> for abort(3), or pro‐
+ * vide an mbccABEND macro (preferred).
+ */
+
+#if !defined(_KERNEL) && !defined(_STANDALONE)
+#include <stddef.h>
+#else
+#include <sys/stddef.h>
+#endif
+
+/* mbccABEND is called by mbsd*.h and should be provided by the user */
+#ifndef mbccABEND
+#define mbccABEND(reasonstr)	abort()
+#endif
+
+/* monkey-patch known-bad offsetof versions */
+#if (defined(__KLIBC__) || defined(__dietlibc__)) && \
+    ((defined(__GNUC__) && (__GNUC__ > 3)) || defined(__NWCC__))
+#undef offsetof
+#define offsetof(struc,memb)	__builtin_offsetof(struc, memb)
+#endif
+
+/* should be defined by <sys/cdefs.h> already */
+#ifndef __predict_true
+#if defined(__GNUC__) && (__GNUC__ >= 3) /* 2.96, but keep it simple here */
+#define __predict_true(exp)	__builtin_expect(!!(exp), 1)
+#define __predict_false(exp)	__builtin_expect(!!(exp), 0)
+#else
+#define __predict_true(exp)	(!!(exp))
+#define __predict_false(exp)	(!!(exp))
+#endif /* !GCC 3.x */
+#endif /* ndef(__predict_true) */
+
+/* mbsdint.h replaces this with mbiSIZE_MAX */
+#undef mbccSIZE_MAX
+#if defined(SIZE_MAX)
+#define mbccSIZE_MAX		((size_t)(SIZE_MAX)
+#elif defined(SIZE_T_MAX)
+#define mbccSIZE_MAX		((size_t)(SIZE_T_MAX)
+#elif defined(MAXSIZE_T)
+#define mbccSIZE_MAX		((size_t)(MAXSIZE_T)
+#else
+#define mbccSIZE_MAX		((size_t)~(size_t)0)
+#endif
+
+#ifdef __cplusplus
+#define mbcextern		extern "C"
+/* for headers (BSD __BEGIN_DECLS/__END_DECLS) */
+#define mbcextern_beg		extern "C" {
+#define mbcextern_end		}
+#else
+#define mbcextern		extern
+#define mbcextern_beg
+#define mbcextern_end
+#endif
+
+/* compiler warning pragmas, NOP for other compilers */
+#ifdef _MSC_VER
+/* push, suppress space-separated listed warning numbers */
+#define mbmscWd(d)		__pragma(warning(push)) \
+				__pragma(warning(disable: d))
+/* suppress for only the next line */
+#define mbmscWs(d)		__pragma(warning(suppress: d))
+/* pop from mbmscWd */
+#define mbmscWpop		__pragma(warning(pop))
+#else
+#define mbmscWd(d)
+#define mbmscWs(d)
+#define mbmscWpop
+#endif
+
+/* in-expression compile-time check evaluating to 0 */
+#ifdef __cplusplus
+template<bool> struct mbccChkExpr_sa;
+template<> struct mbccChkExpr_sa<true> { typedef int Type; };
+#define mbccChkExpr(test)	(static_cast<mbccChkExpr_sa<!!(0+(test))>::Type>(0))
+#else
+#define mbccChkExpr(test)	mbmscWs(4116) \
+				(sizeof(struct { unsigned int (mbccChkExpr):((0+(test)) ? 1 : -1); }) * 0)
+#endif
+
+/* ensure value x is a constant expression */
+#ifdef __cplusplus
+template<bool,bool> struct mbccCEX_sa;
+template<> struct mbccCEX_sa<true,false> { typedef int Type; };
+template<> struct mbccCEX_sa<false,true> { typedef int Type; };
+#define mbccCEX(x)		(static_cast<mbccCEX_sa<!!(0+(x)), !(0+(x))>::Type>(0) + (x))
+#else
+#define mbccCEX(x)		mbmscWs(4116) \
+				(sizeof(struct { unsigned int (mbccCEX):(((0+(x)) && 1) + 1); }) * 0 + (x))
+#endif
+
+/* flexible array member */
+#if defined(MBSDCC_H_NO_FAM)
+#define mbccFAMslot(type,memb)	type memb[1] mbmscWs(4820)
+#elif defined(__cplusplus)
+#ifdef __cpp_flexible_array_members
+#define mbccFAMslot(type,memb)	type memb[]
+#elif defined(__GNUC__) || defined(__clang__) || defined(_MSC_VER)
+#define mbccFAMslot(type,memb)	type memb[0] mbmscWs(4200 4820)
+#else
+#define mbccFAMslot(type,memb)	type memb[1] mbmscWs(4820)
+#endif
+#elif (defined(__STDC_VERSION__) && ((__STDC_VERSION__) >= 199901L))
+#define mbccFAMslot(type,memb)	type memb[]
+#elif defined(__GNUC__)
+#define mbccFAMslot(type,memb)	type memb[0] mbmscWs(4200 4820)
+#else
+#define mbccFAMslot(type,memb)	type memb[1] mbmscWs(4820) /* SOL */
+#endif
+#define mbccFAMsz_i(t,memb,sz)	/*private*/ (size_t)(offsetof(t, memb) + (size_t)sz)
+/* compile-time constant */
+#define mbccFAMSZ(struc,memb,sz) ((size_t)( \
+	    mbccChkExpr(mbccSIZE_MAX - sizeof(struc) > mbccCEX((size_t)(sz))) + \
+	    (mbccFAMsz_i(struc, memb, (sz)) > sizeof(struc) ? \
+	     mbccFAMsz_i(struc, memb, (sz)) : sizeof(struc))))
+/* run-time */
+#define mbccFAMsz(struc,memb,sz) ((size_t)( \
+	    !(mbccSIZE_MAX - sizeof(struc) > (size_t)(sz)) ? \
+	    (mbccABEND("mbccFAMsz: " mbccS(sz) " too large for " mbccS(struc) "." mbccS(memb)), 0) : \
+	    (mbccFAMsz_i(struc, memb, (sz)) > sizeof(struc) ? \
+	     mbccFAMsz_i(struc, memb, (sz)) : sizeof(struc))))
+/* example:
+ *
+ * struct s {
+ *	int type;
+ *	mbccFAMslot(char, label);	// like char label[…];
+ * };
+ * struct t {
+ *	int count;
+ *	mbccFAMslot(time_t, value);
+ * };
+ * union fixed_s {
+ *	struct s s;
+ *	char storage[mbccFAMSZ(struct s, label, 28)];
+ * };
+ * struct s *sp = malloc(mbccFAMsz(struct s, label, strlen(labelvar) + 1U));
+ * struct t *tp = malloc(mbccFAMsz(struct t, value, sizeof(time_t[cnt])));
+ * tp->count = cnt;
+ * struct s *np = malloc(mbccFAMSZ(struct s, label, sizeof("myname")));
+ * memcpy(np->label, "myname", sizeof("myname"));
+ * static union fixed_s preallocated;
+ * preallocated.s.label[0] = '\0';
+ * somefunc((struct s *)&preallocated);
+ */
+
+/* field sizeof */
+#if defined(__cplusplus)
+/* TODO: add better way on CFrustFrust once it has one */
+#define mbccFSZ(struc,memb)	(sizeof(((struc *)0)->memb))
+#elif (defined(__STDC_VERSION__) && ((__STDC_VERSION__) >= 199901L))
+#define mbccFSZ(struc,memb)	(sizeof(((struc){0}).memb))
+#else
+#define mbccFSZ(struc,memb)	(sizeof(((struc *)0)->memb))
+#endif
+
+/* stringification with expansion */
+#define mbccS(x)		#x
+#define mbccS2(x)		mbccS(x)
+
+/* compile-time assertions */
+#undef mbccCTA
+#if defined(__WATCOMC__) && !defined(__WATCOM_CPLUSPLUS__)
+				/* “Comparison result always 0” */
+#define mbccCTA_wb		_Pragma("warning 124 5")
+				/*XXX no pop so set to visible info */
+#define mbccCTA_we		_Pragma("warning 124 4")
+#else
+#define mbccCTA_wb		/* nothing */
+#define mbccCTA_we		/* nothing */
+#endif
+#if defined(__cplusplus)
+#ifdef __cpp_static_assert
+#define mbccCTA(fldn,cond)	static_assert(cond, mbccS(fldn))
+#endif
+#elif (defined(__STDC_VERSION__) && ((__STDC_VERSION__) >= 202311L))
+#define mbccCTA(fldn,cond)	static_assert(cond, mbccS(fldn))
+#elif (defined(__STDC_VERSION__) && ((__STDC_VERSION__) >= 201112L))
+#define mbccCTA(fldn,cond)	_Static_assert(cond, mbccS(fldn))
+#elif defined(__GNUC__) && \
+    ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))
+#define mbccCTA(fldn,cond)	__extension__ _Static_assert(cond, mbccS(fldn))
+#endif
+#ifndef mbccCTA
+/* single assertion for macros (with fldn prefixed, cond parenthesised) */
+#define mbccCTA(fldn,cond)	unsigned int fldn:(cond ? 1 : -1)
+/* begin/end assertion block */
+#define mbCTA_BEG(name)		struct ctassert_ ## name { mbccCTA_wb	\
+					int _ctabeg /* plus user semicolon */
+#define mbCTA_END(name)			int _ctaend;			\
+				};					\
+				struct ctassert2 ## name {		\
+					char t[sizeof(struct ctassert_ ## name) > 1U ? 1 : -1]; \
+				mbccCTA_we } /* semicolon provided by user */
+#else
+/* nothing, but syntax-check equally to manual compile-time assert macro */
+#define mbCTA_BEG(name)		struct ctassert_ ## name { mbccCTA_wb	\
+					char t[2];			\
+				} /* semicolon provided by user */
+#define mbCTA_END(name)		struct ctassert2 ## name {		\
+					char t[sizeof(struct ctassert_ ## name) > 1U ? 1 : -1]; \
+				mbccCTA_we } /* semicolon provided by user */
+#endif
+/* single assertion */
+#define mbCTA(name,cond)	mbccCTA(cta_ ## name, (cond))
+
+/* nil pointer constant */
+#if (defined(__cplusplus) && (__cplusplus >= 201103L)) || \
+    (defined(__STDC_VERSION__) && ((__STDC_VERSION__) >= 202311L))
+#define mbnil			nullptr
+#elif defined(__GNUG__)
+#define mbnil			__null
+#elif defined(__cplusplus)
+#define mbnil			(size_t)0UL	/* wtf, why? */
+#else
+#define mbnil			(void *)0UL
+#endif
+
+/* præfix to avoid -Wunused-result when it really cannot be helped */
+#ifdef _FORTIFY_SOURCE
+/* workaround via https://stackoverflow.com/a/64407070/2171120 */
+#define SHIKATANAI		(void)!
+#else
+#define SHIKATANAI		(void)
+#endif
+
+/* macros to cast to unsigned {int,long,long long} with ingress type check */
+
+/* …from (un)signed integers */
+#define mbito(x)		((x)|0)	/* only does integer promotions */
+#define mbitou(x)		((unsigned)((x)|0))
+#define mbitolu(x)		((unsigned long)((x)|0))
+#define mbitollu(x)		((unsigned long long)((x)|0))
+/* …from floats or integers */
+#define mbfto(x)		(+(x))
+#define mbftou(x)		((unsigned)+(x))
+#define mbftolu(x)		((unsigned long)+(x))
+#define mbftollu(x)		((unsigned long long)+(x))
+
+#endif /* !SYSKERN_MBSDCC_H */
--- /dev/null
+++ mksh-59c/mbsdint.h
@@ -0,0 +1,1245 @@
+/*-
+ * MirBSD sanitisation attempt for C integer madness
+ *
+ * © mirabilos Ⓕ CC0 or The MirOS Licence (MirBSD)
+ */
+
+#ifndef SYSKERN_MBSDINT_H
+#define SYSKERN_MBSDINT_H "$MirOS: src/bin/mksh/mbsdint.h,v 1.62 2025/12/08 01:25:11 tg Exp $"
+
+/*
+ * cpp defines to set:
+ *
+ * -DHAVE_INTCONSTEXPR_RSIZE_MAX=1 if RSIZE_MAX is an integer constexpr
+ * -DHAVE_OFF_T=0 if you do not supply the POSIX off_t typedef
+ *
+ * -DMBSDINT_H_SMALL_SYSTEM=1 (or 2) to shorten some macros, for old systems
+ * or -DMBSDINT_H_SMALL_SYSTEM=3 in very tiny systems, e.g. 16-bit
+ *
+ * -DMBSDINT_H_MBIPTR_IS_SIZET=0 stop assuming mbiPTR is size_t-ranged
+ * -DMBSDINT_H_MBIPTR_IN_LARGE=0 mbiPTR fits mbiHUGE but no longer mbiLARGE
+ * -DMBSDINT_H_WANT_LONG_IN_SIZET=0 don’t ensure long fits in size_t (16-bit)
+ *
+ * -DMBSDINT_H_WANT_PTR_IN_SIZET (breaks some) ensure pointers fit in size_t
+ * -DMBSDINT_H_WANT_SIZET_IN_LONG (breaks LLP64) ensure size_t fits in long
+ * -DMBSDINT_H_WANT_INT32=1 to ensure unsigned int has at least 32 bit width
+ * -DMBSDINT_H_WANT_LRG64=1 to ensure mbiLARGE_U has at least 64 bit width
+ * -DMBSDINT_H_WANT_SAFEC=1 to ensure mbiSAFECOMPLEMENT==1
+ * (these trigger extra compile-time assertion checks)
+ *
+ * This header always includes <limits.h> so please ensure any possible
+ * prerequisites as well as all existing of the following headers…
+ *	<sys/types.h>		// from POSIX
+ *	<basetsd.h>		// on Windows®
+ *	<inttypes.h>		// some pre-C99
+ *	<stdint.h>		// ISO C99
+ *	"mbsdcc.h"		// from this directory, in this order
+ * … are included before this header, for full functionality.
+ */
+
+#if !defined(_KERNEL) && !defined(_STANDALONE)
+#include <limits.h>
+#else
+#include <sys/cdefs.h>
+#include <sys/limits.h>
+#endif
+
+#ifdef _MSC_VER
+#pragma warning(push)
+#pragma warning(disable:4127 4146 4296)
+#endif
+
+#if !defined(MBSDINT_H_SMALL_SYSTEM) || ((MBSDINT_H_SMALL_SYSTEM) < 1)
+#undef MBSDINT_H_SMALL_SYSTEM	/* in case someone defined it as 0 */
+#define mbiMASK_bitmax		279
+#elif (MBSDINT_H_SMALL_SYSTEM) >= 2
+#define mbiMASK_bitmax		75
+#else
+#define mbiMASK_bitmax		93
+#endif
+
+#if defined(HAVE_INTCONSTEXPR_RSIZE_MAX) && ((HAVE_INTCONSTEXPR_RSIZE_MAX) < 1)
+#undef HAVE_INTCONSTEXPR_RSIZE_MAX
+#endif
+#if defined(MBSDINT_H_WANT_PTR_IN_SIZET) && ((MBSDINT_H_WANT_PTR_IN_SIZET) < 1)
+#undef MBSDINT_H_WANT_PTR_IN_SIZET
+#endif
+#if defined(MBSDINT_H_WANT_SIZET_IN_LONG) && ((MBSDINT_H_WANT_SIZET_IN_LONG) < 1)
+#undef MBSDINT_H_WANT_SIZET_IN_LONG
+#endif
+#if defined(MBSDINT_H_WANT_INT32) && ((MBSDINT_H_WANT_INT32) < 1)
+#undef MBSDINT_H_WANT_INT32
+#endif
+#if defined(MBSDINT_H_WANT_LRG64) && ((MBSDINT_H_WANT_LRG64) < 1)
+#undef MBSDINT_H_WANT_LRG64
+#endif
+#if defined(MBSDINT_H_WANT_SAFEC) && ((MBSDINT_H_WANT_SAFEC) < 1)
+#undef MBSDINT_H_WANT_SAFEC
+#endif
+
+#ifndef HAVE_OFF_T
+#define HAVE_OFF_T 1
+#endif
+#ifndef MBSDINT_H_MBIPTR_IS_SIZET
+#define MBSDINT_H_MBIPTR_IS_SIZET 1
+#endif
+#ifndef MBSDINT_H_MBIPTR_IN_LARGE
+#define MBSDINT_H_MBIPTR_IN_LARGE 1
+#endif
+#ifndef MBSDINT_H_WANT_LONG_IN_SIZET
+#define MBSDINT_H_WANT_LONG_IN_SIZET 1
+#endif
+
+/* expose SIZE_MAX if possible and provided, not guessed */
+#ifndef SIZE_MAX
+#if defined(SIZE_T_MAX)
+#define SIZE_MAX		SIZE_T_MAX
+#elif defined(MAXSIZE_T)
+#define SIZE_MAX		MAXSIZE_T
+#endif
+#endif
+
+/* expose POSIX SSIZE_MAX and ssize_t on Win32 */
+#if defined(SIZE_MAX) && !defined(SSIZE_MAX) && \
+    defined(MINSSIZE_T) && defined(MAXSSIZE_T) && !defined(ssize_t)
+#define SSIZE_MIN		MINSSIZE_T
+#define SSIZE_MAX		MAXSSIZE_T
+#define ssize_t			SSIZE_T
+#endif
+
+/* special compile-time assertions */
+#define mbiCTA_TYPE_MBIT(nm,ty)	mbccCTA(ctatm_ ## nm, \
+	(sizeof(ty) <= (mbiMASK_bitmax / (CHAR_BIT))))
+
+/* kinds of types */
+	/* compile-time and runtime */
+#define mbiTYPE_ISF(type)	(!!(0+(int)(2 * (type)0.5)))
+#define mbiTYPE_ISU(type)	((type)-1 > (type)0)
+/* limits of types */
+#define mbiTYPE_UMAX(type)	((type)~(type)0U)
+#define mbiTYPE_UBITS(type)	mbiMASK_BITS(mbiTYPE_UMAX(type))
+/* calculation by Hallvard B Furuseth (via comp.lang.c), ≤ 2039 bit */
+#define mbiMASK__lh(maxv)	((maxv) / ((maxv) % 255 + 1) / 255 % 255 * 8)
+#define mbiMASK__rh(maxv)	(7 - 86 / (mbito(maxv) % 255 + 12))
+/* mbiMASK_BITS everywhere except #if uses (castless) mbiMASK__BITS */
+#define mbiMASK__BITS(maxv)	(mbiMASK__lh(maxv) + mbiMASK__rh(maxv))
+#define mbiMASK__type(maxv)	(mbiMASK__lh(maxv) + (int)mbiMASK__rh(maxv))
+#define mbiMASK_BITS(maxv)	(0U + (unsigned int)mbiMASK__type(maxv))
+
+/* ensure v is a positive (2ⁿ-1) number (n>0), up to 279 (or less) bits */
+#define mbiMASK_CHK(v)		mbmscWd(4296) \
+				((v) > 0 ? mbi_maskchk31_1((v)) : 0) \
+				mbmscWpop
+#define mbi_maskchks(v,m,o,n)	(v <= m ? o : ((v & m) == m) && n)
+#define mbi_maskchk31s(v,n)	mbi_maskchks(v, 0x7FFFFFFFUL, \
+				    mbi_maskchk16(v), n)
+#define mbi_maskchk15s(v,n)	mbi_maskchks(v, 0x7FFFUL, \
+				    mbi_maskchk8(v), n)
+#if !defined(MBSDINT_H_SMALL_SYSTEM)
+#define mbi_maskchk31_1(v)	mbi_maskchk31s(v, mbi_maskchk31_2(v >> 31))
+#define mbi_maskchk31_2(v)	mbi_maskchk31s(v, mbi_maskchk31_3(v >> 31))
+#define mbi_maskchk31_3(v)	mbi_maskchk31s(v, mbi_maskchk31_4(v >> 31))
+#define mbi_maskchk31_4(v)	mbi_maskchk31s(v, mbi_maskchk31_5(v >> 31))
+#define mbi_maskchk31_5(v)	mbi_maskchk31s(v, mbi_maskchk31_6(v >> 31))
+#define mbi_maskchk31_6(v)	mbi_maskchk31s(v, mbi_maskchk31_7(v >> 31))
+#define mbi_maskchk31_7(v)	mbi_maskchk31s(v, mbi_maskchk31_8(v >> 31))
+#define mbi_maskchk31_8(v)	mbi_maskchk31s(v, mbi_maskchk31_9(v >> 31))
+#elif (MBSDINT_H_SMALL_SYSTEM) >= 2
+#define mbi_maskchk31_1(v)	mbi_maskchk15s(v, mbi_maskchk15_2(v >> 15))
+#define mbi_maskchk15_2(v)	mbi_maskchk15s(v, mbi_maskchk15_3(v >> 15))
+#define mbi_maskchk15_3(v)	mbi_maskchk15s(v, mbi_maskchk15_4(v >> 15))
+#define mbi_maskchk15_4(v)	mbi_maskchk15s(v, mbi_maskchk15_9(v >> 15))
+#define mbi_maskchk15_9(v)	(v <= 0x7FFFUL && mbi_maskchk8(v))
+#else /* (MBSDINT_H_SMALL_SYSTEM) == 1 */
+#define mbi_maskchk31_1(v)	mbi_maskchk31s(v, mbi_maskchk31_8(v >> 31))
+#define mbi_maskchk31_8(v)	mbi_maskchk31s(v, mbi_maskchk31_9(v >> 31))
+#endif
+#define mbi_maskchk31_9(v)	(v <= 0x7FFFFFFFUL && mbi_maskchk16(v))
+#define mbi_maskchk16(v)	mbi_maskchks(v, 0xFFFFU, \
+				    mbi_maskchk8(v), mbi_maskchk8(v >> 16))
+#define mbi_maskchk8(v)		mbi_maskchks(v, 0xFFU, \
+				    mbi_maskchk4(v), mbi_maskchk4(v >> 8))
+#define mbi_maskchk4(v)		mbi_maskchks(v, 0xFU, \
+				    mbi_maskchkF(v), mbi_maskchkF(v >> 4))
+#define mbi_maskchkF(v)		(v == 0xF || v == 7 || v == 3 || v == 1 || !v)
+
+/* limit maximum object size so we can express pointer differences w/o UB */
+#if defined(HAVE_INTCONSTEXPR_RSIZE_MAX)
+/* trust but verify operating environment */
+#define mbiRSZCHK	RSIZE_MAX
+#define mbiSIZE_MAX	((size_t)RSIZE_MAX)
+#elif !defined(SIZE_MAX)
+#ifdef PTRDIFF_MAX
+#define mbiRSZCHK	PTRDIFF_MAX
+#define mbiSIZE_MAX	((size_t)PTRDIFF_MAX)
+#elif defined(MBSDINT_H_SMALL_SYSTEM) && ((MBSDINT_H_SMALL_SYSTEM) >= 3)
+#define mbiSIZE_MAX	mbiTYPE_UMAX(size_t)
+#else
+#define mbiSIZE_MAX	((size_t)(mbiTYPE_UMAX(size_t) >> 1))
+#endif /* !PTRDIFF_MAX !MBSDINT_H_SMALL_SYSTEM>=3 */
+#elif !defined(PTRDIFF_MAX) || \
+    (((SIZE_MAX) == (PTRDIFF_MAX)) && ((SIZE_MAX) > 0x7FFFFFFFUL))
+#if defined(MBSDINT_H_SMALL_SYSTEM) && ((MBSDINT_H_SMALL_SYSTEM) >= 3)
+#define mbiSIZE_MAX	((size_t)SIZE_MAX)
+#else
+#define mbiSIZE_MAX	((size_t)(((size_t)SIZE_MAX) >> 1))
+#endif
+#elif (SIZE_MAX) < (PTRDIFF_MAX)
+#define mbiSIZE_MAX	((size_t)SIZE_MAX)
+#else
+#define mbiRSZCHK	PTRDIFF_MAX
+#define mbiSIZE_MAX	((size_t)PTRDIFF_MAX)
+#endif
+/* size_t must fit %lu/%llu if there is no %zu support yet */
+#if (defined(__STDC_VERSION__) && ((__STDC_VERSION__) >= 199901L)) || \
+    (defined(__cplusplus) && ((__cplusplus) >= 201103L))
+#define mbiSIZE_S	ssize_t
+#define mbiSIZE_U	size_t
+#define mbiSIZE_P(c)	"z" #c
+#elif defined(ULLONG_MAX) && defined(SIZE_MAX) && ((SIZE_MAX) > (ULONG_MAX))
+#define mbiSIZE_S	long long
+#define mbiSIZE_U	unsigned long long
+#define mbiSIZE_P(c)	"ll" #c
+#else
+#define mbiSIZE_S	long
+#define mbiSIZE_U	unsigned long
+#define mbiSIZE_P(c)	"l" #c
+#endif
+#define mbiSIZE_PV(v)	((mbiSIZE_U)(v))
+#ifndef SSIZE_MAX
+#undef mbiSIZE_S
+#endif
+
+/* update mbsdcc.h definition */
+#undef mbccSIZE_MAX
+#define mbccSIZE_MAX	mbiSIZE_MAX
+
+/* largest integer (need not fit a full wide pointer, e.g. on CHERI) */
+#if defined(INTMAX_MIN)
+#define mbiHUGE_S		intmax_t
+#define mbiHUGE_S_MIN		INTMAX_MIN
+#define mbiHUGE_S_MAX		INTMAX_MAX
+#define mbiHUGE_U		uintmax_t
+#define mbiHUGE_U_MAX		UINTMAX_MAX
+#define mbiHUGE_P(c)		PRI ## c ## MAX
+#elif defined(LLONG_MIN)
+#define mbiHUGE_S		long long
+#define mbiHUGE_S_MIN		LLONG_MIN
+#define mbiHUGE_S_MAX		LLONG_MAX
+#define mbiHUGE_U		unsigned long long
+#define mbiHUGE_U_MAX		ULLONG_MAX
+#define mbiHUGE_P(c)		"ll" #c
+#elif defined(_UI64_MAX) && (mbiMASK__BITS(_UI64_MAX) > mbiMASK__BITS(ULONG_MAX))
+#define mbiHUGE_S		signed __int64
+#define mbiHUGE_S_MIN		_I64_MIN
+#define mbiHUGE_S_MAX		_I64_MAX
+#define mbiHUGE_U		unsigned __int64
+#define mbiHUGE_U_MAX		_UI64_MAX
+#define mbiHUGE_UBITS		64
+#define mbiHUGE_P(c)		"I64" #c
+#elif defined(QUAD_MIN)
+#define mbiHUGE_S		quad_t
+#define mbiHUGE_S_MIN		QUAD_MIN
+#define mbiHUGE_S_MAX		QUAD_MAX
+#define mbiHUGE_U		u_quad_t
+#define mbiHUGE_U_MAX		UQUAD_MAX
+#define mbiHUGE_UBITS		64
+#define mbiHUGE_P(c)		"q" #c
+#else /* C89? */
+#define mbiHUGE_S		long
+#define mbiHUGE_S_MIN		LONG_MIN
+#define mbiHUGE_S_MAX		LONG_MAX
+#define mbiHUGE_U		unsigned long
+#define mbiHUGE_U_MAX		ULONG_MAX
+#define mbiHUGE_P(c)		"l" #c
+#endif
+/* larger than int, 64 bit if possible; storage fits off_t, size_t */
+#if (mbiMASK__BITS(ULONG_MAX) >= 64)
+#define mbiLARGE_S		long
+#define mbiLARGE_S_MIN		LONG_MIN
+#define mbiLARGE_S_MAX		LONG_MAX
+#define mbiLARGE_U		unsigned long
+#define mbiLARGE_U_MAX		ULONG_MAX
+#define mbiLARGE_P(c)		"l" #c
+#elif defined(ULLONG_MAX) && (mbiMASK__BITS(ULLONG_MAX) >= 64)
+#define mbiLARGE_S		long long
+#define mbiLARGE_S_MIN		LLONG_MIN
+#define mbiLARGE_S_MAX		LLONG_MAX
+#define mbiLARGE_U		unsigned long long
+#define mbiLARGE_U_MAX		ULLONG_MAX
+#define mbiLARGE_P(c)		"ll" #c
+#elif defined(_UI64_MAX) && (mbiMASK__BITS(_UI64_MAX) >= 64)
+#define mbiLARGE_S		signed __int64
+#define mbiLARGE_S_MIN		_I64_MIN
+#define mbiLARGE_S_MAX		_I64_MAX
+#define mbiLARGE_U		unsigned __int64
+#define mbiLARGE_U_MAX		_UI64_MAX
+#define mbiLARGE_UBITS		64
+#define mbiLARGE_P(c)		"I64" #c
+#elif defined(UQUAD_MAX)
+#define mbiLARGE_S		quad_t
+#define mbiLARGE_S_MIN		QUAD_MIN
+#define mbiLARGE_S_MAX		QUAD_MAX
+#define mbiLARGE_U		u_quad_t
+#define mbiLARGE_U_MAX		UQUAD_MAX
+#define mbiLARGE_UBITS		64
+#define mbiLARGE_P(c)		"q" #c
+#else
+#define mbiLARGE_S		mbiHUGE_S
+#define mbiLARGE_S_MIN		mbiHUGE_S_MIN
+#define mbiLARGE_S_MAX		mbiHUGE_S_MAX
+#define mbiLARGE_U		mbiHUGE_U
+#define mbiLARGE_U_MAX		mbiHUGE_U_MAX
+#define mbiLARGE_P		mbiHUGE_P
+#endif
+/* integer type that can keep the base address of a pointer */
+#ifdef __CHERI__
+#define mbiPTR_U		ptraddr_t
+#define mbiPTR_U_MAX		mbiTYPE_UMAX(mbiPTR_U)
+#elif defined(UINTPTR_MAX)
+#define mbiPTR_U		uintptr_t
+#define mbiPTR_U_MAX		UINTPTR_MAX
+#else
+#define mbiPTR_U		size_t
+#define mbiPTR_U_MAX		mbiTYPE_UMAX(mbiPTR_U)
+#endif
+#if MBSDINT_H_MBIPTR_IS_SIZET || \
+    (!defined(__CHERI__) && !defined(UINTPTR_MAX))
+#define mbiPTR_P		mbiSIZE_P
+#define mbiPTR_PV(v)		((mbiSIZE_U)(v))
+#elif MBSDINT_H_MBIPTR_IN_LARGE
+#define mbiPTR_P		mbiLARGE_P
+#define mbiPTR_PV(v)		((mbiLARGE_U)(v))
+#else
+#define mbiPTR_P		mbiHUGE_P
+#define mbiPTR_PV(v)		((mbiHUGE_U)(v))
+#endif
+
+#undef mbiSAFECOMPLEMENT
+#if ((SCHAR_MIN) == -(SCHAR_MAX))
+#define mbiSAFECOMPLEMENT 0
+#elif ((SCHAR_MIN)+1 == -(SCHAR_MAX))
+#define mbiSAFECOMPLEMENT 1
+#endif
+
+#ifndef MBSDINT_H_SKIP_CTAS
+/* compile-time assertions for mbsdint.h */
+mbCTA_BEG(mbsdint_h);
+ /* compiler (in)sanity, from autoconf */
+#define mbiCTf(x) 'x'
+ mbCTA(xlc6, mbiCTf(a) == 'x');
+#undef mbiCTf
+ mbCTA(osf4, '\x00' == 0);
+ /* C types */
+ mbCTA(basic_char_smask, mbiMASK_CHK(SCHAR_MAX));
+ mbCTA(basic_char_umask, mbiMASK_CHK(UCHAR_MAX));
+ mbCTA(basic_char,
+	sizeof(char) == 1 && (CHAR_BIT) >= 7 && (CHAR_BIT) < 2040 &&
+	(((CHAR_MAX) == (SCHAR_MAX) && (CHAR_MIN) == (SCHAR_MIN)) ||
+	 ((CHAR_MAX) == (UCHAR_MAX) && (CHAR_MIN) == 0)) &&
+	mbiTYPE_UMAX(unsigned char) == (UCHAR_MAX) &&
+	sizeof(signed char) == 1 &&
+	sizeof(unsigned char) == 1 &&
+	mbiTYPE_UBITS(unsigned char) >= 8 && (SCHAR_MIN) < 0 &&
+	((SCHAR_MIN) == -(SCHAR_MAX) || (SCHAR_MIN)+1 == -(SCHAR_MAX)) &&
+	mbiTYPE_UBITS(unsigned char) == mbitou(CHAR_BIT));
+#ifndef mbiSAFECOMPLEMENT
+ mbCTA(basic_char_complement, /* fail */ 0);
+#endif
+ mbiCTA_TYPE_MBIT(short, short);
+ mbiCTA_TYPE_MBIT(ushort, unsigned short);
+ mbiCTA_TYPE_MBIT(int, int);
+ mbiCTA_TYPE_MBIT(uint, unsigned int);
+ mbiCTA_TYPE_MBIT(long, long);
+ mbiCTA_TYPE_MBIT(ulong, unsigned long);
+#ifdef LLONG_MIN
+ mbiCTA_TYPE_MBIT(llong, long long);
+ mbiCTA_TYPE_MBIT(ullong, unsigned long long);
+#endif
+#ifdef INTMAX_MIN
+ mbiCTA_TYPE_MBIT(imax, intmax_t);
+ mbiCTA_TYPE_MBIT(uimax, uintmax_t);
+#endif
+#ifdef _UI64_MAX
+ mbiCTA_TYPE_MBIT(ms_i64, signed __int64);
+ mbiCTA_TYPE_MBIT(ms_ui64, unsigned __int64);
+#endif
+#ifdef QUAD_MIN
+ mbiCTA_TYPE_MBIT(ucb_sq, quad_t);
+ mbiCTA_TYPE_MBIT(ucb_uq, u_quad_t);
+#endif
+ mbiCTA_TYPE_MBIT(shuge, mbiHUGE_S);
+ mbiCTA_TYPE_MBIT(uhuge, mbiHUGE_U);
+ mbiCTA_TYPE_MBIT(slarge, mbiLARGE_S);
+ mbiCTA_TYPE_MBIT(ularge, mbiLARGE_U);
+ mbiCTA_TYPE_MBIT(uptr, mbiPTR_U);
+ mbCTA(basic_short_smask, mbiMASK_CHK(SHRT_MAX));
+ mbCTA(basic_short_umask, mbiMASK_CHK(USHRT_MAX));
+ mbCTA(basic_short,
+	mbiTYPE_UMAX(unsigned short) == (USHRT_MAX) &&
+	mbiTYPE_UBITS(unsigned short) >= 16 && (SHRT_MIN) < 0 &&
+	((SHRT_MIN) == -(SHRT_MAX) || (SHRT_MIN)+1 == -(SHRT_MAX)) &&
+	((SHRT_MIN) == -(SHRT_MAX)) == ((SCHAR_MIN) == -(SCHAR_MAX)) &&
+	sizeof(short) >= sizeof(signed char) &&
+	sizeof(unsigned short) >= sizeof(unsigned char) &&
+	mbiMASK_BITS(SHRT_MAX) >= mbiMASK_BITS(SCHAR_MAX) &&
+	mbiMASK_BITS(SHRT_MAX) < mbiMASK_BITS(mbiHUGE_S_MAX) &&
+	mbiMASK_BITS(USHRT_MAX) >= mbiMASK_BITS(UCHAR_MAX) &&
+	mbiMASK_BITS(USHRT_MAX) < mbiMASK_BITS(mbiHUGE_U_MAX) &&
+	sizeof(short) == sizeof(unsigned short));
+ mbCTA(basic_int_smask, mbiMASK_CHK(INT_MAX));
+ mbCTA(basic_int_umask, mbiMASK_CHK(UINT_MAX));
+ mbCTA(basic_int,
+	mbiTYPE_UMAX(unsigned int) == (UINT_MAX) &&
+	mbiTYPE_UBITS(unsigned int) >= 16 && (INT_MIN) < 0 &&
+	((INT_MIN) == -(INT_MAX) || (INT_MIN)+1 == -(INT_MAX)) &&
+	((INT_MIN) == -(INT_MAX)) == ((SCHAR_MIN) == -(SCHAR_MAX)) &&
+	sizeof(int) >= sizeof(short) &&
+	sizeof(unsigned int) >= sizeof(unsigned short) &&
+	mbiMASK_BITS(INT_MAX) >= mbiMASK_BITS(SHRT_MAX) &&
+	mbiMASK_BITS(INT_MAX) <= mbiMASK_BITS(mbiHUGE_S_MAX) &&
+	mbiMASK_BITS(UINT_MAX) >= mbiMASK_BITS(USHRT_MAX) &&
+	mbiMASK_BITS(UINT_MAX) <= mbiMASK_BITS(mbiHUGE_U_MAX) &&
+	sizeof(int) == sizeof(unsigned int));
+ mbCTA(basic_long_smask, mbiMASK_CHK(LONG_MAX));
+ mbCTA(basic_long_umask, mbiMASK_CHK(ULONG_MAX));
+ mbCTA(basic_long,
+	mbiTYPE_UMAX(unsigned long) == (ULONG_MAX) &&
+	mbiTYPE_UBITS(unsigned long) >= 32 && (LONG_MIN) < 0 &&
+	((LONG_MIN) == -(LONG_MAX) || (LONG_MIN)+1 == -(LONG_MAX)) &&
+	((LONG_MIN) == -(LONG_MAX)) == ((SCHAR_MIN) == -(SCHAR_MAX)) &&
+	sizeof(long) >= sizeof(int) &&
+	sizeof(unsigned long) >= sizeof(unsigned int) &&
+	mbiMASK_BITS(LONG_MAX) >= mbiMASK_BITS(INT_MAX) &&
+	mbiMASK_BITS(LONG_MAX) <= mbiMASK_BITS(mbiHUGE_S_MAX) &&
+	mbiMASK_BITS(ULONG_MAX) >= mbiMASK_BITS(UINT_MAX) &&
+	mbiMASK_BITS(ULONG_MAX) <= mbiMASK_BITS(mbiHUGE_U_MAX) &&
+	sizeof(long) == sizeof(unsigned long));
+ /* __int64 is MSC */
+#ifdef _UI64_MAX
+ mbCTA(basic_i64_smask, mbiMASK_CHK(_I64_MAX));
+ mbCTA(basic_i64_umask, mbiMASK_CHK(_UI64_MAX));
+ mbCTA(basic_i64,
+	!mbiTYPE_ISF(unsigned __int64) && !mbiTYPE_ISF(signed __int64) &&
+	mbiTYPE_ISU(unsigned __int64) && !mbiTYPE_ISU(signed __int64) &&
+	mbiTYPE_UMAX(unsigned __int64) == (_UI64_MAX) &&
+	mbiTYPE_UBITS(unsigned __int64) == 64 && (_I64_MIN) < 0 &&
+	((_I64_MIN)+1 == -(_I64_MAX)) &&
+	((_I64_MIN) == -(_I64_MAX)) == ((SCHAR_MIN) == -(SCHAR_MAX)) &&
+	sizeof(signed __int64) >= sizeof(long) &&
+	sizeof(unsigned __int64) >= sizeof(unsigned long) &&
+	sizeof(signed __int64) <= sizeof(mbiHUGE_S) &&
+	sizeof(unsigned __int64) <= sizeof(mbiHUGE_U) &&
+	mbiMASK_BITS(_I64_MAX) >= mbiMASK_BITS(LONG_MAX) &&
+	mbiMASK_BITS(_I64_MAX) <= mbiMASK_BITS(mbiHUGE_S_MAX) &&
+	mbiMASK_BITS(_UI64_MAX) >= mbiMASK_BITS(ULONG_MAX) &&
+	mbiMASK_BITS(_UI64_MAX) <= mbiMASK_BITS(mbiHUGE_U_MAX) &&
+	sizeof(signed __int64) == sizeof(unsigned __int64));
+#endif
+ /* legacy 4.4BSD extension, not cpp-safe, no suffixed constants */
+#ifdef QUAD_MIN
+ mbCTA(basic_quad_smask, mbiMASK_CHK(QUAD_MAX));
+ mbCTA(basic_quad_umask, mbiMASK_CHK(UQUAD_MAX));
+ mbCTA(basic_quad,
+	!mbiTYPE_ISF(u_quad_t) && !mbiTYPE_ISF(quad_t) &&
+	mbiTYPE_ISU(u_quad_t) && !mbiTYPE_ISU(quad_t) &&
+	mbiTYPE_UMAX(u_quad_t) == (UQUAD_MAX) &&
+	mbiTYPE_UBITS(u_quad_t) == 64 && (QUAD_MIN) < 0 &&
+	((QUAD_MIN)+1 == -(QUAD_MAX)) &&
+	((QUAD_MIN) == -(QUAD_MAX)) == ((SCHAR_MIN) == -(SCHAR_MAX)) &&
+	sizeof(quad_t) >= sizeof(long) &&
+	sizeof(u_quad_t) >= sizeof(unsigned long) &&
+	sizeof(quad_t) <= sizeof(mbiHUGE_S) &&
+	sizeof(u_quad_t) <= sizeof(mbiHUGE_U) &&
+	mbiMASK_BITS(QUAD_MAX) >= mbiMASK_BITS(LONG_MAX) &&
+	mbiMASK_BITS(QUAD_MAX) <= mbiMASK_BITS(mbiHUGE_S_MAX) &&
+	mbiMASK_BITS(UQUAD_MAX) >= mbiMASK_BITS(ULONG_MAX) &&
+	mbiMASK_BITS(UQUAD_MAX) <= mbiMASK_BITS(mbiHUGE_U_MAX) &&
+	sizeof(quad_t) == sizeof(u_quad_t));
+#endif
+ /* common pre-C99 extension now standardised */
+#ifdef LLONG_MIN
+ mbCTA(basic_llong_smask, mbiMASK_CHK(LLONG_MAX));
+ mbCTA(basic_llong_umask, mbiMASK_CHK(ULLONG_MAX));
+ mbCTA(basic_llong,
+	mbiTYPE_UMAX(unsigned long long) == (ULLONG_MAX) &&
+	mbiTYPE_UBITS(unsigned long long) >= 64 && (LLONG_MIN) < 0 &&
+	((LLONG_MIN) == -(LLONG_MAX) || (LLONG_MIN)+1 == -(LLONG_MAX)) &&
+	((LLONG_MIN) == -(LLONG_MAX)) == ((SCHAR_MIN) == -(SCHAR_MAX)) &&
+	sizeof(long long) >= sizeof(long) &&
+	sizeof(unsigned long long) >= sizeof(unsigned long) &&
+	sizeof(long long) <= sizeof(mbiHUGE_S) &&
+	sizeof(unsigned long long) <= sizeof(mbiHUGE_U) &&
+	mbiMASK_BITS(LLONG_MAX) >= mbiMASK_BITS(LONG_MAX) &&
+	mbiMASK_BITS(LLONG_MAX) <= mbiMASK_BITS(mbiHUGE_S_MAX) &&
+	mbiMASK_BITS(ULLONG_MAX) >= mbiMASK_BITS(ULONG_MAX) &&
+	mbiMASK_BITS(ULLONG_MAX) <= mbiMASK_BITS(mbiHUGE_U_MAX) &&
+	sizeof(long long) == sizeof(unsigned long long));
+#endif
+ /* {,u}intmax_t are C99 */
+#ifdef INTMAX_MIN
+ mbCTA(basic_imax_smask, mbiMASK_CHK(INTMAX_MAX));
+ mbCTA(basic_imax_umask, mbiMASK_CHK(UINTMAX_MAX));
+ mbCTA(basic_imax,
+	!mbiTYPE_ISF(uintmax_t) && !mbiTYPE_ISF(intmax_t) &&
+	mbiTYPE_ISU(uintmax_t) && !mbiTYPE_ISU(intmax_t) &&
+	mbiTYPE_UMAX(uintmax_t) == (UINTMAX_MAX) &&
+	mbiTYPE_UBITS(uintmax_t) >= 32 && (INTMAX_MIN) < 0 &&
+	((INTMAX_MIN) == -(INTMAX_MAX) || (INTMAX_MIN)+1 == -(INTMAX_MAX)) &&
+	((INTMAX_MIN) == -(INTMAX_MAX)) == ((SCHAR_MIN) == -(SCHAR_MAX)) &&
+	sizeof(intmax_t) >= sizeof(long) &&
+	sizeof(uintmax_t) >= sizeof(unsigned long) &&
+	sizeof(intmax_t) <= sizeof(mbiHUGE_S) &&
+	sizeof(uintmax_t) <= sizeof(mbiHUGE_U) &&
+	mbiMASK_BITS(INTMAX_MAX) >= mbiMASK_BITS(LONG_MAX) &&
+	mbiMASK_BITS(INTMAX_MAX) <= mbiMASK_BITS(mbiHUGE_S_MAX) &&
+	mbiMASK_BITS(UINTMAX_MAX) >= mbiMASK_BITS(ULONG_MAX) &&
+	mbiMASK_BITS(UINTMAX_MAX) <= mbiMASK_BITS(mbiHUGE_U_MAX) &&
+	sizeof(intmax_t) == sizeof(uintmax_t));
+#ifdef LLONG_MIN
+ mbCTA(basic_imax_llong,
+	mbiMASK_BITS(INTMAX_MAX) >= mbiMASK_BITS(LLONG_MAX) &&
+	mbiMASK_BITS(UINTMAX_MAX) >= mbiMASK_BITS(ULLONG_MAX) &&
+	sizeof(intmax_t) >= sizeof(long long) &&
+	sizeof(uintmax_t) >= sizeof(unsigned long long));
+#endif /* INTMAX_MIN && LLONG_MIN */
+#ifdef _I64_MIN
+ mbCTA(basic_imax_i64,
+	mbiMASK_BITS(INTMAX_MAX) >= mbiMASK_BITS(_I64_MAX) &&
+	mbiMASK_BITS(UINTMAX_MAX) >= mbiMASK_BITS(_UI64_MAX) &&
+	sizeof(intmax_t) >= sizeof(signed __int64) &&
+	sizeof(uintmax_t) >= sizeof(unsigned __int64));
+#endif /* INTMAX_MIN && _I64_MIN */
+#ifdef QUAD_MIN
+ mbCTA(basic_imax_quad,
+	mbiMASK_BITS(INTMAX_MAX) >= mbiMASK_BITS(QUAD_MAX) &&
+	mbiMASK_BITS(UINTMAX_MAX) >= mbiMASK_BITS(UQUAD_MAX) &&
+	sizeof(intmax_t) >= sizeof(quad_t) &&
+	sizeof(uintmax_t) >= sizeof(u_quad_t));
+#endif /* INTMAX_MIN && QUAD_MIN */
+#endif /* INTMAX_MIN */
+ /* mbi{LARGE,HUGE}_{S,U} are defined by us */
+ mbCTA(basic_large_smask, mbiMASK_CHK(mbiLARGE_S_MAX));
+ mbCTA(basic_large_umask, mbiMASK_CHK(mbiLARGE_U_MAX));
+ mbCTA(basic_large,
+	!mbiTYPE_ISF(mbiLARGE_U) && !mbiTYPE_ISF(mbiLARGE_S) &&
+	mbiTYPE_ISU(mbiLARGE_U) && !mbiTYPE_ISU(mbiLARGE_S) &&
+	mbiTYPE_UMAX(mbiLARGE_U) == (mbiLARGE_U_MAX) && (mbiLARGE_S_MIN) < 0 &&
+	((mbiLARGE_S_MIN) == -(mbiLARGE_S_MAX) || (mbiLARGE_S_MIN)+1 == -(mbiLARGE_S_MAX)) &&
+	((mbiLARGE_S_MIN) == -(mbiLARGE_S_MAX)) == ((SCHAR_MIN) == -(SCHAR_MAX)) &&
+	sizeof(mbiLARGE_S) >= sizeof(long) &&
+	sizeof(mbiLARGE_U) >= sizeof(unsigned long) &&
+	mbiMASK_BITS(mbiLARGE_S_MAX) >= mbiMASK_BITS(LONG_MAX) &&
+	mbiMASK_BITS(mbiLARGE_S_MAX) <= mbiMASK_BITS(mbiHUGE_S_MAX) &&
+	mbiMASK_BITS(mbiLARGE_U_MAX) >= mbiMASK_BITS(ULONG_MAX) &&
+	mbiMASK_BITS(mbiLARGE_U_MAX) <= mbiMASK_BITS(mbiHUGE_U_MAX) &&
+	sizeof(mbiLARGE_S) == sizeof(mbiLARGE_U));
+ mbCTA(basic_huge_smask, mbiMASK_CHK(mbiHUGE_S_MAX));
+ mbCTA(basic_huge_umask, mbiMASK_CHK(mbiHUGE_U_MAX));
+ mbCTA(basic_huge,
+	!mbiTYPE_ISF(mbiHUGE_U) && !mbiTYPE_ISF(mbiHUGE_S) &&
+	mbiTYPE_ISU(mbiHUGE_U) && !mbiTYPE_ISU(mbiHUGE_S) &&
+	mbiTYPE_UMAX(mbiHUGE_U) == (mbiHUGE_U_MAX) && (mbiHUGE_S_MIN) < 0 &&
+	((mbiHUGE_S_MIN) == -(mbiHUGE_S_MAX) || (mbiHUGE_S_MIN)+1 == -(mbiHUGE_S_MAX)) &&
+	((mbiHUGE_S_MIN) == -(mbiHUGE_S_MAX)) == ((SCHAR_MIN) == -(SCHAR_MAX)) &&
+	sizeof(mbiHUGE_S) >= sizeof(mbiLARGE_S) &&
+	sizeof(mbiHUGE_U) >= sizeof(mbiLARGE_U) &&
+	mbiMASK_BITS(mbiHUGE_S_MAX) >= mbiMASK_BITS(LONG_MAX) &&
+	mbiMASK_BITS(mbiHUGE_U_MAX) >= mbiMASK_BITS(ULONG_MAX) &&
+	sizeof(mbiHUGE_S) == sizeof(mbiHUGE_U));
+ /* off_t is POSIX, with no _MIN/_MAX constants (WTF‽) */
+#if HAVE_OFF_T
+ mbCTA(basic_offt,
+	sizeof(off_t) >= sizeof(int) &&
+	sizeof(off_t) <= sizeof(mbiLARGE_S) &&
+	!mbiTYPE_ISF(off_t) && !mbiTYPE_ISU(off_t));
+#endif
+ /* ptrdiff_t is C */
+ mbCTA(basic_ptrdifft,
+	sizeof(ptrdiff_t) >= sizeof(int) &&
+	sizeof(ptrdiff_t) <= sizeof(mbiHUGE_S) &&
+	!mbiTYPE_ISF(ptrdiff_t) && !mbiTYPE_ISU(ptrdiff_t));
+#ifdef PTRDIFF_MAX
+ mbCTA(basic_ptrdifft_mask, mbiMASK_CHK(PTRDIFF_MAX));
+ mbCTA(basic_ptrdifft_max,
+	mbiMASK_BITS(PTRDIFF_MAX) >= mbiMASK_BITS(INT_MAX) &&
+	mbiMASK_BITS(PTRDIFF_MAX) <= mbiMASK_BITS(mbiHUGE_S_MAX) &&
+	((mbiHUGE_S)(PTRDIFF_MAX) == (mbiHUGE_S)(ptrdiff_t)(PTRDIFF_MAX)));
+#endif
+ /* size_t is C */
+ mbCTA(basic_sizet,
+	sizeof(size_t) >= sizeof(unsigned int) &&
+	sizeof(size_t) <= sizeof(mbiHUGE_U) &&
+	!mbiTYPE_ISF(size_t) && mbiTYPE_ISU(size_t) &&
+	mbiTYPE_UBITS(size_t) >= mbiMASK_BITS(UINT_MAX) &&
+	mbiTYPE_UBITS(size_t) <= mbiMASK_BITS(mbiHUGE_U_MAX));
+#ifdef SIZE_MAX
+ mbCTA(basic_sizet_mask, mbiMASK_CHK(SIZE_MAX));
+ mbCTA(basic_sizet_max,
+	mbiMASK_BITS(SIZE_MAX) >= mbiMASK_BITS(USHRT_MAX) &&
+	mbiMASK_BITS(SIZE_MAX) <= mbiTYPE_UBITS(size_t) &&
+	((mbiHUGE_U)(SIZE_MAX) == (mbiHUGE_U)(size_t)(SIZE_MAX)));
+#endif
+ /* mbiSIZE_S is only defined if ssize_t is defined */
+ /* but consistently mapped, no extra checks here */
+ mbCTA(basic_sizet_P,
+	sizeof(size_t) <= sizeof(mbiSIZE_U) &&
+	mbiTYPE_UBITS(size_t) <= mbiTYPE_UBITS(mbiSIZE_U));
+ /* note mbiSIZE_MAX is not necessarily a bitmask (0b0*1+) */
+#ifdef mbiRSZCHK
+ mbCTA(smax_range, (0U + (mbiRSZCHK)) <= (0U + (mbiHUGE_U_MAX)));
+ mbCTA(smax_check, ((mbiHUGE_U)(mbiRSZCHK) == (mbiHUGE_U)(size_t)(mbiRSZCHK)));
+#undef mbiRSZCHK
+#endif
+ /* ssize_t is POSIX (or mapped from Win32 SSIZE_T by us) */
+#ifdef SSIZE_MAX
+ mbCTA(basic_ssizet_mask, mbiMASK_CHK(SSIZE_MAX));
+ mbCTA(basic_ssizet,
+	sizeof(ssize_t) == sizeof(size_t) &&
+	!mbiTYPE_ISF(ssize_t) && !mbiTYPE_ISU(ssize_t) &&
+	mbiMASK_BITS(SSIZE_MAX) >= mbiMASK_BITS(INT_MAX) &&
+	mbiMASK_BITS(SSIZE_MAX) <= mbiMASK_BITS(mbiHUGE_S_MAX) &&
+	((mbiHUGE_S)(SSIZE_MAX) == (mbiHUGE_S)(ssize_t)(SSIZE_MAX)) &&
+	mbiMASK_BITS(SSIZE_MAX) < mbiTYPE_UBITS(size_t));
+#ifdef SSIZE_MIN
+ mbCTA(basic_ssizet_min,
+	(SSIZE_MIN) < 0 &&
+	((SSIZE_MIN) == -(SSIZE_MAX) || (SSIZE_MIN)+1 == -(SSIZE_MAX)) &&
+	((SSIZE_MIN) == -(SSIZE_MAX)) == ((SCHAR_MIN) == -(SCHAR_MAX)));
+#endif
+#ifdef SIZE_MAX
+ mbCTA(basic_ssizet_sizet,
+	mbiMASK_BITS(SSIZE_MAX) <= mbiMASK_BITS(SIZE_MAX));
+#endif /* SSIZE_MAX && SIZE_MAX */
+#endif /* SSIZE_MAX */
+ /* uintptr_t is C99 */
+#if defined(UINTPTR_MAX) && !defined(__CHERI__)
+ mbCTA(basic_uintptr_mask, mbiMASK_CHK(UINTPTR_MAX));
+ mbCTA(basic_uintptr,
+	sizeof(uintptr_t) >= sizeof(ptrdiff_t) &&
+	sizeof(uintptr_t) >= sizeof(size_t) &&
+	sizeof(uintptr_t) <= sizeof(mbiHUGE_U) &&
+	!mbiTYPE_ISF(uintptr_t) && mbiTYPE_ISU(uintptr_t) &&
+	mbiMASK_BITS(UINTPTR_MAX) == mbiTYPE_UBITS(uintptr_t) &&
+	((mbiHUGE_U)(UINTPTR_MAX) == (mbiHUGE_U)(uintptr_t)(UINTPTR_MAX)) &&
+	mbiTYPE_UBITS(uintptr_t) >= mbiMASK_BITS(UINT_MAX) &&
+	((mbiHUGE_U)(UINTPTR_MAX) >= (mbiHUGE_U)(mbiSIZE_MAX)) &&
+	mbiTYPE_UBITS(uintptr_t) >= mbiTYPE_UBITS(size_t) &&
+	mbiTYPE_UBITS(uintptr_t) <= mbiMASK_BITS(mbiHUGE_U_MAX));
+#ifdef PTRDIFF_MAX
+ mbCTA(basic_uintptr_pdt,
+	mbiMASK_BITS(UINTPTR_MAX) >= mbiMASK_BITS(PTRDIFF_MAX));
+#endif /* UINTPTR_MAX && PTRDIFF_MAX */
+#ifdef SIZE_MAX
+ mbCTA(basic_uintptr_sizet,
+	mbiMASK_BITS(UINTPTR_MAX) >= mbiMASK_BITS(SIZE_MAX));
+#endif /* UINTPTR_MAX && SIZE_MAX */
+#endif /* UINTPTR_MAX */
+ /* mbiPTR_U is defined by us */
+ mbCTA(basic_mbiptr_mask, mbiMASK_CHK(mbiPTR_U_MAX));
+ mbCTA(basic_mbiptr,
+	sizeof(mbiPTR_U) >= sizeof(ptrdiff_t) &&
+	sizeof(mbiPTR_U) >= sizeof(size_t) &&
+	sizeof(mbiPTR_U) <= sizeof(mbiHUGE_U) &&
+	!mbiTYPE_ISF(mbiPTR_U) && mbiTYPE_ISU(mbiPTR_U) &&
+	mbiMASK_BITS(mbiPTR_U_MAX) == mbiTYPE_UBITS(mbiPTR_U) &&
+	((mbiHUGE_U)(mbiPTR_U_MAX) == (mbiHUGE_U)(mbiPTR_U)(mbiPTR_U_MAX)) &&
+	mbiTYPE_UBITS(mbiPTR_U) >= mbiMASK_BITS(UINT_MAX) &&
+	((mbiHUGE_U)(mbiPTR_U_MAX) >= (mbiHUGE_U)(mbiSIZE_MAX)) &&
+	mbiTYPE_UBITS(mbiPTR_U) >= mbiTYPE_UBITS(size_t) &&
+	mbiTYPE_UBITS(mbiPTR_U) <= mbiMASK_BITS(mbiHUGE_U_MAX));
+#ifdef PTRDIFF_MAX
+ mbCTA(basic_mbiptr_pdt,
+	mbiMASK_BITS(mbiPTR_U_MAX) >= mbiMASK_BITS(PTRDIFF_MAX));
+#endif
+#ifdef SIZE_MAX
+ mbCTA(basic_mbiptr_sizet,
+	mbiMASK_BITS(mbiPTR_U_MAX) >= mbiMASK_BITS(SIZE_MAX));
+#endif
+ /* C99 §6.2.6.2(1, 2, 6) permits M ≤ N, but M < N is normally desired */
+ /* here require signed/unsigned types to have same width (M=N-1) */
+ mbCTA(vbits_char, mbiMASK_BITS(UCHAR_MAX) == mbiMASK_BITS(SCHAR_MAX) + 1U);
+ mbCTA(vbits_short, mbiMASK_BITS(USHRT_MAX) == mbiMASK_BITS(SHRT_MAX) + 1U);
+ mbCTA(vbits_int, mbiMASK_BITS(UINT_MAX) == mbiMASK_BITS(INT_MAX) + 1U);
+ mbCTA(vbits_long, mbiMASK_BITS(ULONG_MAX) == mbiMASK_BITS(LONG_MAX) + 1U);
+#ifdef UQUAD_MAX
+ mbCTA(vbits_quad, mbiMASK_BITS(UQUAD_MAX) == mbiMASK_BITS(QUAD_MAX) + 1U);
+#endif
+#ifdef _UI64_MAX
+ mbCTA(vbits_i64, mbiMASK_BITS(_UI64_MAX) == mbiMASK_BITS(_I64_MAX) + 1U);
+#endif
+#ifdef LLONG_MIN
+ mbCTA(vbits_llong, mbiMASK_BITS(ULLONG_MAX) == mbiMASK_BITS(LLONG_MAX) + 1U);
+#endif
+#ifdef INTMAX_MIN
+ mbCTA(vbits_imax, mbiMASK_BITS(UINTMAX_MAX) == mbiMASK_BITS(INTMAX_MAX) + 1U);
+#endif
+ mbCTA(vbits_large, mbiMASK_BITS(mbiLARGE_U_MAX) == mbiMASK_BITS(mbiLARGE_S_MAX) + 1U);
+ mbCTA(vbits_huge, mbiMASK_BITS(mbiHUGE_U_MAX) == mbiMASK_BITS(mbiHUGE_S_MAX) + 1U);
+#ifdef SSIZE_MAX
+ mbCTA(vbits_size, mbiTYPE_UBITS(size_t) == mbiMASK_BITS(SSIZE_MAX) + 1U);
+#endif
+#if !defined(__CHERI__) && defined(UINTPTR_MAX) && defined(PTRDIFF_MAX)
+ mbCTA(vbits_iptr, mbiMASK_BITS(UINTPTR_MAX) == mbiMASK_BITS(PTRDIFF_MAX) + 1U);
+#endif
+ /* do size_t and ulong fit each other? */
+ mbCTA(sizet_minint, sizeof(size_t) >= sizeof(int)); /* for 16-bit systems */
+#if MBSDINT_H_WANT_LONG_IN_SIZET
+ mbCTA(sizet_minlong, sizeof(size_t) >= sizeof(long));
+#endif
+#ifdef MBSDINT_H_WANT_SIZET_IN_LONG
+ /* with MBSDINT_H_WANT_PTR_IN_SIZET breaks LLP64 (e.g. Windows/amd64) */
+ mbCTA(sizet_inulong, sizeof(size_t) <= sizeof(long));
+#endif
+ /* this is as documented above */
+ mbCTA(sizet_inlarge, sizeof(size_t) <= sizeof(mbiLARGE_U));
+#if MBSDINT_H_MBIPTR_IN_LARGE
+ mbCTA(mbiPTRU_inlarge,
+	sizeof(mbiPTR_U) <= sizeof(mbiLARGE_U) &&
+	mbiTYPE_UBITS(mbiPTR_U) <= mbiMASK_BITS(mbiLARGE_U_MAX));
+#endif
+ /* assume ptrdiff_t and (s)size_t will fit each other */
+ mbCTA(sizet_ptrdiff, sizeof(size_t) == sizeof(ptrdiff_t));
+#ifdef SSIZE_MAX
+ mbCTA(sizet_ssize, sizeof(size_t) == sizeof(ssize_t));
+#endif
+ /* also mbiPTR_U, to rule out certain weird machines */
+#if MBSDINT_H_MBIPTR_IS_SIZET
+ /* note mbiMASK_BITS(SIZE_MAX) could be smaller still */
+ mbCTA(sizet_mbiPTRU,
+	sizeof(mbiPTR_U) == sizeof(size_t) &&
+	mbiTYPE_UBITS(mbiPTR_U) == mbiTYPE_UBITS(size_t));
+ /* more loose bonus check */
+#if defined(UINTPTR_MAX) && !defined(__CHERI__)
+ mbCTA(sizet_uintptr, sizeof(size_t) == sizeof(uintptr_t));
+#endif
+#endif
+ /* user-requested extra checks */
+#ifdef MBSDINT_H_WANT_INT32
+ /* guaranteed by POSIX */
+ mbCTA(user_int32, mbiTYPE_UBITS(unsigned int) >= 32);
+#endif
+#ifdef MBSDINT_H_WANT_LRG64
+ /* guaranteed if 64-bit types even exist */
+ mbCTA(user_lrg64, mbiTYPE_UBITS(mbiLARGE_U) >= 64);
+#endif
+#ifdef MBSDINT_H_WANT_SAFEC
+ /* true as of C23 and POSIX unless INT_MIN == -INT_MAX */
+ mbCTA(user_safec, mbiSAFECOMPLEMENT == 1);
+#endif
+#ifdef MBSDINT_H_WANT_PTR_IN_SIZET
+ /* require pointers and size_t to take up the same amount of space */
+ mbCTA(sizet_voidptr, sizeof(size_t) == sizeof(void *));
+ mbCTA(sizet_sintptr, sizeof(size_t) == sizeof(int *));
+ mbCTA(sizet_funcptr, sizeof(size_t) == sizeof(void (*)(void)));
+#endif
+ /* C23 §5.2.4.2.1 */
+#ifdef CHAR_WIDTH
+ mbCTA(char_width, (CHAR_WIDTH) == (CHAR_BIT));
+#endif
+#ifdef SCHAR_WIDTH
+ mbCTA(schar_width, (SCHAR_WIDTH) == (CHAR_BIT));
+#endif
+#ifdef UCHAR_WIDTH
+ mbCTA(uchar_width, (UCHAR_WIDTH) == (CHAR_BIT));
+#endif
+#ifdef USHRT_WIDTH
+ mbCTA(ushrt_width, (USHRT_WIDTH) == mbiMASK_BITS(USHRT_MAX));
+#endif
+#ifdef SHRT_WIDTH
+ mbCTA(shrt_width, (SHRT_WIDTH) == mbiMASK_BITS(SHRT_MAX) + 1);
+#endif
+#ifdef UINT_WIDTH
+ mbCTA(uint_width, (UINT_WIDTH) == mbiMASK_BITS(UINT_MAX));
+#endif
+#ifdef INT_WIDTH
+ mbCTA(int_width, (INT_WIDTH) == mbiMASK_BITS(INT_MAX) + 1);
+#endif
+#ifdef ULONG_WIDTH
+ mbCTA(ulong_width, (ULONG_WIDTH) == mbiMASK_BITS(ULONG_MAX));
+#endif
+#ifdef LONG_WIDTH
+ mbCTA(long_width, (LONG_WIDTH) == mbiMASK_BITS(LONG_MAX) + 1);
+#endif
+#ifdef ULLONG_WIDTH
+ mbCTA(ullong_width, (ULLONG_WIDTH) == mbiMASK_BITS(ULLONG_MAX));
+#endif
+#ifdef LLONG_WIDTH
+ mbCTA(llong_width, (LLONG_WIDTH) == mbiMASK_BITS(LLONG_MAX) + 1);
+#endif
+#ifdef UINTMAX_WIDTH
+ mbCTA(uintmax_width, (UINTMAX_WIDTH) == mbiMASK_BITS(UINTMAX_MAX));
+#endif
+#ifdef INTMAX_WIDTH
+ mbCTA(intmax_width, (INTMAX_WIDTH) == mbiMASK_BITS(INTMAX_MAX) + 1);
+#endif
+#if defined(UINTPTR_WIDTH) && !defined(__CHERI__)
+ mbCTA(uintptr_width, (UINTPTR_WIDTH) == mbiMASK_BITS(UINTPTR_MAX));
+#endif
+#ifdef PTRDIFF_WIDTH
+ mbCTA(ptrdiff_width, (PTRDIFF_WIDTH) == mbiMASK_BITS(PTRDIFF_MAX) + 1);
+#endif
+#ifdef SIZE_WIDTH
+ mbCTA(size_width, (SIZE_WIDTH) == mbiMASK_BITS(SIZE_MAX));
+#endif
+ /* require nōn-cpp (possibly casted) match if extant */
+#ifdef mbiHUGE_UBITS
+ mbCTA(huge_width, mbiHUGE_UBITS == mbiMASK_BITS(mbiHUGE_U_MAX));
+#endif
+#ifdef mbiLARGE_UBITS
+ mbCTA(large_width, mbiLARGE_UBITS == mbiMASK_BITS(mbiLARGE_U_MAX));
+#endif
+mbCTA_END(mbsdint_h);
+#endif /* !MBSDINT_H_SKIP_CTAS */
+
+/* cpp-safe */
+#ifndef mbiHUGE_UBITS
+#define mbiHUGE_UBITS		mbiMASK__BITS(mbiHUGE_U_MAX)
+#endif
+#ifndef mbiLARGE_UBITS
+#define mbiLARGE_UBITS		mbiMASK__BITS(mbiLARGE_U_MAX)
+#endif
+
+/*
+ * various arithmetics, optionally masking
+ *
+ * key:	O = operation, A = arithmetic, M* = masking
+ *	U = unsigned, S = signed, m = magnitude
+ *	VZ = sign (Vorzeichen) 0=positive, 1=negative
+ *	v = value, ut = unsigned type, st = signed type
+ *	w = boolean value, y = yes, n = no
+ *	CA = checked arithmetics, define mbiCfail
+ *	K = k̲alculations for unsigned mantwo’s k̲omplement vars
+ *
+ * masks: HM = half mask (e.g. FM >> 1 or 0x7FFFFFFFUL) == signed _MAX
+ *	  FM = full mask (e.g. ULONG_MAX or 0xFFFFFFFFUL)
+ *	  tM = type-corresponding mask
+ *
+ * Where unsigned values may be either properly unsigned or
+ * manually represented in two’s complement (M=N-1 above),
+ * signed values are the host’s (and conversion will UB for
+ * -type_MAX-1 unless the mbiSAFECOMPLEMENT macro equals 1,
+ * so don’t use that without checking), unsigned magnitude
+ * ranges from 0 to type_MAX+1, and we try pretty hard to
+ * avoid UB and (with one exception, below, casting into
+ * smaller-width signed integers, checked to be safe, but
+ * an implementation-defined signal may be raised, which is
+ * then the caller’s responsibility) IB.
+ *
+ * Every operation needs casting applied, as the type may
+ * have lower integer rank than (signed) int. Additional
+ * masking may be used to guarantee bit widths in the result
+ * even when the executing type is wider. In conversion, if
+ * unsigned and magnitude both exist, magnitude is halfmasked
+ * whereas unsigned is fullmasked with vz acting as neg op.
+ */
+
+/* basic building blocks: arithmetics cast helpers */
+
+#define mbiUI(v)		(0U + (v))
+#define mbiUP(ut,v)		mbiUI((ut)(v))
+#define mbiSP(st,v)		(0 + ((st)(v)))
+
+/* basic building blocks: masking */
+
+#define mbiMM(ut,tM,v)		mbiOU(ut, (v), &, (tM))
+
+/* basic building blocks: operations */
+
+/* 1. unary */
+#define mbiOS1(st,op,v)		((st)(op mbiSP(st, (v))))
+#define mbiOU1(ut,op,v)		((ut)(op mbiUP(ut, (v))))
+#define mbiMO1(ut,tM,op,v)	mbiMM(ut, (tM), mbiOU1(ut, op, (v)))
+
+/* 2. binary or comparison */
+#define mbiOS(st,l,op,r)	((st)(mbiSP(st, (l)) op mbiSP(st, (r))))
+#define mbiOU(ut,l,op,r)	((ut)(mbiUP(ut, (l)) op mbiUP(ut, (r))))
+#define mbiMO(ut,tM,l,op,r)	mbiMM(ut, (tM), mbiOU(ut, (l), op, (r)))
+
+#define mbiOshl(ut,l,r)		((ut)(mbiUP(ut, (l)) << (r)))
+#define mbiOshr(ut,l,r)		((ut)(mbiUP(ut, (l)) >> (r)))
+
+#define mbiCOS(st,l,op,r)	(!!(mbiSP(st, (l)) op mbiSP(st, (r))))
+#define mbiCOU(ut,l,op,r)	(!!(mbiUP(ut, (l)) op mbiUP(ut, (r))))
+
+/* 3. ternary */
+#define mbiOT(t,w,j,n)		((w) ? (t)(j) : (t)(n))
+#define mbiMOT(ut,tM,w,j,n)	mbiMM(ut, (tM), mbiOT(ut, (w), (j), (n)))
+
+/* 4. helpers */
+#define mbiOUneg(ut,v)		mbmscWd(4146) \
+				mbiOU1(ut, -, (v)) \
+				mbmscWpop
+
+/* manual two’s complement in unsigned arithmetics */
+
+/* 1. obtain sign of encoded value */
+#define mbiA_S2VZ(v)		((v) < 0)
+#define mbiA_U2VZ(ut,HM,v)	mbiCOU(ut, (v), >, (HM))
+/* masking */
+#define mbiMA_U2VZ(ut,FM,HM,v)	mbiCOU(ut, mbiMM(ut, (FM), (v)), >, (HM))
+
+/* 2. casting between unsigned(two’s complement) and signed(native) */
+#define mbiA_U2S(ut,st,HM,v)						\
+		mbiOT(st,						\
+		 mbiA_U2VZ(ut, (HM), (v)),				\
+		 mbiOS(st,						\
+		  mbiOS1(st,						\
+		   -,							\
+		   mbiOU1(ut, ~, (v))					\
+		  ),							\
+		  -,							\
+		  1							\
+		 ),							\
+		 (v)							\
+		)
+#define mbiMA_U2S(ut,st,FM,HM,v)					\
+		mbiOT(st,						\
+		 mbiMA_U2VZ(ut, (FM), (HM), (v)),			\
+		 mbiOS(st,						\
+		  mbiOS1(st,						\
+		   -,							\
+		   mbiMO1(ut, (HM), ~, (v))				\
+		  ),							\
+		  -,							\
+		  1							\
+		 ),							\
+		 mbiMM(ut, (HM), (v))					\
+		)
+
+#define mbiA_S2U(ut,st,v)						\
+		mbiOT(ut,						\
+		 mbiA_S2VZ(v),						\
+		 mbiOU1(ut,						\
+		  ~,							\
+		  mbiOS1(st,						\
+		   -,							\
+		   mbiOS(st, (v), +, 1)					\
+		  )							\
+		 ),							\
+		 (v)							\
+		)
+#define mbiMA_S2U(ut,st,FM,v)	mbiMM(ut, (FM), mbiA_S2U(ut, st, (v)))
+
+/* 3. converting from signed(native) or unsigned(manual) to magnitude */
+#define mbiA_S2M(ut,st,v)						\
+		mbiOT(ut,						\
+		 mbiA_S2VZ(v),						\
+		 mbiOU(ut,						\
+		  mbiOS1(st,						\
+		   -,							\
+		   mbiOS(st, (v), +, 1)					\
+		  ),							\
+		  +,							\
+		  1U							\
+		 ),							\
+		 (v)							\
+		)
+#define mbiMA_S2M(ut,st,HM,v)						\
+		mbiOT(ut,						\
+		 mbiA_S2VZ(v),						\
+		 mbiOU(ut,						\
+		  mbiMM(ut, (HM),					\
+		   mbiOS1(st,						\
+		    -,							\
+		    mbiOS(st, (v), +, 1)				\
+		   )							\
+		  ),							\
+		  +,							\
+		  1U							\
+		 ),							\
+		 mbiMM(ut, (HM), (v))					\
+		)
+
+#define mbiA_U2M(ut,HM,v)						\
+		mbiOT(ut,						\
+		 mbiA_U2VZ(ut, (HM), (v)),				\
+		 mbiOUneg(ut, (v)),					\
+		 (v)							\
+		)
+#define mbiMA_U2M(ut,FM,HM,v)						\
+		mbiOT(ut,						\
+		 mbiMA_U2VZ(ut, (FM), (HM), (v)),			\
+		 mbiOU(ut,						\
+		  mbiMO1(ut, (HM), ~, (v)),				\
+		  +,							\
+		  1U							\
+		 ),							\
+		 mbiMM(ut, (HM), (v))					\
+		)
+
+/* 4a. reverse: signbit plus magnitude to signed(native) */
+#define mbiA_VZM2S(ut,st,vz,m)						\
+		mbiOT(st,						\
+		 (vz) && ((m) > 0U),					\
+		 mbiOS(st,						\
+		  mbiOS1(st,						\
+		   -,							\
+		   mbiOU(ut, (m), -, 1U)				\
+		  ),							\
+		  -,							\
+		  1							\
+		 ),							\
+		 (m)							\
+		)
+#define mbiMA_VZM2S(ut,st,FM,HM,vz,m)					\
+		mbiOT(st,						\
+		 (vz) && (mbiMM(ut, (FM), (m)) > 0U),			\
+		 mbiOS(st,						\
+		  mbiOS1(st,						\
+		   -,							\
+		   mbiMO(ut, (HM), (m), -, 1U)				\
+		  ),							\
+		  -,							\
+		  1							\
+		 ),							\
+		 mbiMM(ut, (HM), (m))					\
+		)
+
+/* 4b. same: signbit and magnitude(masked) to unsigned(two’s complement) */
+#define mbiA_VZM2U(ut,HM,vz,m)						\
+		mbiOT(ut,						\
+		 (vz) && ((m) > 0U),					\
+		 mbiOU1(ut,						\
+		  ~,							\
+		  mbiMO(ut, (HM), (m), -, 1U)				\
+		 ),							\
+		 mbiMM(ut, (HM), (m))					\
+		)
+#define mbiMA_VZM2U(ut,FM,HM,vz,m)					\
+		mbiOT(ut,						\
+		 (vz) && (mbiMM(ut, (FM), (m)) > 0U),			\
+		 mbiMO1(ut, (FM),					\
+		  ~,							\
+		  mbiMO(ut, (HM), (m), -, 1U)				\
+		 ),							\
+		 mbiMM(ut, (HM), (m))					\
+		)
+
+/* 4c. signbit and unsigned to unsigned(two’s complement), basically NEG */
+#define mbiA_VZU2U(ut,vz,m)						\
+		mbiOT(ut,						\
+		 (vz),							\
+		 mbiOUneg(ut, (m)),					\
+		 (m)							\
+		)
+#define mbiMA_VZU2U(ut,FM,vz,u)	mbiMM(ut, (FM), mbiA_VZU2U(ut, (vz), (u)))
+
+/*
+ * UB-safe overflow/underflow-checking integer arithmetics
+ *
+ * Before using, #define mbiCfail to the action that should be
+ * taken on check (e.g. "goto fail" or "return (0)"); make sure
+ * to #undef mbiCfail before the end of the function body though!
+ */
+
+/* 0. internal helpers */
+#define mbi__totypeof(templval,dstval)	((1 ? 0 : (templval)) + (dstval))
+#define mbi__halftmax(stmax)		mbi__totypeof(stmax, \
+	(mbi__totypeof(stmax, 1) << (mbiMASK_BITS(stmax) / 2U)))
+/* note: must constant-evaluate even for signed ut */
+#define mbi__halftype(ut)		mbiOT(ut, mbiTYPE_ISU(ut), \
+	mbiOshl(ut, 1U, mbiTYPE_UBITS(ut) / 2U), 2)
+#define mbi__uabovehalftype(ut,a,b)	(((ut)a | (ut)b) >= mbi__halftype(ut))
+/* assert: !(b < 0) */
+#define mbi__sabovehalftype(stmax,a,b)	(a < 0 ? 1 : \
+	(mbi__totypeof(stmax, a) | mbi__totypeof(stmax, b)) >= mbi__halftmax(stmax))
+
+/* 1. for unsigned types checking afterwards is OK */
+#define mbiCAUinc(vl)		mbiCAUadd(vl, 1U)
+#define mbiCAUdec(vl)		mbiCAUsub(vl, 1U)
+#define mbiCAUadd(vl,vr)	do {					\
+	(vl) += mbiUI(vr);						\
+	if (__predict_false(mbiUI(vl) < mbiUI(vr)))			\
+		mbiCfail;						\
+} while (/* CONSTCOND */ 0)
+#define mbiCAUsub(vl,vr)	do {					\
+	if (__predict_false(mbiUI(vl) < mbiUI(vr)))			\
+		mbiCfail;						\
+	(vl) -= mbiUI(vr);						\
+} while (/* CONSTCOND */ 0)
+#define mbiCAUmul(ut,vl,vr)	do {					\
+	if (__predict_false((vr) != 0 &&				\
+	    mbi__uabovehalftype(ut, (vl), (vr)) &&			\
+	    mbiOU(ut, mbiTYPE_UMAX(ut), /, (ut)(vr)) < (ut)(vl)))	\
+		mbiCfail;						\
+	(vl) *= (vr);							\
+} while (/* CONSTCOND */ 0)
+
+/* 2. for signed types; lim is the prefix (e.g. SHRT) */
+#define mbiCASinc(lim,vl)	do {					\
+	if (__predict_false((vl) == lim ## _MAX))			\
+		mbiCfail;						\
+	++(vl);								\
+} while (/* CONSTCOND */ 0)
+#define mbiCASdec(lim,vl)	do {					\
+	if (__predict_false((vl) == lim ## _MIN))			\
+		mbiCfail;						\
+	--(vl);								\
+} while (/* CONSTCOND */ 0)
+/* CAP means vr is positive */
+#define mbiCAPadd(lim,vl,vr)	do {					\
+	if (__predict_false((vl) > (lim ## _MAX - (vr))))		\
+		mbiCfail;						\
+	(vl) += (vr);							\
+} while (/* CONSTCOND */ 0)
+#define mbiCAPsub(lim,vl,vr)	do {					\
+	if (__predict_false((vl) < (lim ## _MIN + (vr))))		\
+		mbiCfail;						\
+	(vl) -= (vr);							\
+} while (/* CONSTCOND */ 0)
+#define mbiCAPmul(lim,vl,vr)	do {					\
+	if (__predict_false((vr) != 0 &&				\
+	    mbi__sabovehalftype(lim ## _MAX, (vl), (vr)) && ((vl) < 0 ?	\
+	    (vl) < (lim ## _MIN / (vr)) :				\
+	    (vl) > (lim ## _MAX / (vr)))))				\
+		mbiCfail;						\
+	(vl) *= (vr);							\
+} while (/* CONSTCOND */ 0)
+/* CAS for add/sub/mul may have negative vr */
+#define mbiCASadd(lim,vl,vr)	do {					\
+	if (__predict_false((vr) < 0 ?					\
+	    (vl) < (lim ## _MIN - (vr)) :				\
+	    (vl) > (lim ## _MAX - (vr))))				\
+		mbiCfail;						\
+	(vl) += (vr);							\
+} while (/* CONSTCOND */ 0)
+#define mbiCASsub(lim,vl,vr)	do {					\
+	if (__predict_false((vr) < 0 ?					\
+	    (vl) > (lim ## _MAX + (vr)) :				\
+	    (vl) < (lim ## _MIN + (vr))))				\
+		mbiCfail;						\
+	(vl) -= (vr);							\
+} while (/* CONSTCOND */ 0)
+#define mbiCASmul(lim,vl,vr)	do {					\
+	if (((vr) >= 0) ? __predict_false((vr) != 0 &&			\
+	    mbi__sabovehalftype(lim ## _MAX, (vl), (vr)) && ((vl) < 0 ?	\
+	    (vl) < (lim ## _MIN / (vr)) :				\
+	    (vl) > (lim ## _MAX / (vr)))) :				\
+	    /* vr < 0 */ __predict_false((vl) < 0 ?			\
+	    (vl) < (lim ## _MAX / (vr)) : /* vl >= 0, vr < 0 */		\
+	    (vr) != -1 && (vl) > (lim ## _MIN / (vr))))			\
+		mbiCfail;						\
+	(vl) *= (vr);							\
+} while (/* CONSTCOND */ 0)
+
+/* 3. autotype or signed narrowing assign; this is checked IB */
+#define mbiCAAlet(vl,srctype,vr) do {					\
+	(vl) = (vr);							\
+	if (__predict_false((srctype)(vl) != (srctype)(vr)))		\
+		mbiCfail;						\
+} while (/* CONSTCOND */ 0)
+#define mbiCASlet(dsttype,vl,srctype,vr) do {				\
+	(vl) = (dsttype)(vr);						\
+	if (__predict_false((srctype)(vl) != (srctype)(vr)))		\
+		mbiCfail;						\
+} while (/* CONSTCOND */ 0)
+
+/* 4. safe to use mbiA_U2S / mbiA_VZM2S for the given in-range value */
+#if mbiSAFECOMPLEMENT
+#define mbiCAsafeU2S(lim,ut,v) do {					\
+	/* nothing */ (void)(ut)(v); (void)(lim ## _MAX);		\
+} while (/* CONSTCOND */ 0)
+#define mbiCAsafeVZM2S(lim,ut,vz,m) do {				\
+	/* nothing */ (void)(ut)(m); (void)(lim ## _MAX); (void)(vz);	\
+} while (/* CONSTCOND */ 0)
+#else /* one’s complement or sign-and-magnitude or -type_MAX-1 is a trap */
+#define mbiCAsafeU2S(lim,ut,v) do {					\
+	if (__predict_false((ut)(v) == mbiOU(ut, lim ## _MAX, +, 1)))	\
+		mbiCfail;						\
+} while (/* CONSTCOND */ 0)
+#define mbiCAsafeVZM2S(lim,ut,vz,m) do {				\
+	if ((vz) &&							\
+	    __predict_false((ut)(m) == mbiOU(ut, lim ## _MAX, +, 1)))	\
+		mbiCfail;						\
+} while (/* CONSTCOND */ 0)
+#endif
+
+/*
+ * calculations on manual two’s k̲omplement signed numbers in unsigned vars
+ *
+ * addition, subtraction and multiplication, bitwise and boolean
+ * operations, as well as equality comparisons can be done on the
+ * unsigned value; other operations follow:
+ */
+
+/* k-signed compare < <= > >= */
+#define mbiK_signbit(ut,HM)	mbiOU(ut, (HM), +, 1)
+#define mbiK_signflip(ut,HM,v)	mbiOU(ut, (v), ^, mbiK_signbit(ut, (HM)))
+#define mbiKcmp(ut,HM,vl,op,vr)	mbiCOU(ut, \
+		mbiK_signflip(ut, (HM), (vl)), \
+		op, \
+		mbiK_signflip(ut, (HM), (vr)))
+#define mbiMKcmp(ut,FM,HM,vl,op,vr) \
+	mbiKcmp(ut, (HM), mbiMM(ut, (FM), (vl)), op, mbiMM(ut, (FM), (vr)))
+
+/* rotate and shift (can also be used on unsigned values) */
+#define mbiKrol(ut,vl,vr)	mbiK_sr(ut, mbiK_rol, (vl), (vr), void)
+#define mbiKror(ut,vl,vr)	mbiK_sr(ut, mbiK_ror, (vl), (vr), void)
+#define mbiKshl(ut,vl,vr)	mbiK_sr(ut, mbiK_shl, (vl), (vr), void)
+/* let vz be sgn(vl): mbi{,M}A_U2VZ(ut,HM,vl) */
+/* mbiA_U2VZ(ut,mbiTYPE_UMAX(ut)>>1,vl) if unsigned and nōn-masking */
+#define mbiKsar(ut,vz,vl,vr)	mbiK_sr(ut, mbiK_sar, (vl), (vr), (vz))
+#define mbiKshr(ut,vl,vr)	mbiK_sr(ut, mbiK_shr, (vl), (vr), 0)
+#define mbiMKrol(ut,FM,vl,vr)	mbiMK_sr(ut, (FM), mbiK_rol, (vl), (vr), void)
+#define mbiMKror(ut,FM,vl,vr)	mbiMK_sr(ut, (FM), mbiK_ror, (vl), (vr), void)
+#define mbiMKshl(ut,FM,vl,vr)	mbiMK_sr(ut, (FM), mbiK_shl, (vl), (vr), void)
+#define mbiMKsar(ut,FM,vz,l,r)	mbiMOT(ut, (FM), (vz), \
+					mbiK_SR(ut, mbiMASK_BITS(FM), \
+					    mbiMK_nr, (l), (r), (FM)), \
+					mbiK_SR(ut, mbiMASK_BITS(FM), \
+					    mbiK_shr, (l), (r), 0))
+#define mbiMKshr(ut,FM,vl,vr)	mbiMK_sr(ut, (FM), mbiK_shr, (vl), (vr), 0)
+/* implementation */
+#define mbiK_sr(ut,n,vl,vr,vz)	mbiK_SR(ut, mbiTYPE_UBITS(ut), n, vl, vr, vz)
+#define mbiMK_sr(ut,FM,n,l,r,z)	mbiMM(ut, (FM), mbiK_SR(ut, mbiMASK_BITS(FM), \
+				    n, mbiMM(ut, (FM), (l)), (r), (z)))
+#define mbiK_SR(ut,b,n,l,r,vz)	mbiK_RS(ut, b, n, l, mbiUI(r) % mbiUI(b), (vz))
+#define mbiK_RS(ut,b,n,v,cl,zx)	mbiOT(ut, cl, n(ut, v, cl, b - (cl), zx), v)
+#define mbiK_shl(ut,ax,cl,CL,z)	mbiOshl(ut, ax, cl)
+#define mbiK_shr(ut,ax,cl,CL,z)	mbiOshr(ut, ax, cl)
+#define mbiK_sar(ut,ax,cl,CL,z)	mbiOT(ut, z, mbiOU1(ut, ~, mbiOshr(ut, \
+				    mbiOU1(ut, ~, ax), cl)), \
+				    mbiOshr(ut, ax, cl))
+#define mbiMK_nr(ut,ax,cl,CL,m)	mbiOU1(ut, ~, mbiOshr(ut, \
+				    mbiMO1(ut, m, ~, ax), cl))
+#define mbiK_rol(ut,ax,cl,CL,z)	\
+	mbiOU(ut, mbiOshl(ut, ax, cl), |, mbiOshr(ut, ax, CL))
+#define mbiK_ror(ut,ax,cl,CL,z)	\
+	mbiOU(ut, mbiOshr(ut, ax, cl), |, mbiOshl(ut, ax, CL))
+
+/* k-signed division and remainder */
+#define mbiKdiv(ut,HM,vl,vr)		mbiA_VZU2U(ut, \
+	mbiA_U2VZ(ut, (HM), (vl)) ^ mbiA_U2VZ(ut, (HM), (vr)), \
+	mbiUI(mbiA_U2M(ut, (HM), (vl))) / mbiUI(mbiA_U2M(ut, (HM), (vr))))
+#define mbiMK_div(ut,FM,HM,vl,vr)	mbiA_VZU2U(ut, \
+	mbiMA_U2VZ(ut, (FM), (HM), (vl)) ^ mbiMA_U2VZ(ut, (FM), (HM), (vr)), \
+	mbiUI(mbiMA_U2M(ut, (FM), (HM), (vl))) / mbiUI(mbiMA_U2M(ut, (FM), (HM), (vr))))
+#define mbiMKdiv(ut,FM,HM,vl,vr)	mbiMM(ut, (FM), \
+	mbiMK_div(ut, (FM), (HM), (vl), (vr)))
+#define mbiK_rem(ut,vl,vr,vdiv)		mbiOU(ut, vl, -, mbiOU(ut, vdiv, *, vr))
+#define mbiKrem(ut,HM,vl,vr)		mbiK_rem(ut, (vl), (vr), \
+					    mbiKdiv(ut, (HM), (vl), (vr)))
+#define mbiMKrem(ut,FM,HM,vl,vr)	mbiMM(ut, (FM), mbiK_rem(ut, (vl), (vr), \
+					    mbiMK_div(ut, (FM), (HM), (vl), (vr))))
+/* statement, assigning to dstdiv and dstrem */
+#define mbiKdivrem(dstdiv,dstrem,ut,HM,vl,vr) do {			\
+	ut mbi__TMP = mbiKdiv(ut, (HM), (vl), (vr));			\
+	(dstdiv) = mbi__TMP;						\
+	(dstrem) = mbiK_rem(ut, (vl), (vr), mbi__TMP);			\
+} while (/* CONSTCOND */ 0)
+#define mbiMKdivrem(dstdiv,dstrem,ut,FM,HM,vl,vr) do {			\
+	ut mbi__TMP = mbiMK_div(ut, (FM), (HM), (vl), (vr));		\
+	(dstdiv) = mbiMM(ut, (FM), mbi__TMP);				\
+	(dstrem) = mbiMM(ut, (FM), mbiK_rem(ut, (vl), (vr), mbi__TMP));	\
+} while (/* CONSTCOND */ 0)
+
+/*
+ * anything else
+ */
+
+#ifdef _MSC_VER
+#pragma warning(pop)
+#endif
+
+#endif /* !SYSKERN_MBSDINT_H */
--- mksh-59c.orig/mirhash.h
+++ mksh-59c/mirhash.h
@@ -1,226 +1,142 @@
 /*-
- * Copyright © 2011, 2014, 2015
- *	mirabilos <m@mirbsd.org>
+ * Copyright (c) 2011, 2014, 2015, 2021, 2022, 2023
+ *	mirabilos <m$(date +%Y)@mirbsd.de>
  *
  * Provided that these terms and disclaimer and all copyright notices
  * are retained or reproduced in an accompanying document, permission
- * is granted to deal in this work without restriction, including un‐
+ * is granted to deal in this work without restriction, including un-
  * limited rights to use, publicly perform, distribute, sell, modify,
  * merge, give away, or sublicence.
  *
- * This work is provided “AS IS” and WITHOUT WARRANTY of any kind, to
+ * This work is provided "AS IS" and WITHOUT WARRANTY of any kind, to
  * the utmost extent permitted by applicable law, neither express nor
  * implied; without malicious intent or gross negligence. In no event
  * may a licensor, author or contributor be held liable for indirect,
  * direct, other damage, loss, or other issues arising in any way out
  * of dealing in the work, even if advised of the possibility of such
  * damage or existence of a defect, except proven that it results out
- * of said person’s immediate fault when using the work as intended.
+ * of said person's immediate fault when using the work as intended.
  *-
- * This file provides BAFH (Better Avalanche for the Jenkins Hash) as
- * inline macro bodies that operate on “register uint32_t” variables,
- * with variants that use their local intermediate registers.
- *
- * Usage note for BAFH with entropy distribution: input up to 4 bytes
- * is best combined into a 32-bit unsigned integer, which is then run
- * through BAFHFinish_reg for mixing and then used as context instead
- * of 0. Longer input should be handled the same: take the first four
- * bytes as IV after mixing then add subsequent bytes the same way.
- * This needs counting input bytes and is endian-dependent, thus not,
- * for speed reasons, specified for the regular stable hash, but very
- * much recommended if the actual output value may differ across runs
- * (so is using a random value instead of 0 for the IV).
+ * This file provides BAFH1-0 (Better Avalanche for the Jenkins Hash)
+ * as macro bodies operating on “register k32” variables (from sh.h),
+ * which must be of u_int (or higher) rank, ≥32 bits width.
  *-
  * Little quote gem:
  *	We are looking into it. Changing the core
  *	hash function in PHP isn't a trivial change
  *	and will take us some time.
- * -- Rasmus Lerdorf
+ *		-- Rasmus Lerdorf
  */
 
-#ifndef SYSKERN_MIRHASH_H
-#define SYSKERN_MIRHASH_H 1
-#define SYSKERN_MIRHASH_BAFH
+#ifndef MKSH_MIRHASH_H
+#define MKSH_MIRHASH_H
 
-#include <sys/types.h>
-
-__RCSID("$MirOS: src/bin/mksh/mirhash.h,v 1.6 2015/11/29 17:05:02 tg Exp $");
+__RCSID("$MirOS: src/bin/mksh/mirhash.h,v 1.21 2025/04/25 23:14:58 tg Exp $");
 
 /*-
- * BAFH itself is defined by the following primitives:
+ * BAFH1-0 is defined by the following primitives:
  *
  * • BAFHInit(ctx) initialises the hash context, which consists of a
- *   sole 32-bit unsigned integer (ideally in a register), to 0.
- *   It is possible to use any initial value out of [0; 2³²[ – which
+ *   sole 32-bit unsigned integer (ideally in a register), to 0^H1.
+ *   It is possible to use any initial value out of [0; 2³²[ — which
  *   is, in fact, recommended if using BAFH for entropy distribution
- *   – but for a regular stable hash, the IV 0 is needed.
+ *   — but for a regular stable hash, the IV 0^H1 is needed: iff the
+ *   sum of ctx and val in BAFHUpdateOctet is 0, leading NULs aren’t
+ *   counted, so apply suitable bias to ensure that state is avoided.
  *
  * • BAFHUpdateOctet(ctx,val) compresses the unsigned 8-bit quantity
- *   into the hash context. The algorithm used is Jenkins’ one-at-a-
- *   time, except that an additional constant 1 is added so that, if
- *   the context is (still) zero, adding a NUL byte is not ignored.
- *
- * • BAFHror(eax,cl) evaluates to the unsigned 32-bit integer “eax”,
- *   rotated right by “cl” ∈ [0; 31] (no casting, be careful!) where
- *   “eax” must be uint32_t and “cl” an in-range integer.
+ *   into the hash context using Jenkins’ one-at-a-time algorithm.
  *
  * • BAFHFinish(ctx) avalanches the context around so every sub-byte
  *   depends on all input octets; afterwards, the context variable’s
  *   value is the hash output. BAFH does not use any padding, nor is
  *   the input length added; this is due to the common use case (for
  *   quick entropy distribution and use with a hashtable).
- *   Warning: BAFHFinish uses the MixColumn algorithm of AES – which
+ *   Warning: BAFHFinish uses the MixColumn algorithm of AES — which
  *   is reversible (to avoid introducing funnels and reducing entro‐
  *   py), so blinding may need to be employed for some uses, e.g. in
- *   mksh, after a fork.
- *
- * The BAFHUpdateOctet and BAFHFinish are available in two flavours:
- * suffixed with _reg (assumes the context is in a register) or _mem
- * (which doesn’t).
+ *   mksh, after a fork. For ctx == 0 only, ctx will be 0 afterwards.
  *
- * The following high-level macros (with _reg and _mem variants) are
- * available:
+ * The following high-level macros are available:
  *
  * • BAFHUpdateMem(ctx,buf,len) adds a memory block to a context.
  * • BAFHUpdateStr(ctx,buf) is equivalent to using len=strlen(buf).
- * • BAFHHostMem(ctx,buf,len) calculates the hash of the memory buf‐
- *   fer using the first 4 octets (mixed) for IV, as outlined above;
- *   the result is endian-dependent; “ctx” assumed to be a register.
- * • BAFHHostStr(ctx,buf) does the same for C strings.
+ * • BAFHUpdateVLQ(ctx,ut,ival) encodes as VLQ with negated A bit.
  *
  * All macros may use ctx multiple times in their expansion, but all
- * other arguments are always evaluated at most once except BAFHror.
- *
- * To stay portable, never use the BAFHHost*() macros (these are for
- * host-local entropy shuffling), and encode numbers using ULEB128.
+ * other arguments are always evaluated at most once.
  */
 
 #define BAFHInit(h) do {					\
-	(h) = 0;						\
-} while (/* CONSTCOND */ 0)
-
-#define BAFHUpdateOctet_reg(h,b) do {				\
-	(h) += (uint8_t)(b);					\
-	++(h);							\
-	(h) += (h) << 10;					\
-	(h) ^= (h) >> 6;					\
-} while (/* CONSTCOND */ 0)
-
-#define BAFHUpdateOctet_mem(m,b) do {				\
-	register uint32_t BAFH_h = (m);				\
-								\
-	BAFHUpdateOctet_reg(BAFH_h, (b));			\
-	(m) = BAFH_h;						\
+	(h) = mbiMM(k32, K32_FM, 1U);				\
 } while (/* CONSTCOND */ 0)
 
-#define BAFHror(eax,cl) (((eax) >> (cl)) | ((eax) << (32 - (cl))))
-
-#define BAFHFinish_reg(h) do {					\
-	register uint32_t BAFHFinish_v;				\
-								\
-	BAFHFinish_v = ((h) >> 7) & 0x01010101U;		\
-	BAFHFinish_v += BAFHFinish_v << 1;			\
-	BAFHFinish_v += BAFHFinish_v << 3;			\
-	BAFHFinish_v ^= ((h) << 1) & 0xFEFEFEFEU;		\
-								\
-	BAFHFinish_v ^= BAFHror(BAFHFinish_v, 8);		\
-	BAFHFinish_v ^= ((h) = BAFHror((h), 8));		\
-	BAFHFinish_v ^= ((h) = BAFHror((h), 8));		\
-	(h) = BAFHror((h), 8) ^ BAFHFinish_v;			\
-} while (/* CONSTCOND */ 0)
-
-#define BAFHFinish_mem(m) do {					\
-	register uint32_t BAFHFinish_v, BAFH_h = (m);		\
-								\
-	BAFHFinish_v = (BAFH_h >> 7) & 0x01010101U;		\
-	BAFHFinish_v += BAFHFinish_v << 1;			\
-	BAFHFinish_v += BAFHFinish_v << 3;			\
-	BAFHFinish_v ^= (BAFH_h << 1) & 0xFEFEFEFEU;		\
-								\
-	BAFHFinish_v ^= BAFHror(BAFHFinish_v, 8);		\
-	BAFHFinish_v ^= (BAFH_h = BAFHror(BAFH_h, 8));		\
-	BAFHFinish_v ^= (BAFH_h = BAFHror(BAFH_h, 8));		\
-	(m) = BAFHror(BAFH_h, 8) ^ BAFHFinish_v;		\
-} while (/* CONSTCOND */ 0)
-
-#define BAFHUpdateMem_reg(h,p,z) do {				\
-	register const uint8_t *BAFHUpdate_p;			\
-	register size_t BAFHUpdate_z = (z);			\
+#define BAFHUpdateOctet(h,b) do {				\
+	(h) = mbiMO(k32, K32_FM, (h), +, KBI(b));		\
+	(h) = mbiMO(k32, K32_FM, (h), +,			\
+	    mbiMKshl(k32, K32_FM, (h), 10));			\
+	(h) = mbiMO(k32, K32_FM, (h), ^,			\
+	    mbiMKshr(k32, K32_FM, (h), 6));			\
+} while (/* CONSTCOND */ 0)
+
+#define BAFHFinish__impl(h,v,d)					\
+	v = mbiMO(k32, K32_FM,					\
+	    mbiMKshr(k32, K32_FM, h, 7), &, 0x01010101U);	\
+	v = mbiMO(k32, K32_FM, v, +,				\
+	    mbiMKshl(k32, K32_FM, v, 1));			\
+	v = mbiMO(k32, K32_FM, v, +,				\
+	    mbiMKshl(k32, K32_FM, v, 3));			\
+	v = mbiMO(k32, K32_FM, v, ^, mbiMO(k32, K32_FM,		\
+	    mbiMKshl(k32, K32_FM, h, 1), &, 0xFEFEFEFEU));	\
+								\
+	v = mbiMO(k32, K32_FM, v, ^,				\
+	    mbiMKror(k32, K32_FM, v, 8));			\
+	v = mbiMO(k32, K32_FM, v, ^,				\
+	    (h = mbiMKror(k32, K32_FM, h, 8)));			\
+	v = mbiMO(k32, K32_FM, v, ^,				\
+	    (h = mbiMKror(k32, K32_FM, h, 8)));			\
+	d = mbiMO(k32, K32_FM, v, ^,				\
+	    mbiMKror(k32, K32_FM, h, 8));
+
+#define BAFHFinish(h) do {					\
+	register k32 BAFHFinish_v;				\
+								\
+	BAFHFinish__impl((h), BAFHFinish_v, (h))		\
+} while (/* CONSTCOND */ 0)
+
+#define BAFHUpdateMem(h,p,z) do {				\
+	register const unsigned char *BAFHUpdate_p;		\
+	register const unsigned char *BAFHUpdate_d;		\
 								\
 	BAFHUpdate_p = (const void *)(p);			\
-	while (BAFHUpdate_z--)					\
-		BAFHUpdateOctet_reg((h), *BAFHUpdate_p++);	\
+	BAFHUpdate_d = BAFHUpdate_p + (z);			\
+	while (BAFHUpdate_p < BAFHUpdate_d)			\
+		BAFHUpdateOctet((h), *BAFHUpdate_p++);		\
 } while (/* CONSTCOND */ 0)
 
-/* meh should have named them _r/m but that’s not valid C */
-#define BAFHUpdateMem_mem(m,p,z) do {				\
-	register uint32_t BAFH_h = (m);				\
-								\
-	BAFHUpdateMem_reg(BAFH_h, (p), (z));			\
-	(m) = BAFH_h;						\
-} while (/* CONSTCOND */ 0)
-
-#define BAFHUpdateStr_reg(h,s) do {				\
-	register const uint8_t *BAFHUpdate_s;			\
-	register uint8_t BAFHUpdate_c;				\
+#define BAFHUpdateStr(h,s) do {					\
+	register const unsigned char *BAFHUpdate_s;		\
+	register unsigned char BAFHUpdate_c;			\
 								\
 	BAFHUpdate_s = (const void *)(s);			\
-	while ((BAFHUpdate_c = *BAFHUpdate_s++) != 0)		\
-		BAFHUpdateOctet_reg((h), BAFHUpdate_c);		\
+	while ((BAFHUpdate_c = *BAFHUpdate_s++))		\
+		BAFHUpdateOctet((h), BAFHUpdate_c);		\
 } while (/* CONSTCOND */ 0)
 
-#define BAFHUpdateStr_mem(m,s) do {				\
-	register uint32_t BAFH_h = (m);				\
-								\
-	BAFHUpdateStr_reg(BAFH_h, (s));				\
-	(m) = BAFH_h;						\
-} while (/* CONSTCOND */ 0)
-
-#define BAFHHostMem(h,p,z) do {					\
-	register const uint8_t *BAFHUpdate_p;			\
-	register size_t BAFHUpdate_z = (z);			\
-	size_t BAFHHost_z;					\
-	union {							\
-		uint8_t as_u8[4];				\
-		uint32_t as_u32;				\
-	} BAFHHost_v;						\
-								\
-	BAFHUpdate_p = (const void *)(p);			\
-	BAFHHost_v.as_u32 = 0;					\
-	BAFHHost_z = BAFHUpdate_z < 4 ? BAFHUpdate_z : 4;	\
-	memcpy(BAFHHost_v.as_u8, BAFHUpdate_p, BAFHHost_z);	\
-	BAFHUpdate_p += BAFHHost_z;				\
-	BAFHUpdate_z -= BAFHHost_z;				\
-	(h) = BAFHHost_v.as_u32;				\
-	BAFHFinish_reg(h);					\
-	while (BAFHUpdate_z--)					\
-		BAFHUpdateOctet_reg((h), *BAFHUpdate_p++);	\
-	BAFHFinish_reg(h);					\
-} while (/* CONSTCOND */ 0)
-
-#define BAFHHostStr(h,s) do {					\
-	register const uint8_t *BAFHUpdate_s;			\
-	register uint8_t BAFHUpdate_c;				\
-	union {							\
-		uint8_t as_u8[4];				\
-		uint32_t as_u32;				\
-	} BAFHHost_v;						\
-								\
-	BAFHUpdate_s = (const void *)(s);			\
-	BAFHHost_v.as_u32 = 0;					\
-	if ((BAFHHost_v.as_u8[0] = *BAFHUpdate_s) != 0)		\
-		++BAFHUpdate_s;					\
-	if ((BAFHHost_v.as_u8[1] = *BAFHUpdate_s) != 0)		\
-		++BAFHUpdate_s;					\
-	if ((BAFHHost_v.as_u8[2] = *BAFHUpdate_s) != 0)		\
-		++BAFHUpdate_s;					\
-	if ((BAFHHost_v.as_u8[3] = *BAFHUpdate_s) != 0)		\
-		++BAFHUpdate_s;					\
-	(h) = BAFHHost_v.as_u32;				\
-	BAFHFinish_reg(h);					\
-	while ((BAFHUpdate_c = *BAFHUpdate_s++) != 0)		\
-		BAFHUpdateOctet_reg((h), BAFHUpdate_c);		\
-	BAFHFinish_reg(h);					\
+#define BAFHUpdateVLQ(h,t,n) do {				\
+	unsigned char BAFHUpdate_s[(sizeof(t)*(CHAR_BIT)+6)/7];	\
+	register size_t BAFHUpdate_n = sizeof(BAFHUpdate_s);	\
+	t BAFHUpdate_v = (n);					\
+								\
+	do {							\
+		BAFHUpdate_s[--BAFHUpdate_n] =			\
+		    BAFHUpdate_v & 0x7FU;			\
+		BAFHUpdate_v >>= 7;				\
+	} while (BAFHUpdate_v);					\
+	BAFHUpdate_s[sizeof(BAFHUpdate_s) - 1] |= 0x80U;	\
+	while (BAFHUpdate_n < sizeof(BAFHUpdate_s))		\
+		BAFHUpdateOctet((h),				\
+		    BAFHUpdate_s[BAFHUpdate_n++]);		\
 } while (/* CONSTCOND */ 0)
 
 #endif
--- mksh-59c.orig/misc.c
+++ mksh-59c/misc.c
@@ -4,8 +4,8 @@
 /*-
  * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
  *		 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2019,
- *		 2020
- *	mirabilos <m@mirbsd.org>
+ *		 2020, 2021, 2022, 2023
+ *	mirabilos <m$(date +%Y)@mirbsd.de>
  * Copyright (c) 2015
  *	Daniel Richard G. <skunk@iSKUNK.ORG>
  *
@@ -26,36 +26,21 @@
  */
 
 #include "sh.h"
-#if !HAVE_GETRUSAGE
-#include <sys/times.h>
-#endif
-#if HAVE_GRP_H
-#include <grp.h>
-#endif
-
-__RCSID("$MirOS: src/bin/mksh/misc.c,v 1.302 2020/08/27 19:52:45 tg Exp $");
-
-#define KSH_CHVT_FLAG
-#ifdef MKSH_SMALL
-#undef KSH_CHVT_FLAG
-#endif
-#ifdef TIOCSCTTY
-#define KSH_CHVT_CODE
-#define KSH_CHVT_FLAG
-#endif
 
-/* type bits for unsigned char */
-unsigned char chtypes[UCHAR_MAX + 1];
+__RCSID("$MirOS: src/bin/mksh/misc.c,v 1.360 2025/04/25 23:14:58 tg Exp $");
 
 static const unsigned char *pat_scan(const unsigned char *,
-    const unsigned char *, bool) MKSH_A_PURE;
+    const unsigned char *, Wahr);
 static int do_gmatch(const unsigned char *, const unsigned char *,
     const unsigned char *, const unsigned char *,
-    const unsigned char *) MKSH_A_PURE;
-static const unsigned char *gmatch_cclass(const unsigned char *, unsigned char)
-    MKSH_A_PURE;
-#ifdef KSH_CHVT_CODE
+    const unsigned char *);
+static const unsigned char *gmatch_cclass(const unsigned char *, unsigned char);
 static void chvt(const Getopt *);
+static unsigned int dollarqU(struct shf *, const unsigned char *);
+#ifndef MKSH_SMALL
+static void dollarq8(struct shf *, const unsigned char *);
+#else
+#define dollarq8 dollarqU
 #endif
 
 /*XXX this should go away */
@@ -65,19 +50,19 @@ static int make_path(const char *, const
 /* we don't need to check for other codes, EPERM won't happen */
 #define DO_SETUID(func,argvec) do {					\
 	if ((func argvec) && errno == EAGAIN)				\
-		errorf("%s failed with EAGAIN, probably due to a"	\
-		    " too low process limit; aborting", #func);		\
+		kerrf(KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE |		\
+		    KWF_TWOMSG, #func, "failed, probably due to a"	\
+		    " too low process limit; aborting");		\
 } while (/* CONSTCOND */ 0)
 #else
 #define DO_SETUID(func,argvec) func argvec
 #endif
 
-
 /* called from XcheckN() to grow buffer */
 char *
 Xcheck_grow(XString *xsp, const char *xp, size_t more)
 {
-	const char *old_beg = xsp->beg;
+	size_t old_ofs = xp - xsp->beg;
 
 	if (more < xsp->len)
 		more = xsp->len;
@@ -85,24 +70,30 @@ Xcheck_grow(XString *xsp, const char *xp
 	checkoktoadd(more, xsp->len + X_EXTRA);
 	xsp->beg = aresize(xsp->beg, (xsp->len += more) + X_EXTRA, xsp->areap);
 	xsp->end = xsp->beg + xsp->len;
-	return (xsp->beg + (xp - old_beg));
+	return (xsp->beg + old_ofs);
 }
 
-
 #define SHFLAGS_DEFNS
-#define FN(sname,cname,flags,ochar)		\
-	static const struct {			\
-		/* character flag (if any) */	\
-		char c;				\
-		/* OF_* */			\
-		unsigned char optflags;		\
-		/* long name of option */	\
-		char name[sizeof(sname)];	\
-	} shoptione_ ## cname = {		\
-		ochar, flags, sname		\
+#define FN(sname,cname,flags,ochar)			\
+	static const struct shoptionS_ ## cname {	\
+		/* character flag (if any) */		\
+		char c;					\
+		/* OF_* */				\
+		unsigned char optflags;			\
+		/* long name of option */		\
+		char name[sizeof(sname)];		\
+	} shoptione_ ## cname = {			\
+		ochar, flags, sname			\
 	};
 #include "sh_flags.gen"
 
+mbCTA_BEG(sh_flags_gen);
+#define FN(sname,cname,flags,ochar) mbccCTA(o_ ## cname, ( \
+	offsetof(struct shoptionS_ ## cname, optflags) == 1 && \
+	offsetof(struct shoptionS_ ## cname, name) == 2));
+#include "sh_flags.gen"
+mbCTA_END(sh_flags_gen);
+
 #define OFC(i) (options[i][-2])
 #define OFF(i) (((const unsigned char *)options[i])[-1])
 #define OFN(i) (options[i])
@@ -142,7 +133,7 @@ struct options_info {
 };
 
 static void options_fmt_entry(char *, size_t, unsigned int, const void *);
-static int printoptions(bool);
+static int printoptions(Wahr);
 static int printoption(size_t);
 
 /* format a single select menu item */
@@ -178,7 +169,7 @@ printoption(size_t i)
 }
 
 static int
-printoptions(bool verbose)
+printoptions(Wahr verbose)
 {
 	size_t i = 0;
 	int rv = 0;
@@ -205,7 +196,7 @@ printoptions(bool verbose)
 		}
 		co.shf = shl_stdout;
 		co.linesep = '\n';
-		co.prefcol = co.do_last = true;
+		co.prefcol = co.do_last = Ja;
 		print_columns(&co, n, options_fmt_entry, &oi,
 		    octs + 4, oi.opt_width + 4);
 	} else {
@@ -242,13 +233,16 @@ getoptions(void)
 
 /* change a Flag(*) value; takes care of special actions */
 void
-change_flag(enum sh_flag f, int what, bool newset)
+change_flag(enum sh_flag f,
+    /* OF_INTERNAL, OF_FIRSTTIME, OF_CMDLINE, or OF_SET */
+    unsigned int what,
+    Wahr newset)
 {
 	unsigned char oldval = Flag(f);
 	unsigned char newval = (newset ? 1 : 0);
 
 	if (f == FXTRACE) {
-		change_xtrace(newval, true);
+		change_xtrace(newval, Ja);
 		return;
 	} else if (f == FPRIVILEGED) {
 		if (!oldval)
@@ -292,10 +286,6 @@ change_flag(enum sh_flag f, int what, bo
 
 		/* +++ privs changed +++ */
 	} else if ((f == FPOSIX || f == FSH) && newval) {
-		/* Turning on -o posix? */
-		if (f == FPOSIX)
-			/* C locale required for compliance */
-			UTFMODE = 0;
 		/* Turning on -o posix or -o sh? */
 		Flag(FBRACEEXPAND) = 0;
 #ifndef MKSH_NO_CMDLINE_EDITING
@@ -316,7 +306,7 @@ change_flag(enum sh_flag f, int what, bo
 
 	if (f == FTALKING) {
 		/* Changing interactive flag? */
-		if ((what == OF_CMDLINE || what == OF_SET) && procpid == kshpid)
+		if (what == OF_CMDLINE && procpid == kshpid)
 			Flag(FTALKING_I) = newval;
 #ifndef MKSH_UNEMPLOYED
 	} else if (f == FMONITOR) {
@@ -327,9 +317,9 @@ change_flag(enum sh_flag f, int what, bo
 }
 
 void
-change_xtrace(unsigned char newval, bool dosnapshot)
+change_xtrace(unsigned char newval, Wahr dosnapshot)
 {
-	static bool in_xtrace;
+	static Wahr in_xtrace;
 
 	if (in_xtrace)
 		return;
@@ -359,11 +349,11 @@ change_xtrace(unsigned char newval, bool
 
  changed_xtrace:
 	if ((Flag(FXTRACE) = newval) == 2) {
-		in_xtrace = true;
+		in_xtrace = Ja;
 		Flag(FXTRACE) = 0;
-		shf_puts(substitute(str_val(global("PS4")), 0), shl_xtrace);
+		shf_putsv(substitute(str_val(global("PS4")), 0), shl_xtrace);
 		Flag(FXTRACE) = 2;
-		in_xtrace = false;
+		in_xtrace = Nee;
 	}
 }
 
@@ -374,8 +364,8 @@ change_xtrace(unsigned char newval, bool
 int
 parse_args(const char **argv,
     /* OF_FIRSTTIME, OF_CMDLINE, or OF_SET */
-    int what,
-    bool *setargsp)
+    unsigned int what,
+    Wahr *setargsp)
 {
 	static const char cmd_opts[] =
 #define SHFLAGS_NOT_SET
@@ -389,19 +379,18 @@ parse_args(const char **argv,
 #include "sh_flags.gen"
 #undef SHFLAGS_NOT_CMD
 	    ;
-	bool set;
-	const char *opts = what == OF_CMDLINE || what == OF_FIRSTTIME ?
-	    cmd_opts : set_opts;
+	Wahr set;
+	const char * const opts = what == OF_SET ? set_opts : cmd_opts;
 	const char *array = NULL;
 	Getopt go;
 	size_t i;
 	int optc, arrayset = 0;
-	bool sortargs = false;
-	bool fcompatseen = false;
+	Wahr sortargs = Nee;
+	Wahr fcompatseen = Nee;
 
 	ksh_getopt_reset(&go, GF_ERROR|GF_PLUSOPT);
 	while ((optc = ksh_getopt(argv, &go, opts)) != -1) {
-		set = tobool(!(go.info & GI_PLUS));
+		set = isWahr(!(go.info & GI_PLUS));
 		switch (optc) {
 		case 'A':
 			if (what == OF_FIRSTTIME)
@@ -418,13 +407,12 @@ parse_args(const char **argv,
 				 * lone -o: print options
 				 *
 				 * Note that on the command line, -o requires
-				 * an option (ie, can't get here if what is
-				 * OF_CMDLINE).
+				 * an option (i.e. can't get here if what is
+				 * not OF_SET).
 				 */
 #if !defined(MKSH_SMALL) || defined(DEBUG)
 				if (!set && !baseline_flags[(int)FNFLAGS]) {
-					bi_errorf(Tf_s_s, "too early",
-					    Tset_po);
+					bi_errorf(Ttooearly, T_set_po);
 					return (-1);
 				}
 #endif
@@ -442,7 +430,7 @@ parse_args(const char **argv,
 				 */
 				Flag(FPOSIX) = 0;
 				Flag(FSH) = 0;
-				fcompatseen = true;
+				fcompatseen = Ja;
 			}
 			if ((i != (size_t)-1) && (set ? 1U : 0U) == Flag(i))
 				/*
@@ -457,8 +445,7 @@ parse_args(const char **argv,
 			else if (!strcmp(go.optarg, To_reset)) {
 #if !defined(MKSH_SMALL) || defined(DEBUG)
 				if (!baseline_flags[(int)FNFLAGS]) {
-					bi_errorf(Tf_ss, "too early",
-					    To_o_reset);
+					bi_errorf(Ttooearly, To_o_reset);
 					return (-1);
 				}
 #endif
@@ -477,18 +464,11 @@ parse_args(const char **argv,
 			}
 			break;
 
-#ifdef KSH_CHVT_FLAG
 		case 'T':
 			if (what != OF_FIRSTTIME)
 				break;
-#ifndef KSH_CHVT_CODE
-			errorf("no TIOCSCTTY ioctl");
-#else
-			change_flag(FTALKING, OF_CMDLINE, true);
 			chvt(&go);
 			break;
-#endif
-#endif
 
 		case '?':
 			return (-1);
@@ -496,9 +476,9 @@ parse_args(const char **argv,
 		default:
 			if (what == OF_FIRSTTIME)
 				break;
-			/* -s: sort positional params (AT&T ksh stupidity) */
-			if (what == OF_SET && optc == 's') {
-				sortargs = true;
+			/* -s: sort positional params (via AT&T ksh) */
+			if (what == OF_SET && isch(optc, 's')) {
+				sortargs = Ja;
 				break;
 			}
 			for (i = 0; i < NELEM(options); i++)
@@ -508,18 +488,22 @@ parse_args(const char **argv,
 					break;
 				}
 			if (i == NELEM(options))
-				internal_errorf("parse_args: '%c'", optc);
+				kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,
+				    "parse_args: '%c'", optc);
 		}
 	}
-	if (!(go.info & GI_MINUSMINUS) && argv[go.optind] &&
+	/* lone ‘-’ (or ‘+’)? */
+	if (argv[go.optind] &&
 	    ctype(argv[go.optind][0], C_MINUS | C_PLUS) &&
-	    argv[go.optind][1] == '\0') {
-		/* lone - clears -v and -x flags */
-		if (argv[go.optind][0] == '-') {
+	    argv[go.optind][1] == '\0' &&
+	    !(go.info & GI_MINUSMINUS)) {
+		/* POSIX: lone hyphen-minus sh first arg ignored */
+		if (what == OF_SET && isch(argv[go.optind][0], '-')) {
+			/* set; lone dash clears -v and -x flags (obsolete) */
 			Flag(FVERBOSE) = 0;
-			change_xtrace(0, false);
+			change_xtrace(0, Nee);
 		}
-		/* set skips lone - or + option */
+		/* either way, skip it (POSIX only dash but… meh) */
 		go.optind++;
 	}
 	if (setargsp)
@@ -531,7 +515,7 @@ parse_args(const char **argv,
 		const char *ccp = NULL;
 
 		if (array && *array)
-			ccp = skip_varname(array, false);
+			ccp = skip_varname(array, Nee);
 		if (!ccp || !(!ccp[0] || (ccp[0] == '+' && !ccp[1]))) {
 			bi_errorf(Tf_sD_s, array, Tnot_ident);
 			return (-1);
@@ -544,7 +528,7 @@ parse_args(const char **argv,
 		    ascpstrcmp);
 	}
 	if (arrayset)
-		go.optind += set_array(array, tobool(arrayset > 0),
+		go.optind += set_array(array, isWahr(arrayset > 0),
 		    argv + go.optind);
 
 	return (go.optind);
@@ -554,11 +538,41 @@ parse_args(const char **argv,
 int
 getn(const char *s, int *ai)
 {
+	if (!getpn(&s, ai))
+		return (0);
+	if (!*s)
+		return (1);
+	errno = EINVAL;
+	return (0);
+}
+
+int
+getnh(const char *s, mbiHUGE_U *ai)
+{
+	if (!getpnh(&s, ai))
+		return (0);
+	if (!*s)
+		return (1);
+	errno = EINVAL;
+	return (0);
+}
+
+/*
+ * parse a decimal number
+ * on success, returns 1 and *ai contains it and *sp points past it
+ * on overflow, returns 0, *ai is 0, *sp points behind the parsed number
+ * on parse error (not numeric) returns 0, *ai is 0, *sp is not changed
+ */
+int
+getpn(const char **sp, int *ai)
+{
 	char c;
-	mksh_ari_u num;
-	bool neg = false;
+	const char *s;
+	mksh_uari_t num = 0;
+	kby state = 0;
+	Wahr neg = Nee;
 
-	num.u = 0;
+	s = *sp;
 
 	do {
 		c = *s++;
@@ -566,31 +580,103 @@ getn(const char *s, int *ai)
 
 	switch (c) {
 	case '-':
-		neg = true;
+		neg = Ja;
 		/* FALLTHROUGH */
 	case '+':
 		c = *s++;
 		break;
 	}
 
-	do {
-		if (!ctype(c, C_DIGIT))
-			/* not numeric */
-			return (0);
-		if (num.u > 214748364U)
+	while (ctype(c, C_DIGIT)) {
+			  /*XXX this supposed to return int? */
+		if (num > 214748364U) {
 			/* overflow on multiplication */
-			return (0);
-		num.u = num.u * 10U + (unsigned int)ksh_numdig(c);
-		/* now: num.u <= 2147483649U */
-	} while ((c = *s++));
+			state = 2;
+			errno = EOVERFLOW;
+		}
+		if (state < 2) {
+			state = 1;
+			num = num * 10U + (unsigned int)ksh_numdig(c);
+		}
+		/* now: num <= 2147483649U */
+		c = *s++;
+	}
+	--s;
 
-	if (num.u > (neg ? 2147483648U : 2147483647U))
+	if (num > (neg ? 2147483648U : 2147483647U)) {
 		/* overflow for signed 32-bit int */
+		state = 2;
+		errno = EOVERFLOW;
+	}
+
+	if (state)
+		*sp = s;
+	else
+		errno = EINVAL;
+	if (state != 1) {
+		*ai = 0;
 		return (0);
+	}
+	/*XXX this supposed to return int?!?!?!?! */
+	*ai = (neg && num > 0) ?
+	    (mksh_ari_t)(-(mksh_ari_t)((num - 1U) & 0x7FFFFFFF) - 1) :
+	    (mksh_ari_t)num;
+	return (1);
+}
+
+int
+getpnh(const char **sp, mbiHUGE_U *ai)
+{
+	char c;
+	const char *s;
+	mbiHUGE_U num = 0;
+	kby state = 0;
+	Wahr neg = Nee;
+
+	s = *sp;
+
+	do {
+		c = *s++;
+	} while (ctype(c, C_SPACE));
+
+	switch (c) {
+	case '-':
+		neg = Ja;
+		/* FALLTHROUGH */
+	case '+':
+		c = *s++;
+		break;
+	}
 
-	if (neg)
-		num.u = -num.u;
-	*ai = num.i;
+	while (ctype(c, C_DIGIT)) {
+		if (num > (mbiHUGE_U_MAX / 10U)) {
+			/* overflow on multiplication */
+			state = 2;
+			errno = EOVERFLOW;
+		}
+		num *= 10U;
+		if (num > (mbiHUGE_U_MAX - (unsigned int)ksh_numdig(c))) {
+			/* overflow on addition */
+			state = 2;
+			errno = EOVERFLOW;
+		}
+		if (state < 2) {
+			num += (unsigned int)ksh_numdig(c);
+			state = 1;
+		}
+		c = *s++;
+	}
+	--s;
+
+	if (state)
+		*sp = s;
+	else
+		errno = EINVAL;
+	if (state != 1) {
+		*ai = 0;
+		return (0);
+	}
+	*ai = neg ? (mbiHUGE_U)-(mbiHUGE_U)num : num;
 	return (1);
 }
 
@@ -602,7 +688,7 @@ getn(const char *s, int *ai)
 static void *
 simplify_gmatch_pattern(const unsigned char *sp)
 {
-	uint8_t c;
+	kby c;
 	unsigned char *cp, *dp;
 	const unsigned char *ps, *se;
 
@@ -620,12 +706,12 @@ simplify_gmatch_pattern(const unsigned c
 			*dp++ = c;
 			continue;
 		}
-		switch ((c = *sp++)) {
-		case 0x80|'@':
+		switch (ord((c = *sp++))) {
+		case ORD(0x80|'@'):
 		/* simile for @ */
-		case 0x80|' ':
+		case ORD(0x80|' '):
 			/* check whether it has only one clause */
-			ps = pat_scan(sp, se, true);
+			ps = pat_scan(sp, se, Ja);
 			if (!ps || ps[-1] != /*(*/ ')')
 				/* nope */
 				break;
@@ -677,7 +763,7 @@ simplify_gmatch_pattern(const unsigned c
  * pattern character are prefixed with MAGIC by expand.
  */
 int
-gmatchx(const char *s, const char *p, bool isfile)
+gmatchx(const char *s, const char *p, Wahr isfile)
 {
 	const char *se, *pe;
 	char *pnew;
@@ -688,8 +774,8 @@ gmatchx(const char *s, const char *p, bo
 
 	pe = strnul(p);
 	/*
-	 * isfile is false iff no syntax check has been done on
-	 * the pattern. If check fails, just do a strcmp().
+	 * isfile is Nee iff no syntax check has been done on the pattern.
+	 * If check fails just do a strcmp().
 	 */
 	if (!isfile && !has_globbing(p)) {
 		size_t len = pe - p + 1;
@@ -715,8 +801,8 @@ gmatchx(const char *s, const char *p, bo
 }
 
 /**
- * Returns if p is a syntacticly correct globbing pattern, false
- * if it contains no pattern characters or if there is a syntax error.
+ * Returns if p is a syntacticly correct globbing pattern, Nee if it
+ * contains no pattern characters or if there is a syntax error.
  * Syntax errors are:
  *	- [ with no closing ]
  *	- imbalanced $(...) expression
@@ -731,11 +817,11 @@ gmatchx(const char *s, const char *p, bo
  *	return ?
  * - return ?
  */
-bool
+Wahr
 has_globbing(const char *pat)
 {
 	unsigned char c, subc;
-	bool saw_glob = false;
+	Wahr saw_glob = Nee;
 	unsigned int nest = 0;
 	const unsigned char *p = (const unsigned char *)pat;
 	const unsigned char *s;
@@ -746,11 +832,11 @@ has_globbing(const char *pat)
 			continue;
 		/* MAGIC + NUL? abort. */
 		if (!(c = *p++))
-			return (false);
+			return (Nee);
 		/* some specials */
 		if (ord(c) == ORD('*') || ord(c) == ORD('?')) {
 			/* easy glob, accept */
-			saw_glob = true;
+			saw_glob = Ja;
 		} else if (ord(c) == ORD('[')) {
 			/* bracket expression; eat negation and initial ] */
 			if (ISMAGIC(p[0]) && ord(p[1]) == ORD('!'))
@@ -765,12 +851,12 @@ has_globbing(const char *pat)
 					continue;
 				/* MAGIC + NUL cannot happen */
 				if (!(c = *s++))
-					return (false);
+					return (Nee);
 				/* terminating bracket? */
 				if (ord(c) == ORD(']')) {
 					/* accept and continue */
 					p = s;
-					saw_glob = true;
+					saw_glob = Ja;
 					break;
 				}
 				/* sub-bracket expressions */
@@ -801,7 +887,7 @@ has_globbing(const char *pat)
 			}
 		} else if ((c & 0x80) && ctype(c & 0x7F, C_PATMO | C_SPC)) {
 			/* opening pattern */
-			saw_glob = true;
+			saw_glob = Ja;
 			++nest;
 		} else if (ord(c) == ORD(/*(*/ ')')) {
 			/* closing pattern */
@@ -870,7 +956,7 @@ do_gmatch(const unsigned char *s, const
 				return (0);
 			if (UTFMODE) {
 				--s;
-				s += utf_ptradj((const void *)s);
+				s += ez_mbtoc(NULL, (const void *)s);
 			}
 			break;
 
@@ -893,7 +979,7 @@ do_gmatch(const unsigned char *s, const
 		case ORD('+') | 0x80:
 		/* matches zero or more times */
 		case ORD('*') | 0x80:
-			if (!(prest = pat_scan(p, pe, false)))
+			if (!(prest = pat_scan(p, pe, Nee)))
 				return (0);
 			s--;
 			/* take care of zero matches */
@@ -901,7 +987,7 @@ do_gmatch(const unsigned char *s, const
 			    do_gmatch(s, se, prest, pe, smin))
 				return (1);
 			for (psub = p; ; psub = pnext) {
-				pnext = pat_scan(psub, pe, true);
+				pnext = pat_scan(psub, pe, Ja);
 				for (srest = s; srest <= se; srest++) {
 					if (do_gmatch(s, srest, psub, pnext - 2, smin) &&
 					    (do_gmatch(srest, se, prest, pe, smin) ||
@@ -920,7 +1006,7 @@ do_gmatch(const unsigned char *s, const
 		case ORD('@') | 0x80:
 		/* simile for @ */
 		case ORD(' ') | 0x80:
-			if (!(prest = pat_scan(p, pe, false)))
+			if (!(prest = pat_scan(p, pe, Nee)))
 				return (0);
 			s--;
 			/* Take care of zero matches */
@@ -928,7 +1014,7 @@ do_gmatch(const unsigned char *s, const
 			    do_gmatch(s, se, prest, pe, smin))
 				return (1);
 			for (psub = p; ; psub = pnext) {
-				pnext = pat_scan(psub, pe, true);
+				pnext = pat_scan(psub, pe, Ja);
 				srest = prest == pe ? se : s;
 				for (; srest <= se; srest++) {
 					if (do_gmatch(s, srest, psub, pnext - 2, smin) &&
@@ -942,14 +1028,14 @@ do_gmatch(const unsigned char *s, const
 
 		/* matches none of the patterns */
 		case ORD('!') | 0x80:
-			if (!(prest = pat_scan(p, pe, false)))
+			if (!(prest = pat_scan(p, pe, Nee)))
 				return (0);
 			s--;
 			for (srest = s; srest <= se; srest++) {
 				int matched = 0;
 
 				for (psub = p; ; psub = pnext) {
-					pnext = pat_scan(psub, pe, true);
+					pnext = pat_scan(psub, pe, Ja);
 					if (do_gmatch(s, srest, psub,
 					    pnext - 2, smin)) {
 						matched = 1;
@@ -977,7 +1063,7 @@ do_gmatch(const unsigned char *s, const
 /*XXX this is a prime example for bsearch or a const hashtable */
 static const struct cclass {
 	const char *name;
-	uint32_t value;
+	kui value;
 } cclasses[] = {
 	/* POSIX */
 	{ "alnum",	C_ALNUM	},
@@ -1013,14 +1099,14 @@ gmatch_cclass(const unsigned char *pat,
 {
 	unsigned char c, subc, lc;
 	const unsigned char *p = pat, *s;
-	bool found = false;
-	bool negated = false;
+	Wahr found = Nee;
+	Wahr negated = Nee;
 	char *subp;
 
 	/* check for negation */
 	if (ISMAGIC(p[0]) && ord(p[1]) == ORD('!')) {
 		p += 2;
-		negated = true;
+		negated = Ja;
 	}
 	/* make initial ] non-MAGIC */
 	if (ISMAGIC(p[0]) && ord(p[1]) == ORD(']'))
@@ -1076,7 +1162,7 @@ gmatch_cclass(const unsigned char *pat,
 							/* found, match? */
 							if (ctype(sc,
 							    cls->value))
-								found = true;
+								found = Ja;
 							/* break either way */
 							break;
 						} else
@@ -1100,7 +1186,7 @@ gmatch_cclass(const unsigned char *pat,
 				if ((c &= 0x7F) != ' ') {
 					/* check single match NOW */
 					if (sc == c)
-						found = true;
+						found = Ja;
 					/* next character is (...) */
 				}
 				c = '(' /*)*/;
@@ -1113,7 +1199,7 @@ gmatch_cclass(const unsigned char *pat,
 			/* no, check single match */
 			if (sc == c)
 				/* note: sc is never NUL */
-				found = true;
+				found = Ja;
 			/* do the next "first" character */
 			continue;
 		}
@@ -1163,10 +1249,10 @@ gmatch_cclass(const unsigned char *pat,
 
 					/* match single previous char */
 					if (lc && (sc == lc))
-						found = true;
+						found = Ja;
 					/* match hyphen-minus */
 					if (ord(sc) == ORD('-'))
-						found = true;
+						found = Ja;
 					/* handle cclass common part */
 					goto cclass_common;
 				}
@@ -1194,7 +1280,7 @@ gmatch_cclass(const unsigned char *pat,
 		if (lc != 0 /* && c != 0 */ &&
 		    asciibetical(lc) <= asciibetical(sc) &&
 		    asciibetical(sc) <= asciibetical(c))
-			found = true;
+			found = Ja;
 		/* forced next character? */
 		if (subc) {
 			c = subc;
@@ -1212,7 +1298,7 @@ gmatch_cclass(const unsigned char *pat,
 
 /* Look for next ) or | (if match_sep) in *(foo|bar) pattern */
 static const unsigned char *
-pat_scan(const unsigned char *p, const unsigned char *pe, bool match_sep)
+pat_scan(const unsigned char *p, const unsigned char *pe, Wahr match_sep)
 {
 	int nest = 0;
 
@@ -1231,7 +1317,7 @@ pat_scan(const unsigned char *p, const u
 int
 ascstrcmp(const void *s1, const void *s2)
 {
-	const uint8_t *cp1 = s1, *cp2 = s2;
+	const kby *cp1 = s1, *cp2 = s2;
 
 	while (*cp1 == *cp2) {
 		if (*cp1++ == '\0')
@@ -1252,15 +1338,12 @@ ascpstrcmp(const void *pstr1, const void
 void
 ksh_getopt_reset(Getopt *go, int flags)
 {
+	memset(go, '\0', sizeof(Getopt));
 	go->optind = 1;
 	go->optarg = NULL;
-	go->p = 0;
 	go->flags = flags;
-	go->info = 0;
-	go->buf[1] = '\0';
 }
 
-
 /**
  * getopt() used for shell built-in commands, the getopts command, and
  * command line options.
@@ -1271,7 +1354,7 @@ ksh_getopt_reset(Getopt *go, int flags)
  *
  * Non-standard features:
  *	- ';' is like ':' in options, except the argument is optional
- *	  (if it isn't present, optarg is set to 0).
+ *	  (if it isn't present, optarg is set to NULL).
  *	  Used for 'set -o'.
  *	- ',' is like ':' in options, except the argument always immediately
  *	  follows the option character (optarg is set to the null string if
@@ -1321,12 +1404,11 @@ ksh_getopt(const char **argv, Getopt *go
 			go->buf[0] = c;
 			go->optarg = go->buf;
 		} else {
-			warningf(true, Tf_optfoo,
-			    (go->flags & GF_NONAME) ? "" : argv[0],
-			    (go->flags & GF_NONAME) ? "" : Tcolsp,
-			    c, Tunknown_option);
+			ksh_getopt_opterr(c,
+			    (go->flags & GF_NONAME) ? null : argv[0],
+			    Tunknown_option);
 			if (go->flags & GF_ERROR)
-				bi_errorfz();
+				bi_unwind(1);
 		}
 		return (ORD('?'));
 	}
@@ -1349,12 +1431,11 @@ ksh_getopt(const char **argv, Getopt *go
 				go->optarg = go->buf;
 				return (ORD(':'));
 			}
-			warningf(true, Tf_optfoo,
-			    (go->flags & GF_NONAME) ? "" : argv[0],
-			    (go->flags & GF_NONAME) ? "" : Tcolsp,
-			    c, Treq_arg);
+			ksh_getopt_opterr(c,
+			    (go->flags & GF_NONAME) ? null : argv[0],
+			    Treq_arg);
 			if (go->flags & GF_ERROR)
-				bi_errorfz();
+				bi_unwind(1);
 			return (ORD('?'));
 		}
 		go->p = 0;
@@ -1386,6 +1467,20 @@ ksh_getopt(const char **argv, Getopt *go
 	return (ord(c));
 }
 
+void
+ksh_getopt_opterr(int ch, const char *name, const char *msg)
+{
+	static char buf[3] = { '-', KSH_BEL, '\0' };
+
+	buf[1] = ch;
+	if (name == null || name == kshname)
+		kwarnf(KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE |
+		    KWF_TWOMSG | KWF_NOERRNO, buf, msg);
+	else
+		kwarnf(KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE |
+		    KWF_THREEMSG | KWF_NOERRNO, name, buf, msg);
+}
+
 /*
  * print variable/alias value using necessary quotes
  * (POSIX says they should be suitable for re-entry...)
@@ -1396,7 +1491,7 @@ print_value_quoted(struct shf *shf, cons
 {
 	unsigned char c;
 	const unsigned char *p = (const unsigned char *)s;
-	bool inquote = true;
+	Wahr inquote = Ja;
 
 	/* first, special-case empty strings (for re-entrancy) */
 	if (!*s) {
@@ -1406,117 +1501,249 @@ print_value_quoted(struct shf *shf, cons
 	}
 
 	/* non-empty; check whether any quotes are needed */
-	while (rtt2asc(c = *p++) >= 32)
-		if (ctype(c, C_QUOTE | C_SPC))
-			inquote = false;
+	if (UTFMODE) {
+		/* C1 always escaped; multibyte makes this tricky */
+		while ((c = *p++) != 0) {
+			if (ctype(c, C_CNTRL)) {
+				dollarqU(shf, (const unsigned char *)s);
+				return;
+			}
+			/* anything out of ASCII present? */
+			if (rtt2asc(c) > 0x7EU) {
+				/* dollar-quote, but be prepared to redo */
+				char *guess;
+				struct shf to;
+
+				shf_sopen(NULL, 0, SHF_WR | SHF_DYNAMIC, &to);
+				c = dollarqU(&to, (const unsigned char *)s);
+				guess = shf_sclose(&to);
+				/* output guess if it was right */
+				if (c > 1)
+					shf_puts(guess, shf);
+				afree(guess, ATEMP);
+				if (c == 1)
+					goto always_single;
+				if (c == 0)
+ noquoteneeded:
+					shf_puts(s, shf);
+				return;
+			}
+			if (ctype(c, C_QUOTE | C_SPC))
+				inquote = Nee;
+		}
+		/* assert: c == 0; all chars in [20;7E] ASCII */
+#ifndef MKSH_EBCDIC
+	} else if (Flag(FASIS)) {
+		while ((c = *p++), !ksh_asisctrl(c))
+			if (ctype(c, C_QUOTE | C_SPC))
+				inquote = Nee;
+#endif
+	} else {
+		while ((c = *p++), !ksh_isctrl(c))
+			if (ctype(c, C_QUOTE | C_SPC))
+				inquote = Nee;
+	}
+	/* state: if c == 0, all chars printable, inquote shortcuts */
+
+	if (c) {
+		/* otherwise, escape control chars */
+		dollarq8(shf, (const unsigned char *)s);
+		return;
+	}
 
+	/* can we shortcut? */
+	if (inquote)
+		goto noquoteneeded;
+	/* no */
+ always_single:
+	/* all chars printable, no control chars, quote nicely */
+	inquote = Nee;
 	p = (const unsigned char *)s;
-	if (c == 0) {
-		if (inquote) {
-			/* nope, use the shortcut */
-			shf_puts(s, shf);
-			return;
+
+	while ((c = *p++) != 0) {
+		if (c == '\'') {
+			if (inquote) {
+				shf_scheck(3, shf);
+				shf_putc('\'', shf);
+				inquote = Nee;
+			}
+			shf_putc('\\', shf);
+		} else if (!inquote) {
+			shf_putc('\'', shf);
+			inquote = Ja;
 		}
+		shf_putc(c, shf);
+	}
+	if (inquote)
+		shf_putc('\'', shf);
+}
 
-		/* otherwise, quote nicely via state machine */
-		while ((c = *p++) != 0) {
-			if (c == '\'') {
+#define dollarq_Uctrl(c)	(!ctype((c), C_PRINT))
+#ifndef MKSH_SMALL
+#define dollarq_isctrlU(c)	dollarq_Uctrl(c)
+#else
+#define dollarq_isctrlU(c)	(UTFMODE ? dollarq_Uctrl(c) : ksh_isctrl8(c))
+#endif
+
+/* escape with $'...' (!MKSH_SMALL: in UTFMODE) */
+static unsigned int
+dollarqU(struct shf *shf, const unsigned char *s)
+{
+	unsigned char c;
+	unsigned int wc;
+	size_t n;
+	unsigned int rv = 0;
+
+	shf_putc('$', shf);
+	shf_putc('\'', shf);
+	while ((c = *s) != 0) {
+		if (
+#ifdef MKSH_SMALL
+		    UTFMODE &&
+#endif
+		    rtt2asc(c) >= 0xC2U && (n = utf_mbtowc(&wc,
+		    (const char *)s)) != (size_t)-1) {
+			/* valid UTF-8 multibyte character > 0x7F */
+			if ((wc ^ 0x80U) < 0x20U) {
+				/* C1 control character */
+				shf_fprintf(shf, "\\u%04X", wc);
+				rv = 2;
+				s += n;
+			} else {
 				/*
-				 * multiple single quotes or any of them
-				 * at the beginning of a string look nicer
-				 * this way than when simply substituting
+				 * print as-is; we assume the tty DTRT for
+				 * interlinear annotations, LTR/RTL mark,
+				 * U+2028, U+2029, U+2066..U+206F, etc.
 				 */
-				if (inquote) {
-					shf_putc('\'', shf);
-					inquote = false;
-				}
-				shf_putc('\\', shf);
-			} else if (!inquote) {
-				shf_putc('\'', shf);
-				inquote = true;
+				shf_wr_sm(s, n, shf);
 			}
-			shf_putc(c, shf);
+			continue;
 		}
-	} else {
-		unsigned int wc;
-		size_t n;
+		++s;
+		/* single octet */
+		rv |= ctype(c, C_QUOTE | C_SPC);
+		switch (c) {
+		/* see unbksl() in this file for comments */
+		case KSH_BEL:
+			c = 'a';
+			if (0)
+				/* FALLTHROUGH */
+		case '\b':
+			  c = 'b';
+			if (0)
+				/* FALLTHROUGH */
+		case '\f':
+			  c = 'f';
+			if (0)
+				/* FALLTHROUGH */
+		case '\n':
+			  c = 'n';
+			if (0)
+				/* FALLTHROUGH */
+		case '\r':
+			  c = 'r';
+			if (0)
+				/* FALLTHROUGH */
+		case '\t':
+			  c = 't';
+			if (0)
+				/* FALLTHROUGH */
+		case KSH_VTAB:
+			  c = 'v';
+			if (0)
+				/* FALLTHROUGH */
+		case KSH_ESC:
+			/* take E not e because \e is \ in *roff */
+			  c = 'E';
+			rv = 2;
+			/* FALLTHROUGH */
+		case '\\':
+			shf_putc('\\', shf);
 
-		/* use $'...' quote format */
-		shf_putc('$', shf);
-		shf_putc('\'', shf);
-		while ((c = *p) != 0) {
-#ifndef MKSH_EBCDIC
-			if (c >= 0xC2) {
-				n = utf_mbtowc(&wc, (const char *)p);
-				if (n != (size_t)-1) {
-					p += n;
-					shf_fprintf(shf, "\\u%04X", wc);
-					continue;
-				}
-			}
-#endif
-			++p;
-			switch (c) {
-			/* see unbksl() in this file for comments */
-			case KSH_BEL:
-				c = 'a';
-				if (0)
-					/* FALLTHROUGH */
-			case '\b':
-				  c = 'b';
-				if (0)
-					/* FALLTHROUGH */
-			case '\f':
-				  c = 'f';
-				if (0)
-					/* FALLTHROUGH */
-			case '\n':
-				  c = 'n';
-				if (0)
-					/* FALLTHROUGH */
-			case '\r':
-				  c = 'r';
-				if (0)
-					/* FALLTHROUGH */
-			case '\t':
-				  c = 't';
-				if (0)
-					/* FALLTHROUGH */
-			case KSH_VTAB:
-				  c = 'v';
-				if (0)
-					/* FALLTHROUGH */
-			case KSH_ESC:
-				/* take E not e because \e is \ in *roff */
-				  c = 'E';
+			if (0)
 				/* FALLTHROUGH */
-			case '\\':
-				shf_putc('\\', shf);
+		default:
+			  if (dollarq_isctrlU(c)) {
+				rv = 2;
+				/* FALLTHROUGH */
+		case '\'':
+				shf_fprintf(shf, "\\%03o", c);
+				break;
+			}
 
-				if (0)
-					/* FALLTHROUGH */
-			default:
-#if defined(MKSH_EBCDIC) || defined(MKSH_FAUX_EBCDIC)
-				  if (ksh_isctrl(c))
-#else
-				  if (!ctype(c, C_PRINT))
-#endif
-				    {
-					/* FALLTHROUGH */
-			case '\'':
-					shf_fprintf(shf, "\\%03o", c);
-					break;
-				}
+			shf_putc(c, shf);
+			break;
+		}
+	}
+	shf_putc('\'', shf);
+	return (rv);
+}
 
-				shf_putc(c, shf);
+#ifndef MKSH_SMALL
+/* escape with $'...' outside UTFMODE */
+static void
+dollarq8(struct shf *shf, const unsigned char *s)
+{
+	unsigned char c;
+
+	shf_putc('$', shf);
+	shf_putc('\'', shf);
+	while ((c = *s++) != 0) {
+		/* single octet */
+		switch (c) {
+		/* see unbksl() in this file for comments */
+		case KSH_BEL:
+			c = 'a';
+			if (0)
+				/* FALLTHROUGH */
+		case '\b':
+			  c = 'b';
+			if (0)
+				/* FALLTHROUGH */
+		case '\f':
+			  c = 'f';
+			if (0)
+				/* FALLTHROUGH */
+		case '\n':
+			  c = 'n';
+			if (0)
+				/* FALLTHROUGH */
+		case '\r':
+			  c = 'r';
+			if (0)
+				/* FALLTHROUGH */
+		case '\t':
+			  c = 't';
+			if (0)
+				/* FALLTHROUGH */
+		case KSH_VTAB:
+			  c = 'v';
+			if (0)
+				/* FALLTHROUGH */
+		case KSH_ESC:
+			/* take E not e because \e is \ in *roff */
+			  c = 'E';
+			/* FALLTHROUGH */
+		case '\\':
+			shf_putc('\\', shf);
+
+			if (0)
+				/* FALLTHROUGH */
+		default:
+			  if (ksh_isctrl8(c)) {
+				/* FALLTHROUGH */
+		case '\'':
+				shf_fprintf(shf, "\\%03o", c);
 				break;
 			}
+
+			shf_putc(c, shf);
+			break;
 		}
-		inquote = true;
 	}
-	if (inquote)
-		shf_putc('\'', shf);
+	shf_putc('\'', shf);
 }
+#endif
 
 /*
  * Print things in columns and rows - func() is called to format
@@ -1535,7 +1762,8 @@ print_columns(struct columnise_opts *opt
 
 	if (max_colz > 2147483646) {
 #ifndef MKSH_SMALL
-		internal_warningf("print_columns called with %s=%zu >= INT_MAX",
+		kwarnf0(KWF_INTERNAL | KWF_WARNING | KWF_NOERRNO,
+		    "print_columns called with %s=%zu >= INT_MAX",
 		    "max_col", max_colz);
 #endif
 		return;
@@ -1544,7 +1772,8 @@ print_columns(struct columnise_opts *opt
 
 	if (max_oct > 2147483646) {
 #ifndef MKSH_SMALL
-		internal_warningf("print_columns called with %s=%zu >= INT_MAX",
+		kwarnf0(KWF_INTERNAL | KWF_WARNING | KWF_NOERRNO,
+		    "print_columns called with %s=%zu >= INT_MAX",
 		    "max_oct", max_oct);
 #endif
 		return;
@@ -1584,7 +1813,7 @@ print_columns(struct columnise_opts *opt
 	max_col = -max_col;
 	goto prcols_hard;
 	while (r < rows) {
-		shf_putchar(opts->linesep, opts->shf);
+		shf_putc(opts->linesep, opts->shf);
  prcols_hard:
 		for (c = 0; c < cols; c++) {
 			if ((i = c * rows + r) >= n)
@@ -1600,7 +1829,7 @@ print_columns(struct columnise_opts *opt
 	}
  out:
 	if (opts->do_last)
-		shf_putchar(opts->linesep, opts->shf);
+		shf_putc(opts->linesep, opts->shf);
 	afree(str, ATEMP);
 }
 
@@ -1610,6 +1839,7 @@ strip_nuls(char *buf, size_t len)
 {
 	char *cp, *dp, *ep;
 
+	rndpush(buf, len);
 	if (!len || !(dp = memchr(buf, '\0', len)))
 		return;
 
@@ -1635,12 +1865,12 @@ ssize_t
 blocking_read(int fd, char *buf, size_t nbytes)
 {
 	ssize_t ret;
-	bool tried_reset = false;
+	Wahr tried_reset = Nee;
 
 	while ((ret = read(fd, buf, nbytes)) < 0) {
 		if (!tried_reset && errno == EAGAIN) {
 			if (reset_nonblock(fd) > 0) {
-				tried_reset = true;
+				tried_reset = Ja;
 				continue;
 			}
 			errno = EAGAIN;
@@ -1670,30 +1900,6 @@ reset_nonblock(int fd)
 	return (1);
 }
 
-/* getcwd(3) equivalent, allocates from ATEMP but doesn't resize */
-char *
-ksh_get_wd(void)
-{
-#ifdef MKSH__NO_PATH_MAX
-	char *rv, *cp;
-
-	if ((cp = get_current_dir_name())) {
-		strdupx(rv, cp, ATEMP);
-		free_gnu_gcdn(cp);
-	} else
-		rv = NULL;
-#else
-	char *rv;
-
-	if (!getcwd((rv = alloc(PATH_MAX + 1, ATEMP)), PATH_MAX)) {
-		afree(rv, ATEMP);
-		rv = NULL;
-	}
-#endif
-
-	return (rv);
-}
-
 #ifndef ELOOP
 #define ELOOP		E2BIG
 #endif
@@ -1703,17 +1909,9 @@ do_realpath(const char *upath)
 {
 	char *xp, *ip, *tp, *ipath, *ldest = NULL;
 	XString xs;
-	size_t pos, len;
-	int llen;
+	size_t pos, len, ldestlen = 1U;
+	ssize_t llen;
 	struct stat sb;
-#ifdef MKSH__NO_PATH_MAX
-	size_t ldestlen = 0;
-#define pathlen sb.st_size
-#define pathcnd (ldestlen < (pathlen + 1))
-#else
-#define pathlen PATH_MAX
-#define pathcnd (!ldest)
-#endif
 	/* max. recursion depth */
 	int symlinks = 32;
 
@@ -1729,11 +1927,12 @@ do_realpath(const char *upath)
 		strpathx(ipath, ldest, upath + 2, 0);
 #endif
 	} else {
+		const char *tcp;
+
 		/* upath is a relative pathname, prepend cwd */
-		if ((tp = ksh_get_wd()) == NULL || !mksh_abspath(tp))
+		if ((tcp = ksh_getwd()) == NULL)
 			return (NULL);
-		strpathx(ipath, tp, upath, 1);
-		afree(tp, ATEMP);
+		strpathx(ipath, tcp, upath, 1);
 	}
 
 	/* ipath and upath are in memory at the same time -> unchecked */
@@ -1810,21 +2009,24 @@ do_realpath(const char *upath)
 				goto notfound;
 			}
 
-			/* get symlink(7) target */
-			if (pathcnd) {
-#ifdef MKSH__NO_PATH_MAX
-				if (notoktoadd(pathlen, 1)) {
+			/* need to resize link target buffer? */
+			if ((mbiHUGE_U)sb.st_size > (mbiHUGE_U)(ldestlen - 1U)) {
+				/* like notoktoadd() */
+				if ((mbiHUGE_U)sb.st_size >= (mbiHUGE_U)mbiSIZE_MAX) {
 					errno = ENAMETOOLONG;
 					goto notfound;
 				}
-#endif
-				ldest = aresize(ldest, pathlen + 1, ATEMP);
+				ldestlen = (size_t)sb.st_size + 1U;
+				/* assert(ldestlen <= mbiSIZE_MAX) */
+				ldest = aresize(ldest, ldestlen, ATEMP);
 			}
-			llen = readlink(Xstring(xs, xp), ldest, pathlen);
-			if (llen < 0)
+			/* get symlink(7) target */
+			errno = ENAMETOOLONG; /* for overflow case */
+			llen = readlink(Xstring(xs, xp), ldest, ldestlen);
+			if (llen == -1 || (size_t)llen >= ldestlen)
 				/* oops... */
 				goto notfound;
-			ldest[llen] = '\0';
+			ldest[(size_t)llen] = '\0';
 
 			/*
 			 * restart if symlink target is an absolute path,
@@ -1910,15 +2112,12 @@ do_realpath(const char *upath)
 
  notfound:
 	/* save; freeing memory might trash it */
-	llen = errno;
+	symlinks = errno;
 	afree(ldest, ATEMP);
 	afree(ipath, ATEMP);
 	Xfree(xs, xp);
-	errno = llen;
+	errno = symlinks;
 	return (NULL);
-
-#undef pathlen
-#undef pathcnd
 }
 
 /**
@@ -1944,17 +2143,21 @@ make_path(const char *cwd, const char *f
     int *phys_pathp)
 {
 	int rval = 0;
-	bool use_cdpath = true;
+	Wahr use_cdpath = Ja;
 	char *plist;
 	size_t len, plen = 0;
 	char *xp = Xstring(*xsp, xp);
 
-	if (!file)
+	if (!file) {
 		file = null;
+#ifdef DEBUG
+		assert(file[0] == '\0'); /* for Coverity */
+#endif
+	}
 
 	if (mksh_abspath(file)) {
 		*phys_pathp = 0;
-		use_cdpath = false;
+		use_cdpath = Nee;
 	} else {
 		if (file[0] == '.') {
 			char c = file[1];
@@ -1962,12 +2165,12 @@ make_path(const char *cwd, const char *f
 			if (c == '.')
 				c = file[2];
 			if (mksh_cdirsep(c) || c == '\0')
-				use_cdpath = false;
+				use_cdpath = Nee;
 		}
 
 		plist = *cdpathp;
 		if (!plist)
-			use_cdpath = false;
+			use_cdpath = Nee;
 		else if (use_cdpath) {
 			char *pend = plist;
 
@@ -2037,17 +2240,17 @@ simplify_path(char *p)
 {
 	char *dp, *ip, *sp, *tp;
 	size_t len;
-	bool needslash;
+	Wahr needslash;
 #ifdef MKSH_DOSPATH
-	bool needdot = true;
+	Wahr needdot = Ja;
 
 	/* keep drive letter */
 	if (mksh_drvltr(p)) {
 		p += 2;
-		needdot = false;
+		needdot = Nee;
 	}
 #else
-#define needdot true
+#define needdot Ja
 #endif
 
 	switch (*p) {
@@ -2066,10 +2269,10 @@ simplify_path(char *p)
 			++p;
 #endif
 		}
-		needslash = true;
+		needslash = Ja;
 		break;
 	default:
-		needslash = false;
+		needslash = Nee;
 	}
 	dp = ip = sp = p;
 
@@ -2098,7 +2301,7 @@ simplify_path(char *p)
 					goto strip_last_component;
 				else if (dp > sp) {
 					/* relative path, with subpaths */
-					needslash = false;
+					needslash = Nee;
  strip_last_component:
 					/* strip off last pathname component */
 					while (dp > sp)
@@ -2112,7 +2315,7 @@ simplify_path(char *p)
 					/* keep dotdot-slash if not absolute */
 					*dp++ = '.';
 					*dp++ = '.';
-					needslash = true;
+					needslash = Ja;
 					sp = dp;
 				}
 				/* then continue with the next one */
@@ -2128,7 +2331,7 @@ simplify_path(char *p)
 		dp += len;
 
 		/* append slash if we continue */
-		needslash = true;
+		needslash = Ja;
 		/* try next component */
 	}
 	if (dp == p) {
@@ -2145,28 +2348,25 @@ simplify_path(char *p)
 void
 set_current_wd(const char *nwd)
 {
-	char *allocd = NULL;
-
 	if (nwd == NULL) {
-		allocd = ksh_get_wd();
-		nwd = allocd ? allocd : null;
+		nwd = ksh_getwd();
+		if (nwd == NULL)
+			nwd = null;
 	}
 
 	afree(current_wd, APERM);
 	strdupx(current_wd, nwd, APERM);
-
-	afree(allocd, ATEMP);
 }
 
 int
 c_cd(const char **wp)
 {
 	int optc, rv, phys_path;
-	bool physical = tobool(Flag(FPHYSICAL));
+	Wahr physical = isWahr(Flag(FPHYSICAL));
 	/* was a node from cdpath added in? */
 	int cdnode;
 	/* show where we went?, error for $PWD */
-	bool printpath = false, eflag = false;
+	Wahr printpath = Nee, eflag = Nee;
 	struct tbl *pwd_s, *oldpwd_s;
 	XString xs;
 	char *dir, *allocd = NULL, *tryp, *pwd, *cdpath;
@@ -2174,13 +2374,13 @@ c_cd(const char **wp)
 	while ((optc = ksh_getopt(wp, &builtin_opt, "eLP")) != -1)
 		switch (optc) {
 		case 'e':
-			eflag = true;
+			eflag = Ja;
 			break;
 		case 'L':
-			physical = false;
+			physical = Nee;
 			break;
 		case 'P':
-			physical = true;
+			physical = Ja;
 			break;
 		case '?':
 			return (2);
@@ -2209,7 +2409,7 @@ c_cd(const char **wp)
 				bi_errorf(Tno_OLDPWD);
 				return (2);
 			}
-			printpath = true;
+			printpath = Ja;
 		} else {
 			strdupx(allocd, wp[0], ATEMP);
 			dir = allocd;
@@ -2228,25 +2428,23 @@ c_cd(const char **wp)
 		 * substitution fails because the cd fails we could try to
 		 * find another substitution. For now, we don't.
 		 */
-		if ((cp = strstr(current_wd, wp[0])) == NULL) {
+		if ((cp = ucstrstr(current_wd, wp[0])) == NULL) {
 			bi_errorf(Tbadsubst);
 			return (2);
 		}
 		/*-
 		 * ilen = part of current_wd before wp[0]
 		 * elen = part of current_wd after wp[0]
-		 * because current_wd and wp[1] need to be in memory at the
-		 * same time beforehand the addition can stay unchecked
 		 */
 		ilen = cp - current_wd;
 		olen = strlen(wp[0]);
 		nlen = strlen(wp[1]);
 		elen = strlen(current_wd + ilen + olen) + 1;
-		dir = allocd = alloc(ilen + nlen + elen, ATEMP);
+		dir = allocd = alloc1(ilen + elen, nlen, ATEMP);
 		memcpy(dir, current_wd, ilen);
 		memcpy(dir + ilen, wp[1], nlen);
 		memcpy(dir + ilen + nlen, current_wd + ilen + olen, elen);
-		printpath = true;
+		printpath = Ja;
 	} else {
 		bi_errorf(Ttoo_many_args);
 		return (2);
@@ -2263,12 +2461,8 @@ c_cd(const char **wp)
 	}
 #endif
 
-#ifdef MKSH__NO_PATH_MAX
 	/* only a first guess; make_path will enlarge xs if necessary */
-	XinitN(xs, 1024, ATEMP);
-#else
-	XinitN(xs, PATH_MAX, ATEMP);
-#endif
+	XinitN(xs, 384U, ATEMP);
 
 	cdpath = str_val(global("CDPATH"));
 	do {
@@ -2298,14 +2492,14 @@ c_cd(const char **wp)
 	allocd = NULL;
 
 	/* Clear out tracked aliases with relative paths */
-	flushcom(false);
+	flushcom(Nee);
 
 	/*
 	 * Set OLDPWD (note: unsetting OLDPWD does not disable this
 	 * setting in AT&T ksh)
 	 */
 	if (current_wd[0])
-		/* Ignore failure (happens if readonly or integer) */
+		/* Ignore failure (happens if read-only or integer) */
 		setstr(oldpwd_s, current_wd, KSH_RETURN_ERROR);
 
 	if (!mksh_abspath(Xstring(xs, xp))) {
@@ -2324,7 +2518,7 @@ c_cd(const char **wp)
 		char *ptmp = pwd;
 
 		set_current_wd(ptmp);
-		/* Ignore failure (happens if readonly or integer) */
+		/* Ignore failure (happens if read-only or integer) */
 		setstr(pwd_s, ptmp, KSH_RETURN_ERROR);
 	} else {
 		set_current_wd(null);
@@ -2341,116 +2535,176 @@ c_cd(const char **wp)
 	return (rv);
 }
 
-
-#ifdef KSH_CHVT_CODE
 extern void chvt_reinit(void);
 
 static void
 chvt(const Getopt *go)
 {
+	char buf[99], ch;
 	const char *dv = go->optarg;
-	char *cp = NULL;
-	int fd;
+	int fd, pfd[2];
+	pid_t cpid;
+	Wahr isdaemon = Nee, dowait = Nee;
+#ifndef MKSH_DISABLE_REVOKE_WARNING
+	int revwarn = 0;
+#if !HAVE_REVOKE
+#define ifrevwarn
+#else
+#define ifrevwarn if (revwarn)
+#endif
+#endif
 
-	switch (*dv) {
-	case '-':
+	switch (ord(*dv)) {
+	case ORD('-'):
+		isdaemon = Ja;
 		dv = "/dev/null";
 		break;
-	case '!':
+	case ORD('!'):
+		dowait = Ja;
 		++dv;
 		/* FALLTHROUGH */
 	default: {
 		struct stat sb;
 
 		if (stat(dv, &sb)) {
-			cp = shf_smprintf("/dev/ttyC%s", dv);
-			dv = cp;
-			if (stat(dv, &sb)) {
-				memmove(cp + 1, cp, /* /dev/tty */ 8);
-				dv = cp + 1;
-				if (stat(dv, &sb)) {
-					errorf(Tf_sD_sD_s, "chvt",
-					    "can't find tty", go->optarg);
-				}
-			}
-		}
-		if (!(sb.st_mode & S_IFCHR))
-			errorf(Tf_sD_sD_s, "chvt", "not a char device", dv);
+			int E = errno;
+
+			memcpy(buf, "/dev/ttyC", 9U);
+			strlcpy(buf + 9U, dv, sizeof(buf) - 9U);
+			if (stat(buf, &sb)) {
+				strlcpy(buf + 8U, dv, sizeof(buf) - 8U);
+				if (stat(buf, &sb))
+					kerrf(KWF_VERRNO | KWF_ERR(1) |
+					    KWF_PREFIX | KWF_TWOMSG, E,
+					    "chvt", dv);
+			}
+			dv = buf;
+		}
+		if (!S_ISCHR(sb.st_mode))
+			kerrf(KWF_VERRNO | KWF_ERR(1) | KWF_PREFIX |
+			    KWF_TWOMSG, (int)(ENOTTY), "chvt", dv);
 #ifndef MKSH_DISABLE_REVOKE_WARNING
-#if HAVE_REVOKE
-		if (revoke(dv))
+#if !HAVE_REVOKE
+#ifdef ENOSYS
+		revwarn = ENOSYS;
+#else
+		revwarn = EINVAL;
 #endif
-			warningf(false, Tf_sD_s_s, "chvt",
-			    "new shell is potentially insecure, can't revoke",
-			    dv);
+#else
+		revwarn = revoke(dv) ? errno : 0;
+#endif
+		ifrevwarn kwarnf(KWF_VERRNO | KWF_PREFIX | KWF_THREEMSG,
+		    revwarn, "chvt", dv,
+		    "can't revoke; new shell is potentially insecure");
 #endif
 	    }
 	}
-	if ((fd = binopen2(dv, O_RDWR)) < 0) {
-		sleep(1);
-		if ((fd = binopen2(dv, O_RDWR)) < 0) {
-			errorf(Tf_sD_s_s, "chvt", Tcant_open, dv);
-		}
-	}
-	if (go->optarg[0] != '!') {
-		switch (fork()) {
-		case -1:
-			errorf(Tf_sD_s_s, "chvt", "fork", "failed");
-		case 0:
-			break;
-		default:
-			exit(0);
+	if (pipe(pfd))
+		kerrf(KWF_ERR(1) | KWF_PREFIX | KWF_TWOMSG, "chvt", "pipe");
+	switch ((cpid = fork())) {
+	case -1:
+		close(pfd[0]);
+		close(pfd[1]);
+		kerrf(KWF_ERR(1) | KWF_PREFIX | KWF_TWOMSG, "chvt", "fork");
+	case 0:
+		close(pfd[0]);
+		break;
+	default:
+		close(pfd[1]);
+		if (read(pfd[0], &ch, 1) != 1 || !isch(ch, '.'))
+			kerrf(KWF_ERR(1) | KWF_PREFIX | KWF_THREEMSG |
+			    KWF_NOERRNO, "chvt", dv,
+			    "child process initialisation failure");
+		close(pfd[0]);
+		if (dowait) {
+			pid_t corpse;
+			int status;
+
+			while (/* CONSTCOND */ 1) {
+#ifndef MKSH_NOPROSPECTOFWORK
+				corpse = waitpid(cpid, &status, 0);
+#else
+				corpse = wait(&status);
+#endif
+				if (corpse == -1) {
+					status = errno;
+					if (status == ECHILD)
+						break;
+					if (status == EINTR)
+						continue;
+					kerrf(KWF_ERR(1) | KWF_PREFIX |
+					    KWF_TWOMSG, "chvt", "wait");
+				}
+#ifdef MKSH_NOPROSPECTOFWORK
+				/* should not happen but… */
+				if (corpse != cpid)
+					continue;
+#endif
+				if (WIFSIGNALED(status)) {
+					status = WTERMSIG(status);
+					if (status > 0 && status < ksh_NSIG)
+						dv = ksh_sigmess(status);
+					else
+						dv = NULL;
+					if (ksh_sigmessf(dv))
+						dv = "Signalled";
+					kwarnf(KWF_PREFIX | KWF_TWOMSG |
+					    KWF_NOERRNO, "chvt", dv);
+				} else if (WIFEXITED(status)) {
+					status = (WEXITSTATUS(status)) & 255;
+					if (!status)
+						break;
+					kwarnf0(KWF_PREFIX | KWF_NOERRNO,
+					    TchvtDone, status);
+				} else
+					continue;
+			}
 		}
+		exit(0);
 	}
 	if (setsid() == -1)
-		errorf(Tf_sD_s_s, "chvt", "setsid", "failed");
-	if (go->optarg[0] != '-') {
+		kerrf(KWF_ERR(1) | KWF_PREFIX | KWF_TWOMSG, "chvt", "setsid");
+	if ((fd = binopen2(dv, O_RDWR)) < 0) {
+		sleep(1);
+		if ((fd = binopen2(dv, O_RDWR)) < 0)
+			kerrf(KWF_ERR(1) | KWF_PREFIX | KWF_THREEMSG,
+			    "chvt", dv, Topen);
+	}
+	if (!isdaemon) {
+#ifdef TIOCSCTTY
 		if (ioctl(fd, TIOCSCTTY, NULL) == -1)
-			errorf(Tf_sD_s_s, "chvt", "TIOCSCTTY", "failed");
+			kerrf(KWF_ERR(1) | KWF_PREFIX | KWF_TWOMSG,
+			    "chvt", "TIOCSCTTY");
+#endif
+#if HAVE_TERMIOS_H
 		if (tcflush(fd, TCIOFLUSH))
-			errorf(Tf_sD_s_s, "chvt", "TCIOFLUSH", "failed");
+			kerrf(KWF_ERR(1) | KWF_PREFIX | KWF_TWOMSG,
+			    "chvt", "TCIOFLUSH");
+#else
+		if (ioctl(fd, TCFLSH, 2) == -1)
+			kerrf(KWF_ERR(1) | KWF_PREFIX | KWF_TWOMSG,
+			    "chvt", "TCFLSH");
+#endif
 	}
-	ksh_dup2(fd, 0, false);
-	ksh_dup2(fd, 1, false);
-	ksh_dup2(fd, 2, false);
+	ksh_dup2(fd, 0, Nee);
+	ksh_dup2(fd, 1, Nee);
+	ksh_dup2(fd, 2, Nee);
+#ifndef MKSH_DISABLE_REVOKE_WARNING
+	if (!isdaemon) {
+		ifrevwarn kwarnf(KWF_VERRNO | KWF_PREFIX | KWF_THREEMSG,
+		    revwarn, "chvt", dv,
+		    "can't revoke; new shell is potentially insecure");
+	}
+#endif
 	if (fd > 2)
 		close(fd);
-	rndset((unsigned long)chvt_rndsetup(go, sizeof(Getopt)));
+	chvt_rndsetup(go, sizeof(Getopt));
 	chvt_reinit();
+	/* signal parent the all OK */
+	if (write(pfd[1], Tdot, 1) != 1)
+		kwarnf(KWF_PREFIX | KWF_TWOMSG, "chvt", "write");
+	close(pfd[1]);
 }
-#endif
-
-#ifdef DEBUG
-char *
-strchr(char *p, int ch)
-{
-	for (;; ++p) {
-		if (*p == ch)
-			return (p);
-		if (!*p)
-			return (NULL);
-	}
-	/* NOTREACHED */
-}
-
-char *
-strstr(char *b, const char *l)
-{
-	char first, c;
-	size_t n;
-
-	if ((first = *l++) == '\0')
-		return (b);
-	n = strlen(l);
- strstr_look:
-	while ((c = *b++) != first)
-		if (c == '\0')
-			return (NULL);
-	if (strncmp(b, l, n))
-		goto strstr_look;
-	return (b - 1);
-}
-#endif
 
 #if defined(MKSH_SMALL) && !defined(MKSH_SMALL_BUT_FAST)
 char *
@@ -2480,10 +2734,13 @@ strdup_i(const char *src, Area *ap)
 } while (/* CONSTCOND */ 0)
 
 int
-getrusage(int what, struct rusage *ru)
+ksh_getrusage(int what, struct rusage *ru)
 {
 	struct tms tms;
 	clock_t u, s;
+#ifndef CLK_TCK
+	long CLK_TCK;
+#endif
 
 	if (/* ru == NULL || */ times(&tms) == (clock_t)-1)
 		return (-1);
@@ -2501,6 +2758,16 @@ getrusage(int what, struct rusage *ru)
 		errno = EINVAL;
 		return (-1);
 	}
+#ifndef CLK_TCK
+#ifdef ENOSYS
+	errno = ENOSYS;
+#else
+	errno = EINVAL;
+#endif
+	if ((CLK_TCK = sysconf(_SC_CLK_TCK)) == -1L)
+		kerrf(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_ONEMSG,
+		    "sysconf(_SC_CLK_TCK)");
+#endif
 	INVTCK(ru->ru_utime, u);
 	INVTCK(ru->ru_stime, s);
 	return (0);
@@ -2516,7 +2783,7 @@ getrusage(int what, struct rusage *ru)
  * escape sequence was found
  */
 int
-unbksl(bool cstyle, int (*fg)(void), void (*fp)(int))
+unbksl(Wahr cstyle, int (*fg)(void), void (*fp)(int))
 {
 	int wc, i, c, fc, n;
 
@@ -2532,7 +2799,7 @@ unbksl(bool cstyle, int (*fg)(void), voi
 		if (!cstyle)
 			goto unknown_escape;
 		c = (*fg)();
-		wc = ksh_toctrl(c);
+		wc = asc2rtt(ord(c) == ORD('?') ? 0x7F : rtt2asc(c) & 0x9F);
 		break;
 	case 'E':
 	case 'e':
@@ -2637,3 +2904,61 @@ unbksl(bool cstyle, int (*fg)(void), voi
 
 	return (wc);
 }
+
+#ifdef DEBUG
+#undef strchr
+/* pre-initio() */
+char *
+ucstrchr(char *s, int c)
+{
+	return (strchr(s, c));
+}
+
+const char *
+cstrchr(const char *s, int c)
+{
+	return (strchr(s, c));
+}
+#endif
+
+#if !HAVE_STRSTR
+char *
+ucstrstr(char *big, const char *little)
+{
+	union mksh_cchack res;
+
+	res.ro = cstrstr(big, little);
+	return (res.rw);
+}
+
+const char *
+cstrstr(const char *big, const char *little)
+{
+	char first, c;
+	size_t n;
+
+	if ((first = *little++) == '\0')
+		return (big);
+	n = strlen(little);
+ strstr_look:
+	while ((c = *big++) != first)
+		if (c == '\0')
+			return (NULL);
+	if (strncmp(big, little, n))
+		goto strstr_look;
+	return (big - 1);
+}
+#elif defined(DEBUG)
+#undef strstr
+char *
+ucstrstr(char *big, const char *little)
+{
+	return (strstr(big, little));
+}
+
+const char *
+cstrstr(const char *big, const char *little)
+{
+	return (strstr(big, little));
+}
+#endif
--- mksh-59c.orig/mksh.1
+++ mksh-59c/mksh.1
@@ -1,10 +1,10 @@
-.\" $MirOS: src/bin/mksh/mksh.1,v 1.494 2020/10/01 22:39:57 tg Exp $
+.\" $MirOS: src/bin/mksh/mksh.1,v 1.549+locale-tracking 2025/12/23 21:49:52 tg Exp $
 .\" $OpenBSD: ksh.1,v 1.160 2015/07/04 13:27:04 feinerer Exp $
 .\"-
 .\" Copyright © 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
 .\"		2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017,
-.\"		2018, 2019, 2020
-.\"	mirabilos <m@mirbsd.org>
+.\"		2018, 2019, 2020, 2021, 2022, 2023, 2024, 2025
+.\"	mirabilos <m$(date +%Y)@mirbsd.de>
 .\"
 .\" Provided that these terms and disclaimer and all copyright notices
 .\" are retained or reproduced in an accompanying document, permission
@@ -21,7 +21,15 @@
 .\" damage or existence of a defect, except proven that it results out
 .\" of said person’s immediate fault when using the work as intended.
 .\"-
-.\" Try to make GNU groff and AT&T nroff more compatible
+.\" $miros: contrib/samples/portmdoc,v 1.27 2025/06/20 17:30:44 tg Exp $
+.\"-
+.\" Copyright © 2008, 2009, 2010, 2016, 2018, 2020, 2023, 2025
+.\"	mirabilos <m$(date +%Y)@mirbsd.de>
+.\" Copyright © 1991, 1993
+.\"	The Regents of the University of California. (Ⓕ 3-clause BSD)
+.\" All rights reserved.
+.\"
+.\" Glue GNU groff (BSD and GNU mdoc both) to AT&T nroff (UCB mdoc).
 .\" * ` generates ‘ in gnroff, so use \`
 .\" * ' generates ’ in gnroff, \' generates ´, so use \*(aq
 .\" * - generates ‐ in gnroff, \- generates −, so .tr it to -
@@ -29,23 +37,41 @@
 .\" * ~ is size-reduced and placed atop in groff, so use \*(TI
 .\" * ^ is size-reduced and placed atop in groff, so use \*(ha
 .\" * \(en does not work in nroff, so use \*(en for a solo en dash
-.\" *   and \*(EM for a correctly spaced em dash
+.\" *   and \*(EM for a correctly spaced em dash (omit space around!)
 .\" * <>| are problematic, so redefine and use \*(Lt\*(Gt\*(Ba
 .\" Also make sure to use \& *before* a punctuation char that is to not
 .\" be interpreted as punctuation, and especially with two-letter words
 .\" but also (after) a period that does not end a sentence (“e.g.\&”).
-.\" The section after the "doc" macropackage has been loaded contains
-.\" additional code to convene between the UCB mdoc macropackage (and
-.\" its variant as BSD mdoc in groff) and the GNU mdoc macropackage.
+.\"-
+.\"
+.\" Implement .Dd with the Mdocdate RCS keyword
+.\"
+.rn Dd xD
+.de Dd
+.ie \\$1$Mdocdate: \{\
+.	xD \\$2 \\$3, \\$4
+.\}
+.el .xD \\$1 \\$2 \\$3
+..
+.\"
+.\" .Dd must come before most everything, because when called
+.\" with -mandoc it loads -mdoc via .so in .Dd (first macro).
+.\"
+.Dd $Mdocdate: December 23 2025 $
+.\"
+.\" Check which macro package we use, and do other -mdoc setup.
 .\"
 .ie \n(.g \{\
+.	if n .ss \n[.ss] 0
 .	if \*[.T]ascii .tr \-\N'45'
 .	if \*[.T]latin1 .tr \-\N'45'
 .	if \*[.T]utf8 .tr \-\N'45'
-.	ds <= \[<=]
-.	ds >= \[>=]
-.	ds Rq \[rq]
-.	ds Lq \[lq]
+.	if \*[.T]utf8 .tr \(la\*(Lt
+.	if \*[.T]utf8 .tr \(ra\*(Gt
+.	ds <= \(<=
+.	ds >= \(>=
+.	ds Rq \(rq
+.	ds Lq \(lq
 .	ds sL \(aq
 .	ds sR \(aq
 .	if \*[.T]utf8 .ds sL `
@@ -56,56 +82,36 @@
 .	ds TI \(ti
 .	ds ha \(ha
 .	ds en \(en
+.	ie d volume-ds-1 .ds tT gnu
+.	el .ie d doc-volume-ds-1 .ds tT gnp
+.	el .ds tT bsd
 .\}
 .el \{\
 .	ds aq '
 .	ds TI ~
 .	ds ha ^
 .	ds en \(em
+.	ds tT ucb
 .\}
 .ie n \{\
-.	ds EM \ \*(en\ \&
+.	ds EM \ \(em\ \&
 .\}
 .el \{\
-.	ds EM \f(TR\^\(em\^\fP
-.\}
-.\"
-.\" Implement .Dd with the Mdocdate RCS keyword
-.\"
-.rn Dd xD
-.de Dd
-.ie \\$1$Mdocdate: \{\
-.	xD \\$2 \\$3, \\$4
-.\}
-.el .xD \\$1 \\$2 \\$3 \\$4 \\$5 \\$6 \\$7 \\$8
-..
-.\"
-.\" .Dd must come before definition of .Mx, because when called
-.\" with -mandoc, it might implement .Mx itself, but we want to
-.\" use our own definition. And .Dd must come *first*, always.
-.\"
-.Dd $Mdocdate: October 1 2020 $
-.\"
-.\" Check which macro package we use, and do other -mdoc setup.
-.\"
-.ie \n(.g \{\
-.	if \*[.T]utf8 .tr \[la]\*(Lt
-.	if \*[.T]utf8 .tr \[ra]\*(Gt
-.	ie d volume-ds-1 .ds tT gnu
-.	el .ie d doc-volume-ds-1 .ds tT gnp
-.	el .ds tT bsd
+.	ds EM \f(TR\|\(em\|\fP\&
 .\}
-.el .ds tT ucb
 .\"
+.\" Add UCB mdoc compatibility to GNU mdoc
 .\" Implement .Mx (MirBSD)
 .\"
 .ie "\*(tT"gnu" \{\
+.	ds sP \s0
+.	ds tN \*[Tn-font-size]
 .	eo
 .	de Mx
 .	nr curr-font \n[.f]
 .	nr curr-size \n[.ps]
 .	ds str-Mx \f[\n[curr-font]]\s[\n[curr-size]u]
-.	ds str-Mx1 \*[Tn-font-size]\%MirBSD\*[str-Mx]
+.	ds str-Mx1 \*(tN\%MirBSD\*[str-Mx]
 .	if !\n[arg-limit] \
 .	if \n[.$] \{\
 .	ds macro-name Mx
@@ -114,7 +120,7 @@
 .	if (\n[arg-limit] > \n[arg-ptr]) \{\
 .	nr arg-ptr +1
 .	ie (\n[type\n[arg-ptr]] == 2) \
-.	as str-Mx1 \~\*[arg\n[arg-ptr]]
+.	ds str-Mx1 \*(tN\%MirBSD\~#\*[arg\n[arg-ptr]]\*[str-Mx]
 .	el \
 .	nr arg-ptr -1
 .	\}
@@ -127,17 +133,31 @@
 .	parse-space-vector
 .	print-recursive
 ..
+.	de Aq
+.	if !\n[arg-limit] \
+.	ds macro-name Aq
+.	ie \n[in-authors-section] \{\
+.		ds quote-left \*(Lt
+.		ds quote-right \*(Gt
+.	\}
+.	el \{\
+.		ds quote-left \[la]
+.		ds quote-right \[ra]
+.	\}
+.	enclose-string \$@
+..
 .	ec
-.	ds sP \s0
-.	ds tN \*[Tn-font-size]
 .\}
 .el .ie "\*(tT"gnp" \{\
+.	ds sP \s0
+.	ie t .ds tN \s[(\n[.ps]u-1z)]
+.	el .ds tN
 .	eo
 .	de Mx
 .	nr doc-curr-font \n[.f]
 .	nr doc-curr-size \n[.ps]
 .	ds doc-str-Mx \f[\n[doc-curr-font]]\s[\n[doc-curr-size]u]
-.	ds doc-str-Mx1 \*[doc-Tn-font-size]\%MirBSD\*[doc-str-Mx]
+.	ds doc-str-Mx1 \*(tN\%MirBSD\*[doc-str-Mx]
 .	if !\n[doc-arg-limit] \
 .	if \n[.$] \{\
 .	ds doc-macro-name Mx
@@ -146,7 +166,7 @@
 .	if (\n[doc-arg-limit] > \n[doc-arg-ptr]) \{\
 .	nr doc-arg-ptr +1
 .	ie (\n[doc-type\n[doc-arg-ptr]] == 2) \
-.	as doc-str-Mx1 \~\*[doc-arg\n[doc-arg-ptr]]
+.	ds doc-str-Mx1 \*(tN\%MirBSD\~#\*[doc-arg\n[doc-arg-ptr]]\*[doc-str-Mx]
 .	el \
 .	nr doc-arg-ptr -1
 .	\}
@@ -159,9 +179,13 @@
 .	doc-parse-space-vector
 .	doc-print-recursive
 ..
+.	am1 Sh
+.	if d doc-sec-head .if !"\*[doc-sec-head]"" \{\
+.		if "\*[doc-sec-head]"\*[doc-section-synopsis]" .na
+.		if "\*[doc-sec-head]"\*[doc-section-see-also]" .na
+.	\}
+..
 .	ec
-.	ds sP \s0
-.	ds tN \*[doc-Tn-font-size]
 .\}
 .el \{\
 .	de Mx
@@ -169,13 +193,18 @@
 .	nr cZ \\n(.s
 .	ds aa \&\f\\n(cF\s\\n(cZ
 .	if \\n(aC==0 \{\
-.		ie \\n(.$==0 \&MirBSD\\*(aa
+.		ie \\n(.$==0 \&\\*(tNMirBSD\\*(aa
 .		el .aV \\$1 \\$2 \\$3 \\$4 \\$5 \\$6 \\$7 \\$8 \\$9
 .	\}
 .	if \\n(aC>\\n(aP \{\
 .		nr aP \\n(aP+1
 .		ie \\n(C\\n(aP==2 \{\
-.			as b1 \&MirBSD\ #\&\\*(A\\n(aP\\*(aa
+.			nr xX 0
+.			nr xX 1+\\*(A\\n(aP
+.			as b1 \&\\*(tNMirBSD\ \&
+.			if \\n(xX>0 .as b1 #\&
+.			as b1 \&\\*(A\\n(aP\\*(aa
+.			rr xX
 .			ie \\n(aC>\\n(aP \{\
 .				nr aP \\n(aP+1
 .				nR
@@ -183,12 +212,13 @@
 .			el .aZ
 .		\}
 .		el \{\
-.			as b1 \&MirBSD\\*(aa
+.			as b1 \&\\*(tNMirBSD\\*(aa
 .			nR
 .		\}
 .	\}
 ..
 .\}
+.\" </MirCVS://contrib/samples/portmdoc>
 .\"-
 .Dt MKSH 1
 .Os MirBSD
@@ -198,29 +228,39 @@
 .Nd MirBSD Korn shell
 .Sh SYNOPSIS
 .Nm
-.Bk -words
 .Op Fl +abCefhiklmnprUuvXx
-.Oo
-.Fl T Oo Ar \&! Oc Ns Ar tty
-\*(Ba
-.Ar \&\-
+.Op Fl +o Ar option
+.Oo Fl T Oo Ar !\&
+.Oc Ns Ar tty Ns \*(Ba Ns Ar \-\&
 .Oc
+.Op Ar file Op Ar arg1 ...
+.Nm
+.Op Fl +abCefhiklmnprUuvXx
 .Op Fl +o Ar option
-.Oo
-.Fl c Ar string \*(Ba
-.Fl s \*(Ba
-.Ar file
-.Op Ar argument ...
+.Oo Fl T Oo Ar !\&
+.Oc Ns Ar tty Ns \*(Ba Ns Ar \-\&
+.Oc
+.Fl c
+.Ar cmd
+.Op Ar arg0 ...
+.Nm
+.Op Fl +abCefhiklmnprUuvXx
+.Op Fl +o Ar option
+.Oo Fl T Oo Ar !\&
+.Oc Ns Ar tty Ns \*(Ba Ns Ar \-\&
 .Oc
-.Ek
+.Fl s
+.Op Ar arg1 ...
 .Nm builtin-name
 .Op Ar argument ...
 .Sh DESCRIPTION
 .Nm
 is a command interpreter intended for both interactive and shell
 script use.
-Its command language is a superset of the
+Its command language is a superset of both
 .Xr sh C
+and
+.Tn POSIX
 shell language and largely compatible to the original Korn shell.
 At times, this manual page may give scripting advice; while it
 sometimes does take portable shell scripting or various standards
@@ -231,15 +271,43 @@ in mind and should be taken as such.
 Please refer to:
 .Pa http://www.mirbsd.org/mksh\-faq.htm#sowhatismksh
 .Ss Invocation
-Most builtins can be called directly, for example if a link points from its
-name to the shell; not all make sense, have been tested or work at all though.
+Most builtins can be called directly, for example if a link or
+.Xr symlink 7
+points to
+.Nm ,
+or if
+.Va argv[0]
+is set correspondingly;
+this does not make sense for, or works properly with, all built-in utilities though.
+Debug builds can also be invoked as
+.Nm \-\-unparse
+to display the parse tree of each command before running it.
 .Pp
 The options are as follows:
-.Bl -tag -width XcXstring
-.It Fl c Ar string
+.Bl -tag -width 2n
+.It Fl c
 .Nm
 will execute the command(s) contained in
-.Ar string .
+.Ar cmd ,
+setting
+.Li $0
+to
+.Ar arg0
+.Pq if present ,
+.Li $1
+to the next argument, etc.
+If compiled with
+.Dv \-DMKSH_MIDNIGHTBSD01ASH_COMPAT
+and in
+.Fl o Ic sh
+mode, a
+.Dq Li \-\-
+argument directly following
+.Ar cmd
+is ignored for compatibility with the legacy
+.Fx
+.Nm sh ;
+this is deprecated and may go away in the future.
 .It Fl i
 Interactive shell.
 A shell that reads commands from standard input is
@@ -270,36 +338,42 @@ option is on by default (see the
 command below).
 .It Fl l
 Login shell.
-If the name or basename the shell is called with (i.e. argv[0])
-starts with
+If the name the shell is called as
+.Pq i.e.\& Va argv[0]
+or its basename begins with a dash
+.Pq hyphen-minus
 .Ql \-
-or if this option is used,
-the shell is assumed to be a login shell; see
+or if this option is given,
+the shell is a
+.Dq login shell ;
+see
 .Sx Startup files
 below.
 .It Fl p
 Privileged shell.
 A shell is
 .Dq privileged
-if the real user ID or group ID does not match the
-effective user ID or group ID (see
+if the real user ID from
 .Xr getuid 2
-and
-.Xr getgid 2 ) .
+or group ID from
+.Xr getgid 2
+does not match the effective user ID or group ID.
 Clearing the privileged option causes the shell to set
-its effective user ID (group ID) to its initial real user ID (group ID).
+its effective user ID and group ID to its initial real user ID
+and group ID, respectively.
 For further implications, see
+.Ic set Fl p
+and
 .Sx Startup files .
-If the shell is privileged and this flag is not explicitly set, the
+If the shell is privileged and this flag is not set explicitly on invocation,
+nor during processing the startup files, the
 .Dq privileged
-option is cleared automatically after processing the startup files.
+flag is cleared automatically afterwards.
 .It Fl r
 Restricted shell.
 A shell is
 .Dq restricted
-if the basename the shell is called with, after
-.Ql \-
-processing, starts with
+if the basename the shell is called with, after dash removal, begins with
 .Ql r
 or if this option is used.
 The following restrictions come into effect after the shell processes any
@@ -309,36 +383,43 @@ files:
 .Pp
 .Bl -bullet -compact
 .It
+Command names cannot be specified with pathnames, either absolute or relative;
+the
+.Fl p
+flag of the
+.Ic command
+built-in utility is not usable.
 The
-.Ic cd
-.Po and Ic chdir Pc
-command is disabled.
-.It
-The
-.Ev SHELL ,
-.Ev ENV
-and
+.Ev ENV ,
 .Ev PATH
+and
+.Ev SHELL
 parameters cannot be changed.
 .It
-Command names can't be specified with absolute or relative paths.
-.It
-The
-.Fl p
-option of the built-in command
-.Ic command
-can't be used.
+The current location is fixed: the
+.Ic cd
+builtin is disabled.
 .It
-Redirections that create files can't be used (i.e.\&
+Redirections that create files, i.e.\&
 .Dq Li \*(Gt ,
 .Dq Li \*(Gt\*(Ba ,
-.Dq Li \*(Gt\*(Gt ,
-.Dq Li \*(Lt\*(Gt ) .
+.Dq Li \*(Gt\*(Gt
+and
+.Dq Li \*(Lt\*(Gt ,
+cannot be used, and the
+.Ev HISTFILE
+parameter cannot be changed.
 .El
 .It Fl s
-The shell reads commands from standard input; all non-option arguments
-are positional parameters.
-.It Fl T Ar name
+.Nm
+will read and execute commands from standard input; all non-option arguments
+are assigned to the positional parameters.
+.It Fl T Ar \-
+Detach from the controlling terminal, return immediately
+.Pq daemonise .
+.It Xo
+.Fl T Oo Ar !\& Oc Ns Ar name
+.Xc
 Spawn
 .Nm
 on the
@@ -346,52 +427,53 @@ on the
 device given.
 The paths
 .Ar name ,
-.Pa /dev/ttyC Ns Ar name
+.Li /dev/ttyC Ns Ar name
 and
-.Pa /dev/tty Ns Ar name
+.Li /dev/tty Ns Ar name
 are attempted in order.
-Unless
-.Ar name
-begins with an exclamation mark
-.Pq Ql \&! ,
-this is done in a subshell and returns immediately.
 If
 .Ar name
-is a dash
-.Pq Ql \&\- ,
-detach from controlling terminal (daemonise) instead.
+is prefixed with an exclamation mark
+.Pq Ql \&! ,
+wait for the spawned shell to return,
+report its exit status or terminating signal visually.
+Exit 0 if spawned.
 .El
 .Pp
-In addition to the above, the options described in the
-.Ic set
-built-in command can also be used on the command line:
-both
-.Op Fl +abCefhkmnuvXx
+In addition to the above, the flags
+.Op Fl +abCefhkmnUuvXx
 and
-.Op Fl +o Ar option
-can be used for single letter or long options, respectively.
+.Op Fl +o Ar option ,
+respectively for single-letter and long options,
+as described for the
+.Ic set
+built-in utility, can be used on the command line.
 .Pp
 If neither the
 .Fl c
 nor the
 .Fl s
-option is specified, the first non-option argument specifies the name
-of a file the shell reads commands from.
-If there are no non-option
-arguments, the shell reads commands from the standard input.
-The name of the shell (i.e. the contents of $0)
-is determined as follows: if the
-.Fl c
-option is used and there is a non-option argument, it is used as the name;
-if commands are being read from a file, the file is used as the name;
-otherwise, the name the shell was called with (i.e. argv[0]) is used.
-.Pp
-The exit status of the shell is 127 if the command file specified on the
-command line could not be opened, or non-zero if a fatal syntax error
-occurred during the execution of a script.
-In the absence of fatal errors,
-the exit status is that of the last command executed, or zero if no
-command is executed.
+options are specified,
+.Nm mksh
+will read and execute commands as if the
+.Fl s
+flag was passed iff the
+.Ar file
+argument is absent or
+.Dq Li \- ;
+otherwise, it sets $0 to
+.Ar file
+and reads commands from it.
+Further arguments
+.Ar arg1 ...
+are assigned to positional parameters.
+.Pp
+The exit status of the shell is 127 if the
+.Ar file
+specified on the command line could not be opened,
+or non-zero if a fatal error occurred during execution of the script.
+Otherwise, the errorlevel is that of the last command executed,
+0 if no command was executed.
 .Ss Startup files
 For the actual location of these files, see
 .Sx FILES .
@@ -900,6 +982,7 @@ The
 section describes the
 .Ic time
 reserved word.
+When not a reserved word, a builtin runs the passed command.
 .It Xo Ic until Ar list ;
 .Ic do Ar list ; Ic done
 .Xc
@@ -1227,27 +1310,31 @@ Parameter substitutions,
 which are described in detail in the next section, take the form
 .Pf $ Ns Ar name
 or
-.Pf ${ Ns Ar ... Ns } ;
-command substitutions take the form
+.Pf ${ Ns Ar name... Ns } ;
+arithmetic substitutions take the form
+.Pf $(( Ns Ar expression Ns )) ;
+and command substitutions take the form
 .Pf $( Ns Ar command Ns \&)
 or (deprecated)
 .Pf \` Ns Ar command Ns \`
 or (executed in the current environment)
 .Pf ${\ \& Ar command Ns \&;}
-and strip trailing newlines;
-and arithmetic substitutions take the form
-.Pf $(( Ns Ar expression Ns )) .
-Parsing the current-environment command substitution requires a space,
+and evaluate to the output of
+.Ar command
+with any trailing newlines stripped.
+The latter form requires a space,
 tab or newline after the opening brace and that the closing brace be
 recognised as a keyword (i.e. is preceded by a newline or semicolon).
-They are also called funsubs (function substitutions) and behave like
-functions in that
+They are also called funsubs (function substitutions) and behave
+similar to functions in that shell options are shared and
 .Ic local
 and
 .Ic return
-work, and in that
+work, though, in contrast to valsubs (see below),
 .Ic exit
-terminates the parent shell; shell options are shared.
+does not terminate the parent shell for compatibility with
+.At
+.Nm ksh93 .
 .Pp
 Another variant of substitution are the valsubs (value substitutions)
 .Pf ${\*(Ba\& Ns Ar command Ns \&;}
@@ -1256,7 +1343,8 @@ share their I/O with the parent; instead
 the, initially empty, expression-local variable
 .Ev REPLY
 is set to within the
-.Ar command Ns s .
+.Ar command Ns s ; Ic exit
+affects the parent like in a function call.
 .Pp
 If a substitution appears outside of double quotes, the results of the
 substitution are generally subject to word or field splitting according to
@@ -1316,7 +1404,7 @@ not
 .Dq Li D
 and
 .Dq Li E .
-This behavior is POSIX compliant, but incompatible with some other shell
+This behaviour is POSIX compliant but incompatible with some other shell
 implementations which do field splitting on the word which contained the
 substitution or use
 .Dv IFS
@@ -1325,15 +1413,17 @@ as a general whitespace delimiter.
 The results of substitution are, unless otherwise specified, also subject to
 brace expansion and file name expansion (see the relevant sections below).
 .Pp
-A command substitution is replaced by the output generated by the specified
-command which is run in a subshell.
+A command substitution of the regular (comsub), deprecated, funsub or valsub
+form is replaced by the output generated by the specified
+.Ar command
+which is run in a subshell except for the funsub and valsub types which run
+in the current execution environment.
 For
-.Pf $( Ns Ar command Ns \&)
+.Pf $( Ns Ar command Ns \&) ,
+.Pf ${\ \& Ar command Ns \&;}
 and
 .Pf ${\*(Ba\& Ns Ar command Ns \&;}
-and
-.Pf ${\ \& Ar command Ns \&;}
-substitutions, normal quoting rules are used when
+forms, normal quoting rules are used when
 .Ar command
 is parsed; however, for the deprecated
 .Pf \` Ns Ar command Ns \`
@@ -1347,16 +1437,18 @@ or
 is stripped (as is
 .Ql \&"
 when the substitution is part of a double-quoted string); a backslash
-.Ql \e
 followed by any other character is unchanged.
 As a special case in command substitutions, a command of the form
 .Pf \*(Lt Ar file
 is interpreted to mean substitute the contents of
-.Ar file .
-Note that
+.Ar file
+so that
 .Ic $(\*(Ltfoo)
-has the same effect as
-.Ic $(cat foo) .
+has the same effect, if
+.Pa foo
+is readable, as
+.Ic $(cat foo)
+but is much more performant.
 .Pp
 Note that some shells do not use a recursive parser for command substitutions,
 leading to failure for certain constructs; to be portable, use as workaround
@@ -1384,25 +1476,20 @@ See
 .Sx Arithmetic expressions
 for a description of an expression.
 .Ss Parameters
-Parameters are shell variables; they can be assigned values and their values
+Parameters are shell variables; they can be assigned values, and their values
 can be accessed using a parameter substitution.
 A parameter name is either one
-of the special single punctuation or digit character parameters described
-below, or a letter followed by zero or more letters or digits
-.Po
-.Ql _
-counts as a letter
-.Pc .
-The latter form can be treated as arrays by appending an array index of the
-form
-.Op Ar expr
-where
+of the special single punctuation character or positional parameters described
+below, or a letter followed by zero or more letters, digits or underscores.
+The latter form can be accessed as array appending an index of the form
+.Li [\& Ns Ar expr Ns Li ]\&
+(in which
 .Ar expr
-is an arithmetic expression.
-Array indices in
-.Nm
-are limited to the range 0 through 4294967295, inclusive.
-That is, they are a 32-bit unsigned integer.
+is an arithmetic expression).
+Array indices range from 0 to 4294967295
+.Pq 2\*(ha32\-1 ,
+inclusive, in
+.Nm .
 .Pp
 Parameter substitutions take the form
 .Pf $ Ns Ar name ,
@@ -1493,11 +1580,8 @@ the environment (see
 of commands run by the shell as
 .Ar name Ns = Ns Ar value
 pairs.
-The order in which parameters appear in the environment of a command is
-unspecified.
 When the shell starts up, it extracts parameters and their values
-from its environment and automatically sets the export attribute for those
-parameters.
+from its environment setting the export attribute for those.
 .Pp
 Modifiers can be applied to the
 .Pf ${ Ns Ar name Ns }
@@ -1749,7 +1833,7 @@ and
 are evaluated as arithmetic expressions.
 .Pp
 .It Pf ${ Ns Ar name Ns @#}
-The hash (using the BAFH algorithm) of the expansion of
+The hash (using the BAFH1-0 algorithm) of the expansion of
 .Ar name .
 This is also used internally for the shell's hashtables.
 .Pp
@@ -1757,6 +1841,15 @@ This is also used internally for the she
 A quoted expression safe for re-entry, whose value is the value of the
 .Ar name
 parameter, is substituted.
+.Pp
+.It Pf ${ Ns Ar name Ns @\*(ha}
+The value of
+.Ar name
+in extended caret notation, with both caret
+.Pq Ql \*(ha\&
+and backslash
+.Pq Ql \e\&
+backslash-escaped to avoid ambiguity.
 .El
 .Pp
 Note that
@@ -1813,8 +1906,9 @@ keyword (i.e. a Korn shell style functio
 .It Ev 1 No .. Ev 9
 The first nine positional parameters that were supplied to the shell, function,
 or script sourced using the
-.Dq Li \&.
-built-in.
+.Dq Li .\&
+.Pq Dq dot
+builtin.
 Further positional parameters may be accessed using
 .Pf ${ Ar number Ns } .
 .It Ev *
@@ -1907,13 +2001,13 @@ command (see below).
 .It Ev FPATH
 Like
 .Ev PATH ,
-but used when an undefined function is executed to locate the file defining the
-function.
-It is also searched when a command can't be found using
-.Ev PATH .
+but used when an undefined function is executed
+(or when a command cannot be found using
+.Ev PATH )
+to locate the function definition file.
 See
 .Sx Functions
-below for more information.
+below.
 .It Ev HISTFILE
 The name of the file used to store command history.
 When assigned to or unset, the file is opened, history is truncated
@@ -2316,17 +2410,26 @@ Ranges of octets can be specified by sep
 matches the letter
 .Ql a
 or any digit).
+Character classes can be specified by wrapping the name of the class between
+.Dq Li \&[:
+and
+.Dq Li \&:]
+(e.g.\&
+.Dq Li \&[[:alpha:][:digit:].]
+matches any ASCII letter or digit and the full stop).
+.Pp
 In order to represent itself, a
 .Ql \-
 must either be quoted or the first or last octet in the octet list.
-Similarly, a
+Similarly, if it is to represent itself instead of the end of the list, a
 .Ql \&]
-must be quoted or the first octet in the list if it is to represent itself
-instead of the end of the list.
-Also, a
+must be quoted or the first octet in the list.
+Also, an
 .Ql \&!
 appearing at the start of the list has special meaning (see below), so to
 represent itself it must be quoted or appear later in the list.
+.Ql \*(ha\&
+at the beginning of the list must be quoted or appear later.
 .It \&[!...]
 Like [...],
 except it matches any octet not inside the brackets.
@@ -2394,6 +2497,114 @@ matches no strings; the pattern
 matches all strings (think about it).
 .El
 .Pp
+The following character classes are supported (note all
+.Tn POSIX
+references assume the
+.Dv C
+locale; EBCDIC systems use the bytes from the codepage
+that map to the named ASCII characters so e.g.\&
+.Dq Li \&[[:upper:]]
+is correct while
+.Dq Li \&[A\-Z]
+will contain probably-unwanted characters on EBCDIC systems):
+.Pp
+.Bl -tag -width sh_quote -offset indent -compact
+.It Ic \*(Lt
+.Pq Tn BSD
+the null string at the beginning of a word
+.It Ic \*(Gt
+.Pq Tn BSD
+the null string at the end of a word
+.It Ic alnum
+.Pq Tn POSIX
+alphanumerical
+.Pq Ic alpha No or Ic digit
+.It Ic alpha
+.Pq Tn POSIX
+alphabetical
+.Pq Ic upper No or Ic lower
+.It Ic ascii
+.Pq Tn GNU Nm bash
+any 7-bit
+.Tn ASCII
+character except
+.Dv NUL
+.It Ic blank
+.Pq Tn POSIX
+space or horizontal\ tab
+.It Ic cntrl
+.Pq Tn POSIX
+ASCII C0 control characters
+.Pq \ex00\*(en\ex1F
+or \ex7F
+.It Ic digit
+.Pq Tn POSIX
+ASCII decimal digits
+.Pq 0\*(en9
+.It Ic graph
+.Pq Tn POSIX
+.Ic alnum No or Ic punct
+.Pq !\*(en\*(TI
+.It Ic lower
+.Pq Tn POSIX
+ASCII lowercase letters
+.Pq a\*(enz
+.It Ic print
+.Pq Tn POSIX
+.No space or Ic graph
+.Pq \ex20\*(en\*(TI
+.It Ic punct
+.Pq Tn POSIX
+punctuation
+.Pq Ic graph No except Ic alnum :
+.Li \&!"#$%&\*(aq()*+,\-./:;\*(Lt=\*(Gt?@[\e\e]\*(ha_\`{\*(Ba}\*(TI
+.It Ic sh_alias
+.Pq Nm mksh
+valid in alias names:
+.Ic alnum
+or
+.Li \&!%+,\-.:@[]_
+.It Ic sh_edq
+.Pq Nm mksh
+quoted by tab completion:
+.Li \&"#$&\*(aq()*:;\*(Lt=\*(Gt?[\e\e\`{\*(Ba}\*(TI
+.It Ic sh_ifs
+.Pq Nm mksh
+IFS whitespace, IFS non-whitespace,
+.Dv NUL
+.Pq via Ev $IFS
+.It Ic sh_ifsws
+.Pq Nm mksh
+IFS WS candidates: space, horizontal\ tab, linefeed
+.It Ic sh_nl
+.Pq Nm mksh
+linefeed or (OS/2 TEXTMODE only) carriage\ return
+.It Ic sh_quote
+.Pq Nm mksh
+characters requiring quoting, minus space:
+.Li \&\ex09\ex0A"#$&\*(aq()*;\*(Lt=\*(Gt?[\e\e]\`{\*(Ba}\*(TI
+.It Ic space
+.Pq Tn POSIX
+horizontal\ tab, line\ feed, vertical\ tab, form\ feed,
+carriage\ return, space
+.Pq \ex09\*(en\ex0D\ex20
+.It Ic upper
+.Pq Tn POSIX
+ASCII uppercase letters
+.Pq A\*(enZ
+.It Ic word
+.Pq Tn GNU Nm bash
+alphanumerical
+.Pq Ic alnum
+or underscore
+.Pq Dq Li \&_
+.It Ic xdigit
+.Pq Tn POSIX
+hexadecimal digits
+.Pq 0\*(en9A\*(enFa\*(enf
+a.k.a. nybbles
+.El
+.Pp
 Note that complicated globbing, especially with alternatives,
 is slow; using separate comparisons may (or may not) be faster.
 .Pp
@@ -2624,7 +2835,9 @@ This also affects implicit conversion to
 .Ic let
 command.
 .Em Never
-use unchecked user input, e.g. from the environment, in an arithmetic context!
+use unchecked user input, e.g. from the environment (although the shell
+tracks import status and refuses to automatically coerce those), in
+arithmetic context!
 .Pp
 Expressions are calculated using signed arithmetic and the
 .Vt mksh_ari_t
@@ -2670,7 +2883,8 @@ Grouping operators:
 .Ed
 .Pp
 Integer constants and expressions are calculated using an exactly 32-bit
-wide, signed or unsigned, type with silent wraparound on integer overflow.
+wide, signed (two's complement) or unsigned, type with silent wraparound
+on integer overflow.
 Integer constants may be specified with arbitrary bases using the notation
 .Ar base Ns # Ns Ar number ,
 where
@@ -2678,7 +2892,7 @@ where
 is a decimal integer specifying the base (up to 36), and
 .Ar number
 is a number in the specified base.
-Additionally, base-16 integers may be specified by prefixing them with
+Additionally, base-16 integers may be specified by prefixing with
 .Dq Li 0x
 .Pq case-insensitive
 in all forms of arithmetic expressions, except as numeric arguments to the
@@ -2687,7 +2901,11 @@ built-in utility.
 Prefixing numbers with a sole digit zero
 .Pq Dq Li 0
 does not cause interpretation as octal (except in POSIX mode,
-as required by the standard), as that's unsafe to do.
+as required by the standard), as that's unsafe.
+Prefixing with
+.Dq Li 10#\&
+forces interpretation as decimal, even with leading zeros.
+An unset or empty parameter evaluates to 0 in integer context.
 .Pp
 As a special
 .Nm mksh
@@ -2705,7 +2923,6 @@ instead of
 .Dq Li 1#x
 is also supported.
 Note that NUL bytes (integral value of zero) cannot be used.
-An unset or empty parameter evaluates to 0 in integer context.
 If
 .Sq Li x
 isn't comprised of exactly one valid character, the behaviour is undefined
@@ -2716,6 +2933,12 @@ must validate the input first.
 See
 .Sx CAVEATS
 for UTF-8 mode handling.
+Base-1 integers don't work well with a number of other shell features,
+such as reentry-safe output; use
+.Ic print Fl A
+or
+.Ic read Fl a
+if possible.
 .Pp
 The operators are evaluated as follows:
 .Bl -tag -width Ds -offset indent
@@ -2999,6 +3222,8 @@ outside the function).
 .It
 Shell options
 .Pq Ic set Fl o
+except
+.Fl p Pq Fl o Ic privileged
 have local scope, i.e. changes inside a function are reset upon its exit.
 .El
 .Pp
@@ -3046,13 +3271,12 @@ commands keeping assignments:
 All other builtins are not special; these are at least:
 .Pp
 .Ic [\& , alias , bg , bind ,
-.Ic builtin , cat , cd , command ,
-.Ic echo , false , fc , fg ,
-.Ic getopts , jobs , kill , let ,
-.Ic print , pwd , read , realpath ,
-.Ic rename , sleep , suspend , test ,
-.Ic true , ulimit , umask , unalias ,
-.Ic wait , whence
+.Ic builtin , cd , command , echo ,
+.Ic false , fc , fg , getopts ,
+.Ic jobs , kill , let , print ,
+.Ic pwd , read , realpath , rename ,
+.Ic suspend , test , true , ulimit ,
+.Ic umask , unalias , wait , whence
 .Pp
 Once the type of command has been determined, any command-line parameter
 assignments are performed and exported for the duration of the command.
@@ -3100,7 +3324,8 @@ or standard input as base64.
 .It Ic Lbafh_add Op Ar string
 .It Ic Lbafh_finish
 .Pq Li dot.mkshrc No functions
-Implement the Better Avalance for the Jenkins Hash.
+Implement the Better Avalance for Jenkins Hash
+.Pq IV=1 .
 This is the same hash
 .Nm
 currently uses internally.
@@ -3114,7 +3339,7 @@ variable for your consumption.
 .It Ic Lstripcom Op Ar
 .Pq Li dot.mkshrc No function
 Same as
-.Ic cat
+.Xr cat 1
 but strips any empty lines and comments (from any
 .Sq #
 character onwards, no escapes)
@@ -3130,8 +3355,7 @@ See
 .Fl +x Oc
 .Op Fl p
 .Op Cm +
-.Oo Ar name
-.Op Ns = Ns Ar value
+.Oo Ar name Ns Op = Ns Ar value
 .Ar ... Oc
 .Xc
 .Pq regular
@@ -3251,14 +3475,28 @@ string, wherein prefix/control/tilde cha
 .Pq but not those mapped to other macros
 will be processed.
 .Pp
-Prefix and control characters may be written using caret notation, i.e.\&
+The entire argument may be written using extended caret notation:
 .No \*(ha Ns Li Z
 represents
-.No Ctrl- Ns Li Z .
-Use a backslash to escape the caret, an equals sign or another backslash.
+.No Ctrl- Ns Li Z ;
+.No \*(ha Ns Li +Z
+represents UTF-8
+.No Meta-Ctrl- Ns Li Z ,
+and both
+.No \*(ha Ns Li !Z
+and
+.No \ex Ns Li 9A
+represent ASCII
+.No Meta-Ctrl- Ns Li Z .
+Otherwise, a backslash escapes the next character,
+removing the special meaning from backslashes, carets and
+.Pq for the Ar string No part
+equals signs.
+.Pf ( Em These
+backslashes obviously must be quoted for the shell.)
 Note that, although only three prefix characters
 .Pq usually Esc, \*(haX and NUL
-are supported, some multi-character sequences can be supported.
+are usable, some multi-character sequences can be supported.
 .Pp
 .It Ic break Op Ar level
 .Pq keeps assignments , special
@@ -3297,26 +3535,6 @@ declaration utility (see
 is a declaration utility.
 .Pp
 .It Xo
-.Ic cat
-.Op Fl u
-.Op Ar
-.Xc
-.Pq defer with flags
-Copy files in command line order to standard output.
-If a
-.Ar file
-is a single dash
-.Pq Dq Li \-
-or absent, read from standard input.
-For direct builtin calls, the
-.Tn POSIX
-.Fl u
-option is supported as a no-op.
-For calls from shell, if any options are given, an external
-.Xr cat 1
-utility is preferred over the builtin.
-.Pp
-.It Xo
 .Ic cd
 .Op Fl L
 .Op Ar dir
@@ -3590,6 +3808,15 @@ clears the environment before executing
 .Ev _
 parameter and direct assignments.
 .Pp
+In
+.Sx POSIX mode ,
+a failed
+.Ic exec
+.Em does
+return to an interactive shell prompt.
+Note that the execution environment may still contain traces of
+the attempt to pass control and is not fully restored.
+.Pp
 If no command is given except for I/O redirection, the I/O redirection is
 permanent and the shell is
 not replaced.
@@ -3813,8 +4040,7 @@ Same as
 .It Xo
 .Ic integer
 .Op flags
-.Oo Ar name
-.Op Ns = Ns Ar value
+.Oo Ar name Ns Op = Ns Ar value
 .Ar ... Oc
 .Xc
 .Pq built-in alias
@@ -3893,8 +4119,7 @@ is syntactic sugar for:
 .It Xo
 .Ic local
 .Op flags
-.Oo Ar name
-.Op Ns = Ns Ar value
+.Oo Ar name Ns Op = Ns Ar value
 .Ar ... Oc
 .Xc
 .Pq built-in alias
@@ -3941,8 +4166,7 @@ however, distributors may have added thi
 .It Xo
 .Ic nameref
 .Op flags
-.Oo Ar name
-.Op Ns = Ns Ar value
+.Oo Ar name Ns Op = Ns Ar value
 .Ar ... Oc
 .Xc
 .Pq built-in alias
@@ -3989,14 +4213,16 @@ resulting value is printed.
 Empty
 .Ar argument Ns s
 separate input words.
+No backslash expansion.
 .It Fl c
-The output is printed columnised, line by line, similar to how the
-.Xr rs 1
-utility, tab completion, the
+The output is printed columnised, top to bottom then left to right,
+similar to how tab completion (control character escaping excepted), the
 .Ic kill Fl l
-built-in utility and the
+built-in utility, the
 .Ic select
-statement do.
+statement and the
+.Xr rs 1
+utility do.
 .It Fl e
 Restore backslash expansion after a previous
 .Fl r .
@@ -4213,8 +4439,7 @@ exits with a non-zero status.
 .It Xo
 .Ic readonly
 .Op Fl p
-.Oo Ar parameter
-.Op Ns = Ns Ar value
+.Oo Ar parameter Ns Op = Ns Ar value
 .Ar ... Oc
 .Xc
 .Pq keeps assignments , special, decl-util
@@ -4255,16 +4480,15 @@ resolving to an extant non-directory is
 .Op Fl \-
 .Ar from to
 .Xc
-.Pq defer always
+.Pq defer always , needs Xr rename 2
 Renames the file
 .Ar from
 to
 .Ar to .
-Both must be complete pathnames and on the same device.
+Both pathnames must be on the same device.
 Intended for emergency situations
 .Pq where Pa /bin/mv No becomes unusable ;
-directly calls
-.Xr rename 2 .
+thin syscall wrapper.
 .Pp
 .It Ic return Op Ar status
 .Pq keeps assignments , special
@@ -4294,12 +4518,17 @@ scripts.
 ROT13-encrypts/-decrypts stdin to stdout.
 .Pp
 .It Xo
-.Ic set Op Fl +abCefhiklmnprsUuvXx
+.Ic set Op Fl +abCefhkmnpsUuvXx
 .Op Fl +o Ar option
 .Op Fl +A Ar name
 .Op Fl \-
-.Op Ar arg ...
+.Op Ar argument ...
+.Xc
+.It Xo
+.Ic set Fl \-
+.Op Ar argument ...
 .Xc
+.It Ic set Fl +o
 .Pq keeps assignments , special
 The
 .Ic set
@@ -4319,15 +4548,16 @@ is the long name of an option, or using
 .Fl + Ns Ar letter
 syntax, where
 .Ar letter
-is the option's single letter name (not all options have a single letter name).
-The following table lists short (if extant) and long names
+is the option's single letter name (not all options have both names).
+The following table lists short and long names
+.Pq if extant
 along with a description of what each option does:
 .Bl -tag -width 3n
 .It Fl A Ar name
 Sets the elements of the array parameter
 .Ar name
 to
-.Ar arg ...
+.Ar argument ...
 .Pp
 If
 .Fl A
@@ -4353,15 +4583,16 @@ and also supported by
 is:
 .Ic foo=(a b c); foo+=(d e)
 .It Fl a \*(Ba Fl o Ic allexport
-All new parameters are created with the export attribute.
+Make all variables assigned to while enabled as exported.
 .It Fl b \*(Ba Fl o Ic notify
 Print job notification messages asynchronously instead of just before the
 prompt.
 Only used with job control
 .Pq Fl m .
 .It Fl C \*(Ba Fl o Ic noclobber
-Prevent \*(Gt redirection from overwriting existing files.
-Instead, \*(Gt\*(Ba must be used to force an overwrite.
+Prevent \*(Gt redirection from overwriting existing files;
+.Ql \*(Gt\*(Ba
+must be used to force overwriting instead.
 .Em Note:
 This is not safe to use for creation of temporary files or
 lockfiles due to a TOCTOU in a check allowing one to redirect output to
@@ -4369,6 +4600,9 @@ lockfiles due to a TOCTOU in a check all
 or other device files even in
 .Ic noclobber
 mode.
+.It Fl c
+Commands are read from an argument string.
+Can only be used when the shell is invoked.
 .It Fl e \*(Ba Fl o Ic errexit
 Exit (after executing the
 .Dv ERR
@@ -4418,10 +4652,10 @@ the real UID or GID does not match
 the effective UID (EUID) or GID (EGID), respectively.
 See above for a description of what this means.
 .Pp
-If the shell is privileged, setting this flag after startup files
-have been processed let it go full setuid and/or setgid.
-Clearing this flag makes the shell drop privileges.
-Changing this flag resets the groups vector.
+If the shell is privileged, setting this flag after startup file
+processing let it go full setuid and/or setgid.
+Clearing the flag makes the shell drop privileges.
+Changing this flag resets the supplementary groups vector.
 .It Fl r \*(Ba Fl o Ic restricted
 The shell is a restricted shell.
 This option can only be used when the shell is invoked.
@@ -4445,25 +4679,18 @@ Enable UTF-8 support in the
 and internal string handling functions.
 This flag is disabled by default, but can be enabled by setting it on the
 shell command line; is enabled automatically for interactive shells if
-requested at compile time, your system supports
-.Fn setlocale LC_CTYPE \&""
-and optionally
-.Fn nl_langinfo CODESET ,
-or the
+the POSIX locale uses the UTF-8 codeset or, lacking POSIX locales, the
 .Ev LC_ALL ,
 .Ev LC_CTYPE
 or
 .Ev LANG
-environment variables,
-and at least one of these returns something that matches
-.Dq UTF\-8
-or
-.Dq utf8
-case-insensitively; for direct builtin calls depending on the
-aforementioned environment variables; or for stdin or scripts,
-if the input begins with a UTF-8 Byte Order Mark.
+environment variables either case-insensitively equal
+.Dq Li UTF\-8
+or
+.Dq Li utf8
+or have that as codeset modifier.
 .Pp
-In near future, locale tracking will be implemented, which means that
+This build of the shell implements baroque locale tracking, that is,
 .Ic set Fl +U
 is changed whenever one of the
 .Tn POSIX
@@ -4488,6 +4715,15 @@ during globbing.
 .It Fl x \*(Ba Fl o Ic xtrace
 Print commands when they are executed, preceded by
 .Ev PS4 .
+.It Fl o Ic asis
+When quoting output, if not in EBCDIC mode and
+.Ic utf8\-mode
+is disabled, show C1 control characters
+.Dq as is ,
+that is, do not escape them.
+Use with codepages where the range 0x80..0x9F contains printable
+characters (such as 437, 850, 1252, etc. but not the ISO\ 8859
+series, for example).
 .It Fl o Ic bgnice
 Background jobs are run with lower priority.
 .It Fl o Ic braceexpand
@@ -4517,14 +4753,7 @@ upon entering functions (default).
 Do not kill running jobs with a
 .Dv SIGHUP
 signal when a login shell exits.
-Currently set by default, but this may
-change in the future to be compatible with
-.At
-.Nm ksh ,
-which
-doesn't have this option, but does send the
-.Dv SIGHUP
-signal.
+Currently enabled by default.
 .It Fl o Ic nolog
 No effect.
 In the original Korn shell, this prevented function definitions from
@@ -4574,9 +4803,7 @@ and
 this autodetection feature is compiled in.
 As a side effect, setting this flag turns off the
 .Ic braceexpand
-and
-.Ic utf8\-mode
-flags, which can be turned back on manually, and
+flag, which can be turned back on manually, and
 .Pq unless both are set in the same command
 .Ic sh
 mode.
@@ -4627,7 +4854,7 @@ is always in viraw mode.
 .Pp
 These options can also be used upon invocation of the shell.
 The current set of
-options (with single letter names) can be found in the parameter
+options with single letter names can be found in the parameter
 .Dq Li $\- .
 .Ic set Fl o
 with no option name will list all the options and whether each is on or off;
@@ -4637,18 +4864,29 @@ prints a command to restore the current
 construct, which is an implementation detail; these commands are transient
 .Pq only valid within the current shell session .
 .Pp
-Remaining arguments, if any, are positional parameters and are assigned, in
-order, to the positional parameters (i.e. $1, $2, etc.).
-If options end with
-.Dq Li \-\-
-and there are no remaining arguments, all positional parameters are cleared.
-For unknown historical reasons, a lone
+A lone
 .Dq Li \-
-option is treated specially\*(EMit clears both the
+clears both the
 .Fl v
 and
 .Fl x
-options.
+options (obsolete); it
+.Pq or a lone Dq Li +\&
+terminates option processing and is otherwise ignored.
+.Pp
+.No Remaining Ar argument Ns s ,
+if any, are assigned (in order, unless
+.Fl s
+is given) to
+.Ar name
+.Pq with Fl A
+or the positional parameters
+.Pq i.e.,\& $1, $2, etc .
+.No Use Fl \-
+if the first argument begins with plus or dash.
+If options end with
+.Dq Li \-\-
+and there are no remaining arguments, all positional parameters are cleared.
 If no options or arguments are given, the values of all parameters are printed
 .Pq suitably quoted .
 .Pp
@@ -4672,13 +4910,6 @@ etc.
 .Pq Ar number No defaults to 1
 are renamed to 1, 2, etc.
 .Pp
-.It Ic sleep Ar seconds
-.Pq regular , needs Xr select 2
-Suspends execution for a minimum of the
-.Ar seconds
-(specified as positive decimal value with an optional fractional part).
-Signal delivery may continue execution earlier.
-.Pp
 .It Ic smores Op Ar
 .Pq Li dot.mkshrc No function
 Simple pager:
@@ -4944,15 +5175,16 @@ or
 .Dq Li \-n .
 Use tests like
 .Dq Li if \&[ x\&"$foo\&" = x"bar" \&]
-instead, or the double-bracket operator (see
-.Ic \&[[
-above):
+instead, or the double-bracket construct
+.Pq see Ic \&[[ No above :
 .Dq Li if \&[[ $foo = bar \&]]
 or, to avoid pattern matching,
 .Dq Li if \&[[ $foo = \&"$bar" \&]] ;
 the
 .Ic \&[[ ... \&]]
 construct is not only more secure to use but also often faster.
+Similarly, operators need to be quoted as usual for
+.Nm test No / Nm \&[ .
 .Pp
 .It Xo
 .Ic time
@@ -5017,7 +5249,7 @@ as
 .Ar handler ,
 followed by the arguments (interpreted as signals).
 .Pp
-.It Ic trap Op Ar handler signal ...
+.It Ic trap Ar handler signal ...
 .Pq keeps assignments , special
 Sets a trap handler that is to be executed when any of the specified
 .Ar signal Ns s
@@ -5070,14 +5302,41 @@ in functions are not yet implemented.
 Note that, for non-interactive shells, the trap handler cannot be changed
 for signals that were ignored when the shell started.
 .Pp
+.It Xo
+.Ic trap
+.Op Fl p Op Ar signal ...
+.Xc
 With no arguments, the current state of the traps that have been set since
 the shell started is shown as a series of
 .Ic trap
 commands.
+With
+.Fl p ,
+the state of all traps
+.Pq or all listed traps
+is shown, not just modified traps; this is useful to save and later
+restore the current state of traps.
+.Pp
 Note that the output of
 .Ic trap
-cannot be usefully captured or piped to another process (an artifact
+cannot be easily captured or piped to another process (an artifact
 of the fact that traps are cleared when subprocesses are created).
+Using
+.Nm ksh93 Ns -style
+funsubs works:
+.Bd -literal -offset indent
+save_traps=${ trap \-p;}
+# ...
+eval "$save_traps"
+.Ed
+.Pp
+.Dv SIGKILL , SIGSTOP
+and some OS-specific signals
+.Pq such as 32 and 33 on GNU/Linux
+cannot be trapped.
+Attempts are normally silently ignored; the output of
+.Ic trap Fl p
+does not necessarily reflect this.
 .Pp
 .It Ic true
 .Pq regular
@@ -5096,8 +5355,7 @@ would be interpreted as command.
 .No \*(Ba Fl R Ns Op Ar n
 .No \*(Ba Fl Z Ns Op Ar n Oc
 .Op Fl i Ns Op Ar n
-.Oo Ar name
-.Op Ns = Ns Ar value
+.Oo Ar name Ns Op = Ns Ar value
 .Ar ... Oc
 .Xc
 .It Xo
@@ -5405,6 +5663,12 @@ Limit the size of
 message queues to
 .Ar n
 bytes.
+.It Fl R Ar n
+.Pq Cm Linux
+Limit the CPU time slice a real-time process can use before
+performing a blocking syscall to
+.Ar n
+milliseconds.
 .It Fl r Ar n
 .Pq Cm AIX
 Limit the number of threads per process to
@@ -5786,6 +6050,8 @@ does not accept options with a leading
 skips builtins, functions and other commands and uses a
 .Ev PATH
 search to determine the utility to execute.
+Interactive shells do not exit on failure
+.Pq note: the execution environment may be tainted .
 .El
 .Ss SH mode
 Compatibility mode; intended for use with legacy scripts that
@@ -5806,7 +6072,7 @@ The
 builtin does not interpret backslashes and only supports the exact option
 .Fl n ,
 unless built with
-.Ev \-DMKSH_MIDNIGHTBSD01ASH_COMPAT .
+.Dv \-DMKSH_MIDNIGHTBSD01ASH_COMPAT .
 .It
 The substitution operations
 .Sm off
@@ -5845,7 +6111,7 @@ passes through the errorlevel.
 eats a leading
 .Fl \-
 if built with
-.Ev \-DMKSH_MIDNIGHTBSD01ASH_COMPAT .
+.Dv \-DMKSH_MIDNIGHTBSD01ASH_COMPAT .
 .El
 .Ss Interactive input line editing
 The shell supports three modes of reading command lines from a
@@ -5907,21 +6173,28 @@ command.
 .Pp
 The following is a list of available editing commands.
 Each description starts with the name of the command,
-suffixed with a colon;
-an
+suffixed with a colon; a
 .Op Ar n
 (if the command can be prefixed with a count); and any keys the command is
 bound to by default, written using caret notation
-e.g. the ASCII Esc character is written as \*(ha[.
-These control sequences are not case sensitive.
+(e.g. the ASCII Esc character is written as
+.Li \*(ha[ )
+or terminal-specific indications.
 A count prefix for a command is entered using the sequence
 .Pf \*(ha[ Ns Ar n ,
 where
 .Ar n
-is a sequence of 1 or more digits.
+is one or more digits.
 Unless otherwise specified, if a count is
 omitted, it defaults to 1.
 .Pp
+Bigwords, as used below, are separated by spaces or tabs;
+words consist of alphanumerics, underscore
+.Pq Ql _
+or dollar sign
+.Pq Ql $
+characters.
+.Pp
 Note that editing command names are used only with the
 .Ic bind
 command.
@@ -5944,8 +6217,13 @@ Emacs key bindings:
 Abort the current command, save it to the history, empty the line buffer and
 set the exit state to interrupted.
 .It auto\-insert: Op Ar n
+.Pq Most ordinary characters are bound to this command.
 Simply causes the character to appear as literal input.
-Most ordinary characters are bound to this.
+.It Xo backward\-bigword:
+.Op Ar n
+.No \*(ha[B
+.Xc
+Moves the cursor backward to the beginning of the bigword.
 .It Xo backward\-char:
 .Op Ar n
 .No \*(haB , \*(haXD , ANSI-CurLeft , PC-CurLeft
@@ -5957,19 +6235,21 @@ characters.
 .Op Ar n
 .No \*(ha[b , ANSI-Ctrl-CurLeft , ANSI-Alt-CurLeft
 .Xc
-Moves the cursor backward to the beginning of the word; words consist of
-alphanumerics, underscore
-.Pq Ql _
-and dollar sign
-.Pq Ql $
-characters.
+Moves the cursor backward to the beginning of the word.
 .It beginning\-of\-history: \*(ha[\*(Lt
 Moves to the beginning of the history.
 .It beginning\-of\-line: \*(haA, ANSI-Home, PC-Home
 Moves the cursor to the beginning of the edited input line.
+.It Xo capitalise\-bigword:
+.Op Ar n
+.No \*(ha[C
+.Xc
+Uppercase the first character in the next
+.Ar n
+bigwords as below.
 .It Xo capitalise\-word:
 .Op Ar n
-.No \*(ha[C , \*(ha[c
+.No \*(ha[c
 .Xc
 Uppercase the first ASCII character in the next
 .Ar n
@@ -5984,6 +6264,7 @@ If the current line does not begin with
 the beginning of the line and the line is entered (as if return had been
 pressed); otherwise, the existing comment characters are removed and the cursor
 is placed at the beginning of the line.
+Does not update the mark.
 .It complete: \*(ha[\*(ha[
 Automatically completes as much as is unique of the command name or the file
 name containing the cursor.
@@ -6013,6 +6294,20 @@ match as in the
 .Ic complete
 command above.
 Note that \*(haI is usually generated by the Tab (tabulator) key.
+.It Xo delete\-bigword\-backward:
+.Op Ar n
+.No \*(ha[H
+.Xc
+Deletes
+.Ar n
+bigwords before the cursor.
+.It Xo delete\-bigword\-forward:
+.Op Ar n
+.No \*(ha[D
+.Xc
+Deletes characters after the cursor up to the end of
+.Ar n
+bigwords.
 .It Xo delete\-char\-backward:
 .Op Ar n
 .No ERASE Pq \*(haH ,
@@ -6060,9 +6355,16 @@ is not useful until either
 or
 .Ic up\-history
 has been performed.
+.It Xo downcase\-bigword:
+.Op Ar n
+.No \*(ha[L
+.Xc
+Lowercases the next
+.Ar n
+bigwords.
 .It Xo downcase\-word:
 .Op Ar n
-.No \*(ha[L , \*(ha[l
+.No \*(ha[l
 .Xc
 Lowercases the next
 .Ar n
@@ -6113,6 +6415,13 @@ Appends a
 to the current word and replaces the word with the result of performing file
 globbing on the word.
 If no files match the pattern, the bell is rung.
+.It Xo forward\-bigword:
+.Op Ar n
+.No \*(ha[F
+.Xc
+Moves the cursor forward to the end of the
+.Ar n Ns th
+bigword.
 .It Xo forward\-char:
 .Op Ar n
 .No \*(haF , \*(haXC , ANSI-CurRight , PC-CurRight
@@ -6136,9 +6445,12 @@ Goes to history number
 .It Xo kill\-line:
 .No KILL Pq \*(haU
 .Xc
-Deletes the entire input line.
-.It kill\-region: \*(haW
+Deletes the entire input line and unsets the mark.
+.It kill\-region: \*(ha[\*(haW
 Deletes the input between the cursor and the mark.
+Note: this used to be bound to \*(haW like in Emacs, which is usually taken by
+.Dv WERASE
+though, so it was moved.
 .It Xo kill\-to\-eol:
 .Op Ar n
 .No \*(haK
@@ -6181,15 +6493,18 @@ This does nothing.
 Introduces a 2-character command sequence.
 .It prefix\-2: \*(haX , \*(ha[[ , \*(ha[O
 Introduces a multi-character command sequence.
-.It Xo prev\-hist\-word:
+.It prefix\-3: \*(ha@
+Introduces a PC keyboard scancode.
+.It Xo prev\-hist\-bigword:
 .Op Ar n
 .No \*(ha[. , \*(ha[_
 .Xc
-The last word or, if given, the
-.Ar n Ns th
-word (zero-based) of the previous (on repeated execution, second-last,
-third-last, etc.) command is inserted at the cursor.
-Use of this editing command trashes the mark.
+If no count is given, the last bigword, otherwise the
+.No ( Ar n Ns +1)th
+bigword of the previous line is inserted at the cursor,
+and the mark is set to the beginning of the inserted word.
+When invoked repeatedly, the inserted text is replaced by the corresponding
+bigword from the second-last, third-last, etc. line.
 .It quote: \*(ha\*(ha , \*(haV
 The following character is taken literally rather than as an editing command.
 .It quote\-region: \*(ha[Q
@@ -6219,7 +6534,7 @@ The internal history list is searched
 backwards for commands matching the input.
 An initial
 .Ql \*(ha
-in the search string anchors the search.
+in the search string anchors the search at the beginning of the line.
 The escape key will leave search mode.
 Other commands, including sequences of escape as
 .Ic prefix\-1
@@ -6227,31 +6542,33 @@ followed by a
 .Ic prefix\-1
 or
 .Ic prefix\-2
-key will be executed after leaving search mode.
+key, will be executed after leaving search mode.
 The
 .Ic abort Pq \*(haG
-command will restore the input line before search started.
+command will restore the input line from before search started.
 Successive
 .Ic search\-history
-commands continue searching backward to the next previous occurrence of the
-pattern.
+commands continue searching backward to the following previous occurrence
+of the pattern.
 The history buffer retains only a finite number of lines; the oldest
 are discarded as necessary.
-.It search\-history\-up: ANSI-PgUp, PC-PgUp
-Search backwards through the history buffer for commands whose beginning match
-the portion of the input line before the cursor.
-When used on an empty line, this has the same effect as
-.Ic up\-history .
 .It search\-history\-down: ANSI-PgDn, PC-PgDn
-Search forwards through the history buffer for commands whose beginning match
+Search forwards (this command is only useful after an
+.Ic up\-history ,
+.Ic search\-history\-up
+or
+.Ic search\-history )
+through the history buffer for commands whose beginning matches
 the portion of the input line before the cursor.
 When used on an empty line, this has the same effect as
 .Ic down\-history .
-This is only useful after an
-.Ic up\-history ,
-.Ic search\-history
-or
-.Ic search\-history\-up .
+.It search\-history\-up: ANSI-PgUp, PC-PgUp
+Search backwards through the history buffer for commands whose beginning
+matches the portion of the input line before the cursor.
+When used on an empty line, this has the same effect as
+.Ic up\-history .
+.It set\-arg: \*(ha[0 .. \*(ha[9
+Mapped to begin prefixing a count to a command.
 .It set\-mark\-command: \*(ha[ Ns Aq space
 Set the mark at the cursor position.
 .It transpose\-chars: \*(haT
@@ -6267,9 +6584,16 @@ character to the right.
 Scrolls the history buffer backward
 .Ar n
 lines (earlier).
+.It Xo upcase\-bigword:
+.Op Ar n
+.No \*(ha[U
+.Xc
+Uppercase the next
+.Ar n
+bigwords.
 .It Xo upcase\-word:
 .Op Ar n
-.No \*(ha[U , \*(ha[u
+.No \*(ha[u
 .Xc
 Uppercase the next
 .Ar n
@@ -6279,6 +6603,8 @@ Display the version of
 .Nm mksh .
 The current edit buffer is restored as soon as a key is pressed.
 The restoring keypress is processed, unless it is a space.
+.It vt100\-hack: \*(ha[[1
+Mapped to internally represent some longer key sequences.
 .It yank: \*(haY
 Inserts the most recently killed text string at the current cursor position.
 .It yank\-pop: \*(ha[y
@@ -6289,7 +6615,7 @@ replaces the inserted text string with t
 .Pp
 The tab completion escapes characters the same way as the following code:
 .Bd -literal
-print \-nr \-\- "${x@/[\e"\-\e$\e&\-*:\-?[\e\e\e`\e{\-\e}${IFS\-$\*(aq \et\en\*(aq}]/\e\e$KSH_MATCH}"
+print \-nr \-\- "${x@/[\e"\-\e$\e&\-*:\-?[\e\e\e\`\e{\-\e\*(TI${IFS\-$\*(aq \et\en\*(aq}]/\e\e$KSH_MATCH}"
 .Ed
 .Ss Vi editing mode
 .Em Note:
@@ -6989,14 +7315,14 @@ file.
 .An -nosplit
 .Nm "The MirBSD Korn Shell"
 is developed by
-.An mirabilos Aq Mt m@mirbsd.org
-as part of The MirOS Project.
+.An mirabilos
+.Pq formerly The MirOS Project.
 This shell is based on the public domain 7th edition Bourne shell clone by
 .An Charles Forsyth ,
 who kindly agreed to, in countries where the Public Domain status of the work
 may not be valid, grant a copyright licence to the general public to deal in
 the work without restriction and permission to sublicence derivatives under
-the terms of any (OSI approved) Open Source licence,
+the terms of any OSI-approved Open Source licence,
 and parts of the BRL shell by
 .An Doug A. Gwyn ,
 .An Doug Kingston ,
@@ -7013,9 +7339,9 @@ and it was subsequently maintained by
 .An Simon J. Gerraty
 and
 .An Michael Rendell .
-The effort of several projects, such as Debian and OpenBSD, and other
-contributors including our users, to improve the shell is appreciated.
-See the documentation, website and source code (CVS) for details.
+The effort by Debian, OpenBSD, and other contributors including our users,
+to improve the shell is appreciated.
+See the documentation, website and the CVS repository (source code) for details.
 .Pp
 .Nm mksh\-os2
 is developed by
@@ -7023,7 +7349,7 @@ is developed by
 .Pp
 .Nm mksh\-w32
 is developed by
-.An Michael Langguth Aq Mt lan@scalaris.com .
+.An Michael Langguth Aq Mt mail@michael-langguth.de .
 .Pp
 .Nm mksh Ns / Ns Tn z/OS
 is contributed by
@@ -7064,8 +7390,10 @@ and wraparound defined, even (defying PO
 .Pp
 .Nm mksh
 currently uses OPTU-16 internally, which is the same as UTF-8 and CESU-8
-with 0000..FFFD being valid codepoints; raw octets are mapped into the
-PUA range EF80..EFFF, which is assigned by CSUR for this purpose.
+with 0000..FFFD being valid codepoints; raw octets map to U+EF80..U+EFFF.
+.Em Future compatibility note :
+mksh R60 will use full 21-bit UTF-8 and map raw octets to
+U\-001BBB80..U\-001BBBFF instead.
 .Sh BUGS
 Suspending (using \*(haZ) pipelines like the one below will only suspend
 the currently running part of the pipeline; in this example,
@@ -7089,9 +7417,9 @@ for the in-memory portion of the history
 .Xr memmove 3 .
 .Pp
 This document attempts to describe
-.Nm mksh\ R59c
+.Nm mksh\ R59-CURRENT
 and up,
-.\" with vendor patches from insert-your-name-here,
+with vendor patches from Debian,
 compiled without any options impacting functionality, such as
 .Dv MKSH_SMALL ,
 when not called as
@@ -7105,15 +7433,7 @@ for an operating environment supporting
 .Pp
 Please report bugs in
 .Nm
-to the public development mailing list at
-.Aq Mt miros\-mksh@mirbsd.org
-(please note the EU-DSGVO/GDPR notice on
-.Pa http://www.mirbsd.org/rss.htm#lists
-and in the SMTP banner!) or in the
+in the
 .Li \&#\&!/bin/mksh
-.Pq or Li \&#ksh
-IRC channel at
-.Pa irc.freenode.net
-.Pq Port 6697 SSL, 6667 unencrypted ,
-or at:
-.Pa https://launchpad.net/mksh
+channel, on IRC; note the information at:
+.Pa http://www.mirbsd.org/mksh\-faq.htm#contact
--- mksh-59c.orig/mksh.faq
+++ mksh-59c/mksh.faq
@@ -1,4 +1,4 @@
-RCSID: $MirOS: src/bin/mksh/mksh.faq,v 1.10 2020/10/01 22:59:12 tg Exp $
+RCSID: $MirOS: src/bin/mksh/mksh.faq,v 1.46+locale-tracking 2025/12/23 22:06:36 tg Exp $
 ToC: spelling
 Title: How do you spell <tt>mksh</tt>? How do you pronounce it?
 
@@ -8,12 +8,15 @@ Title: How do you spell <tt>mksh</tt>? H
  initial lowercase letter</a>; this is important) or “MirBSD Korn Shell”,
  possibly with “the”.</p>
 <p>I usually pronounce it as “<span xml:lang="de-DE-1901">em-ka-es-ha</span>”,
- that is, the letters individually in my native German, or say “MirBSD Korn
- Shell”, although it is manageable, mostly for Slavic speakers, to actually
- say “mksh” as if it were a word ☺</p>
+ that is, the letters individually in my native German, emphasis on the
+ first syllable, or say “MirBSD Korn Shell”, although it is manageable,
+ mostly for Slavic speakers, to actually say “mksh” as if it were a word ☺</p>
 <p>Oh… I’ve run into this one, didn’t I? “MirBSD” is pronounced “<span
  xml:lang="de-DE-1901">Mir-Be-Es-De</span>” germanically, for anglophones
  “Mir-beas’tie” is fine.</p>
+<p>This translates well into other languages, such as <span
+ xml:lang="es">eme-ka-ese-ache</span> in Spanish, although English
+ speakers may still find “Mir-beastie korn shell” more palatable.</p>
 ----
 ToC: sowhatismksh
 Title: I’m a $OS (<i>Android, OS/2, …</i>) user, so what’s mksh?
@@ -52,6 +55,16 @@ Title: I’m an OS/2 user, what else do
  users will want to use “textmode” unless they need absolute compatibility
  with Unix mksh and other Unix shells and tools.</p>
 ----
+ToC: pass
+Title: Your CVSweb and gitweb links don’t work!
+
+This is because LLM scrapers not only thieve websites, they also do so
+in a manner that overloads the servers. Putting such highly dynamic CGIs
+behind HTTP Basic Auth is the only measure that helps. The credentials
+are both rather obvious and documented in the realm (the info that recent
+browsers unfortunately stopped showing in the password popups) and on the
+error page that is shown when you abort the popup dialogue. Try it!
+----
 ToC: kornshell
 Title: How does this relate to ksh or the Korn Shell?
 
@@ -59,9 +72,10 @@ Title: How does this relate to ksh or th
  flavours exist (ksh88 and ksh93), the latter having been maintained
  until 2012 (last formal release) and 2014 (last beta snapshot, buggy).
  A ksh86 did exist.</p>
-<p>There’s now <tt>ksh2020</tt>, a project having restarted development
- around November 2017 forking the last <tt>ksh93 v-</tt> (beta) snapshot
- and continuing to develop it, presented at FOSDEM.</p>
+<p>The <tt>ksh2020</tt> project to restart development around November
+ 2017 forking the last <tt>ksh93 v-</tt> (beta) snapshot is now dead,
+ but the <tt>ksh93u+m</tt> project from 2021 onwards is active and more
+ stable.</p>
 <p>AT&amp;T ksh88 is “the (original) Korn Shell”. Other implementations,
  of varying quality (MKS Toolkit’s MKS ksh being named as an example of
  the lower end, MirBSD’s mksh at the upper end). They are all <em>not</em>
@@ -98,8 +112,8 @@ Title: How does this relate to ksh or th
  getting close to, ksh88 compatibility.</p>
 <p>SKsh is an AmigaOS-specific Korn Shell-lookalike by Steve Koren.</p>
 <p>The <a href="@@RELPATH@@ksh-chan.htm">Homepage of the <tt>#ksh</tt>
- channel on Freenode IRC</a> contains more information about the Korn
- Shell in general and its flavours.</p>
+ channel on IRC</a> contains more information about the Korn Shell in
+ general and its flavours.</p>
 ----
 ToC: packaging
 Title: How should I package mksh? (common cases)
@@ -190,6 +204,23 @@ Title: I forbid stat(2) in my SELinux po
 
 Don’t break Unix. Read up on the GIGO principle. Duh.
 ----
+ToC: printf-c
+Title: Which revision of printf.c do I use?
+
+<p>If you have to add printf(1) as an extra, nōn-standard, builtin,
+ use <tt>src/usr.bin/printf/printf.c,v</tt> revision…</p>
+<ul>
+ <li>r1.25 or newer for mksh CVS HEAD (R59d/R60+)</li>
+ <li>r1.22 for mksh R59c</li>
+</ul>
+<p>… and add <tt>USE_PRINTF_BUILTIN=1</tt> to the <tt>Build.sh</tt>
+ environment. Do note that this can no longer be used as “speed hack”
+ because as of R51, if an external printf(1) exists, it is preferred,
+ as the OS’ own implementations will often have extensions, and they
+ usually will have floating point support (which the one embedded in
+ mksh cannot provide). It mostly exists for invocations where no such
+ utility is in <tt>$PATH</tt> but scripts are targetting POSIX.</p>
+----
 ToC: makefile
 Title: Why doesn’t this use a Makefile to build?
 
@@ -238,15 +269,18 @@ so you are probably best off starting wi
 or ksh88 reference such as the first edition (the second one deals
 with ksh93 which differs far more from mksh than ksh88, as ancient
 as it is, does) of the O’Reilly book (⚠ disclaimer: only an example,
-not a recommendation) and going forward by reading scripts (the
-“shellsnippets” repository referenced in the <tt>#ksh</tt> channel
-homepage (see the top of this document) has many examples) and
+not a recommendation) “Learning the Korn Shell” and going forward
+by reading scripts (the “<a
+href="https://evolvis.org/plugins/scmgit/cgi-bin/gitweb.cgi?p=shellsnippets/shellsnippets.git;a=tree"
+>shellsnippets</a>” repository, also referenced in <a
+href="@@RELPATH@@ksh-chan.htm">the <tt>#ksh</tt> IRC channel
+homepage</a>, has many examples) and
 trying to understand them and the mksh specifics from the manpage.
 ----
 ToC: ps1conv
 Title: My prompt from &lt;<i>some other shell</i>&gt; does not work!
 
-<a href="#contact">Contact</a> us on the mailing list or on IRC,
+<a href="#contact">Contact</a> us by eMail, Fediverse or on IRC,
 we’ll convert it for you. Also have a look at the PS1 section in
 the mksh(1) manpage (search for “otherwise unused char”, e.g. with
 <tt>/</tt> in less(1), to spot it quickly).
@@ -260,7 +294,7 @@ Title: My prompt is weird!
  (This was agreed upon as suggestion in a discussion between bash, zsh and
  Korn shell developers.) The feature set of different shells vastly differs
  and each shell should use its default PS1 or from its startup files.</li>
-<li><tt>$ENV</tt> <a href="#env">is set and/or <tt>export</tt>ed</a>.</li>
+<li><tt>$ENV</tt> <a href="#env">is set and probably <tt>export</tt>ed</a>.</li>
 <li>Your prompt is just “<tt># </tt>”: you’re entering a root shell, and
  <tt>$PS1</tt> does not contain the ‘#’ character, in which case the shell
  forces this prompt, making extra privileges obvious.</li>
@@ -281,10 +315,25 @@ Title: My prompt is weird!
  a line break after it when rendering.</li>
 </ul>
 ----
+ToC: aliasify
+Title: How do I write an alias?
+
+<p class="boxhead">Define the following function:</p><div class="boxtext">
+ <pre>
+	function aliasify {
+		local x=$(fc -ln -1)
+		x=${x#$'\t'}
+		print -r -- "alias ${1@Q}=${x@Q}"
+	}
+</pre>
+</div><p class="boxfoot">Then type the command you want to aliasify, and
+ then <tt>aliasify <i>foo</i></tt>, where <i>foo</i> is what name you want
+ to give to the alias. Add the result to <tt>~/.mkshrc</tt> or so.</p>
+----
 ToC: env
 Title: On startup files and <tt>$ENV</tt> across and detecting various shells
 
-Interactive shells look at <tt>~/.mkshrc</tt> (or <tt>/system/etc/mkshrc</tt>
+<p>Interactive shells look at <tt>~/.mkshrc</tt> (or <tt>/system/etc/mkshrc</tt>
 on Android and <tt>/etc/mkshrc</tt> on FreeWRT and OpenWrt) by default. This
 location can, however, be overridden by setting the <tt>ENV</tt> environment
 variable. (FreeBSD is rumoured to set it in their system profile.) It’s better
@@ -295,7 +344,30 @@ or “MIRBSD KSH” for mksh, “PD KSH
 for ksh93); <tt>$NETBSD_SHELL</tt> (NetBSD ash); <tt>POSH_VERSION</tt> (posh, a
 pdksh derivative); <tt>$SH_VERSION</tt> (“PD KSH” as sh), <tt>$YASH_VERSION</tt>
 (yash), <tt>$ZSH_VERSION</tt> (or if <tt>$VERSION</tt> begins with “zsh”); a <a
-href="@@RELPATH@@ksh-chan.htm#which-shell">list of more approaches</a> exists.
+href="@@RELPATH@@ksh-chan.htm#which-shell">list of more approaches</a> exists.</p>
+
+<p>Note that, in some scenarios, it might be very useful to actually set
+ <tt>$ENV</tt>: the regular interactive shell startup file lies in the
+ user’s home directory, relying on being copied from <tt>/etc/skel/</tt>
+ which normally is only done at user creation time. If mksh was installed
+ later, the user often won’t get it at all, and delivering updates is
+ challenging. One way of partially working around this is to ship an
+ <tt>/etc/skel/.mkshrc</tt> that reads <tt>/etc/mkshrc</tt> by default
+ (but the user can change it of course) and ship the <tt>dot.mkshrc</tt>
+ file as <tt>/etc/mkshrc</tt>, but that won’t fully help. This is where
+ <tt>$ENV</tt> comes into play:</p><ul>
+  <li>In <tt>/etc/profile</tt>, set <tt>ENV</tt> to a, say, <tt>shrc</tt>
+   file shipped in <tt>/etc/</tt> and export it.</li>
+  <li>In that new file, which must use only constructs compatible with
+   all shells, usually a subset of POSIX, read the various rc files
+   (<tt>.mkshrc</tt> for mksh, <tt>.kshrc</tt> for AT&amp;T ksh93, etc.)
+   from the user’s home if they exist, from <tt>/etc/skel/</tt> otherwise.</li>
+</ul><p>This may very well be <em>required</em> if the alternative would
+ be <a href="#ps1weird">to <del><tt>export PS1</tt></del>[sic!]</a>. <a
+  href="https://gitlab.alpinelinux.org/alpine/aports/-/issues/12398#note_146574"
+ >alpine Linux</a> encountered this very problem, and the linked post is
+ a (draft) solution using the <tt>$ENV</tt> method and looks at various
+ other shells’ startup file situation as well.</p>
 ----
 ToC: ctrl-x-e
 Title: Multiline command editing
@@ -320,6 +392,40 @@ Title: Multiline command editing
  nōn-zero (e.g. using jupp’s “abendjoe” command) to prevent execution.
  This is <em>really</em> useful to write ad-hōc scripts as well.</p>
 ----
+ToC: escaping
+Title: Some characters don’t display right
+
+<p>First, make sure that either you’re using a UTF-8 terminal and system
+ and the shell’s UTF-8 mode is on (<tt>set -U</tt>) or that you’re using
+ an 8-bit codepage/CCSID and the UTF-8 mode is off (<tt>set +U</tt>). If
+ you’re on an EBCDIC system ensure to pick a codepage that has a bijective
+ mapping to (Extended) ASCII and in which all necessary characters are
+ present, for example 1047. Furthermore ensure the compile-time and runtime
+ codepages match. (Other encoding schemes, e.g. DBCS or ISO-2022-JP, are
+ not supported.) This should already fix most relevant issues.</p>
+<p>If using an 8-bit coding system that (unlike e.g. ISO 8859 or EBCDIC)
+ does not assign control characters to “Extended ASCII” codepoints 0x80‥0x9F,
+ such as codepages 437, 850, 1252, … (usually on OS/2 or DOS-based systems),
+ enable the option <tt>set -o asis</tt> (new in R60); otherwise, they will
+ be escaped to avoid accidentally setting off terminal control sequences.</p>
+<p>Note that escaping of characters is, at runtime, dependent on whether the
+ shell was compiled for EBCDIC and/or <tt>utf8-mode</tt> and/or <tt>asis</tt>
+ are enabled, the latter being ignored if either of the former two are true
+ (in UTF-8 mode, UCS C1 codepoints are always escaped).</p>
+----
+ToC: carets
+Title: What’s with these ^Q, ^!Q and ^+Q (e.g. from tab completion)? \x80 too!
+
+The extended caret notation escapes characters that can be harmful for your
+terminal from being output as active control characters. This is dependent
+on the shell mode (see <a href="#escaping">above</a>. The caret (<tt>^</tt>)
+means Ctrl; <tt>^+</tt> is used to denote UTF-8 C1 control characters, while
+raw 8-bit C1 control characters use <tt>^!</tt>, and invalid UTF-8 sequences
+show up as <tt>\x</tt> in <tt>utf8-mode</tt>. The manpage also documents
+these (search for “caret”). Note that the <tt>bind</tt> utility and explicit
+parameter escaping also quote carets and backslashes with a backslash, while
+mere output (tab completion, input line editing) don’t.
+----
 ToC: ctrl-l-cls
 Title: ^L (Ctrl-L) does not clear the screen
 
@@ -329,9 +435,36 @@ Use ^[^L (Escape+Ctrl-L) or rebind it:<b
 ToC: ctrl-u-pico
 Title: ^U (Ctrl-U) clears the entire line
 
-If it should only delete the line up to the cursor, use:<br />
+If you want it to only delete the line up to the cursor, use:<br />
 <tt>bind -m ^U='^[0^K'</tt>
 ----
+ToC: ctrl-w-bash
+Title: ^W (Ctrl-W) deletes a word, not a bigword
+
+If you want it to delete more, with R59d+ you can use:<br />
+<tt>bind '^W=delete-bigword-backward'</tt>
+----
+ToC: esc-d-whole-word
+Title: I want Esc+d to delete the entire word, not just to the right from the cursor
+
+<p class="boxhead">This is not possible with a simple editing
+ command; however, you can use a macro definition to create a
+ matching effect. First, you need to bind the current definition
+ of Esc+d, i.e. <tt>delete-word-forward</tt>, to something else;
+ Esc+Ctrl-D is currently unused, so we’ll use that. Then you’ll
+ define a macro that inserts two letters and moves one back (to
+ work at the beginning and end of words safely), then run both
+ delete word backward and forward:</p>
+<div class="boxtext">
+ <pre>
+	bind '^[^D=delete-word-forward'
+	bind -m '^[d=aa^B^[^H^[^D'
+</pre>
+</div><p class="boxfoot">If your shell is sufficiently recent to
+ do so and you want to delete by <a href="#ctrl-w-bash">bigwords</a>,
+ you do not need the first redefinition and simply swap the deletion
+ commands:<br /><tt>bind -m '^[d=aa^B^[H^[D'</tt></p>
+----
 ToC: cur-up-zsh
 Title: Cursor Up behaves differently from zsh
 
@@ -341,6 +474,61 @@ Cursor Up goes up one command and PgUp s
 above. You can, of course, rebind:<br />
 <tt>bind '^XA=search-history-up'</tt>
 ----
+ToC: amend-git-branch
+Title: Display the current git branch in the prompt
+
+<p style="font-size:small;">Originally posted as wlog entry and
+ for Plänet Debian and Plänet Commanline on 2012-07-14T22:17:01Z</p>
+<p class="boxhead">Originally <a
+ href="http://web.archive.org/web/20161008060953/http://www.perrier.eu.org/weblog/2012/07/15#cool-prompt">posted
+ by bubulle</a> on Planet Debian, a shell prompt that displays the
+ current git branch, in colour on some terminals, after the current
+ working directory. The following snippet does similar things for
+ <a href="@@RELPATH@@mksh.htm">mksh</a> users, except it doesn’t
+ redefine your prompt but amend it — just throw it at the bottom of
+ your <tt>~/.mkshrc</tt> before that last line beginning with a colon
+ (copy from <a href="https://evolvis.org/plugins/scmgit/cgi-bin/gitweb.cgi?p=alioth/mksh.git;a=blob;f=debian/.mkshrc;hb=HEAD"><tt>/etc/skel/.mkshrc</tt></a>
+ if you haven’t done that yet):</p><div class="boxtext">
+ <pre>
+	function parse_git_branch {
+		git branch 2&gt;/dev/null | sed -n '/^\* \(.*\)/s//(\1)/p'
+	}
+
+	function amend_prompt_with_git {
+		[[ -o utf8-mode ]]; local u=$?
+		set +U
+		local p q='$(parse_git_branch)' r
+
+		if [[ $TERM = @(xterm-color|xterm|screen*) ]]; then
+			if [[ ${PS1:1:1} = $'\r' ]]; then
+				p=${PS1:0:1}
+			else
+				p=$'\001'
+				PS1=$p$'\r'$PS1
+			fi
+			q=$p$'\e[1;33m'$p$q$p$'\e[0m'$p
+		fi
+
+		p=${PS1%%*( )[#$]*( )}
+		if [[ $p != "$PS1" ]]; then
+			# prompt ends with space + #-or-$ + space, we can amend
+			r=${PS1: ${#p}}
+			PS1=$p$q$r
+		fi
+
+		(( u )) || set -U
+	}
+	amend_prompt_with_git
+	unset -f amend_prompt_with_git
+</pre>
+</div><p class="boxfoot">The indirection by use of a function is not
+ strictly necessary but allows the use of locals. I took the liberty
+ of adding an asterisk after “screen” to match the GNU/Linux nonsense
+ of having <tt>TERM=screen.xterm</tt> or somesuch.</p>
+<p>The insertion point is right before the trailing space plus (either
+ dollar or number sign) plus space, i.e. after the cwd from the default
+ prompt. YMMV so you may need to customise that, or ask me to help.</p>
+----
 ToC: current
 Title: Can mksh set the title of the window according to the command running?
 
@@ -380,11 +568,38 @@ Title: What about programmable tab compl
 The shell itself provides static deterministic tab completion.
 However, you can use hooks like reprogramming the Tab key to a
 command line editor macro, and using the <tt>evaluate-region</tt>
-editor command (modulo a bugfix) together with <tt>quote-region</tt> and shell functions to
+editor command together with <tt>quote-region</tt> and shell functions to
 implement a programmable completion engine. Multiple people have
 been considering doing so in our IRC channel; we’ll hyperlink to
 these engines when they are available.
 ----
+ToC: complete-pathword
+Title: But other shells can complete paths more nicely!
+
+<p class="boxhead">You could put something like…</p><div class="boxtext">
+ <pre>
+	function _complete_pathword {
+		local p=${1//'/'/'*/'}
+		[[ $1 != /* ]] || p=${p#?}
+		[[ $1 = */ ]] || p+=*
+		print -nr -- "$p"
+	}
+	# set-mark-command, backward-bigword, "_complete_pathword ",
+	# quote-region, exchange-point-and-mark, (19)backward-char,
+	# evaluate-region, complete-list
+	bind -m '^[OS=^[ ^[B_complete_pathword ^[Q^X^X^[19^B^[^E^I'
+</pre>
+</div><p class="boxfoot">… in your <tt>~/.mkshrc</tt>; this will map
+ the F4 key (in common terminals) to an operation sequence that will
+ expand, for example, <tt>/u/l//val</tt> via <tt>/u*/l*/*/val*</tt>
+ to the complete path, if it’s sufficiently unique (this will complete
+ to <tt>/usr/lib/x86_64-linux-gnu/valgrind/</tt> on Debian, or to
+ <tt>/usr/libdata/perl5/validate.pl</tt> on MirBSD). If you place the
+ cursor in the middle of the current bigword, not its end, completion
+ can become interesting, for example you could require an extension to
+ match (<tt>/u///valh</tt> then Cur← (^B) and F4, for example, can become
+ <tt>/usr/include/valgrind/valgrind.h</tt> via <tt>/u*/*/*/val*h</tt>).</p>
+----
 ToC: posix-mode
 Title: How POSIX compliant is mksh? Also, UTF-8 vs. locales?
 
@@ -395,10 +610,22 @@ Title: How POSIX compliant is mksh? Also
  (<tt>set -o posix</tt>) explicitly, which also disables brace expansion upon
  being enabled (use <tt>set -o braceexpand</tt> to reenable if needed).</p>
 <p>For the purpose of POSIX, mksh supports only the <tt>C</tt> locale. mksh’s
- <tt>utf8-mode</tt> (which only supports the BMP (Basic Multilingual Plane) of
- UCS and maps raw octets into the U+EF80‥U+EFFF wide character range; see
- <tt>Arithmetic expressions</tt> in mksh(1) for details) <em>must</em> stay
- disabled in POSIX mode (it is disabled upon enabling POSIX mode in R56+).</p>
+ <tt>utf8-mode</tt> <em>must</em> stay disabled in POSIX mode (it was disabled
+ upon enabling POSIX mode in R56‥R59c but decoupled again with R59d).</p>
+<p>EBCDIC interacts with <tt>utf8-mode</tt> in a special way: UTF-EBCDIC is
+ not used by anyone, we cannot use UCS-2/4 in the shell, so “nega-UTF-8”, a
+ scheme in which UTF-8 calculations are done on the octets converted per the
+ current EBCDIC codepage to “extended ASCII”.</p>
+<p>The shell’s <tt>utf8-mode</tt> <em>before</em> mksh R60 supported only the
+ BMP (Basic Multilingual Plane) of UCS and mapped raw (extended ASCII) octets,
+ i.e. these which are not valid UTF-8 BMP codepoints) into the U+EF80‥U+EFFF
+ range, which is allocated at the CSUR for this purpose. (It otherwise lies in
+ the PUA; however, there is ambiguity if encountering those UTF-8-encoded, so
+ it changed for R60.) The <tt>Arithmetic expressions</tt> and <tt>CAVEATS</tt>
+ sections in mksh(1) contain more details about encoding and mapping.</p>
+<p>As of R60, <tt>utf8-mode</tt> maps “raw octets” to U-001BBB80‥U-001BBBFF,
+ which is outside the UCS and therefore collision-free, using full
+ 21-bit UTF-8 (without explicit CESU-8 compatibility).</p>
 <p class="boxhead">The following POSIX sh-compatible code toggles the
  <tt>utf8-mode</tt> option dependent on the current POSIX locale, for mksh
  to allow using the UTF-8 mode, within the constraints outlined above, in
@@ -406,18 +633,21 @@ Title: How POSIX compliant is mksh? Also
 <div class="boxtext">
  <pre>
 	case ${KSH_VERSION:-} in
-	*MIRBSD KSH*|*LEGACY KSH*)
+	*MIRBSD\ KSH*|*LEGACY\ KSH*)
 		case ${LC_ALL:-${LC_CTYPE:-${LANG:-}}} in
 		*[Uu][Tt][Ff]8*|*[Uu][Tt][Ff]-8*) set -U ;;
 		*) set +U ;;
 		esac ;;
 	esac
- </pre>
-</div><p class="boxfoot">In near future, (UTF-8) locale tracking will
- be implemented, though.</p>
+</pre>
+</div><p class="boxfoot">This only applies to mksh before R60 without
+ locale tracking and is obsolete as of R60’s release, except for backwards
+ compatibility. <strong>This build of mksh already enables it.</strong></p>
 <p>The shell is pretty close to POSIX, when run as <tt>lksh -o posix</tt>
  under the "C" locale it is intended to match. It does not do everything
  like other POSIX-compatible or ‑compliant shells, though.</p>
+<p>Like pretty much all other POSIX-compatible shells, builtins are
+ <em>independent</em> of paths and always recognised in mksh.</p>
 ----
 ToC: function-local-scopes
 Title: What differences in function-local scopes are there?
@@ -447,7 +677,7 @@ Title: What differences in function-loca
 		\\builtin alias unset=unset_compat
 		;;
 	esac
- </pre>
+</pre>
 </div><p class="boxfoot">When a local variable is created (e.g. using
  <tt>local</tt>, <tt>typeset</tt>, <tt>integer</tt> or
  <tt>\\builtin typeset</tt>) it does not, like in other shells, inherit
@@ -462,6 +692,86 @@ Title: I get an error in this regex comp
  … becomes…<br />
  <tt>[[ foo = *@(foo|bar)*baz* ]]</tt></p>
 ----
+ToC: cfor
+Title: How can I do C-style “for” loops?
+
+<p>The <tt>for</tt> loop in shell is always a “foreach” loop,
+ not a C-style “for” loop. However, you <em>can</em> use the
+ <tt>while</tt> loop.</p>
+<p class="boxhead">The following three constructs are equivalent:
+ the first is using the GNU bash‑ and AT&amp;T ksh93 C-style for
+ loop, which the second naïvely transfers into a <tt>while</tt>
+ loop that the third example does natively:</p>
+<div class="boxtext">
+ <pre>
+	#     expr1    expr2    expr3
+	for ((idx = 9; idx &gt; 6; --idx)); do
+		echo $idx
+	done
+
+	idx=9
+	while (( idx &gt; 6 )); do
+		echo $idx
+		(( --idx ))
+	done
+
+	idx=10
+	while (( --idx &gt; 6 )); do
+		echo $idx
+	done
+</pre>
+</div><p class="boxfoot">The latter two also run on bash and ksh93,
+ so it’s better to use that anyway.</p>
+<p>The last (native) example rolls the “expr3” part, which otherwise
+ is run at the end of every body, into the loop condition (“expr2”)
+ accounting for the extra first execution by “undoing” its effect in
+ the “expr1” initialisation, here by pre-incrementing as the “expr3”
+ is a decrement.</p>
+<p class="boxhead">Classic counting loops look like this:</p>
+<div class="boxtext">
+ <pre>
+	i=-1
+	while (( ++i &lt; 6 )); do
+		(( j = i ))
+		while (( ++j &lt; 6 )); do
+			print -r -- $i, $j
+		done
+	done
+</pre>
+</div><p class="boxfoot">Here, the increment is offset by a pre-decrement.</p>
+----
+ToC: local-arrays
+Title: How can I do local arrays?
+
+<p class="boxhead">mksh supports function-local arrays with an “onion
+ model” in which you can basically create (and unset) a local variable
+ in a function, which may of course be array-typed:</p>
+<div class="boxtext">
+ <pre>
+	function foo {
+		a[1]=x		# modifies the outer array
+		echo ${a[*]}
+		local a		# makes a local variable…
+		set -A a	# … of type array…
+		a[0]=yz		# modifies the inner array
+		echo ${a[*]}
+		unset a		# removes the local variable
+		echo ${a[*]}
+		a[2]=!		# modifies the unveiled outer again
+		echo ${a[*]}
+	}
+	set -A a -- 1 2 3 4 5
+	echo ${a[*]}		# shows the outer array before…
+	foo
+	echo ${a[*]}		# …and after the function ran
+</pre>
+</div><p class="boxfoot">This also works with <tt>a=(…)</tt> and
+ in POSIX-style functions <tt>foo() { …; }</tt> (in mksh, although
+ not in AT&amp;T ksh which uses a different scope model) and with
+ appending <tt>a+=(…)</tt> (and <tt>set -A a+ -- …</tt>), and even
+ no-truncation array assignments <tt>set +A a -- …</tt> behave in
+ a consistent manner.</p>
+----
 ToC: trim-vector
 Title: ${@?}: bad substitution
 
@@ -471,12 +781,24 @@ Title: ${@?}: bad substitution
  applied to <tt>$1</tt> only and <tt>${@?}</tt> can be replaced
  with a test whether <tt>$# -eq 0</tt>.</p>
 ----
+ToC: lineno
+Title: error line numbers are… somewhat close
+
+<p>For block constructs (such as <tt>if</tt>) and function calls,
+ the shell currently reports the line number of the call site (the
+ trailing <tt>fi</tt>), not the line with the command where the
+ actual error occurred.</p>
+<p>While unfortunate, the line numbers are currently only updated
+ when reading commands, not tracked through the internal AST. This
+ is not easy to change and therefore will only be fixed as part of
+ introduction of BASH_SOURCE, FUNCNAME, BASH_LINENO, etc.</p>
+----
 ToC: extensions-to-avoid
 Title: Are there any extensions to avoid?
 
-<p>GNU <tt>bash</tt> supports “<tt>&amp;&gt;</tt>” (and “|&amp;”) to redirect
- both stdout and stderr in one go, but this breaks POSIX and Korn Shell syntax;
- use POSIX redirections instead:</p>
+<p>GNU <tt>bash</tt> supports “<tt>&amp;&gt;</tt>” (and “<tt>|&amp;</tt>”)
+ to redirect both stdout and stderr in one go, but this breaks POSIX
+ and Korn Shell syntax; use POSIX redirections instead:</p>
 <table border="1" cellpadding="3">
  <tr><td>GNU bash</td><td>
   <tt>foo |&amp; bar |&amp; baz &amp;&gt;log</tt>
@@ -496,7 +818,7 @@ Title: Something is going wrong with my
 <div class="boxtext">
  <pre>
 	bar | baz | while read foo; do ...; done
- </pre>
+</pre>
 </div><p class="boxfoot">Note that <tt>exit</tt> in the inner loop will
  also only exit the subshell and not the original shell. Likewise, if the
  code is inside a function, <tt>return</tt> in the inner loop will only
@@ -507,7 +829,7 @@ Title: Something is going wrong with my
 	bar | baz |&amp;
 	while read -p foo; do ...; done
 	exec 3&gt;&amp;p; exec 3&gt;&amp;-
- </pre>
+</pre>
 </div><p class="boxfoot">If <tt>read</tt> is run in a way such as
  <tt>while read foo; do ...; done</tt> then leading whitespace will be
  removed (IFS) and backslashes processed. You might want to use
@@ -521,7 +843,7 @@ Title: Something is going wrong with my
 	    while IFS= read -d '' -pr filename; do
 		print -r -- "found &lt;${filename#./}&gt;"
 	done
- </pre>
+</pre>
 </div>
 ----
 ToC: command-alias
@@ -532,6 +854,15 @@ This is because AT&amp;T ksh93 ships a p
 put this into your <tt>~/.mkshrc</tt>
 (note the space before the closing single quote)
 ----
+ToC: builtin-cat
+Title: Didn’t there used to be a cat(1) builtin?
+
+<p>Up to and including mksh R59c, we indeed shipped a built-in cat(1)
+ inside mksh; this was added originally because Android did not have
+ one <em>at all</em> (but they have since imported a BSD cat). While
+ it could speed up some sh scripts correct signal handling is hard to
+ get right, so (with regret) it was removed in 2021. 🙀</p>
+----
 ToC: builtin-rename
 Title: “rename” doesn’t work as expected!
 
@@ -539,6 +870,7 @@ Title: “rename” doesn’t work as ex
  thin wrapper around the rename(2) syscall. It receives two pathnames,
  source and destination where the first is then atomically renamed to
  the latter. It does not move, i.e. fails for different filesystems.</p>
+<p>The builtin may be absent if your OS doesn’t have rename(2), e.g. Xenix.</p>
 <p>The GNU package <tt>util-linux</tt> has a different <tt>rename</tt>
  command. If you wish to invoke an external utility (in favour over a
  builtin), you can use <tt>dot.mkshrc</tt>’s function <tt>enable</tt>
@@ -546,23 +878,39 @@ Title: “rename” doesn’t work as ex
 <pre>alias rename="$(whence -p rename)"</pre>
 ----
 ToC: builtin-sleep
-Title: “sleep” does not accept ‘m’ for minutes!
+Title: Didn’t there used to be a sleep(1) builtin?
 
-<p>mksh contains a <tt>sleep</tt> built-in utility, in order to be
- able to offer sub-second sleep to shell scripts for most platforms.
- (It does not exist if the platform lacks select(2) — which should
- be rare.)</p>
-<p>GNU coreutils contains a sleep implementation accepting suffixed
- numbers. If you wish to invoke an external utility (in favour over a
- builtin), you can use <tt>dot.mkshrc</tt>’s function <tt>enable</tt>
- or put something along the following lines into <tt>~/.mkshrc</tt>:</p>
-<pre>alias sleep="$(whence -p sleep)"</pre>
-<pre>timer() { sleep $(($1*60${2:++$2})); } # timer mins [secs]</pre>
-<pre>timer() {
-	local arg=${1/m/'*60+'}
-	[[ $arg = *+ ]] &amp;&amp; arg+=0
-	sleep $(($arg)
-}</pre>
+<p>Up to and including mksh R59c, we indeed shipped a subsecond-capable
+ select(2)-based built-in sleep(1). This got originally added because
+ too many platforms do not support sub-second sleep, which nowadays is
+ of less concern. It also led to users complaining about lack for system
+ *ahem* GNU extensions, but the cause of its demise is that getting signal
+ handling right, in a portable way and without too many syscalls (there’s
+ a threshold over which fork+exec is cheaper!), isn’t feasible if even at
+ all possible.</p>
+<p>The MirOS Project now ships <a href="@@RELPATH@@subprj.htm#sleep">a
+ portable sleep</a> which similarly is select(2)-based and capable of
+ subsecond sleep but in addition supports all GNU extensions related to
+ specifying the amount of time to sleep. It will work on <em>at least</em>
+ all platforms on which mksh had a builtin before. Please install this
+ if your operating system lacks a good enough sleep(1) utility.</p>
+<p>Note that, if your OS lacks select(2), you’ll lose out either way.
+ In that case, GNU coreutils’ sleep, which is built on older syscalls,
+ may work if the copyleft licence isn’t a showstopper for you.</p>
+----
+ToC: arith-import
+Title: Some integer variables are 0?
+
+<p class="boxhead">To mitigate potential exploits, variables imported
+ from the environment are not trusted in arithmetic context; that is…</p>
+<div class="boxtext">
+ <pre>
+	foo=1+1 mksh -c 'integer foo; print $foo'
+	foo=1+1 mksh -c 'integer foo=$foo; print $foo'
+</pre>
+</div><p class="boxfoot">… will lose the value in the first line,
+ while the second line explicitly “untaints”, to use a Perl term,
+ the content. Purely numeric values will pass, though.</p>
 ----
 ToC: string-concat
 Title: “+=” behaves differently from other shells
@@ -624,7 +972,7 @@ Title: I use “set -eo pipefail” and
 	for x in 1 2; do
 		false &amp;&amp; echo $x
 	done | cat
- </pre>
+</pre>
 </div><p class="boxfoot">This is because, while the <tt>&amp;&amp;</tt>
  ensures that the inner command’s failure is not taken, it sets the entire
  <tt>for</tt>‥<tt>done</tt> loop’s errorlevel, which is passed on by
@@ -635,18 +983,27 @@ Title: I use “set -eo pipefail” and
 ToC: faq
 Title: My question is not answered here!
 
-Do read the mksh(1) manual page. You might also wish to read the <a
- href="@@RELPATH@@ksh-chan.htm">homepage of the <tt>#ksh</tt> IRC channel
-on Freenode</a> which lists several resources for Korn or POSIX-compatible
-shells in general. Or, <a href="#contact">contact</a> us (developer and
-users), for example via IRC.
+Do read the mksh(1) and lksh(1) manual pages and the <a
+ href="@@RELPATH@@mksh.htm">homepage</a> and other pages like the <a
+ href="@@RELPATH@@mksh_oe.htm">operating environment-specific notes
+ for mksh</a> overview page. You might also wish to read the <a
+ href="@@RELPATH@@ksh-chan.htm">homepage of the <tt>#ksh</tt> IRC channel</a>
+which lists several resources for Korn or POSIX-compatible shells in general.
+Or, <a href="#contact">contact</a> us (developer and users).
 ----
 ToC: contact
-Title: How do I contact you (to say thanks)?
+Title: How do I contact you (to say thanks, for bugreports and questions)?
 
-You can say hi in the <tt>#!/bin/mksh</tt> channel on Freenode <a
- href="@@RELPATH@@irc.htm">IRC</a>, although a <a
- href="@@RELPATH@@danke.htm">donation</a> wouldn’t be amiss ☺ The <a
- href="http://www.mail-archive.com/miros-mksh@mirbsd.org/">mailing
-list</a> can also be used.
+<p>You can say hi in the <tt>#!/bin/mksh</tt> channel on <a
+ href="@@RELPATH@@irc.htm">IRC</a> (OFTC, for now), where not
+ only the developer but also helpful other people idle around.</p>
+<p>The <a href="#faq">extra resources</a> from the FAQ
+ entry just one above should also be considered ;-)</p>
+<p>If you insist on sending a bugreport, IRC, Fedi (AP) and eMail are
+ great places for that; <a href="https://launchpad.net/mksh">Launchpad</a>,
+ an external gratis service provided by a company, can also be used if you
+ like web-based issue trackers better.</p>
+<p>The primary developer can be reached via Fediverse at
+ <tt>@mirabilos@toot.mirbsd.org</tt> (primary account) or
+ <tt>@mirabilos@ipv6.camp</tt> (backup account).</p>
 ----
--- mksh-59c.orig/os2.c
+++ mksh-59c/os2.c
@@ -1,8 +1,8 @@
 /*-
  * Copyright (c) 2015, 2017, 2020
  *	KO Myung-Hun <komh@chollian.net>
- * Copyright (c) 2017, 2020
- *	mirabilos <m@mirbsd.org>
+ * Copyright (c) 2017, 2020, 2022, 2025
+ *	mirabilos <m$(date +%Y)@mirbsd.de>
  *
  * Provided that these terms and disclaimer and all copyright notices
  * are retained or reproduced in an accompanying document, permission
@@ -20,35 +20,37 @@
  * of said person's immediate fault when using the work as intended.
  */
 
+#define OS2EMX_PLAIN_CHAR
 #define INCL_KBD
 #define INCL_DOS
 #include <os2.h>
 
-#include "sh.h"
-
 #include <klibc/startup.h>
-#include <errno.h>
-#include <io.h>
-#include <unistd.h>
 #include <process.h>
 
-__RCSID("$MirOS: src/bin/mksh/os2.c,v 1.11 2020/10/01 21:13:45 tg Exp $");
+#include "sh.h"
+
+__RCSID("$MirOS: src/bin/mksh/os2.c,v 1.28 2025/05/01 00:58:35 tg Exp $");
 
 struct a_s_arg {
 	union {
 		int (*i)(const char *, int);
-		int (*p)(const char *, void *);
+		int (*s)(const char *, struct stat *);
+		int (*r)(const char *, char **);
 	} fn;
 	union {
 		int i;
-		void *p;
+		struct stat *s;
+		char **r;
 	} arg;
-	bool isint;
+	enum {
+		A_S_INT, A_S_STAT, A_S_RETNAME
+	} type;
 };
 
 static void remove_trailing_dots(char *, size_t);
 static int access_stat_ex(const char *, struct a_s_arg *);
-static int test_exec_exist(const char *, void *);
+static int test_exec_exist(const char *, char **);
 static void response(int *, const char ***);
 static char *make_response_file(char * const *);
 static void add_temp(const char *);
@@ -68,6 +70,7 @@ static void cleanup(void);
 #define KLIBC_ARG_RESPONSE_EXCLUDE	\
 	(__KLIBC_ARG_DQUOTE | __KLIBC_ARG_WILDCARD | __KLIBC_ARG_SHELL)
 
+/* pre-initio() */
 static void
 response(int *argcp, const char ***argvp)
 {
@@ -106,14 +109,15 @@ response(int *argcp, const char ***argvp
 			line = malloc(filesize + /* type */ 1 + /* NUL */ 1);
 			if (!line) {
  exit_out_of_memory:
-				fputs("Out of memory while reading response file\n", stderr);
+				SHIKATANAI write(2,
+				    SC("mksh: out of memory reading response file\n"));
 				exit(255);
 			}
 
 			line[0] = __KLIBC_ARG_NONZERO | __KLIBC_ARG_RESPONSE;
 			l = line + 1;
 			while (fgets(l, (filesize + 1) - (l - (line + 1)), f)) {
-				p = strchr(l, '\n');
+				p = ucstrchr(l, '\n');
 				if (p) {
 					/*
 					 * if a line ends with a backslash,
@@ -148,7 +152,8 @@ response(int *argcp, const char ***argvp
 			free(line);
 
 			if (ferror(f)) {
-				fputs("Cannot read response file\n", stderr);
+				SHIKATANAI write(2,
+				    SC("mksh: can't read response file\n"));
 				exit(255);
 			}
 
@@ -163,6 +168,7 @@ response(int *argcp, const char ***argvp
 	*argvp = new_argv;
 }
 
+/* pre-initio() */
 static void
 init_extlibpath(void)
 {
@@ -182,6 +188,7 @@ init_extlibpath(void)
 	}
 }
 
+/* pre-initio() */
 void
 os2_init(int *argcp, const char ***argvp)
 {
@@ -287,7 +294,7 @@ access(const char *name, int mode)
 #define MAX_X_SUFFIX_LEN	4
 
 static const char *x_suffix_list[] =
-    { "", ".ksh", ".exe", ".sh", ".cmd", ".com", ".bat", NULL };
+    { "", ".exe", ".ksh", ".sh", ".cmd", ".com", ".bat", NULL };
 
 /* call fn() by appending executable extensions */
 static int
@@ -305,8 +312,17 @@ access_stat_ex(const char *name, struct
 		strlcpy(x_name, name, x_namelen);
 		strlcat(x_name, *x_suffix, x_namelen);
 
-		rc = action->isint ? action->fn.i(x_name, action->arg.i) :
-		    action->fn.p(x_name, action->arg.p);
+		switch (action->type) {
+		case A_S_INT:
+			rc = action->fn.i(x_name, action->arg.i);
+			break;
+		case A_S_STAT:
+			rc = action->fn.s(x_name, action->arg.s);
+			break;
+		case A_S_RETNAME:
+			rc = action->fn.r(x_name, action->arg.r);
+			break;
+		}
 	}
 
 	afree(x_name, ATEMP);
@@ -322,7 +338,7 @@ access_ex(int (*fn)(const char *, int),
 
 	arg.fn.i = fn;
 	arg.arg.i = mode;
-	arg.isint = true;
+	arg.type = A_S_INT;
 	return (access_stat_ex(name, &arg));
 }
 
@@ -333,14 +349,14 @@ stat_ex(int (*fn)(const char *, struct s
 {
 	struct a_s_arg arg;
 
-	arg.fn.p = fn;
-	arg.arg.p = buffer;
-	arg.isint = false;
+	arg.fn.s = fn;
+	arg.arg.s = buffer;
+	arg.type = A_S_STAT;
 	return (access_stat_ex(name, &arg));
 }
 
 static int
-test_exec_exist(const char *name, void *arg)
+test_exec_exist(const char *name, char **arg)
 {
 	struct stat sb;
 	char *real_name;
@@ -350,7 +366,7 @@ test_exec_exist(const char *name, void *
 
 	/*XXX memory leak */
 	strdupx(real_name, name, ATEMP);
-	*((char **)arg) = real_name;
+	*arg = real_name;
 	return (0);
 }
 
@@ -360,9 +376,9 @@ real_exec_name(const char *name)
 	struct a_s_arg arg;
 	char *real_name;
 
-	arg.fn.p = &test_exec_exist;
-	arg.arg.p = (void *)(&real_name);
-	arg.isint = false;
+	arg.fn.r = &test_exec_exist;
+	arg.arg.r = &real_name;
+	arg.type = A_S_RETNAME;
 	return (access_stat_ex(name, &arg) ? name : real_name);
 }
 
@@ -392,6 +408,18 @@ make_response_file(char * const *argv)
 	return (result);
 }
 
+static int child_pid = -1;
+
+/* kill a child process when exits */
+static VOID APIENTRY
+kill_child(void)
+{
+	if (child_pid != -1)
+		kill(child_pid, SIGTERM);
+
+	DosExitList(EXLST_EXIT, NULL);
+}
+
 /* alias of execve() */
 extern int _std_execve(const char *, char * const *, char * const *);
 
@@ -408,6 +436,7 @@ execve(const char *name, char * const *a
 	int rc;
 	int saved_mode;
 	int saved_errno;
+	ULONG nesting;
 
 	/*
 	 * #! /bin/sh : append .exe
@@ -447,6 +476,9 @@ execve(const char *name, char * const *a
 	if (errno == ENOEXEC)
 		return (-1);
 
+	nesting = 0;
+	DosEnterMustComplete(&nesting);
+
 	/*
 	 * Normal OS/2 programs expect that standard IOs, especially stdin,
 	 * are opened in text mode at the startup. By the way, on OS/2 kLIBC
@@ -480,11 +512,17 @@ execve(const char *name, char * const *a
 
 	if (pid == -1) {
 		cleanup_temps();
+		DosExitMustComplete(&nesting);
 
 		errno = saved_errno;
 		return (-1);
 	}
 
+	child_pid = pid;
+	DosExitList(EXLST_ADD | 0x7000, (PFNEXITLIST)kill_child);
+
+	DosExitMustComplete(&nesting);
+
 	/* close all opened handles */
 	for (fd = 0; fd < NUFILE; fd++) {
 		if (fcntl(fd, F_GETFD) == -1)
@@ -514,9 +552,11 @@ static void
 add_temp(const char *name)
 {
 	struct temp *tp;
+	size_t len;
 
-	tp = alloc(offsetof(struct temp, tffn[0]) + strlen(name) + 1, APERM);
-	memcpy(tp->tffn, name, strlen(name) + 1);
+	len = strlen(name) + 1U;
+	tp = alloc(mbccFAMsz(struct temp, tffn, len), APERM);
+	memcpy(tp->tffn, name, len);
 	tp->next = templist;
 	templist = tp;
 }
@@ -577,8 +617,7 @@ getdrvwd(char **cpp, unsigned int drvltr
 	}
 
 	/* allocate 'X:/' plus sz plus NUL */
-	checkoktoadd((size_t)sz, (size_t)4);
-	cp = aresize(*cpp, (size_t)sz + (size_t)4, ATEMP);
+	cp = aresize1(*cpp, sz, 4, ATEMP);
 	cp[0] = ksh_toupper(drvltr);
 	cp[1] = ':';
 	cp[2] = '/';
--- mksh-59c.orig/rlimits.opt
+++ mksh-59c/rlimits.opt
@@ -1,6 +1,6 @@
 /*-
- * Copyright (c) 2013, 2015, 2019
- *	mirabilos <m@mirbsd.org>
+ * Copyright (c) 2013, 2015, 2019, 2021
+ *	mirabilos <m$(date +%Y)@mirbsd.de>
  *
  * Provided that these terms and disclaimer and all copyright notices
  * are retained or reproduced in an accompanying document, permission
@@ -21,7 +21,7 @@
  */
 
 @RLIMITS_DEFNS
-__RCSID("$MirOS: src/bin/mksh/rlimits.opt,v 1.5 2020/07/24 20:11:18 tg Exp $");
+__RCSID("$MirOS: src/bin/mksh/rlimits.opt,v 1.7 2025/04/25 23:14:59 tg Exp $");
 @RLIMITS_ITEMS
 #define FN(lname,lid,lfac,lopt) (const struct limits *)(&rlimits_ ## lid),
 @@
@@ -94,6 +94,9 @@ FN("threadsperprocess", RLIMIT_THREADS,
 >e|RLIMIT_NICE
 FN("maxnice", RLIMIT_NICE, 1
 
+>R|RLIMIT_RTTIME
+FN("rttime(ms)", RLIMIT_RTTIME, 1
+
 >r|RLIMIT_RTPRIO
 FN("maxrtprio", RLIMIT_RTPRIO, 1
 
--- mksh-59c.orig/sh.h
+++ mksh-59c/sh.h
@@ -9,44 +9,56 @@
 /*	$OpenBSD: tty.h,v 1.5 2004/12/20 11:34:26 otto Exp $	*/
 
 /*-
- * Copyright © 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
- *	       2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018,
- *	       2019, 2020
- *	mirabilos <m@mirbsd.org>
+ * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
+ *		 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018,
+ *		 2019, 2020, 2021, 2022, 2023, 2025
+ *	mirabilos <m$(date +%Y)@mirbsd.de>
  *
  * Provided that these terms and disclaimer and all copyright notices
  * are retained or reproduced in an accompanying document, permission
- * is granted to deal in this work without restriction, including un‐
+ * is granted to deal in this work without restriction, including un-
  * limited rights to use, publicly perform, distribute, sell, modify,
  * merge, give away, or sublicence.
  *
- * This work is provided “AS IS” and WITHOUT WARRANTY of any kind, to
+ * This work is provided "AS IS" and WITHOUT WARRANTY of any kind, to
  * the utmost extent permitted by applicable law, neither express nor
  * implied; without malicious intent or gross negligence. In no event
  * may a licensor, author or contributor be held liable for indirect,
  * direct, other damage, loss, or other issues arising in any way out
  * of dealing in the work, even if advised of the possibility of such
  * damage or existence of a defect, except proven that it results out
- * of said person’s immediate fault when using the work as intended.
+ * of said person's immediate fault when using the work as intended.
  */
 
-#ifdef __dietlibc__
-/* XXX imake style */
-#define _BSD_SOURCE	/* live, BSD, live❣ */
+#define MKSH_SH_H_ID "$MirOS: src/bin/mksh/sh.h,v 1.1041 2025/12/24 04:51:54 tg Exp $"
+
+#ifdef MKSH_USE_AUTOCONF_H
+/* things that “should” have been on the command line */
+#include "autoconf.h"
+#undef MKSH_USE_AUTOCONF_H
 #endif
 
 #if HAVE_SYS_PARAM_H
 #include <sys/param.h>
 #endif
 #include <sys/types.h>
-#if HAVE_BOTH_TIME_H
+#if HAVE_BOTH_TIME_H && HAVE_SELECT_TIME_H
 #include <sys/time.h>
 #include <time.h>
-#elif HAVE_SYS_TIME_H
+#elif HAVE_SYS_TIME_H && HAVE_SELECT_TIME_H
 #include <sys/time.h>
 #elif HAVE_TIME_H
 #include <time.h>
 #endif
+#if HAVE_SYS_BSDTYPES_H
+#include <sys/bsdtypes.h>
+#endif
+#if HAVE_SYS_SELECT_H
+#include <sys/select.h>
+#endif
+#if HAVE_SYS_FILE_H
+#include <sys/file.h>
+#endif
 #include <sys/ioctl.h>
 #if HAVE_SYS_SYSMACROS_H
 #include <sys/sysmacros.h>
@@ -57,14 +69,35 @@
 #if HAVE_SYS_MMAN_H
 #include <sys/mman.h>
 #endif
+#if HAVE_SYS_PTEM_H
+/* prerequisite */
+#include <sys/stream.h>
+/* struct winsize */
+#include <sys/ptem.h>
+#endif
+#if defined(HAVE_GETRANDOM) && (HAVE_GETRANDOM)
+#include <sys/random.h>
+#endif
 #if HAVE_SYS_RESOURCE_H
 #include <sys/resource.h>
 #endif
 #include <sys/stat.h>
+#if !HAVE_GETRUSAGE
+#include <sys/times.h>
+#endif
 #include <sys/wait.h>
+#ifdef DEBUG
+#include <assert.h>
+#endif
+#if HAVE_SELECT && HAVE_BSTRING_H
+#include <bstring.h>
+#endif
 #include <dirent.h>
 #include <errno.h>
 #include <fcntl.h>
+#if HAVE_GRP_H
+#include <grp.h>
+#endif
 #if HAVE_IO_H
 #include <io.h>
 #endif
@@ -75,9 +108,18 @@
 #include <libutil.h>
 #endif
 #include <limits.h>
+#if defined(MKSH_EBCDIC) || defined(MKSH_FAUX_EBCDIC) || HAVE_POSIX_UTF8_LOCALE
+#include <locale.h>
+#if HAVE_POSIX_UTF8_LOCALE
+#include <langinfo.h>
+#endif
+#endif
 #if HAVE_PATHS_H
 #include <paths.h>
 #endif
+#ifdef MKSH_POLL_FOR_PAUSE
+#include <poll.h>
+#endif
 #ifndef MKSH_NOPWNAM
 #include <pwd.h>
 #endif
@@ -108,18 +150,31 @@
 #include <ulimit.h>
 #endif
 #include <unistd.h>
-#if HAVE_VALUES_H
-#include <values.h>
-#endif
 #ifdef MIRBSD_BOOTFLOPPY
 #include <wchar.h>
 #endif
 
-/* monkey-patch known-bad offsetof versions to quell a warning */
-#if (defined(__KLIBC__) || defined(__dietlibc__)) && \
-    ((defined(__GNUC__) && (__GNUC__ > 3)) || defined(__NWCC__))
-#undef offsetof
-#define offsetof(s,e)		__builtin_offsetof(s, e)
+#undef MBSDINT_H_SKIP_CTAS
+#ifndef MKSH_DO_MBI_CTAS
+#define MBSDINT_H_SKIP_CTAS
+#endif
+/* formatting routines assume this */
+#define MBSDINT_H_WANT_PTR_IN_SIZET 1
+#define MBSDINT_H_WANT_SIZET_IN_LONG 1
+/* POSIX guarantees a 32-bit int */
+#define MBSDINT_H_WANT_INT32 1
+/* the code cannot cope without yet */
+#define MBSDINT_H_WANT_SAFEC 1
+#include "mbsdcc.h"
+#include "mbsdint.h"
+
+/* monkey-patch nil pointer constant */
+#undef NULL
+#define NULL mbnil
+
+/* conflict with GCC attributes; fixed in later dietlibcs */
+#ifdef __dietlibc__
+#undef __noinline__
 #endif
 
 #undef __attribute__
@@ -138,11 +193,6 @@
 #else
 #define MKSH_A_NORETURN		/* nothing */
 #endif
-#if HAVE_ATTRIBUTE_PURE
-#define MKSH_A_PURE		__attribute__((__pure__))
-#else
-#define MKSH_A_PURE		/* nothing */
-#endif
 #if HAVE_ATTRIBUTE_UNUSED
 #define MKSH_A_UNUSED		__attribute__((__unused__))
 #else
@@ -192,22 +242,60 @@
 #define __SCCSID(x)		__IDSTRING(sccsid,x)
 #endif
 
-#ifdef EXTERN
-__RCSID("$MirOS: src/bin/mksh/sh.h,v 1.904 2020/10/31 03:53:06 tg Exp $");
-#endif
-#define MKSH_VERSION "R59 2020/10/31"
+#define MKSH_VERSION "R59 2025/12/23"
 
-/* arithmetic types: C implementation */
-#if !HAVE_CAN_INTTYPES
-#if !HAVE_CAN_UCBINTS
-typedef signed int int32_t;
-typedef unsigned int uint32_t;
+/* shell types */
+typedef unsigned char kby;		/* byte */
+typedef unsigned int kui;		/* wchar; kby or EOF; ⊇k32; etc. */
+/* MBSDINT_H_WANT_INT32 guaranteed; u_int rank also guaranteed */
+typedef unsigned int k32;		/* 32-bit arithmetic (hashes etc.) */
+/* for use with/without 32-bit masking */
+typedef unsigned long kul;		/* long, arithmetic */
+typedef signed long ksl;		/* signed long, arithmetic */
+#define KUL_FM ULONG_MAX
+#define KUL_HM LONG_MAX
+/* if mbiHUGE is wider than long, then that, else long */
+#if mbiHUGE_UBITS > mbiMASK__BITS(ULONG_MAX)
+#define MKSH_HAVE_HUGE
+typedef mbiHUGE_U kuH;
+typedef mbiHUGE_S ksH;
+#define KUH_FM mbiHUGE_U_MAX
+#define KUH_HM mbiHUGE_S_MAX
+#else
+#undef MKSH_HAVE_HUGE
+typedef kul kuH;
+typedef ksl ksH;
+#define KUH_FM ULONG_MAX
+#define KUH_HM LONG_MAX
+#endif
+
+#define KBY(c)	((kby)(KUI(c) & 0xFFU))	/* byte, truncated if necessary */
+#define KBI(c)	((kui)(KUI(c) & 0xFFU))	/* byte as u_int, truncated */
+#define KUI(u)	((kui)(u))		/* int as u_int, not truncated */
+
+#define K32_HM		0x7FFFFFFFUL
+#define K32_FM		0xFFFFFFFFUL
+
+/*XXX TODO:
+ * arithmetic type need not be long, it can be unsigned int if we can
+ * guarantee that it’s exactly⚠ 32 bit wide; in the !lksh case, never
+ * shall a signed integer be needed; for lksh signed arithmetic, only
+ * I think, the values need to be converted temporarily; !lksh signed
+ * arithmetic is instead done in unsigned; kul → kua (ksl → ksa lksh)
+ */
+#ifdef MKSH_LEGACY_MODE
+#define KUA_HM		LONG_MAX
+#define KUA_FM		ULONG_MAX
 #else
-typedef u_int32_t uint32_t;
-#endif
+#define KUA_HM		K32_HM
+#define KUA_FM		K32_FM
 #endif
 
 /* arithmetic types: shell arithmetics */
+
+/* new arithmetics tbd, using mbiMA_* */
+
+/* older arithmetics, to be replaced later */
 #ifdef MKSH_LEGACY_MODE
 /*
  * POSIX demands these to be the C environment's long type
@@ -220,32 +308,18 @@ typedef unsigned long mksh_uari_t;
  * integer wraparound, even across division and modulo, for
  * any shell code using them, is guaranteed.
  */
-typedef int32_t mksh_ari_t;
-typedef uint32_t mksh_uari_t;
+/* relies on compile-time asserts and CFLAGS to validate that */
+typedef signed int mksh_ari_t;
+typedef unsigned int mksh_uari_t;
 #endif
 
+/* new arithmetics in preparation */
+
 /* boolean type (no <stdbool.h> deliberately) */
-typedef unsigned char mksh_bool;
-#undef bool
-/* false MUST equal the same 0 as written by static storage initialisation */
-#undef false
-#undef true
-/* access macros for boolean type */
-#define bool		mksh_bool
-/* values must have identity mapping between mksh_bool and short */
-#define false		0
-#define true		1
-/* make any-type into bool or short */
-#define tobool(cond)	((cond) ? true : false)
-
-/* char (octet) type: C implementation */
-#if !HAVE_CAN_INT8TYPE
-#if !HAVE_CAN_UCBINT8
-typedef unsigned char uint8_t;
-#else
-typedef u_int8_t uint8_t;
-#endif
-#endif
+typedef unsigned char Wahr;
+#define Ja		1U
+#define Nee		0U
+#define isWahr(cond)	((cond) ? Ja : Nee)
 
 /* other standard types */
 
@@ -258,10 +332,6 @@ typedef void (*sig_t)(int);
 typedef MKSH_TYPEDEF_SIG_ATOMIC_T sig_atomic_t;
 #endif
 
-#ifdef MKSH_TYPEDEF_SSIZE_T
-typedef MKSH_TYPEDEF_SSIZE_T ssize_t;
-#endif
-
 #if defined(MKSH_SMALL) && !defined(MKSH_SMALL_BUT_FAST)
 #define MKSH_SHF_NO_INLINE
 #endif
@@ -278,12 +348,8 @@ typedef MKSH_TYPEDEF_SSIZE_T ssize_t;
 #undef PRINT		/* LynxOS defines that somewhere */
 #undef flock		/* SCO UnixWare defines that to flock64 but ENOENT */
 
-
 #ifndef MKSH_INCLUDES_ONLY
 
-/* compile-time assertions */
-#define cta(name,expr)	struct cta_ ## name { char t[(expr) ? 1 : -1]; }
-
 /* EBCDIC fun */
 
 /* see the large comment in shf.c for an EBCDIC primer */
@@ -295,16 +361,12 @@ typedef MKSH_TYPEDEF_SSIZE_T ssize_t;
 # if __CHARSET_LIB && defined(MKSH_EBCDIC)
 #  error "Please compile without -E argument to Build.sh for ASCII!"
 # endif
-# if __CHARSET_LIB && !defined(_ENHANCED_ASCII_EXT)
-   /* go all-out on ASCII */
-#  define _ENHANCED_ASCII_EXT 0xFFFFFFFF
-# endif
 #endif
 
 /* extra types */
 
-/* getrusage does not exist on OS/2 kLIBC */
-#if !HAVE_GETRUSAGE && !defined(__OS2__)
+/* getrusage does not exist on OS/2 kLIBC and is stubbed on SerenityOS */
+#if !HAVE_GETRUSAGE
 #undef rusage
 #undef RUSAGE_SELF
 #undef RUSAGE_CHILDREN
@@ -316,6 +378,10 @@ struct rusage {
 	struct timeval ru_utime;
 	struct timeval ru_stime;
 };
+
+extern int ksh_getrusage(int, struct rusage *);
+#else
+#define ksh_getrusage getrusage
 #endif
 
 /* extra macros */
@@ -348,24 +414,25 @@ struct rusage {
 		}							\
 	} while (/* CONSTCOND */ 0)
 #endif
-
-#ifdef MKSH__NO_PATH_MAX
-#undef PATH_MAX
-#else
-#ifndef PATH_MAX
-#ifdef MAXPATHLEN
-#define PATH_MAX	MAXPATHLEN
-#else
-#define PATH_MAX	1024
-#endif
+#ifndef timercmp
+#define timercmp(tvp,uvp,cmp) (((tvp)->tv_sec == (uvp)->tv_sec) ?	\
+	    ((tvp)->tv_usec cmp (uvp)->tv_usec) :			\
+	    ((tvp)->tv_sec cmp (uvp)->tv_sec))
 #endif
+
+/* if this breaks, see sh.h,v 1.954 commit message and diff */
+#ifndef _POSIX_VDISABLE
+/* Linux klibc lacks this definition */
+#define _POSIX_VDISABLE 0xFFU /* unsigned (for cc_t) default (BSD) value */
 #endif
-#ifndef SIZE_MAX
-#ifdef SIZE_T_MAX
-#define SIZE_MAX	SIZE_T_MAX
-#else
-#define SIZE_MAX	((size_t)-1)
+#define KSH_ISVDIS(x,d)	((x) == _POSIX_VDISABLE ? (d) : KBI(x))
+#define KSH_DOVDIS(x)	(x) = _POSIX_VDISABLE
+
+#ifndef S_ISFIFO
+#define S_ISFIFO(m)	((m & 0170000) == 0010000)
 #endif
+#ifndef S_ISCHR
+#define S_ISCHR(m)	((m & 0170000) == 0020000)
 #endif
 #ifndef S_ISLNK
 #define S_ISLNK(m)	((m & 0170000) == 0120000)
@@ -380,7 +447,6 @@ struct rusage {
 #define DEFFILEMODE	(S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH)
 #endif
 
-
 /* determine ksh_NSIG: first, use the traditional definitions */
 #undef ksh_NSIG
 #if defined(NSIG)
@@ -427,6 +493,38 @@ struct rusage {
 
 #define ksh_sigmask(sig) (((sig) < 1 || (sig) > 127) ? 255 : 128 + (sig))
 
+#if HAVE_SIGACTION
+typedef struct sigaction ksh_sigsaved;
+#define ksh_sighandler(saved) ((saved)->sa_handler)
+#else
+typedef sig_t ksh_sigsaved;
+#define ksh_sighandler(saved) (*(saved))
+#endif
+
+#if HAVE_SIGDESCR_NP
+#define ksh_sigmess(nr) sigdescr_np(nr)
+#elif HAVE_SYS_SIGLIST
+#if !HAVE_SYS_SIGLIST_DECL
+extern const char * const sys_siglist[];
+#endif
+#define ksh_sigmess(nr) sys_siglist[nr]
+#elif HAVE_STRSIGNAL
+#define ksh_sigmess(nr) strsignal(nr)
+#else
+#define ksh_sigmess(nr) NULL
+#endif
+#define ksh_sigmessf(mess) (!(mess) || !*(mess))
+
+/* contract: masks the signal, may restart, not oneshot */
+int ksh_sigset(int, sig_t, ksh_sigsaved *);
+int ksh_sigrestore(int, ksh_sigsaved *);
+sig_t ksh_sigget(int);
+
+#if HAVE_SIGACTION && !defined(SIG_ERR)
+void ksh_sigerr(int);
+#define SIG_ERR (&ksh_sigerr)
+#define NEED_KSH_SIGERR
+#endif
 
 /* OS-dependent additions (functions, variables, by OS) */
 
@@ -467,23 +565,23 @@ extern int flock(int, int);
 #define mksh_TIME(tv) gettimeofday(&(tv), NULL)
 #endif
 
-#if !HAVE_GETRUSAGE
-extern int getrusage(int, struct rusage *);
-#endif
-
 #if !HAVE_MEMMOVE
-/* we assume either memmove or bcopy exist, at the moment */
-#define memmove(dst,src,len)	bcopy((src), (dst), (len))
+#undef memmove
+#define memmove rpl_memmove
+void *rpl_memmove(void *, const void *, size_t);
 #endif
 
 #if !HAVE_REVOKE_DECL
 extern int revoke(const char *);
 #endif
 
+#ifndef EOVERFLOW
+#define EOVERFLOW		ERANGE
+#endif
+
 #if defined(DEBUG) || !HAVE_STRERROR
 #undef strerror
 #define strerror		/* poisoned */ dontuse_strerror
-#define cstrerror		/* replaced */ cstrerror
 extern const char *cstrerror(int);
 #else
 #define cstrerror(errnum)	((const char *)strerror(errnum))
@@ -553,7 +651,6 @@ extern int __cdecl setegid(gid_t);
 #define KSH_VTAB	11
 #endif
 
-
 /* some useful #defines */
 #ifdef EXTERN
 # define E_INIT(i) = i
@@ -565,6 +662,11 @@ extern int __cdecl setegid(gid_t);
 
 /* define bit in flag */
 #define BIT(i)		(1U << (i))
+/* check bit(s) */
+#define HAS(v,f)	(((v) & (f)) == (f))
+#define IS(v,f,t)	(((v) & (f)) == (t))
+/* array sizing */
+#undef NELEM
 #define NELEM(a)	(sizeof(a) / sizeof((a)[0]))
 
 /*
@@ -588,6 +690,11 @@ EXTERN const char *safe_prompt; /* safe
 #else
 #define KSH_VERSIONNAME_ISLEGACY	"MIRBSD"
 #endif
+#ifdef DEBUG
+#define KSH_VERSIONNAME_DEBUG		" +DEBUG_dont_ship_to_users"
+#else
+#define KSH_VERSIONNAME_DEBUG		""
+#endif
 #ifdef MKSH_WITH_TEXTMODE
 #define KSH_VERSIONNAME_TEXTMODE	" +TEXTMODE"
 #else
@@ -602,7 +709,8 @@ EXTERN const char *safe_prompt; /* safe
 #define KSH_VERSIONNAME_VENDOR_EXT	""
 #endif
 EXTERN const char initvsn[] E_INIT("KSH_VERSION=@(#)" KSH_VERSIONNAME_ISLEGACY \
-    " KSH " MKSH_VERSION KSH_VERSIONNAME_EBCDIC KSH_VERSIONNAME_TEXTMODE \
+    " KSH " MKSH_VERSION KSH_VERSIONNAME_DEBUG \
+    KSH_VERSIONNAME_EBCDIC KSH_VERSIONNAME_TEXTMODE \
     KSH_VERSIONNAME_VENDOR_EXT);
 #define KSH_VERSION	(initvsn + /* "KSH_VERSION=@(#)" */ 16)
 
@@ -621,44 +729,26 @@ union mksh_ccphack {
 	const char **ro;
 };
 
-/*
- * Evil hack since casting uint to sint is implementation-defined
- */
-typedef union {
-	mksh_ari_t i;
-	mksh_uari_t u;
-} mksh_ari_u;
-
 /* for const debugging */
-#if defined(DEBUG) && defined(__GNUC__) && !defined(__ICC) && \
-    !defined(__INTEL_COMPILER) && !defined(__SUNPRO_C)
+#if defined(DEBUG)
 char *ucstrchr(char *, int);
-char *ucstrstr(char *, const char *);
+const char *cstrchr(const char *, int);
 #undef strchr
-#define strchr ucstrchr
-#define strstr ucstrstr
-#define cstrchr(s,c) ({			\
-	union mksh_cchack in, out;	\
-					\
-	in.ro = (s);			\
-	out.rw = ucstrchr(in.rw, (c));	\
-	(out.ro);			\
-})
-#define cstrstr(b,l) ({			\
-	union mksh_cchack in, out;	\
-					\
-	in.ro = (b);			\
-	out.rw = ucstrstr(in.rw, (l));	\
-	(out.ro);			\
-})
-#define vstrchr(s,c)	(cstrchr((s), (c)) != NULL)
-#define vstrstr(b,l)	(cstrstr((b), (l)) != NULL)
-#else /* !DEBUG, !gcc */
+#define strchr		poisoned_strchr
+#else
+#define ucstrchr(s,c)	strchr((s), (c))
 #define cstrchr(s,c)	((const char *)strchr((s), (c)))
+#endif
+#define vstrchr(s,c)	(cstrchr((s), (c)) != NULL)
+#if defined(DEBUG) || !HAVE_STRSTR
+char *ucstrstr(char *, const char *);
+const char *cstrstr(const char *, const char *);
+#define strstr		poisoned_strstr
+#else
+#define ucstrstr(s,c)	strstr((s), (c))
 #define cstrstr(s,c)	((const char *)strstr((s), (c)))
-#define vstrchr(s,c)	(strchr((s), (c)) != NULL)
-#define vstrstr(b,l)	(strstr((b), (l)) != NULL)
 #endif
+#define vstrstr(b,l)	(cstrstr((b), (l)) != NULL)
 
 #if defined(DEBUG) || defined(__COVERITY__)
 #ifndef DEBUG_LEAKS
@@ -666,8 +756,8 @@ char *ucstrstr(char *, const char *);
 #endif
 #endif
 
-#if (!defined(MKSH_BUILDMAKEFILE4BSD) && !defined(MKSH_BUILDSH)) || (MKSH_BUILD_R != 593)
-#error Must run Build.sh to compile this.
+#if (!defined(MKSH_BUILDMEAT)) || (MKSH_BUILD_R != 599)
+#error Use the documented way to build this.
 extern void thiswillneverbedefinedIhope(void);
 int
 im_sorry_dave(void)
@@ -680,9 +770,9 @@ im_sorry_dave(void)
 /* use this ipv strchr(s, 0) but no side effects in s! */
 #define strnul(s)	((s) + strlen((const void *)s))
 
-#define utf_ptradjx(src,dst) do {					\
-	(dst) = (src) + utf_ptradj(src);				\
-} while (/* CONSTCOND */ 0)
+/* inspired by jupp, where they are in lowercase though */
+#define SC(s)		(s), (sizeof(s) / sizeof(s[0]) - 1U)
+#define SZ(s)		(s), strlen(s)
 
 #if defined(MKSH_SMALL) && !defined(MKSH_SMALL_BUT_FAST)
 #define strdupx(d,s,ap) do {						\
@@ -698,7 +788,7 @@ im_sorry_dave(void)
 	char *strdup_dst = NULL;					\
 									\
 	if (strdup_src != NULL) {					\
-		size_t strdup_len = strlen(strdup_src) + 1;		\
+		size_t strdup_len = strlen(strdup_src) + 1U;		\
 		strdup_dst = alloc(strdup_len, (ap));			\
 		memcpy(strdup_dst, strdup_src, strdup_len);		\
 	}								\
@@ -710,19 +800,32 @@ im_sorry_dave(void)
 									\
 	if (strdup_src != NULL) {					\
 		size_t strndup_len = (n);				\
-		strdup_dst = alloc(strndup_len + 1, (ap));		\
+		strdup_dst = alloc(strndup_len + 1U, (ap));		\
 		memcpy(strdup_dst, strdup_src, strndup_len);		\
 		strdup_dst[strndup_len] = '\0';				\
 	}								\
 	(d) = strdup_dst;						\
 } while (/* CONSTCOND */ 0)
 #endif
+#define strnbdupx(d,s,n,ap,b) do {					\
+	const char *strdup_src = (const void *)(s);			\
+	char *strdup_dst = NULL;					\
+									\
+	if (strdup_src != NULL) {					\
+		size_t strndup_len = (n);				\
+		strdup_dst = strndup_len < sizeof(b) ? (b) :		\
+		    alloc(strndup_len + 1U, (ap));			\
+		memcpy(strdup_dst, strdup_src, strndup_len);		\
+		strdup_dst[strndup_len] = '\0';				\
+	}								\
+	(d) = strdup_dst;						\
+} while (/* CONSTCOND */ 0)
 #define strdup2x(d,s1,s2) do {						\
 	const char *strdup_src = (const void *)(s1);			\
 	const char *strdup_app = (const void *)(s2);			\
 	size_t strndup_len = strlen(strdup_src);			\
-	size_t strndup_ln2 = strlen(strdup_app) + 1;			\
-	char *strdup_dst = alloc(strndup_len + strndup_ln2, ATEMP);	\
+	size_t strndup_ln2 = strlen(strdup_app) + 1U;			\
+	char *strdup_dst = alloc1(strndup_len, strndup_ln2, ATEMP);	\
 									\
 	memcpy(strdup_dst, strdup_src, strndup_len);			\
 	memcpy(strdup_dst + strndup_len, strdup_app, strndup_ln2);	\
@@ -731,19 +834,20 @@ im_sorry_dave(void)
 #define strpathx(d,s1,s2,cond) do {					\
 	const char *strdup_src = (const void *)(s1);			\
 	const char *strdup_app = (const void *)(s2);			\
-	size_t strndup_len = strlen(strdup_src) + 1;			\
+	size_t strndup_len = strlen(strdup_src) + 1U;			\
 	size_t strndup_ln2 = ((cond) || *strdup_app) ?			\
-	    strlen(strdup_app) + 1 : 0;					\
-	char *strdup_dst = alloc(strndup_len + strndup_ln2, ATEMP);	\
+	    strlen(strdup_app) + 1U : 0;				\
+	char *strdup_dst = alloc1(strndup_len, strndup_ln2, ATEMP);	\
 									\
 	memcpy(strdup_dst, strdup_src, strndup_len);			\
 	if (strndup_ln2) {						\
-		strdup_dst[strndup_len - 1] = '/';			\
+		strdup_dst[strndup_len - 1U] = '/';			\
 		memcpy(strdup_dst + strndup_len, strdup_app,		\
 		    strndup_ln2);					\
 	}								\
 	(d) = strdup_dst;						\
 } while (/* CONSTCOND */ 0)
+#define memstr(d,s) memcpy((d), (s), sizeof(s))
 
 #ifdef MKSH_SMALL
 #ifndef MKSH_NOPWNAM
@@ -762,14 +866,38 @@ im_sorry_dave(void)
 #define MKSH_UNEMPLOYED		1
 #endif
 
-#define NUFILE		32	/* Number of user-accessible files */
-#define FDBASE		10	/* First file usable by Shell */
+/* savedfd data type */
+typedef kby ksh_fdsave;
+/* savedfd “index is closed” mask */
+#define FDICLMASK	((ksh_fdsave)0x80U)
+/* savedfd “fd number” mask */
+#define FDNUMMASK	((ksh_fdsave)0x7FU)
+/* savedfd fd numbers are ≥ FDBASE */
+/* savedfd “not saved” number: 0 */
+/* savedfd “saved is closed” or savefd error indicator number */
+#define FDCLOSED	((ksh_fdsave)0x01U)
+/* savefd() to savedfd mapper */
+#define FDSAVE(i,sfd)	do {					\
+	int FDSAVEsavedfd = (sfd);				\
+	e->savedfd[i] = FDSAVEsavedfd < FDBASE ? FDCLOSED :	\
+	    /* ≤ FDMAXNUM checked in savefd() already */	\
+	    (ksh_fdsave)(FDSAVEsavedfd & FDNUMMASK);		\
+} while (/* CONSTCOND */ 0)
+/* savedfd to restfd mapper */
+#define FDSVNUM(ep,i)	((kui)((ep)->savedfd[i] & FDNUMMASK))
+#define SAVEDFD(ep,i)	(FDSVNUM(ep, i) == (kui)FDCLOSED ? \
+			    -1 : (int)FDSVNUM(ep, i))
+/* first fd number usable by the shell for its own purposes */
+#define FDBASE		10
+/* … and last one */
+#define FDMAXNUM	127 /* 0x7FU, cf. FDNUMMASK */
+/* number of user-accessible file descriptors */
+#define NUFILE		10
 
 /*
  * simple grouping allocator
  */
 
-
 /* 0. OS API: where to get memory from and how to free it (grouped) */
 
 /* malloc(3)/realloc(3) -> free(3) for use by the memory allocator */
@@ -787,12 +915,11 @@ im_sorry_dave(void)
 #define free_ossetmode(p)	free(p)
 #endif
 
-#ifdef MKSH__NO_PATH_MAX
+#if HAVE_GET_CURRENT_DIR_NAME
 /* GNU libc: get_current_dir_name(3) -> free(3) */
 #define free_gnu_gcdn(p)	free(p)
 #endif
 
-
 /* 1. internal structure */
 struct lalloc_common {
 	struct lalloc_common *next;
@@ -818,7 +945,6 @@ struct lalloc_item {
 /* 3. group structure */
 typedef struct lalloc_common Area;
 
-
 EXTERN Area aperm;		/* permanent object space */
 #define APERM	&aperm
 #define ATEMP	&e->area
@@ -839,6 +965,8 @@ enum sh_flag {
  * parsing & execution environment
  *
  * note that kshlongjmp MUST NOT be passed 0 as second argument!
+ *
+ * kshsetjmp() is to *not* save (and kshlongjmp() to not restore) signals!
  */
 #ifdef MKSH_NO_SIGSETJMP
 #define kshjmp_buf	jmp_buf
@@ -861,13 +989,13 @@ extern struct env {
 	Area area;		/* temporary allocation area */
 	struct env *oenv;	/* link to previous environment */
 	struct block *loc;	/* local variables and functions */
-	short *savefd;		/* original redirected fds */
+	ksh_fdsave *savedfd;	/* original fds for redirected fds */
 	struct temp *temps;	/* temp files */
 	/* saved parser recursion state */
 	struct yyrecursive_state *yyrecursive_statep;
 	kshjmp_buf jbuf;	/* long jump back to env creator */
-	uint8_t type;		/* environment type - see below */
-	uint8_t flags;		/* EF_* */
+	kby type;		/* environment type - see below */
+	kby flags;		/* EF_* */
 } *e;
 
 /* struct env.type values */
@@ -897,7 +1025,7 @@ extern struct env {
 /* note that i MUST NOT be zero */
 #define LRETURN	1	/* return statement */
 #define LEXIT	2	/* exit statement */
-#define LERROR	3	/* errorf() called */
+#define LERROR	3	/* kerrf() called */
 #define LERREXT 4	/* set -e caused */
 #define LINTR	5	/* ^C noticed */
 #define LBREAK	6	/* break statement */
@@ -905,6 +1033,7 @@ extern struct env {
 #define LSHELL	8	/* return to interactive shell() */
 #define LAEXPR	9	/* error in arithmetic expression */
 #define LLEAVE	10	/* untrappable exit/error */
+#define LRDERR	11	/* read error of script */
 
 /* sort of shell global state */
 EXTERN pid_t procpid;		/* PID of executing process */
@@ -912,14 +1041,14 @@ EXTERN int exstat;		/* exit status */
 EXTERN int subst_exstat;	/* exit status of last $(..)/`..` */
 EXTERN struct tbl *vp_pipest;	/* global PIPESTATUS array */
 EXTERN short trap_exstat;	/* exit status before running a trap */
-EXTERN uint8_t trap_nested;	/* running nested traps */
-EXTERN uint8_t shell_flags[FNFLAGS];
-EXTERN uint8_t baseline_flags[FNFLAGS
+EXTERN kby trap_nested;		/* running nested traps */
+EXTERN kby shell_flags[FNFLAGS];
+EXTERN kby baseline_flags[FNFLAGS
 #if !defined(MKSH_SMALL) || defined(DEBUG)
     + 1
 #endif
     ];
-EXTERN bool as_builtin;		/* direct builtin call */
+EXTERN Wahr as_builtin;		/* direct builtin call */
 EXTERN const char *kshname;	/* $0 */
 EXTERN struct {
 	uid_t kshuid_v;		/* real UID of shell at startup */
@@ -939,17 +1068,16 @@ EXTERN struct {
 #define kshegid		rndsetupstate.kshegid_v
 #define kshppid		rndsetupstate.kshppid_v
 
-
 /* option processing */
-#define OF_CMDLINE	0x01	/* command line */
-#define OF_SET		0x02	/* set builtin */
-#define OF_SPECIAL	0x04	/* a special variable changing */
-#define OF_INTERNAL	0x08	/* set internally by shell */
-#define OF_FIRSTTIME	0x10	/* as early as possible, once */
-#define OF_ANY		(OF_CMDLINE | OF_SET | OF_SPECIAL | OF_INTERNAL)
+#define OF_CMDLINE	0x01U	/* command line */
+#define OF_SET		0x02U	/* set builtin */
+#define OF_INTERNAL	0x04U	/* set internally by shell */
+#define OF_FIRSTTIME	0x08U	/* as early as possible, once */
+#define OF_ANY		(OF_CMDLINE | OF_SET | OF_INTERNAL)
 
 /* null value for variable; comparison pointer for unset */
-EXTERN char null[] E_INIT("");
+#define null (&null_string[2])
+extern char null_string[4];	/* backing, initialised */
 
 /* string pooling: do we rely on the compiler? */
 #ifndef HAVE_STRING_POOLING
@@ -970,12 +1098,11 @@ EXTERN char null[] E_INIT("");
 #endif
 
 #ifndef HAVE_STRING_POOLING /* helpers for pooled strings */
-EXTERN const char T4spaces[] E_INIT("    ");
+#define Tnl (Tf_s_s_sN + 8)
 #define T1space (Treal_sp2 + 5)
-#define Tcolsp (Tf_sD_ + 2)
 #define TC_IFSWS (TinitIFS + 4)
 EXTERN const char TinitIFS[] E_INIT("IFS= \t\n");
-EXTERN const char TFCEDIT_dollaru[] E_INIT("${FCEDIT:-/bin/ed} $_");
+EXTERN const char TFCEDIT_dollaru[] E_INIT("${FCEDIT:-/bin/ed} \"$_\"");
 #define Tspdollaru (TFCEDIT_dollaru + 18)
 EXTERN const char Tsgdot[] E_INIT("*=.");
 EXTERN const char Taugo[] E_INIT("augo");
@@ -985,46 +1112,44 @@ EXTERN const char Tbracket[] E_INIT("[")
 EXTERN const char Tbadnum[] E_INIT("bad number");
 #define Tbadsubst (Tfg_badsubst + 10)
 EXTERN const char Tbg[] E_INIT("bg");
-EXTERN const char Tbad_bsize[] E_INIT("bad shf/buf/bsize");
-#define Tbsize (Tbad_bsize + 12)
-EXTERN const char Tbad_sig_ss[] E_INIT("%s: bad signal '%s'");
-#define Tbad_sig_s (Tbad_sig_ss + 4)
+EXTERN const char Tbad_buf[] E_INIT("%s: buf %zX len %zd");
+EXTERN const char Tbad_flags[] E_INIT("%s: flags 0x%08X");
+EXTERN const char Tbad_sig[] E_INIT("bad signal");
 EXTERN const char Tsgbreak[] E_INIT("*=break");
 #define Tbreak (Tsgbreak + 2)
 EXTERN const char T__builtin[] E_INIT("-\\builtin");
 #define T_builtin (T__builtin + 1)
 #define Tbuiltin (T__builtin + 2)
-EXTERN const char Toomem[] E_INIT("can't allocate %zu data bytes");
 EXTERN const char Tcant_cd[] E_INIT("restricted shell - can't cd");
-EXTERN const char Tcant_find[] E_INIT("can't find");
-EXTERN const char Tcant_open[] E_INIT("can't open");
-#define Tbytes (Toomem + 24)
-EXTERN const char Tbcat[] E_INIT("!cat");
-#define Tcat (Tbcat + 1)
+EXTERN const char Tcant_filesub[] E_INIT("can't open $(<...) file");
 #define Tcd (Tcant_cd + 25)
+EXTERN const char Tcloexec_failed[] E_INIT("failed to %s close-on-exec flag for fd#%d");
 #define T_command (T_funny_command + 9)
-#define Tcommand (T_funny_command + 10)
+#define Tcommand (Trderr + 14)
 EXTERN const char Tsgcontinue[] E_INIT("*=continue");
 #define Tcontinue (Tsgcontinue + 2)
 EXTERN const char Tcreate[] E_INIT("create");
+EXTERN const char TchvtDone[] E_INIT("chvt: Done (%d)");
+#define TDone (TchvtDone + 6)
 EXTERN const char TELIF_unexpected[] E_INIT("TELIF unexpected");
 EXTERN const char TEXECSHELL[] E_INIT("EXECSHELL");
 EXTERN const char TENV[] E_INIT("ENV");
 EXTERN const char Tdsgexport[] E_INIT("^*=export");
 #define Texport (Tdsgexport + 3)
-#ifdef __OS2__
-EXTERN const char Textproc[] E_INIT("extproc");
-#endif
 EXTERN const char Tfalse[] E_INIT("false");
 EXTERN const char Tfg[] E_INIT("fg");
 EXTERN const char Tfg_badsubst[] E_INIT("fileglob: bad substitution");
-#define Tfile (Tfile_fd + 20)
-EXTERN const char Tfile_fd[] E_INIT("function definition file");
+#define Tfile (Tcant_filesub + 19)
+EXTERN const char Tyankfirst[] E_INIT("\nyank something first");
+#define Tfirst (Tyankfirst + 16)
 EXTERN const char TFPATH[] E_INIT("FPATH");
 EXTERN const char T_function[] E_INIT(" function");
 #define Tfunction (T_function + 1)
 EXTERN const char T_funny_command[] E_INIT("funny $()-command");
+#define Tget (Tnameref_empty + 17)
 EXTERN const char Tgetopts[] E_INIT("getopts");
+#define Tgetrusage (Ttime_getrusage + 6)
+EXTERN const char Ttime_getrusage[] E_INIT("time: getrusage");
 #define Thistory (Tnot_in_history + 7)
 EXTERN const char Tintovfl[] E_INIT("integer overflow %zu %c %zu prevented");
 EXTERN const char Tinvname[] E_INIT("%s: invalid %s name");
@@ -1032,40 +1157,49 @@ EXTERN const char Tjobs[] E_INIT("jobs")
 EXTERN const char Tjob_not_started[] E_INIT("job not started");
 EXTERN const char Tmksh[] E_INIT("mksh");
 #define Tname (Tinvname + 15)
+EXTERN const char Tnameref_empty[] E_INIT("empty nameref target");
+EXTERN const char Tnil[] E_INIT("(null)");
 EXTERN const char Tno_args[] E_INIT("missing argument");
 EXTERN const char Tno_OLDPWD[] E_INIT("no OLDPWD");
-EXTERN const char Tnot_ident[] E_INIT("is not an identifier");
+EXTERN const char Tnot_ident[] E_INIT("not an identifier");
 EXTERN const char Tnot_in_history[] E_INIT("not in history");
-EXTERN const char Tnot_found_s[] E_INIT("%s not found");
-#define Tnot_found (Tnot_found_s + 3)
+#define Tnot_found (Tinacc_not_found + 16)
+#define Tsp_not_found (Tinacc_not_found + 15)
+EXTERN const char Tinacc_not_found[] E_INIT("inaccessible or not found");
 #define Tnot_started (Tjob_not_started + 4)
 #define TOLDPWD (Tno_OLDPWD + 3)
-#define Topen (Tcant_open + 6)
+EXTERN const char Topen[] E_INIT("open");
+EXTERN const char Ttooearly[] E_INIT("too early%s");
 EXTERN const char To_o_reset[] E_INIT(" -o .reset");
 #define To_reset (To_o_reset + 4)
 #define TPATH (TFPATH + 1)
-#define Tpo (Tset_po + 4)
+#define Tpo (T_set_po + 5)
 #define Tpv (TpVv + 1)
 EXTERN const char TpVv[] E_INIT("Vpv");
 #define TPWD (Tno_OLDPWD + 6)
+EXTERN const char Trderr[] E_INIT("while reading command");
 #define Tread (Tshf_read + 4)
 EXTERN const char Tdsgreadonly[] E_INIT("^*=readonly");
 #define Treadonly (Tdsgreadonly + 3)
+EXTERN const char Tread_only[] E_INIT("read-only");
 EXTERN const char Tredirection_dup[] E_INIT("can't finish (dup) redirection");
 #define Tredirection (Tredirection_dup + 19)
 #define Treal_sp1 (Treal_sp2 + 1)
 EXTERN const char Treal_sp2[] E_INIT(" real ");
 EXTERN const char TREPLY[] E_INIT("REPLY");
 EXTERN const char Treq_arg[] E_INIT("requires an argument");
+EXTERN const char Trestore[] E_INIT("restore");
 EXTERN const char Tselect[] E_INIT("select");
-#define Tset (Tf_parm + 18)
-EXTERN const char Tset_po[] E_INIT("set +o");
+#define Tset (Tf_parm + 14)
+#define Tset_po (T_set_po + 1)
+EXTERN const char T_set_po[] E_INIT(" set +o");
 EXTERN const char Tsghset[] E_INIT("*=#set");
 #define Tsh (Tmksh + 2)
 #define TSHELL (TEXECSHELL + 4)
-#define Tshell (Ttoo_many_files + 23)
+EXTERN const char Tshell[] E_INIT("shell");
 EXTERN const char Tshf_read[] E_INIT("shf_read");
 EXTERN const char Tshf_write[] E_INIT("shf_write");
+EXTERN const char Tsigerr[] E_INIT("could not %s SIG%s");
 EXTERN const char Tgsource[] E_INIT("=source");
 #define Tsource (Tgsource + 1)
 EXTERN const char Tj_suspend[] E_INIT("j_suspend");
@@ -1073,10 +1207,8 @@ EXTERN const char Tj_suspend[] E_INIT("j
 EXTERN const char Tsynerr[] E_INIT("syntax error");
 EXTERN const char Ttime[] E_INIT("time");
 EXTERN const char Ttoo_many_args[] E_INIT("too many arguments");
-EXTERN const char Ttoo_many_files[] E_INIT("too many open files in shell");
+EXTERN const char Ttoo_many_files[] E_INIT("too many open files (%d -> %d)");
 EXTERN const char Ttrue[] E_INIT("true");
-EXTERN const char Ttty_fd_dupof[] E_INIT("dup of tty fd");
-#define Ttty_fd (Ttty_fd_dupof + 7)
 EXTERN const char Tdgtypeset[] E_INIT("^=typeset");
 #define Ttypeset (Tdgtypeset + 2)
 #define Tugo (Taugo + 1)
@@ -1088,61 +1220,46 @@ EXTERN const char Tunwind[] E_INIT("unwi
 #define Tuser_sp1 (Tuser_sp2 + 1)
 EXTERN const char Tuser_sp2[] E_INIT(" user ");
 #define Twrite (Tshf_write + 4)
+#define Thex32 (Tbad_flags + 12)
 EXTERN const char Tf__S[] E_INIT(" %S");
 #define Tf__d (Tunexpected_type + 22)
-#define Tf_ss (Tf__ss + 1)
-EXTERN const char Tf__ss[] E_INIT(" %s%s");
 #define Tf__sN (Tf_s_s_sN + 5)
+EXTERN const char Tf_s_T[] E_INIT("%s %T");
 #define Tf_T (Tf_s_T + 3)
 EXTERN const char Tf_dN[] E_INIT("%d\n");
 EXTERN const char Tf_s_[] E_INIT("%s ");
-EXTERN const char Tf_s_T[] E_INIT("%s %T");
 EXTERN const char Tf_s_s_sN[] E_INIT("%s %s %s\n");
-#define Tf_s_s (Tf_sD_s_s + 4)
 #define Tf__s_s (Tf_sD_s_s + 3)
-#define Tf_s_sD_s (Tf_cant_ss_s + 6)
-EXTERN const char Tf_optfoo[] E_INIT("%s%s-%c: %s");
-EXTERN const char Tf_sD_[] E_INIT("%s: ");
-EXTERN const char Tf_szs[] E_INIT("%s: %zd %s");
-EXTERN const char Tf_parm[] E_INIT("%s: parameter not set");
-EXTERN const char Tf_coproc[] E_INIT("-p: %s");
+EXTERN const char Tf_s_sD_s[] E_INIT("%s %s: %s");
+EXTERN const char Tf_parm[] E_INIT("parameter not set");
 EXTERN const char Tf_cant_s[] E_INIT("%s: can't %s");
-EXTERN const char Tf_cant_ss_s[] E_INIT("can't %s %s: %s");
 EXTERN const char Tf_heredoc[] E_INIT("here document '%s' unclosed");
-#if HAVE_MKNOD
-EXTERN const char Tf_nonnum[] E_INIT("non-numeric %s %s '%s'");
-#endif
 EXTERN const char Tf_S_[] E_INIT("%S ");
 #define Tf_S (Tf__S + 1)
-#define Tf_lu (Tf_toolarge + 17)
-EXTERN const char Tf_toolarge[] E_INIT("%s %s too large: %lu");
-EXTERN const char Tf_ldfailed[] E_INIT("%s %s(%d, %ld) failed: %s");
-EXTERN const char Tf_sD_s_sD_s[] E_INIT("%s: %s %s: %s");
+EXTERN const char Tf_sSQlu[] E_INIT("%s[%lu]");
+#define Tf_SQlu (Tf_sSQlu + 2)
+#define Tf_lu (Tf_toolarge + 14)
+EXTERN const char Tf_toolarge[] E_INIT("%s too large: %lu");
+EXTERN const char Tf_ldfailed[] E_INIT("%s tcsetpgrp(%d, %ld)");
 EXTERN const char Tf_toomany[] E_INIT("too many %ss");
 EXTERN const char Tf_sd[] E_INIT("%s %d");
-#define Tf_s (Tf_temp + 28)
+#define Tf_s (Tf_temp + 24)
 EXTERN const char Tft_end[] E_INIT("%;");
-EXTERN const char Tft_R[] E_INIT("%R");
-#define Tf_d (Tunexpected_type + 23)
+#define Tf_d (Tcloexec_failed + 39)
 EXTERN const char Tf_sD_s_qs[] E_INIT("%s: %s '%s'");
-EXTERN const char Tf_ro[] E_INIT("read-only: %s");
-EXTERN const char Tf_flags[] E_INIT("%s: flags 0x%X");
-EXTERN const char Tf_temp[] E_INIT("can't %s temporary file %s: %s");
-EXTERN const char Tf_ssfaileds[] E_INIT("%s: %s failed: %s");
-EXTERN const char Tf_sD_sD_s[] E_INIT("%s: %s: %s");
+EXTERN const char Tf_temp[] E_INIT("can't %s temporary file %s");
+EXTERN const char Tf_ssfailed[] E_INIT("%s: %s failed");
 EXTERN const char Tf__c_[] E_INIT("-%c ");
 EXTERN const char Tf_sD_s_s[] E_INIT("%s: %s %s");
 #define Tf_sN (Tf_s_s_sN + 6)
-#define Tf_sD_s (Tf_temp + 24)
-EXTERN const char T_devtty[] E_INIT("/dev/tty");
+#define Tf_sD_s (Tf_s_sD_s + 3)
 #else /* helpers for string pooling */
-#define T4spaces "    "
+#define Tnl "\n"
 #define T1space " "
-#define Tcolsp ": "
 #define TC_IFSWS " \t\n"
 #define TinitIFS "IFS= \t\n"
-#define TFCEDIT_dollaru "${FCEDIT:-/bin/ed} $_"
-#define Tspdollaru " $_"
+#define TFCEDIT_dollaru "${FCEDIT:-/bin/ed} \"$_\""
+#define Tspdollaru " \"$_\""
 #define Tsgdot "*=."
 #define Taugo "augo"
 #define Tbracket "["
@@ -1151,46 +1268,44 @@ EXTERN const char T_devtty[] E_INIT("/de
 #define Tbadnum "bad number"
 #define Tbadsubst "bad substitution"
 #define Tbg "bg"
-#define Tbad_bsize "bad shf/buf/bsize"
-#define Tbsize "bsize"
-#define Tbad_sig_ss "%s: bad signal '%s'"
-#define Tbad_sig_s "bad signal '%s'"
+#define Tbad_buf "%s: buf %zX len %zd"
+#define Tbad_flags "%s: flags 0x%08X"
+#define Tbad_sig "bad signal"
 #define Tsgbreak "*=break"
 #define Tbreak "break"
 #define T__builtin "-\\builtin"
 #define T_builtin "\\builtin"
 #define Tbuiltin "builtin"
-#define Toomem "can't allocate %zu data bytes"
 #define Tcant_cd "restricted shell - can't cd"
-#define Tcant_find "can't find"
-#define Tcant_open "can't open"
-#define Tbytes "bytes"
-#define Tbcat "!cat"
-#define Tcat "cat"
+#define Tcant_filesub "can't open $(<...) file"
 #define Tcd "cd"
+#define Tcloexec_failed "failed to %s close-on-exec flag for fd#%d"
 #define T_command "-command"
 #define Tcommand "command"
 #define Tsgcontinue "*=continue"
 #define Tcontinue "continue"
 #define Tcreate "create"
+#define TchvtDone "chvt: Done (%d)"
+#define TDone "Done (%d)"
 #define TELIF_unexpected "TELIF unexpected"
 #define TEXECSHELL "EXECSHELL"
 #define TENV "ENV"
 #define Tdsgexport "^*=export"
 #define Texport "export"
-#ifdef __OS2__
-#define Textproc "extproc"
-#endif
 #define Tfalse "false"
 #define Tfg "fg"
 #define Tfg_badsubst "fileglob: bad substitution"
 #define Tfile "file"
-#define Tfile_fd "function definition file"
+#define Tyankfirst "\nyank something first"
+#define Tfirst "first"
 #define TFPATH "FPATH"
 #define T_function " function"
 #define Tfunction "function"
 #define T_funny_command "funny $()-command"
+#define Tget "get"
 #define Tgetopts "getopts"
+#define Tgetrusage "getrusage"
+#define Ttime_getrusage "time: getrusage"
 #define Thistory "history"
 #define Tintovfl "integer overflow %zu %c %zu prevented"
 #define Tinvname "%s: invalid %s name"
@@ -1198,15 +1313,19 @@ EXTERN const char T_devtty[] E_INIT("/de
 #define Tjob_not_started "job not started"
 #define Tmksh "mksh"
 #define Tname "name"
+#define Tnameref_empty "empty nameref target"
+#define Tnil "(null)"
 #define Tno_args "missing argument"
 #define Tno_OLDPWD "no OLDPWD"
-#define Tnot_ident "is not an identifier"
+#define Tnot_ident "not an identifier"
 #define Tnot_in_history "not in history"
-#define Tnot_found_s "%s not found"
 #define Tnot_found "not found"
+#define Tsp_not_found " not found"
+#define Tinacc_not_found "inaccessible or not found"
 #define Tnot_started "not started"
 #define TOLDPWD "OLDPWD"
 #define Topen "open"
+#define Ttooearly "too early%s"
 #define To_o_reset " -o .reset"
 #define To_reset ".reset"
 #define TPATH "PATH"
@@ -1214,24 +1333,29 @@ EXTERN const char T_devtty[] E_INIT("/de
 #define Tpv "pv"
 #define TpVv "Vpv"
 #define TPWD "PWD"
+#define Trderr "while reading command"
 #define Tread "read"
 #define Tdsgreadonly "^*=readonly"
 #define Treadonly "readonly"
+#define Tread_only "read-only"
 #define Tredirection_dup "can't finish (dup) redirection"
 #define Tredirection "redirection"
 #define Treal_sp1 "real "
 #define Treal_sp2 " real "
 #define TREPLY "REPLY"
 #define Treq_arg "requires an argument"
+#define Trestore "restore"
 #define Tselect "select"
 #define Tset "set"
 #define Tset_po "set +o"
+#define T_set_po " set +o"
 #define Tsghset "*=#set"
 #define Tsh "sh"
 #define TSHELL "SHELL"
 #define Tshell "shell"
 #define Tshf_read "shf_read"
 #define Tshf_write "shf_write"
+#define Tsigerr "could not %s SIG%s"
 #define Tgsource "=source"
 #define Tsource "source"
 #define Tj_suspend "j_suspend"
@@ -1239,10 +1363,8 @@ EXTERN const char T_devtty[] E_INIT("/de
 #define Tsynerr "syntax error"
 #define Ttime "time"
 #define Ttoo_many_args "too many arguments"
-#define Ttoo_many_files "too many open files in shell"
+#define Ttoo_many_files "too many open files (%d -> %d)"
 #define Ttrue "true"
-#define Ttty_fd_dupof "dup of tty fd"
-#define Ttty_fd "tty fd"
 #define Tdgtypeset "^=typeset"
 #define Ttypeset "typeset"
 #define Tugo "ugo"
@@ -1254,56 +1376,46 @@ EXTERN const char T_devtty[] E_INIT("/de
 #define Tuser_sp1 "user "
 #define Tuser_sp2 " user "
 #define Twrite "write"
+#define Thex32 "%08X"
 #define Tf__S " %S"
 #define Tf__d " %d"
-#define Tf_ss "%s%s"
-#define Tf__ss " %s%s"
 #define Tf__sN " %s\n"
+#define Tf_s_T "%s %T"
 #define Tf_T "%T"
 #define Tf_dN "%d\n"
 #define Tf_s_ "%s "
-#define Tf_s_T "%s %T"
 #define Tf_s_s_sN "%s %s %s\n"
-#define Tf_s_s "%s %s"
 #define Tf__s_s " %s %s"
 #define Tf_s_sD_s "%s %s: %s"
-#define Tf_optfoo "%s%s-%c: %s"
-#define Tf_sD_ "%s: "
-#define Tf_szs "%s: %zd %s"
-#define Tf_parm "%s: parameter not set"
-#define Tf_coproc "-p: %s"
+#define Tf_parm "parameter not set"
 #define Tf_cant_s "%s: can't %s"
-#define Tf_cant_ss_s "can't %s %s: %s"
 #define Tf_heredoc "here document '%s' unclosed"
-#if HAVE_MKNOD
-#define Tf_nonnum "non-numeric %s %s '%s'"
-#endif
 #define Tf_S_ "%S "
 #define Tf_S "%S"
+#define Tf_sSQlu "%s[%lu]"
+#define Tf_SQlu "[%lu]"
 #define Tf_lu "%lu"
-#define Tf_toolarge "%s %s too large: %lu"
-#define Tf_ldfailed "%s %s(%d, %ld) failed: %s"
-#define Tf_sD_s_sD_s "%s: %s %s: %s"
+#define Tf_toolarge "%s too large: %lu"
+#define Tf_ldfailed "%s tcsetpgrp(%d, %ld)"
 #define Tf_toomany "too many %ss"
 #define Tf_sd "%s %d"
 #define Tf_s "%s"
 #define Tft_end "%;"
-#define Tft_R "%R"
 #define Tf_d "%d"
 #define Tf_sD_s_qs "%s: %s '%s'"
-#define Tf_ro "read-only: %s"
-#define Tf_flags "%s: flags 0x%X"
-#define Tf_temp "can't %s temporary file %s: %s"
-#define Tf_ssfaileds "%s: %s failed: %s"
-#define Tf_sD_sD_s "%s: %s: %s"
+#define Tf_temp "can't %s temporary file %s"
+#define Tf_ssfailed "%s: %s failed"
 #define Tf__c_ "-%c "
 #define Tf_sD_s_s "%s: %s %s"
 #define Tf_sN "%s\n"
 #define Tf_sD_s "%s: %s"
-#define T_devtty "/dev/tty"
 #endif /* end of string pooling */
 
-typedef uint8_t Temp_type;
+#ifdef __OS2__
+EXTERN const char Textproc[] E_INIT("extproc");
+#endif
+
+typedef kby Temp_type;
 /* expanded heredoc */
 #define TT_HEREDOC_EXP	0
 /* temporary file used for history editing (fc -e) */
@@ -1318,8 +1430,8 @@ struct temp {
 	/* pid of process parsed here-doc */
 	pid_t pid;
 	Temp_type type;
-	/* actually longer: name (variable length) */
-	char tffn[3];
+	/* name */
+	mbccFAMslot(char, tffn);
 };
 
 /*
@@ -1332,7 +1444,8 @@ struct temp {
 #ifdef DF
 #define shl_dbg		(&shf_iob[3])	/* for DF() */
 #endif
-EXTERN bool shl_stdout_ok;
+EXTERN Wahr initio_done;		/* shl_*out:Ja/1, shl_dbg:2 */
+EXTERN Wahr shl_stdout_ok;
 
 /*
  * trap handlers
@@ -1343,9 +1456,13 @@ typedef struct trap {
 	char *trap;		/* trap command */
 	sig_t cursig;		/* current handler (valid if TF_ORIG_* set) */
 	sig_t shtrap;		/* shell signal handler */
+	sig_t oshtrap;		/* for unrestoresigs() */
+	ksh_sigsaved prev;	/* for unrestoresigs() */
 	int signal;		/* signal number */
 	int flags;		/* TF_* */
+	int oflags;		/* for unrestoresigs() */
 	volatile sig_atomic_t set; /* trap pending */
+	kby touched;		/* for unrestoresigs() */
 } Trap;
 
 /* values for Trap.flags */
@@ -1382,7 +1499,7 @@ extern Trap sigtraps[ksh_NSIG + 1];
 #ifdef SIGWINCH
 EXTERN volatile sig_atomic_t got_winch E_INIT(1);
 #else
-#define got_winch	true
+#define got_winch	Ja
 #endif
 
 /*
@@ -1398,7 +1515,7 @@ EXTERN unsigned int ksh_tmout;
 EXTERN enum tmout_enum ksh_tmout_state;
 
 /* For "You have stopped jobs" message */
-EXTERN bool really_exit;
+EXTERN Wahr really_exit;
 
 /*
  * fast character classes
@@ -1415,9 +1532,9 @@ EXTERN bool really_exit;
 #define CiOCTAL	BIT(5)	/* 0‥7				*/
 #define CiQCL	BIT(6)	/* &();|			*/
 #define CiALIAS	BIT(7)	/* !,.@				*/
-#define CiQCX	BIT(8)	/* *[\\				*/
+#define CiQCX	BIT(8)	/* *[\\~			*/
 #define CiVAR1	BIT(9)	/* !*@				*/
-#define CiQCM	BIT(10)	/* /^~				*/
+#define CiQCM	BIT(10)	/* /^				*/
 #define CiDIGIT	BIT(11)	/* 89				*/
 #define CiQC	BIT(12)	/* "'				*/
 #define CiSPX	BIT(13)	/* \x0B\x0C			*/
@@ -1442,9 +1559,9 @@ EXTERN bool really_exit;
 /* out of space, but one for *@ would make sense, possibly others */
 
 /* compile-time initialised, ASCII only */
-extern const uint32_t tpl_ctypes[128];
+extern const kui tpl_ctypes[128];
 /* run-time, contains C_IFS as well, full 2⁸ octet range */
-EXTERN uint32_t ksh_ctypes[256];
+EXTERN kui ksh_ctypes[256];
 /* first octet of $IFS, for concatenating "$*" */
 EXTERN char ifs0;
 
@@ -1461,20 +1578,20 @@ EXTERN char ifs0;
 /* A‥Z_a‥z		alphabetical plus underscore (identifier lead) */
 #define C_ALPHX	(CiLOWER | CiUNDER | CiUPPER)
 /* \x01‥\x7F		7-bit ASCII except NUL */
-#define C_ASCII (CiALIAS | CiANGLE | CiBRACK | CiCNTRL | CiCOLON | CiCR | CiCURLY | CiDIGIT | CiEQUAL | CiGRAVE | CiHASH | CiLOWER | CiMINUS | CiNL | CiOCTAL | CiPERCT | CiPLUS | CiQC | CiQCL | CiQCM | CiQCX | CiQUEST | CiSP | CiSPX | CiSS | CiTAB | CiUNDER | CiUPPER)
+#define C_ASCII	(C_GRAPH | CiCNTRL | CiCR | CiNL | CiSP | CiSPX | CiTAB)
 /* \x09\x20		tab and space */
 #define C_BLANK	(CiSP | CiTAB)
-/* \x09\x20"'		separator for completion */
-#define C_CFS	(CiQC | CiSP | CiTAB)
 /* \x00‥\x1F\x7F	POSIX control characters */
 #define C_CNTRL	(CiCNTRL | CiCR | CiNL | CiNUL | CiSPX | CiTAB)
 /* 0‥9			decimal digits */
 #define C_DIGIT	(CiDIGIT | CiOCTAL)
 /* &();`|			editor x_locate_word() command */
 #define C_EDCMD	(CiGRAVE | CiQCL)
+/* $*?[\\`~			escape for globbing */
+#define C_EDGLB	(CiGRAVE | CiQCX | CiQUEST | CiSS)
 /* \x09\x0A\x20"&'():;<=>`|	editor non-word characters */
 #define C_EDNWC	(CiANGLE | CiCOLON | CiEQUAL | CiGRAVE | CiNL | CiQC | CiQCL | CiSP | CiTAB)
-/* "#$&'()*:;<=>?[\\`{|}	editor quotes for tab completion */
+/* "#$&'()*:;<=>?[\\`{|}~	editor quotes for tab completion */
 #define C_EDQ	(CiANGLE | CiCOLON | CiCURLY | CiEQUAL | CiGRAVE | CiHASH | CiQC | CiQCL | CiQCX | CiQUEST | CiSS)
 /* !‥~			POSIX graphical (alphanumerical plus punctuation) */
 #define C_GRAPH	(C_PUNCT | CiDIGIT | CiLOWER | CiOCTAL | CiUPPER)
@@ -1482,7 +1599,7 @@ EXTERN char ifs0;
 #define C_HEXLT	CiHEXLT
 /* \x00 + $IFS		IFS whitespace, IFS non-whitespace, NUL */
 #define C_IFS	(CiIFS | CiNUL)
-/* \x09\x0A\x20		IFS whitespace */
+/* \x09\x0A\x20		IFS whitespace candidates */
 #define C_IFSWS	(CiNL | CiSP | CiTAB)
 /* \x09\x0A\x20&();<>|	(for the lexer) */
 #define C_LEX1	(CiANGLE | CiNL | CiQCL | CiSP | CiTAB)
@@ -1498,8 +1615,8 @@ EXTERN char ifs0;
 #define C_PRINT	(C_GRAPH | CiSP)
 /* !"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~	POSIX punctuation */
 #define C_PUNCT	(CiALIAS | CiANGLE | CiBRACK | CiCOLON | CiCURLY | CiEQUAL | CiGRAVE | CiHASH | CiMINUS | CiPERCT | CiPLUS | CiQC | CiQCL | CiQCM | CiQCX | CiQUEST | CiSS | CiUNDER)
-/* \x09\x0A"#$&'()*;<=>?[\\]`|	characters requiring quoting, minus space */
-#define C_QUOTE	(CiANGLE | CiBRACK | CiEQUAL | CiGRAVE | CiHASH | CiNL | CiQC | CiQCL | CiQCX | CiQUEST | CiSS | CiTAB)
+/* \x09\x0A"#$&'()*;<=>?[\\]`{|}~	characters requiring quoting, minus space */
+#define C_QUOTE	(CiANGLE | CiBRACK | CiCURLY | CiEQUAL | CiGRAVE | CiHASH | CiNL | CiQC | CiQCL | CiQCX | CiQUEST | CiSS | CiTAB)
 /* 0‥9A‥Fa‥f		hexadecimal digit */
 #define C_SEDEC	(CiDIGIT | CiHEXLT | CiOCTAL)
 /* \x09‥\x0D\x20	POSIX space class */
@@ -1524,9 +1641,9 @@ EXTERN char ifs0;
 #define C_LF	CiNL		/* \x0A	ASCII line feed */
 #define C_MINUS	CiMINUS		/* -	hyphen-minus */
 #ifdef MKSH_WITH_TEXTMODE
-#define C_NL	(CiNL | CiCR)	/* 	CR or LF under OS/2 TEXTMODE */
+#define C_NL	(CiNL | CiCR)	/*	CR or LF under OS/2 TEXTMODE */
 #else
-#define C_NL	CiNL		/* 	LF only like under Unix */
+#define C_NL	CiNL		/*	LF only like under Unix */
 #endif
 #define C_NUL	CiNUL		/* \x00	ASCII NUL */
 #define C_PLUS	CiPLUS		/* +	plus sign */
@@ -1539,22 +1656,21 @@ EXTERN char ifs0;
 /* identity transform of octet */
 #if defined(DEBUG) && defined(__GNUC__) && !defined(__ICC) && \
     !defined(__INTEL_COMPILER) && !defined(__SUNPRO_C)
-extern unsigned int eek_ord;
-#define ORD(c)	((size_t)(c) > 0xFF ? eek_ord : \
-		    ((unsigned int)(unsigned char)(c)))
-#define ord(c)	__builtin_choose_expr(				\
-    __builtin_types_compatible_p(__typeof__(c), char) ||	\
-    __builtin_types_compatible_p(__typeof__(c), unsigned char),	\
-    ((unsigned int)(unsigned char)(c)), ({			\
-	size_t ord_c = (c);					\
-								\
-	if (ord_c > (size_t)0xFFU)				\
-		internal_errorf("%s:%d:ord(%zX)",		\
-		    __FILE__, __LINE__, ord_c);			\
-	((unsigned int)(unsigned char)(ord_c));			\
+extern kui eek_ord;
+#define ORD(c)	((size_t)(c) > 0xFF ? eek_ord : KBI(c))
+#define ord(c)	__builtin_choose_expr(					\
+    __builtin_types_compatible_p(__typeof__(c), char) ||		\
+    __builtin_types_compatible_p(__typeof__(c), unsigned char),		\
+    KBI(c), ({								\
+	size_t ord_c = (c);						\
+									\
+	if (ord_c > (size_t)0xFFU)					\
+		kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,	\
+		    "%s:%d:ord(%zX)", __FILE__, __LINE__, ord_c);	\
+	(KBI(ord_c));							\
 }))
 #else
-#define ord(c)	((unsigned int)(unsigned char)(c))
+#define ord(c)	KBI(c)
 #define ORD(c)	ord(c) /* may evaluate arguments twice */
 #endif
 #if defined(MKSH_EBCDIC) || defined(MKSH_FAUX_EBCDIC)
@@ -1563,30 +1679,38 @@ EXTERN unsigned char ebcdic_rtt_toascii[
 EXTERN unsigned char ebcdic_rtt_fromascii[256];
 extern void ebcdic_init(void);
 /* one-way to-ascii-or-high conversion, for POSIX locale ordering */
-#define asciibetical(c)	((unsigned int)ebcdic_map[(unsigned char)(c)])
+#define asciibetical(c)	KUI(ebcdic_map[ord(c)])
 /* two-way round-trip conversion, for general use */
-#define rtt2asc(c)	ebcdic_rtt_toascii[(unsigned char)(c)]
-#define asc2rtt(c)	ebcdic_rtt_fromascii[(unsigned char)(c)]
+#define rtt2asc(c)	ebcdic_rtt_toascii[KBY(c)]
+#define asc2rtt(c)	ebcdic_rtt_fromascii[KBY(c)]
 /* case-independent char comparison */
-#define ksh_eq(c,u,l)	(ord(c) == ord(u) || ord(c) == ord(l))
+#define isCh(c,u,l)	(ord(c) == ord(u) || ord(c) == ord(l))
 #else
-#define asciibetical(c)	ord(c)
-#define rtt2asc(c)	((unsigned char)(c))
-#define asc2rtt(c)	((unsigned char)(c))
-#define ksh_eq(c,u,l)	((ord(c) | 0x20) == ord(l))
+/* POSIX locale ordering */
+#define asciibetical(c)	KUI(ord(c)) /* ranging to USHRT_MAX */
+/* if inspecting numerical values (mapping on EBCDIC) */
+#define rtt2asc(c)	KBY(c)
+#define asc2rtt(c)	KBY(c)
+/* case-independent char comparison */
+#define isCh(c,u,l)	((ord(c) | 0x20U) == ord(l))
 #endif
+/* vs case-sensitive char comparison */
+#define isch(c,t)	(ord(c) == ORD(t))
 /* control character foo */
 #ifdef MKSH_EBCDIC
-#define ksh_isctrl(c)	(ord(c) < 0x40 || ord(c) == 0xFF)
+#define ksh_isctrl(c)	(ord(c) < 0x40U || ord(c) == 0xFFU)
+#define ksh_isctrl8(c)	ksh_isctrl(c)
 #else
-#define ksh_isctrl(c)	((ord(c) & 0x7F) < 0x20 || ord(c) == 0x7F)
+#define ksh_isctrl(c)	((ord(c) & 0x7FU) < 0x20U || ord(c) == 0x7FU)
+#define ksh_asisctrl(c)	(ord(c) < 0x20U || ord(c) == 0x7FU)
+#define ksh_isctrl8(c)	(Flag(FASIS) ? ksh_asisctrl(c) : ksh_isctrl(c))
 #endif
 /* new fast character classes */
-#define ctype(c,t)	tobool(ksh_ctypes[ord(c)] & (t))
+#define ctype(c,t)	isWahr(ksh_ctypes[ord(c)] & (t))
 #define cinttype(c,t)	((c) >= 0 && (c) <= 0xFF ? \
-			tobool(ksh_ctypes[(unsigned char)(c)] & (t)) : false)
+			isWahr(ksh_ctypes[KBY(c)] & (t)) : Nee)
 /* helper functions */
-#define ksh_isdash(s)	tobool(ord((s)[0]) == '-' && ord((s)[1]) == '\0')
+#define ksh_isdash(s)	isWahr(ord((s)[0]) == '-' && ord((s)[1]) == '\0')
 /* invariant distance even in EBCDIC */
 #define ksh_tolower(c)	(ctype(c, C_UPPER) ? (c) - 'A' + 'a' : (c))
 #define ksh_toupper(c)	(ctype(c, C_LOWER) ? (c) - 'a' + 'A' : (c))
@@ -1594,8 +1718,6 @@ extern void ebcdic_init(void);
 #define ksh_numdig(c)	(ord(c) - ORD('0'))
 #define ksh_numuc(c)	(rtt2asc(c) - rtt2asc('A'))
 #define ksh_numlc(c)	(rtt2asc(c) - rtt2asc('a'))
-#define ksh_toctrl(c)	asc2rtt(ord(c) == ORD('?') ? 0x7F : rtt2asc(c) & 0x9F)
-#define ksh_unctrl(c)	asc2rtt(rtt2asc(c) ^ 0x40U)
 
 #ifdef MKSH_SMALL
 #define SMALLP(x)	/* nothing */
@@ -1606,7 +1728,7 @@ extern void ebcdic_init(void);
 /* Argument parsing for built-in commands and getopts command */
 
 /* Values for Getopt.flags */
-#define GF_ERROR	BIT(0)	/* call errorf() if there is an error */
+#define GF_ERROR	BIT(0)	/* KWF_BIERR if there is an error */
 #define GF_PLUSOPT	BIT(1)	/* allow +c as an option */
 #define GF_NONAME	BIT(2)	/* don't print argv[0] in errors */
 
@@ -1634,8 +1756,8 @@ EXTERN Getopt user_opt;		/* parsing stat
 
 /* This for co-processes */
 
-/* something that won't (realisticly) wrap */
-typedef int Coproc_id;
+/* something that won't (realistically) wrap */
+typedef unsigned int Coproc_id;
 
 struct coproc {
 	void *job;	/* 0 or job of co-process using input pipe */
@@ -1655,7 +1777,7 @@ EXTERN sigset_t		sm_default, sm_sigchld;
 /* name of called builtin function (used by error functions) */
 EXTERN const char *builtin_argv0;
 /* is called builtin a POSIX special builtin? (error functions only) */
-EXTERN bool builtin_spec;
+EXTERN Wahr builtin_spec;
 
 /* current working directory */
 EXTERN char	*current_wd;
@@ -1670,7 +1792,6 @@ EXTERN char	*current_wd;
 EXTERN mksh_ari_t x_cols E_INIT(80);
 EXTERN mksh_ari_t x_lins E_INIT(24);
 
-
 /* Determine the location of the system (common) profile */
 
 #ifndef MKSH_DEFAULT_PROFILEDIR
@@ -1680,7 +1801,6 @@ EXTERN mksh_ari_t x_lins E_INIT(24);
 #define MKSH_SYSTEM_PROFILE	MKSH_DEFAULT_PROFILEDIR "/profile"
 #define MKSH_SUID_PROFILE	MKSH_DEFAULT_PROFILEDIR "/suid_profile"
 
-
 /* Used by v_evaluate() and setstr() to control action when error occurs */
 #define KSH_UNWIND_ERROR	0	/* unwind the stack (kshlongjmp) */
 #define KSH_RETURN_ERROR	1	/* return 1/0 for success/failure */
@@ -1697,8 +1817,23 @@ EXTERN mksh_ari_t x_lins E_INIT(24);
 				    (shf)->rnleft--, (int)ord(*(shf)->rp++) : \
 				    shf_getchar(shf))
 #define shf_putc_i(c,shf)	((shf)->wnleft == 0 ? \
-				    shf_putchar((uint8_t)(c), (shf)) : \
+				    shf_putchar((kby)(c), (shf)) : \
 				    ((shf)->wnleft--, *(shf)->wp++ = (c)))
+/*
+ * small strings (e.g. one multibyte character) only, atomically
+ * no side effects in arguments please; does s+=n; may do n=0
+ */
+#define shf_wr_sm(s,n,shf)	do {				\
+	if ((shf)->wnleft < (ssize_t)(n)) {			\
+		shf_scheck_grow((n), (shf));			\
+		shf_write((const void *)(s), (n), (shf));	\
+		(s) += (n);					\
+	} else {						\
+		(shf)->wnleft -= n;				\
+		while ((n)--)					\
+			*(shf)->wp++ = *(s)++;			\
+	}							\
+} while (/* CONSTCOND */ 0)
 #define shf_eof(shf)		((shf)->flags & SHF_EOF)
 #define shf_error(shf)		((shf)->flags & SHF_ERROR)
 #define shf_errno(shf)		((shf)->errnosv)
@@ -1725,7 +1860,6 @@ EXTERN mksh_ari_t x_lins E_INIT(24);
 #define SHF_READING	0x2000		/* currently reading: rnleft,rp valid */
 #define SHF_WRITING	0x4000		/* currently writing: wnleft,wp valid */
 
-
 struct shf {
 	Area *areap;		/* area shf/buf were allocated in */
 	unsigned char *rp;	/* read: current position in buffer */
@@ -1747,7 +1881,7 @@ struct table {
 	Area *areap;		/* area to allocate entries */
 	struct tbl **tbls;	/* hashed table items */
 	size_t nfree;		/* free table entries */
-	uint8_t tshift;		/* table size (2^tshift) */
+	kby tshift;		/* table size (2^tshift) */
 };
 
 /* table item */
@@ -1767,28 +1901,32 @@ struct tbl {
 		const char *fpath;	/* temporary path to undef function */
 	} u;
 	union {
+		k32 hval;		/* hash(name) */
+		k32 index;		/* index for an array */
+	} ua;
+	union {
 		int field;		/* field with for -L/-R/-Z */
 		int errnov;		/* CEXEC/CTALIAS */
 	} u2;
-	union {
-		uint32_t hval;		/* hash(name) */
-		uint32_t index;		/* index for an array */
-	} ua;
 	/*
 	 * command type (see below), base (if INTEGER),
 	 * offset from val.s of value (if EXPORT)
 	 */
 	int type;
 	/* flags (see below) */
-	uint32_t flag;
+	kui flag;
 
-	/* actually longer: name (variable length) */
-	char name[4];
+	mbccFAMslot(char, name);
+};
+
+union tbl_static {
+	struct tbl tbl;
+	char storage[mbccFAMSZ(struct tbl, name, 4)];
 };
 
 EXTERN struct tbl *vtemp;
 /* set by isglobal(), global() and local() */
-EXTERN bool last_lookup_was_array;
+EXTERN Wahr last_lookup_was_array;
 
 /* common flag bits */
 #define ALLOC		BIT(0)	/* val.s has been allocated */
@@ -1929,7 +2067,7 @@ EXTERN char *path;		/* copy of either PA
 EXTERN const char *def_path;	/* path to use if PATH not set */
 EXTERN char *tmpdir;		/* TMPDIR value */
 EXTERN const char *prompt;
-EXTERN uint8_t cur_prompt;	/* PS1 or PS2 */
+EXTERN kby cur_prompt;		/* PS1 or PS2 */
 EXTERN int current_lineno;	/* LINENO value */
 
 /*
@@ -1940,19 +2078,23 @@ struct op {
 	char **vars;			/* variable assignments */
 	struct ioword **ioact;		/* IO actions (eg, < > >>) */
 	struct op *left, *right;	/* descendents */
-	char *str;			/* word for case; identifier for for,
-					 * select, and functions;
-					 * path to execute for TEXEC;
-					 * time hook for TCOM.
-					 */
-	int lineno;			/* TCOM/TFUNC: LINENO for this */
+	union {
+		/* TCASE: word */
+		/* TEXEC: path to execute */
+		/* TFOR, TSELECT, TFUNCT: identifier */
+		char *str;
+		/* TCOM: TMX_* between timex and time_hook */
+		int flag;
+	} opstr_u;
+#define op_str opstr_u.str
+#define op_flag opstr_u.flag
+	int lineno;			/* TCOM/TFUNCT: LINENO for this */
 	short type;			/* operation type, see below */
-	/* WARNING: newtp(), tcopy() use evalflags = 0 to clear union */
+	/* note: newtp() uses evalflags = 0; to clear union */
 	union {
 		/* TCOM: arg expansion eval() flags */
 		short evalflags;
-		/* TFUNC: function x (vs x()) */
-		short ksh_func;
+		/* TFUNCT: function x (vs. x()) */
 		/* TPAT: termination character */
 		char charflag;
 	} u;
@@ -1982,6 +2124,7 @@ struct op {
 #define TTIME		20	/* time pipeline */
 #define TEXEC		21	/* fork/exec eval'd TCOM */
 #define TCOPROC		22	/* coprocess |& */
+#define TEXFUNC		23	/* extended function */
 
 /*
  * prefix codes for words in command tree
@@ -2012,7 +2155,7 @@ struct ioword {
 	char *delim;		/* delimiter for <<, <<- */
 	char *heredoc;		/* content of heredoc */
 	unsigned short ioflag;	/* action (below) */
-	short unit;		/* unit (fd) affected */
+	signed char unit;	/* unit (fd) affected */
 };
 
 /* ioword.flag - type of redirection */
@@ -2032,6 +2175,7 @@ struct ioword {
 #define IOBASH		BIT(10)	/* &> etc. */
 #define IOHERESTR	BIT(11)	/* <<< (here string) */
 #define IONDELIM	BIT(12)	/* null delimiter (<<) */
+#define IOSYNIONEXT	BIT(13)	/* already fully configured */
 
 /* execute/exchild flags */
 #define XEXEC	BIT(0)		/* execute without forking */
@@ -2102,10 +2246,10 @@ typedef struct XString {
 #define Xput(xs,xp,c)	(*xp++ = (c))
 
 /* check if there are at least n bytes left */
-#define XcheckN(xs,xp,n) do {					\
-	ssize_t more = ((xp) + (n)) - (xs).end;			\
-	if (more > 0)						\
-		(xp) = Xcheck_grow(&(xs), (xp), (size_t)more);	\
+#define XcheckN(xs,xp,n) do {						\
+	ssize_t XcheckNi = (size_t)((xp) - (xs).beg) + (n) - (xs).len;	\
+	if (XcheckNi > 0)						\
+		(xp) = Xcheck_grow(&(xs), (xp), (size_t)XcheckNi);	\
 } while (/* CONSTCOND */ 0)
 
 /* check for overflow, expand string */
@@ -2166,8 +2310,8 @@ typedef struct {
 struct columnise_opts {
 	struct shf *shf;
 	char linesep;
-	bool do_last;
-	bool prefcol;
+	Wahr do_last;
+	Wahr prefcol;
 };
 
 /*
@@ -2276,7 +2420,7 @@ typedef union {
 #define KEYWORD		BIT(3)	/* recognise keywords */
 #define LETEXPR		BIT(4)	/* get expression inside (( )) */
 #define CMDASN		BIT(5)	/* parse x[1 & 2] as one word, for typeset */
-#define HEREDOC 	BIT(6)	/* parsing a here document body */
+#define HEREDOC		BIT(6)	/* parsing a here document body */
 #define ESACONLY	BIT(7)	/* only accept esac keyword */
 #define CMDWORD		BIT(8)	/* parsing simple command (alias related) */
 #define HEREDELIM	BIT(9)	/* parsing <<,<<- delimiter */
@@ -2378,22 +2522,26 @@ EXTERN struct timeval j_usrtime, j_systi
 #define notok2mul(max,val,c)	(((val) != 0) && ((c) != 0) && \
 				    (((max) / (c)) < (val)))
 #define notok2add(max,val,c)	((val) > ((max) - (c)))
-#define notoktomul(val,cnst)	notok2mul(SIZE_MAX, (val), (cnst))
-#define notoktoadd(val,cnst)	notok2add(SIZE_MAX, (val), (cnst))
+#define notoktomul(val,cnst)	notok2mul(mbiSIZE_MAX, (val), (cnst))
+#define notoktoadd(val,cnst)	notok2add(mbiSIZE_MAX, (val), (cnst))
 #define checkoktoadd(val,cnst) do {					\
 	if (notoktoadd((val), (cnst)))					\
-		internal_errorf(Tintovfl, (size_t)(val),		\
-		    '+', (size_t)(cnst));				\
+		kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,	\
+		    Tintovfl, (size_t)(val), '+', (size_t)(cnst));	\
 } while (/* CONSTCOND */ 0)
-
+#undef mbccABEND
+#define mbccABEND(reason)	kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | \
+				    KWF_ONEMSG | KWF_NOERRNO, (reason))
 
 /* lalloc.c */
 void ainit(Area *);
 void afreeall(Area *);
 /* these cannot fail and can take NULL (not for ap) */
 #define alloc(n,ap)		aresize(NULL, (n), (ap))
+#define alloc1(m,n,ap)		aresize1(NULL, (m), (n), (ap))
 #define alloc2(m,n,ap)		aresize2(NULL, (m), (n), (ap))
 void *aresize(void *, size_t, Area *);
+void *aresize1(void *, size_t, size_t, Area *);
 void *aresize2(void *, size_t, size_t, Area *);
 void afree(void *, Area *);	/* can take NULL */
 #define aresizeif(z,p,n,ap)	(((p) == NULL) || ((z) < (n)) || \
@@ -2401,7 +2549,7 @@ void afree(void *, Area *);	/* can take
 				    aresize((p), (n), (ap)) : (p))
 /* edit.c */
 #ifndef MKSH_NO_CMDLINE_EDITING
-int x_bind(const char * SMALLP(bool));
+int x_bind(const char * SMALLP(Wahr));
 int x_bind_check(void);
 int x_bind_list(void);
 int x_bind_showall(void);
@@ -2409,9 +2557,9 @@ void x_init(void);
 #ifdef DEBUG_LEAKS
 void x_done(void);
 #endif
-int x_read(char *);
+char *x_read(char *);
 #endif
-void x_mkraw(int, mksh_ttyst *, bool);
+void x_mkraw(int, mksh_ttyst *, Wahr);
 void x_initterm(const char *);
 /* eval.c */
 char *substitute(const char *, int);
@@ -2420,36 +2568,46 @@ char *evalstr(const char *cp, int);
 char *evalonestr(const char *cp, int);
 char *debunk(char *, const char *, size_t);
 void expand(const char *, XPtrV *, int);
-int glob_str(char *, XPtrV *, bool);
+int glob_str(char *, XPtrV *, Wahr);
 char *do_tilde(char *);
 /* exec.c */
-int execute(struct op * volatile, volatile int, volatile int * volatile);
+int execute(struct op * volatile, volatile int, int *);
 int c_builtin(const char **);
 struct tbl *get_builtin(const char *);
-struct tbl *findfunc(const char *, uint32_t, bool);
+struct tbl *findfunc(const char *, k32, Wahr);
 int define(const char *, struct op *);
 const char *builtin(const char *, int (*)(const char **));
 struct tbl *findcom(const char *, int);
-void flushcom(bool);
+void flushcom(Wahr);
 int search_access(const char *, int);
 const char *search_path(const char *, const char *, int, int *);
 void pr_menu(const char * const *);
 void pr_list(struct columnise_opts *, char * const *);
 int herein(struct ioword *, char **);
+const char **cpyargv(int *, const char **, Area *);
+int varnamecheck(const char *);
 /* expr.c */
-int evaluate(const char *, mksh_ari_t *, int, bool);
-int v_evaluate(struct tbl *, const char *, volatile int, bool);
+int evaluate(const char *, mksh_ari_t *, int, Wahr);
+int v_evaluate(struct tbl *, const char *, int, Wahr);
 /* UTF-8 stuff */
+char *ez_bs(char *, char *);
 size_t utf_mbtowc(unsigned int *, const char *);
 size_t utf_wctomb(char *, unsigned int);
+#define OPTUISRAW(wc) IS(wc, 0xFFFFFF80U, 0x0000EF80U)
+#define OPTUMKRAW(ch) (ord(ch) | 0x0000EF00U)
+#if defined(MKSH_EBCDIC) || defined(MKSH_FAUX_EBCDIC)
+size_t ez_mbtowc(unsigned int *, const char *);
+#else
+#define ez_mbtowc ez_mbtoc
+#endif
+size_t ez_mbtoc(unsigned int *, const char *);
+size_t ez_ctomb(char *, unsigned int);
 int utf_widthadj(const char *, const char **);
-size_t utf_mbswidth(const char *) MKSH_A_PURE;
-const char *utf_skipcols(const char *, int, int *);
-size_t utf_ptradj(const char *) MKSH_A_PURE;
+size_t utf_mbswidth(const char *);
 #ifdef MIRBSD_BOOTFLOPPY
 #define utf_wcwidth(i) wcwidth((wchar_t)(i))
 #else
-int utf_wcwidth(unsigned int) MKSH_A_PURE;
+int utf_wcwidth(unsigned int);
 #endif
 int ksh_access(const char *, int);
 struct tbl *tempvar(const char *);
@@ -2463,7 +2621,7 @@ int c_printf(const char **);
 int c_whence(const char **);
 int c_command(const char **);
 int c_typeset(const char **);
-bool valid_alias_name(const char *);
+Wahr valid_alias_name(const char *);
 int c_alias(const char **);
 int c_unalias(const char **);
 int c_let(const char **);
@@ -2490,8 +2648,8 @@ int c_set(const char **);
 int c_unset(const char **);
 int c_ulimit(const char **);
 int c_times(const char **);
-int timex(struct op *, int, volatile int *);
-void timex_hook(struct op *, char ** volatile *);
+int timex(struct op *, int, int *);
+int time_hook(struct op *, char ***);
 int c_exec(const char **);
 int c_test(const char **);
 #if HAVE_MKNOD
@@ -2499,17 +2657,15 @@ int c_mknod(const char **);
 #endif
 int c_realpath(const char **);
 int c_rename(const char **);
-int c_cat(const char **);
-int c_sleep(const char **);
 /* histrap.c */
 void init_histvec(void);
 void hist_init(Source *);
 #if HAVE_PERSISTENT_HISTORY
 void hist_finish(void);
 #endif
-void histsave(int *, const char *, int, bool);
+void histsave(int *, const char *, int, Wahr);
 #if !defined(MKSH_SMALL) && HAVE_PERSISTENT_HISTORY
-bool histsync(void);
+Wahr histsync(void);
 #endif
 int c_fc(const char **);
 void sethistsize(mksh_ari_t);
@@ -2517,24 +2673,25 @@ void sethistsize(mksh_ari_t);
 void sethistfile(const char *);
 #endif
 #if !defined(MKSH_NO_CMDLINE_EDITING) && !MKSH_S_NOVI
-char **histpos(void) MKSH_A_PURE;
+char **histpos(void);
 int histnum(int);
 #endif
-int findhist(int, const char *, bool, bool) MKSH_A_PURE;
-char **hist_get_newest(bool);
+int findhist(int, const char *, Wahr, Wahr);
+char **hist_get_newest(Wahr);
 void inittraps(void);
 void alarm_init(void);
-Trap *gettrap(const char *, bool, bool);
+Trap *gettrap(const char *, Wahr, Wahr);
 void trapsig(int);
 void intrcheck(void);
 int fatal_trap_check(void);
 int trap_pending(void);
 void runtraps(int intr);
-void runtrap(Trap *, bool);
+void runtrap(Trap *, Wahr);
 void cleartraps(void);
 void restoresigs(void);
+void unrestoresigs(void);
 void settrap(Trap *, const char *);
-bool block_pipe(void);
+Wahr block_pipe(void);
 void restore_pipe(void);
 int setsig(Trap *, sig_t, int);
 void setexecsig(Trap *, int);
@@ -2548,7 +2705,7 @@ void j_exit(void);
 #ifndef MKSH_UNEMPLOYED
 void j_change(void);
 #endif
-int exchild(struct op *, int, volatile int *, int);
+int exchild(struct op *, int, int *, int);
 void startlast(void);
 int waitlast(void);
 int waitfor(const char *, int *);
@@ -2565,15 +2722,12 @@ pid_t j_async(void);
 int j_stopped_running(void);
 /* lex.c */
 int yylex(int);
-void yyskiputf8bom(void);
-void yyerror(const char *, ...)
-    MKSH_A_NORETURN
-    MKSH_A_FORMAT(__printf__, 1, 2);
 Source *pushs(int, Area *);
 void set_prompt(int, Source *);
 int pprompt(const char *, int);
 /* main.c */
-int include(const char *, int, const char **, bool);
+kby kshname_islogin(const char **);
+int include(const char *, const char **, Wahr);
 int command(const char *, int);
 int shell(Source * volatile, volatile int);
 /* argument MUST NOT be 0 */
@@ -2582,27 +2736,10 @@ void newenv(int);
 void quitenv(struct shf *);
 void cleanup_parents_env(void);
 void cleanup_proc_env(void);
-void errorf(const char *, ...)
-    MKSH_A_NORETURN
-    MKSH_A_FORMAT(__printf__, 1, 2);
-void errorfx(int, const char *, ...)
-    MKSH_A_NORETURN
-    MKSH_A_FORMAT(__printf__, 2, 3);
-void warningf(bool, const char *, ...)
-    MKSH_A_FORMAT(__printf__, 2, 3);
+/* old {{{ */
 void bi_errorf(const char *, ...)
     MKSH_A_FORMAT(__printf__, 1, 2);
-void maybe_errorf(int *, int, const char *, ...)
-    MKSH_A_FORMAT(__printf__, 3, 4);
-#define errorfz()	errorf(NULL)
-#define errorfxz(rc)	errorfx((rc), NULL)
-#define bi_errorfz()	bi_errorf(NULL)
-void internal_errorf(const char *, ...)
-    MKSH_A_NORETURN
-    MKSH_A_FORMAT(__printf__, 1, 2);
-void internal_warningf(const char *, ...)
-    MKSH_A_FORMAT(__printf__, 1, 2);
-void error_prefix(bool);
+/* old }}} */
 void shellf(const char *, ...)
     MKSH_A_FORMAT(__printf__, 1, 2);
 void shprintf(const char *, ...)
@@ -2610,8 +2747,8 @@ void shprintf(const char *, ...)
 int can_seek(int);
 void initio(void);
 void recheck_ctype(void);
-int ksh_dup2(int, int, bool);
-short savefd(int);
+int ksh_dup2(int, int, Wahr);
+int savefd(int);
 void restfd(int, int);
 void openpipe(int *);
 void closepipe(int *);
@@ -2623,11 +2760,11 @@ void coproc_write_close(int);
 int coproc_getfd(int, const char **);
 void coproc_cleanup(int);
 struct temp *maketemp(Area *, Temp_type, struct temp **);
-void ktinit(Area *, struct table *, uint8_t);
-struct tbl *ktscan(struct table *, const char *, uint32_t, struct tbl ***);
+void ktinit(Area *, struct table *, kby);
+struct tbl *ktscan(struct table *, const char *, k32, struct tbl ***);
 /* table, name (key) to search for, hash(n) */
 #define ktsearch(tp,s,h) ktscan((tp), (s), (h), NULL)
-struct tbl *ktenter(struct table *, const char *, uint32_t);
+struct tbl *ktenter(struct table *, const char *, k32);
 #define ktdelete(p)	do { p->flag = 0; } while (/* CONSTCOND */ 0)
 void ktwalk(struct tstate *, struct table *);
 struct tbl *ktnext(struct tstate *);
@@ -2636,17 +2773,22 @@ struct tbl **ktsort(struct table *);
 void DF(const char *, ...)
     MKSH_A_FORMAT(__printf__, 1, 2);
 #endif
+const char *ksh_getwd(void);
 /* misc.c */
-size_t option(const char *) MKSH_A_PURE;
+size_t option(const char *);
 char *getoptions(void);
-void change_flag(enum sh_flag, int, bool);
-void change_xtrace(unsigned char, bool);
-int parse_args(const char **, int, bool *);
+void change_flag(enum sh_flag, unsigned int, Wahr);
+void change_xtrace(unsigned char, Wahr);
+int parse_args(const char **, unsigned int, Wahr *);
 int getn(const char *, int *);
-int gmatchx(const char *, const char *, bool);
-bool has_globbing(const char *) MKSH_A_PURE;
-int ascstrcmp(const void *, const void *) MKSH_A_PURE;
-int ascpstrcmp(const void *, const void *) MKSH_A_PURE;
+int getpn(const char **, int *);
+int getnh(const char *, mbiHUGE_U *);
+int getpnh(const char **, mbiHUGE_U *);
+int gmatchx(const char *, const char *, Wahr);
+Wahr has_globbing(const char *);
+int ascstrcmp(const void *, const void *);
+int ascpstrcmp(const void *, const void *);
+void ksh_getopt_opterr(int, const char *, const char *);
 void ksh_getopt_reset(Getopt *, int);
 int ksh_getopt(const char **, Getopt *, const char *);
 void print_value_quoted(struct shf *, const char *);
@@ -2659,7 +2801,6 @@ void strip_nuls(char *, size_t)
 ssize_t blocking_read(int, char *, size_t)
     MKSH_A_BOUNDED(__buffer__, 2, 3);
 int reset_nonblock(int);
-char *ksh_get_wd(void);
 char *do_realpath(const char *);
 void simplify_path(char *);
 void set_current_wd(const char *);
@@ -2668,7 +2809,7 @@ int c_cd(const char **);
 char *strdup_i(const char *, Area *);
 char *strndup_i(const char *, size_t, Area *);
 #endif
-int unbksl(bool, int (*)(void), void (*)(int));
+int unbksl(Wahr, int (*)(void), void (*)(int));
 #ifdef __OS2__
 /* os2.c */
 void os2_init(int *, const char ***);
@@ -2682,6 +2823,10 @@ struct shf *shf_open(const char *, int,
 struct shf *shf_fdopen(int, int, struct shf *);
 struct shf *shf_reopen(int, int, struct shf *);
 struct shf *shf_sopen(char *, ssize_t, int, struct shf *);
+struct shf *shf_sreopen(char *, ssize_t, Area *, struct shf *);
+int shf_scheck_grow(ssize_t, struct shf *);
+#define shf_scheck(n,shf)	(((shf)->wnleft < (ssize_t)(n)) ? \
+				    shf_scheck_grow((n), (shf)) : 0)
 int shf_close(struct shf *);
 int shf_fdclose(struct shf *);
 char *shf_sclose(struct shf *);
@@ -2698,7 +2843,12 @@ int shf_putc(int, struct shf *);
 #define shf_putc shf_putc_i
 #endif
 int shf_putchar(int, struct shf *);
-ssize_t shf_puts(const char *, struct shf *);
+#ifdef MKSH_SHF_NO_INLINE
+#define shf_puts shf_putsv
+#else
+#define shf_puts(s,shf) ((s) ? shf_write((s), strlen(s), (shf)) : (ssize_t)-1)
+#endif
+ssize_t shf_putsv(const char *, struct shf *);
 ssize_t shf_write(const char *, ssize_t, struct shf *);
 ssize_t shf_fprintf(struct shf *, const char *, ...)
     MKSH_A_FORMAT(__printf__, 2, 3);
@@ -2708,14 +2858,115 @@ ssize_t shf_snprintf(char *, ssize_t, co
 char *shf_smprintf(const char *, ...)
     MKSH_A_FORMAT(__printf__, 1, 2);
 ssize_t shf_vfprintf(struct shf *, const char *, va_list)
-    MKSH_A_FORMAT(__printf__, 2, 0);
+#ifdef MKSH_SHF_VFPRINTF_NO_GCC_FORMAT_ATTRIBUTE
+#define shf_vfprintf poisoned_shf_vfprintf
+#else
+    MKSH_A_FORMAT(__printf__, 2, 0)
+#endif
+    ;
 void set_ifs(const char *);
+/* flags for numfmt below */
+#define FL_SGN		0x0000	/* signed decimal */
+#define FL_DEC		0x0001	/* unsigned decimal */
+#define FL_OCT		0x0002	/* unsigned octal */
+#define FL_HEX		0x0003	/* unsigned sedecimal */
+#define FM_TYPE		0x0003	/* mask: decimal/octal/hex */
+#define FL_UCASE	0x0004	/* use upper-case digits beyond 9 */
+#define FL_UPPER	0x000C	/* use upper-case digits beyond 9 and 'X' */
+#define FL_PLUS		0x0010	/* FL_SGN force sign output */
+#define FL_BLANK	0x0020	/* FL_SGN output space unless sign present */
+#define FL_HASH		0x0040	/* FL_OCT force 0; FL_HEX force 0x/0X */
+/* internal flags to numfmt / shf_vfprintf */
+#define FL_NEG		0x0080	/* negative number, negated */
+#define FL_SHORT	0x0100	/* ‘h’ seen */
+#define FL_LONG		0x0200	/* ‘l’ seen */
+#define FL_SIZET	0x0400	/* ‘z’ seen */
+#ifdef MKSH_HAVE_HUGE
+#define FL_HUGE		0x0800	/* ‘j’ seen */
+#endif
+#define FM_SIZES	0x0F00	/* mask: short/long/sizet/huge */
+#define FL_RIGHT	0x1000	/* ‘-’ seen: right-pad, left-align */
+#define FL_ZERO		0x2000	/* ‘0’ seen: pad with leading zeros */
+#define FL_DOT		0x4000	/* ‘.’ seen: printf(3) precision specified */
+#define FL_NUMBER	0x8000	/* %[douxefg] a number was formatted */
+/*
+ * %#o produces the longest output: '0' + w/3 + NUL
+ * %#x produces '0x' + w/4 + NUL which is at least as long (w=8, w>9)
+ * %+d produces sign + w/log₂(10) + NUL which takes less than octal obviously
+ */
+#define NUMBUFSZ (1U + (mbiTYPE_UBITS(kuH) + 2U) / 3U + /* NUL */ 1U)
+#define NUMBUFLEN(base,result) ((base) + NUMBUFSZ - (result) - 1U)
+char *kulfmt(kul number, kui flags, char *numbuf)
+    MKSH_A_BOUNDED(__minbytes__, 3, NUMBUFSZ);
+char *kslfmt(ksl number, kui flags, char *numbuf)
+    MKSH_A_BOUNDED(__minbytes__, 3, NUMBUFSZ);
+#ifdef MKSH_HAVE_HUGE
+char *kuHfmt(kuH number, kui flags, char *numbuf)
+    MKSH_A_BOUNDED(__minbytes__, 3, NUMBUFSZ);
+char *ksHfmt(ksH number, kui flags, char *numbuf)
+    MKSH_A_BOUNDED(__minbytes__, 3, NUMBUFSZ);
+#else
+#define kuHfmt kulfmt
+#define ksHfmt kslfmt
+#endif
 /* syn.c */
 void initkeywords(void);
-struct op *compile(Source *, bool, bool);
-bool parse_usec(const char *, struct timeval *);
+struct op *compile(Source *, Wahr);
+Wahr parse_usec(const char *, struct timeval *);
 char *yyrecursive(int);
-void yyrecursive_pop(bool);
+void yyrecursive_pop(Wahr);
+void yyerror(const char *, ...)
+    MKSH_A_NORETURN
+    MKSH_A_FORMAT(__printf__, 1, 2);
+/* shell error reporting */
+void bi_unwind(int);
+Wahr error_prefix(Wahr);
+#define KWF_BIERR	(KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE | \
+			    KWF_BUILTIN | KWF_BIUNWIND)
+#define KWF_ERR(n)	((((unsigned int)(n)) & KWF_EXSTAT) | KWF_ERROR)
+#define KWF_EXSTAT	0x0000FFU	/* (mask) errorlevel to use */
+#define KWF_VERRNO	0x000100U	/* int vararg: use ipv errno */
+#define KWF_INTERNAL	0x000200U	/* internal {error,warning} */
+#define KWF_WARNING	0x000000U	/* (default) warning */
+#define KWF_ERROR	0x000400U	/* error + consequences */
+#define KWF_PREFIX	0x000800U	/* run error_prefix() */
+#define KWF_FILELINE	0x001000U	/* error_prefix arg:=Ja */
+#define KWF_BUILTIN	0x002000U	/* possibly show builtin_argv0 */
+#define KWF_MSGMASK	0x00C000U	/* (mask) message to display */
+#define KWF_MSGFMT	0x000000U	/* (default) printf-style variadic */
+#define KWF_ONEMSG	0x004000U	/* only one string to show */
+#define KWF_TWOMSG	0x008000U	/* two strings to show with colon */
+#define KWF_THREEMSG	0x00C000U	/* three strings to colonise */
+#define KWF_NOERRNO	0x010000U	/* omit showing strerror */
+#define KWF_BIUNWIND	0x020000U	/* let kwarnf* tailcall bi_unwind(0) */
+void kwarnf(unsigned int, ...);
+#ifndef MKSH_SMALL
+void kwarnf0(unsigned int, const char *, ...)
+    MKSH_A_FORMAT(__printf__, 2, 3);
+void kwarnf1(unsigned int, int, const char *, ...)
+    MKSH_A_FORMAT(__printf__, 3, 4);
+#else
+#define kwarnf0 kwarnf	/* with KWF_MSGFMT and !KWF_VERRNO */
+#define kwarnf1 kwarnf	/* with KWF_MSGFMT and KWF_VERRNO */
+#endif
+void kerrf(unsigned int, ...)
+    MKSH_A_NORETURN;
+#ifndef MKSH_SMALL
+void kerrf0(unsigned int, const char *, ...)
+    MKSH_A_NORETURN
+    MKSH_A_FORMAT(__printf__, 2, 3);
+void kerrf1(unsigned int, int, const char *, ...)
+    MKSH_A_NORETURN
+    MKSH_A_FORMAT(__printf__, 3, 4);
+#else
+#define kerrf0 kerrf	/* with KWF_MSGFMT and !KWF_VERRNO */
+#define kerrf1 kerrf	/* with KWF_MSGFMT and KWF_VERRNO */
+#endif
+void merrF(int *, unsigned int, ...);
+#define merrf(rv,va) do {	\
+	merrF va;		\
+	return (rv);		\
+} while (/* CONSTCOND */ 0)
 /* tree.c */
 void fptreef(struct shf *, int, const char *, ...);
 char *snptreef(char *, ssize_t, const char *, ...);
@@ -2725,43 +2976,54 @@ const char *wdscan(const char *, int);
 #define WDS_TPUTS	BIT(0)		/* tputS (dumpwdvar) mode */
 char *wdstrip(const char *, int);
 void tfree(struct op *, Area *);
-void dumpchar(struct shf *, unsigned char);
+#ifdef DEBUG
 void dumptree(struct shf *, struct op *);
 void dumpwdvar(struct shf *, const char *);
-void dumpioact(struct shf *shf, struct op *t);
-void vistree(char *, size_t, struct op *)
-    MKSH_A_BOUNDED(__string__, 1, 2);
-void fpFUNCTf(struct shf *, int, bool, const char *, struct op *);
+void dumpioact(struct shf *, struct op *);
+void dumphex(struct shf *, const void *, size_t)
+    MKSH_A_BOUNDED(__string__, 2, 3);
+#endif
+void uprntc(unsigned char, struct shf *);
+#ifndef MKSH_NO_CMDLINE_EDITING
+void uescmbT(unsigned char *, const char **)
+    MKSH_A_BOUNDED(__minbytes__, 1, 5);
+int uwidthmbT(char *, char **);
+#endif
+const char *uprntmbs(const char *, Wahr, struct shf *);
+void fpFUNCTf(const char *, struct op *, struct shf *, int, Wahr);
+void pioact(struct shf *, struct ioword *);
+char *stripioact(struct ioword *);
 /* var.c */
 void newblock(void);
 void popblock(void);
 void initvar(void);
-struct block *varsearch(struct block *, struct tbl **, const char *, uint32_t);
+struct block *varsearch(struct block *, struct tbl **, const char *, k32);
 struct tbl *global(const char *);
-struct tbl *isglobal(const char *, bool);
-struct tbl *local(const char *, bool);
+struct tbl *isglobal(const char *, Wahr);
+struct tbl *local(const char *, Wahr);
 char *str_val(struct tbl *);
 int setstr(struct tbl *, const char *, int);
-struct tbl *setint_v(struct tbl *, struct tbl *, bool);
+struct tbl *setint_v(struct tbl *, struct tbl *, Wahr);
 void setint(struct tbl *, mksh_ari_t);
 void setint_n(struct tbl *, mksh_ari_t, int);
-struct tbl *typeset(const char *, uint32_t, uint32_t, int, int);
+struct tbl *typeset(const char *, kui, kui, int, int);
 void unset(struct tbl *, int);
-const char *skip_varname(const char *, bool) MKSH_A_PURE;
-const char *skip_wdvarname(const char *, bool) MKSH_A_PURE;
-int is_wdvarname(const char *, bool) MKSH_A_PURE;
-int is_wdvarassign(const char *) MKSH_A_PURE;
-struct tbl *arraysearch(struct tbl *, uint32_t);
+const char *skip_varname(const char *, Wahr);
+const char *skip_wdvarname(const char *, Wahr);
+int not_varname(const char *, Wahr);
+int is_wdvarname(const char *, Wahr);
+int is_wdvarassign(const char *, Wahr);
+struct tbl *arraysearch(struct tbl *, k32);
 char **makenv(void);
 void change_winsz(void);
-size_t array_ref_len(const char *) MKSH_A_PURE;
-char *arrayname(const char *);
-mksh_uari_t set_array(const char *, bool, const char **);
-uint32_t hash(const void *) MKSH_A_PURE;
-uint32_t chvt_rndsetup(const void *, size_t) MKSH_A_PURE;
-mksh_ari_t rndget(void);
+size_t array_ref_len(const char *);
+struct tbl *arraybase(const char *);
+mksh_uari_t set_array(const char *, Wahr, const char **);
+k32 hash(const void *);
+void chvt_rndsetup(const void *, size_t);
+k32 rndget(void);
 void rndset(unsigned long);
-void rndpush(const void *);
+void rndpush(const void *, size_t);
 void record_match(const char *);
 
 enum Test_op {
@@ -2805,8 +3067,10 @@ extern const struct t_op u_ops[];
 extern const struct t_op b_ops[];
 /* ensure order with funcs.c */
 #define Tda (u_ops[0].op_text)
+#define Tdc (u_ops[2].op_text)
 #define Tdn (u_ops[12].op_text)
 #define Tdo (u_ops[14].op_text)
+#define Tdp (u_ops[15].op_text)
 #define Tdr (u_ops[16].op_text)
 #define Tdu (u_ops[20].op_text)	/* "-u" */
 #define Tdx (u_ops[23].op_text)
@@ -2823,29 +3087,29 @@ typedef struct test_env {
 	} pos;
 	const char **wp_end;		/* used by ptest_* */
 	Test_op (*isa)(struct test_env *, Test_meta);
-	const char *(*getopnd) (struct test_env *, Test_op, bool);
-	int (*eval)(struct test_env *, Test_op, const char *, const char *, bool);
+	const char *(*getopnd) (struct test_env *, Test_op, Wahr);
+	int (*eval)(struct test_env *, Test_op, const char *, const char *, Wahr);
 	void (*error)(struct test_env *, int, const char *);
 	int flags;			/* TEF_* */
 } Test_env;
 
 extern const char * const dbtest_tokens[];
 
-Test_op	test_isop(Test_meta, const char *) MKSH_A_PURE;
-int test_eval(Test_env *, Test_op, const char *, const char *, bool);
+Test_op	test_isop(Test_meta, const char *);
+int test_eval(Test_env *, Test_op, const char *, const char *, Wahr);
 int test_parse(Test_env *);
 
 /* tty_fd is not opened O_BINARY, it's thus never read/written */
 EXTERN int tty_fd E_INIT(-1);	/* dup'd tty file descriptor */
-EXTERN bool tty_devtty;		/* true if tty_fd is from /dev/tty */
+EXTERN Wahr tty_devtty;		/* if tty_fd is from /dev/tty */
 EXTERN mksh_ttyst tty_state;	/* saved tty state */
-EXTERN bool tty_hasstate;	/* true if tty_state is valid */
+EXTERN Wahr tty_hasstate;	/* if tty_state is valid */
 
 extern int tty_init_fd(void);	/* initialise tty_fd, tty_devtty */
 
 #ifdef __OS2__
 #define binopen2(path,flags)		__extension__({			\
-	int binopen2_fd = open((path), (flags) | O_BINARY);		\
+	int binopen2_fd = open((path), (flags) | O_BINARY, 0);		\
 	if (binopen2_fd >= 0)						\
 		setmode(binopen2_fd, O_BINARY);				\
 	(binopen2_fd);							\
@@ -2857,7 +3121,7 @@ extern int tty_init_fd(void);	/* initial
 	(binopen3_fd);							\
 })
 #else
-#define binopen2(path,flags)		open((path), (flags) | O_BINARY)
+#define binopen2(path,flags)		open((path), (flags) | O_BINARY, 0)
 #define binopen3(path,flags,mode)	open((path), (flags) | O_BINARY, (mode))
 #endif
 
@@ -2888,7 +3152,7 @@ int getdrvwd(char **, unsigned int);
 #else
 #define mksh_abspath(s)			(ord((s)[0]) == ORD('/'))
 #define mksh_cdirsep(c)			(ord(c) == ORD('/'))
-#define mksh_sdirsep(s)			strchr((s), '/')
+#define mksh_sdirsep(s)			ucstrchr((s), '/')
 #define mksh_vdirsep(s)			vstrchr((s), '/')
 #endif
 
--- mksh-59c.orig/sh_flags.opt
+++ mksh-59c/sh_flags.opt
@@ -1,6 +1,6 @@
 /*-
- * Copyright (c) 2013, 2014, 2015, 2017
- *	mirabilos <m@mirbsd.org>
+ * Copyright (c) 2013, 2014, 2015, 2017, 2021
+ *	mirabilos <m$(date +%Y)@mirbsd.de>
  *
  * Provided that these terms and disclaimer and all copyright notices
  * are retained or reproduced in an accompanying document, permission
@@ -19,7 +19,7 @@
  */
 
 @SHFLAGS_DEFNS
-__RCSID("$MirOS: src/bin/mksh/sh_flags.opt,v 1.9 2020/05/16 22:38:25 tg Exp $");
+__RCSID("$MirOS: src/bin/mksh/sh_flags.opt,v 1.11 2025/04/25 23:15:00 tg Exp $");
 @SHFLAGS_ENUMS
 #define FN(sname,cname,flags,ochar)	cname,
 #define F0(sname,cname,flags,ochar)	cname = 0,
@@ -43,6 +43,10 @@ __RCSID("$MirOS: src/bin/mksh/sh_flags.o
 >a|
 F0("allexport", FEXPORT, OF_ANY
 
+/* ./.	when quoting, show C1 control characters as-is; +U only */
+>|
+FN("asis", FASIS, OF_ANY
+
 /* ./.	bgnice */
 >| HAVE_NICE
 FN("bgnice", FBGNICE, OF_ANY
--- mksh-59c.orig/shf.c
+++ mksh-59c/shf.c
@@ -2,8 +2,9 @@
 
 /*-
  * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2011,
- *		 2012, 2013, 2015, 2016, 2017, 2018, 2019
- *	mirabilos <m@mirbsd.org>
+ *		 2012, 2013, 2015, 2016, 2017, 2018, 2019, 2021,
+ *		 2022, 2023
+ *	mirabilos <m$(date +%Y)@mirbsd.de>
  * Copyright (c) 2015
  *	Daniel Richard G. <skunk@iSKUNK.ORG>
  *
@@ -27,7 +28,7 @@
 
 #include "sh.h"
 
-__RCSID("$MirOS: src/bin/mksh/shf.c,v 1.102 2020/06/22 17:11:03 tg Exp $");
+__RCSID("$MirOS: src/bin/mksh/shf.c,v 1.136 2025/05/22 17:07:51 tg Exp $");
 
 /* flags to shf_emptybuf() */
 #define EB_READSW	0x01	/* about to switch to reading */
@@ -57,7 +58,7 @@ shf_open(const char *name, int oflags, i
 	int fd, eno;
 
 	/* Done before open so if alloca fails, fd won't be lost. */
-	shf = alloc(sizeof(struct shf) + bsize, ATEMP);
+	shf = alloc1(sizeof(struct shf), bsize, ATEMP);
 	shf->areap = ATEMP;
 	shf->buf = (unsigned char *)&shf[1];
 	shf->bsize = bsize;
@@ -92,6 +93,7 @@ shf_open(const char *name, int oflags, i
 }
 
 /* helper function for shf_fdopen and shf_reopen */
+/* pre-initio() *sflagsp=SHF_WR */
 static void
 shf_open_hlp(int fd, int *sflagsp, const char *where)
 {
@@ -121,16 +123,18 @@ shf_open_hlp(int fd, int *sflagsp, const
 	}
 
 	if (!(sflags & (SHF_RD | SHF_WR)))
-		internal_errorf(Tf_sD_s, where, "missing read/write");
+		kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,
+		    Tbad_flags, where, sflags);
 }
 
 /* Set up the shf structure for a file descriptor. Doesn't fail. */
+/* pre-initio() sflags=SHF_WR */
 struct shf *
 shf_fdopen(int fd, int sflags, struct shf *shf)
 {
 	ssize_t bsize =
 	    /* at most 512 */
-	    sflags & SHF_UNBUF ? (sflags & SHF_RD ? 1 : 0) : SHF_BSIZE;
+	    (sflags & SHF_UNBUF) ? ((sflags & SHF_RD) ? 1 : 0) : SHF_BSIZE;
 
 	shf_open_hlp(fd, &sflags, "shf_fdopen");
 	if (shf) {
@@ -140,8 +144,11 @@ shf_fdopen(int fd, int sflags, struct sh
 		} else
 			shf->buf = NULL;
 	} else {
-		shf = alloc(sizeof(struct shf) + bsize, ATEMP);
-		shf->buf = (unsigned char *)&shf[1];
+		unsigned char *cp;
+
+		cp = alloc1(sizeof(struct shf), bsize, ATEMP);
+		shf = (void *)cp;
+		shf->buf = cp + sizeof(struct shf);
 		sflags |= SHF_ALLOCS;
 	}
 	shf->areap = ATEMP;
@@ -154,8 +161,8 @@ shf_fdopen(int fd, int sflags, struct sh
 	shf->flags = sflags;
 	shf->errnosv = 0;
 	shf->bsize = bsize;
-	if (sflags & SHF_CLEXEC)
-		fcntl(fd, F_SETFD, FD_CLOEXEC);
+	if ((sflags & SHF_CLEXEC) && fcntl(fd, F_SETFD, FD_CLOEXEC) == -1)
+		kwarnf0(KWF_INTERNAL | KWF_WARNING, Tcloexec_failed, Tset, fd);
 	return (shf);
 }
 
@@ -168,8 +175,9 @@ shf_reopen(int fd, int sflags, struct sh
 	    sflags & SHF_UNBUF ? (sflags & SHF_RD ? 1 : 0) : SHF_BSIZE;
 
 	shf_open_hlp(fd, &sflags, "shf_reopen");
-	if (!shf || !shf->buf || shf->bsize < bsize)
-		internal_errorf(Tf_sD_s, "shf_reopen", Tbad_bsize);
+	if (!shf->buf || shf->bsize < bsize)
+		kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,
+		    Tbad_buf, "shf_reopen", (size_t)shf->buf, shf->bsize);
 
 	/* assumes shf->buf and shf->bsize already set up */
 	shf->fd = fd;
@@ -180,8 +188,8 @@ shf_reopen(int fd, int sflags, struct sh
 	shf->wbsize = sflags & SHF_UNBUF ? 0 : bsize;
 	shf->flags = (shf->flags & (SHF_ALLOCS | SHF_ALLOCB)) | sflags;
 	shf->errnosv = 0;
-	if (sflags & SHF_CLEXEC)
-		fcntl(fd, F_SETFD, FD_CLOEXEC);
+	if ((sflags & SHF_CLEXEC) && fcntl(fd, F_SETFD, FD_CLOEXEC) == -1)
+		kwarnf0(KWF_INTERNAL | KWF_WARNING, Tcloexec_failed, Tset, fd);
 	return (shf);
 }
 
@@ -197,10 +205,9 @@ shf_reopen(int fd, int sflags, struct sh
 struct shf *
 shf_sopen(char *buf, ssize_t bsize, int sflags, struct shf *shf)
 {
-	/* can't have a read+write string */
-	if (!(!(sflags & SHF_RD) ^ !(sflags & SHF_WR)))
-		internal_errorf(Tf_flags, "shf_sopen",
-		    (unsigned int)sflags);
+	if (!((sflags & SHF_RD) ^ (sflags & SHF_WR)))
+		kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,
+		    Tbad_flags, "shf_sopen", sflags);
 
 	if (!shf) {
 		shf = alloc(sizeof(struct shf), ATEMP);
@@ -226,6 +233,44 @@ shf_sopen(char *buf, ssize_t bsize, int
 	return (shf);
 }
 
+/* Open a string for dynamic writing, using already-allocated buffer */
+struct shf *
+shf_sreopen(char *buf, ssize_t bsize, Area *ap, struct shf *oshf)
+{
+	struct shf *shf;
+
+	shf = shf_sopen(buf, bsize, SHF_WR | SHF_DYNAMIC, oshf);
+	shf->areap = ap;
+	shf->flags |= SHF_ALLOCB;
+	return (shf);
+}
+
+/* Check whether the string can grow to take n bytes, close it up otherwise */
+int
+shf_scheck_grow(ssize_t n, struct shf *shf)
+{
+	if (!(shf->flags & SHF_WR))
+		kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,
+		    Tbad_flags, "shf_scheck", shf->flags);
+
+	/* if n < 0 we lose in the macro already */
+
+	/* nōn-string can always grow flushing */
+	if (!(shf->flags & SHF_STRING))
+		return (0);
+
+	while (shf->wnleft < n)
+		if (shf_emptybuf(shf, EB_GROW) == -1)
+			break;
+
+	if (shf->wnleft < n) {
+		/* block subsequent writes as we truncate here */
+		shf->wnleft = 0;
+		return (1);
+	}
+	return (0);
+}
+
 /* Flush and close file descriptor, free the shf structure */
 int
 shf_close(struct shf *shf)
@@ -275,10 +320,8 @@ shf_sclose(struct shf *shf)
 	unsigned char *s = shf->buf;
 
 	/* NUL terminate */
-	if (shf->flags & SHF_WR) {
-		shf->wnleft++;
-		shf_putc('\0', shf);
-	}
+	if (shf->flags & SHF_WR)
+		*shf->wp = '\0';
 	if (shf->flags & SHF_ALLOCS)
 		afree(shf, shf->areap);
 	return ((char *)s);
@@ -296,7 +339,8 @@ shf_flush(struct shf *shf)
 	if (shf->flags & SHF_STRING)
 		rv = (shf->flags & SHF_WR) ? -1 : 0;
 	else if (shf->fd < 0)
-		internal_errorf(Tf_sD_s, "shf_flush", "no fd");
+		kerrf(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_TWOMSG | KWF_NOERRNO,
+		    "shf_flush", "no fd");
 	else if (shf->flags & SHF_ERROR) {
 		errno = shf->errnosv;
 		rv = -1;
@@ -328,7 +372,8 @@ shf_emptybuf(struct shf *shf, int flags)
 	int ret = 0;
 
 	if (!(shf->flags & SHF_STRING) && shf->fd < 0)
-		internal_errorf(Tf_sD_s, "shf_emptybuf", "no fd");
+		kerrf(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_TWOMSG | KWF_NOERRNO,
+		    "shf_emptybuf", "no fd");
 
 	if (shf->flags & SHF_ERROR) {
 		errno = shf->errnosv;
@@ -343,7 +388,7 @@ shf_emptybuf(struct shf *shf, int flags)
 		shf->flags &= ~SHF_READING;
 	}
 	if (shf->flags & SHF_STRING) {
-		unsigned char *nbuf;
+		size_t rp, wp;
 
 		/*
 		 * Note that we assume SHF_ALLOCS is not set if
@@ -354,13 +399,14 @@ shf_emptybuf(struct shf *shf, int flags)
 		    !(shf->flags & SHF_ALLOCB))
 			return (-1);
 		/* allocate more space for buffer */
-		nbuf = aresize2(shf->buf, 2, shf->wbsize, shf->areap);
-		shf->rp = nbuf + (shf->rp - shf->buf);
-		shf->wp = nbuf + (shf->wp - shf->buf);
+		rp = shf->rp - shf->buf;
+		wp = shf->wp - shf->buf;
+		shf->buf = aresize2(shf->buf, 2, shf->wbsize, shf->areap);
+		shf->rp = shf->buf + rp;
+		shf->wp = shf->buf + wp;
 		shf->rbsize += shf->wbsize;
 		shf->wnleft += shf->wbsize;
 		shf->wbsize <<= 1;
-		shf->buf = nbuf;
 	} else {
 		if (shf->flags & SHF_WRITING) {
 			ssize_t n, ntowrite = shf->wp - shf->buf;
@@ -383,6 +429,8 @@ shf_emptybuf(struct shf *shf, int flags)
 						memmove(shf->buf, buf,
 						    ntowrite);
 						shf->wp = shf->buf + ntowrite;
+						/* restore errno for caller */
+						errno = shf->errnosv;
 					}
 					return (-1);
 				}
@@ -414,7 +462,8 @@ shf_fillbuf(struct shf *shf)
 		return (0);
 
 	if (shf->fd < 0)
-		internal_errorf(Tf_sD_s, "shf_fillbuf", "no fd");
+		kerrf(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_TWOMSG | KWF_NOERRNO,
+		    "shf_fillbuf", "no fd");
 
 	if (shf->flags & (SHF_EOF | SHF_ERROR)) {
 		if (shf->flags & SHF_ERROR)
@@ -457,11 +506,12 @@ shf_read(char *buf, ssize_t bsize, struc
 	ssize_t ncopy, orig_bsize = bsize;
 
 	if (!(shf->flags & SHF_RD))
-		internal_errorf(Tf_flags, Tshf_read,
-		    (unsigned int)shf->flags);
+		kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,
+		    Tbad_flags, Tshf_read, shf->flags);
 
 	if (bsize <= 0)
-		internal_errorf(Tf_szs, Tshf_read, bsize, Tbsize);
+		kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,
+		    Tbad_buf, Tshf_read, (size_t)buf, bsize);
 
 	while (bsize > 0) {
 		if (shf->rnleft == 0 &&
@@ -495,8 +545,8 @@ shf_getse(char *buf, ssize_t bsize, stru
 	char *orig_buf = buf;
 
 	if (!(shf->flags & SHF_RD))
-		internal_errorf(Tf_flags, "shf_getse",
-		    (unsigned int)shf->flags);
+		kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,
+		    Tbad_flags, "shf_getse", shf->flags);
 
 	if (bsize <= 0)
 		return (NULL);
@@ -517,7 +567,7 @@ shf_getse(char *buf, ssize_t bsize, stru
 		ncopy = end ? end - shf->rp + 1 : shf->rnleft;
 		if (ncopy > bsize)
 			ncopy = bsize;
-		memcpy(buf, (char *) shf->rp, ncopy);
+		memcpy(buf, shf->rp, ncopy);
 		shf->rp += ncopy;
 		shf->rnleft -= ncopy;
 		buf += ncopy;
@@ -549,8 +599,8 @@ int
 shf_getchar(struct shf *shf)
 {
 	if (!(shf->flags & SHF_RD))
-		internal_errorf(Tf_flags, "shf_getchar",
-		    (unsigned int)shf->flags);
+		kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,
+		    Tbad_flags, "shf_getchar", shf->flags);
 
 	if (shf->rnleft == 0 && (shf_fillbuf(shf) == -1 || shf->rnleft == 0))
 		return (-1);
@@ -566,8 +616,8 @@ int
 shf_ungetc(int c, struct shf *shf)
 {
 	if (!(shf->flags & SHF_RD))
-		internal_errorf(Tf_flags, "shf_ungetc",
-		    (unsigned int)shf->flags);
+		kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,
+		    Tbad_flags, "shf_ungetc", shf->flags);
 
 	if ((shf->flags & SHF_ERROR) || c == -1 ||
 	    (shf->rp == shf->buf && shf->rnleft))
@@ -604,8 +654,8 @@ int
 shf_putchar(int c, struct shf *shf)
 {
 	if (!(shf->flags & SHF_WR))
-		internal_errorf(Tf_flags, "shf_putchar",
-		    (unsigned int)shf->flags);
+		kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,
+		    Tbad_flags, "shf_putchar", shf->flags);
 
 	if (c == -1)
 		return (-1);
@@ -615,7 +665,8 @@ shf_putchar(int c, struct shf *shf)
 		ssize_t n;
 
 		if (shf->fd < 0)
-			internal_errorf(Tf_sD_s, "shf_putchar", "no fd");
+			kerrf(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_TWOMSG | KWF_NOERRNO,
+			    "shf_putchar", "no fd");
 		if (shf->flags & SHF_ERROR) {
 			errno = shf->errnosv;
 			return (-1);
@@ -641,11 +692,11 @@ shf_putchar(int c, struct shf *shf)
 }
 
 /*
- * Write a string. Returns the length of the string if successful, -1
- * if the string could not be written.
+ * Write a string. Returns the length of the string if successful,
+ * less if truncated, and -1 if the string could not be written.
  */
 ssize_t
-shf_puts(const char *s, struct shf *shf)
+shf_putsv(const char *s, struct shf *shf)
 {
 	if (!s)
 		return (-1);
@@ -653,18 +704,22 @@ shf_puts(const char *s, struct shf *shf)
 	return (shf_write(s, strlen(s), shf));
 }
 
-/* Write a buffer. Returns nbytes if successful, -1 if there is an error. */
+/*
+ * Write a buffer. Returns nbytes if successful, less if truncated
+ * (outputting to string only), and -1 if there is an error.
+ */
 ssize_t
 shf_write(const char *buf, ssize_t nbytes, struct shf *shf)
 {
 	ssize_t n, ncopy, orig_nbytes = nbytes;
 
 	if (!(shf->flags & SHF_WR))
-		internal_errorf(Tf_flags, Tshf_write,
-		    (unsigned int)shf->flags);
+		kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,
+		    Tbad_flags, Tshf_write, shf->flags);
 
 	if (nbytes < 0)
-		internal_errorf(Tf_szs, Tshf_write, nbytes, Tbytes);
+		kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,
+		    Tbad_buf, Tshf_write, (size_t)buf, nbytes);
 
 	/* don't buffer if buffer is empty and we're writing a large amount */
 	if ((ncopy = shf->wnleft) &&
@@ -681,8 +736,13 @@ shf_write(const char *buf, ssize_t nbyte
 		if (shf->flags & SHF_STRING) {
 			/* resize buffer until there's enough space left */
 			while (nbytes > shf->wnleft)
-				if (shf_emptybuf(shf, EB_GROW) == -1)
-					return (-1);
+				if (shf_emptybuf(shf, EB_GROW) == -1) {
+					/* truncate if possible */
+					if (shf->wnleft == 0)
+						return (-1);
+					nbytes = shf->wnleft;
+					break;
+				}
 			/* then write everything into the buffer */
 		} else {
 			/* flush deals with sticky errors */
@@ -747,8 +807,8 @@ shf_snprintf(char *buf, ssize_t bsize, c
 	ssize_t n;
 
 	if (!buf || bsize <= 0)
-		internal_errorf("shf_snprintf: buf %zX, bsize %zd",
-		    (size_t)buf, bsize);
+		kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,
+		    Tbad_buf, "shf_snprintf", (size_t)buf, bsize);
 
 	shf_sopen(buf, bsize, SHF_WR, &shf);
 	va_start(args, fmt);
@@ -773,31 +833,156 @@ shf_smprintf(const char *fmt, ...)
 	return (shf_sclose(&shf));
 }
 
-#define	FL_HASH		0x001	/* '#' seen */
-#define FL_PLUS		0x002	/* '+' seen */
-#define FL_RIGHT	0x004	/* '-' seen */
-#define FL_BLANK	0x008	/* ' ' seen */
-#define FL_SHORT	0x010	/* 'h' seen */
-#define FL_LONG		0x020	/* 'l' seen */
-#define FL_ZERO		0x040	/* '0' seen */
-#define FL_DOT		0x080	/* '.' seen */
-#define FL_UPPER	0x100	/* format character was uppercase */
-#define FL_NUMBER	0x200	/* a number was formatted %[douxefg] */
-#define FL_SIZET	0x400	/* 'z' seen */
-#define FM_SIZES	0x430	/* h/l/z mask */
+/* pre-initio() */
+char *
+kslfmt(ksl number, kui flags, char *numbuf)
+{
+	/* easy for positive number */
+	if (number >= 0)
+		return (kulfmt((kul)number, flags, numbuf));
+	/* negative signed quantity */
+	if (!IS(flags, FM_TYPE, FL_SGN)) {
+		/* uh-oh, output a signed quantity unsignedly */
+		return (kulfmt(mbiA_S2U(kul, ksl, number), flags, numbuf));
+	}
+	return (kulfmt(mbiA_S2M(kul, ksl, number), flags | FL_NEG, numbuf));
+}
+
+/* pre-initio() */
+char *
+kulfmt(kul number, kui flags, char *numbuf)
+{
+	char *cp;
+
+	cp = numbuf + NUMBUFSZ;
+	*--cp = '\0';
+	switch (flags & FM_TYPE) {
+	case FL_OCT:
+		do {
+			*--cp = digits_lc[number & 07UL];
+			number >>= 3;
+		} while (number);
+
+		if (HAS(flags, FL_HASH) && ord(*cp) != ORD('0'))
+			*--cp = '0';
+		break;
+	case FL_HEX: {
+		const char *digits;
+
+		digits = HAS(flags, FL_UCASE) ? digits_uc : digits_lc;
+		do {
+			*--cp = digits[number & 0xFUL];
+			number >>= 4;
+		} while (number);
+
+		if (HAS(flags, FL_HASH)) {
+			*--cp = IS(flags, FL_UPPER, FL_UPPER) ? 'X' : 'x';
+			*--cp = '0';
+		}
+		break;
+	    }
+	default:
+		do {
+			*--cp = digits_lc[number % 10UL];
+			number /= 10UL;
+		} while (number);
+
+		if (IS(flags, FM_TYPE, FL_SGN)) {
+			if (HAS(flags, FL_NEG))
+				*--cp = '-';
+			else if (HAS(flags, FL_PLUS))
+				*--cp = '+';
+			else if (HAS(flags, FL_BLANK))
+				*--cp = ' ';
+		}
+		break;
+	}
+
+	return (cp);
+}
+
+#ifdef MKSH_HAVE_HUGE
+/* pre-initio() */
+char *
+ksHfmt(ksH number, kui flags, char *numbuf)
+{
+	/* easy for positive number */
+	if (number >= 0)
+		return (kuHfmt((kuH)number, flags, numbuf));
+	/* negative signed quantity */
+	if (!IS(flags, FM_TYPE, FL_SGN)) {
+		/* uh-oh, output a signed quantity unsignedly */
+		return (kuHfmt(mbiA_S2U(kuH, ksH, number), flags, numbuf));
+	}
+	return (kuHfmt(mbiA_S2M(kuH, ksH, number), flags | FL_NEG, numbuf));
+}
+
+/* pre-initio() */
+char *
+kuHfmt(kuH number, kui flags, char *numbuf)
+{
+	char *cp;
+
+	cp = numbuf + NUMBUFSZ;
+	*--cp = '\0';
+	switch (flags & FM_TYPE) {
+	case FL_OCT:
+		do {
+			*--cp = digits_lc[number & 07UL];
+			number >>= 3;
+		} while (number);
+
+		if (HAS(flags, FL_HASH) && ord(*cp) != ORD('0'))
+			*--cp = '0';
+		break;
+	case FL_HEX: {
+		const char *digits;
+
+		digits = HAS(flags, FL_UCASE) ? digits_uc : digits_lc;
+		do {
+			*--cp = digits[number & 0xFUL];
+			number >>= 4;
+		} while (number);
+
+		if (HAS(flags, FL_HASH)) {
+			*--cp = IS(flags, FL_UPPER, FL_UPPER) ? 'X' : 'x';
+			*--cp = '0';
+		}
+		break;
+	    }
+	default:
+		do {
+			*--cp = digits_lc[number % 10UL];
+			number /= 10UL;
+		} while (number);
+
+		if (IS(flags, FM_TYPE, FL_SGN)) {
+			if (HAS(flags, FL_NEG))
+				*--cp = '-';
+			else if (HAS(flags, FL_PLUS))
+				*--cp = '+';
+			else if (HAS(flags, FL_BLANK))
+				*--cp = ' ';
+		}
+		break;
+	}
+
+	return (cp);
+}
+#endif
 
 ssize_t
 shf_vfprintf(struct shf *shf, const char *fmt, va_list args)
 {
+	char numbuf[NUMBUFSZ];
 	const char *s;
-	char c, *cp;
+	char c;
 	int tmp = 0, flags;
 	size_t field, precision, len;
-	unsigned long lnum;
-	/* %#o produces the longest output */
-	char numbuf[(8 * sizeof(long) + 2) / 3 + 1 + /* NUL */ 1];
 	/* this stuff for dealing with the buffer */
 	ssize_t nwritten = 0;
+	/* for width determination */
+	const char *lp, *np;
 
 #define VA(type) va_arg(args, type)
 
@@ -862,14 +1047,23 @@ shf_vfprintf(struct shf *shf, const char
 					field = (unsigned int)tmp;
 				continue;
 
-			case 'l':
+			case 'h':
 				flags &= ~FM_SIZES;
+				flags |= FL_SHORT;
+				continue;
+
+			case 'j':
+				flags &= ~FM_SIZES;
+#ifdef MKSH_HAVE_HUGE
+				flags |= FL_HUGE;
+#else
 				flags |= FL_LONG;
+#endif
 				continue;
 
-			case 'h':
+			case 'l':
 				flags &= ~FM_SIZES;
-				flags |= FL_SHORT;
+				flags |= FL_LONG;
 				continue;
 
 			case 'z':
@@ -878,17 +1072,8 @@ shf_vfprintf(struct shf *shf, const char
 				continue;
 			}
 			if (ctype(c, C_DIGIT)) {
-				bool overflowed = false;
-
-				tmp = ksh_numdig(c);
-				while (ctype((c = *fmt++), C_DIGIT))
-					if (notok2mul(2147483647, tmp, 10))
-						overflowed = true;
-					else
-						tmp = tmp * 10 + ksh_numdig(c);
 				--fmt;
-				if (overflowed)
-					tmp = 0;
+				getpn((const char **)&fmt, &tmp);
 				if (flags & FL_DOT)
 					precision = (unsigned int)tmp;
 				else
@@ -910,83 +1095,39 @@ shf_vfprintf(struct shf *shf, const char
 		switch (c) {
 		case 'd':
 		case 'i':
-			if (flags & FL_SIZET)
-				lnum = (long)VA(ssize_t);
-			else if (flags & FL_LONG)
-				lnum = VA(long);
-			else if (flags & FL_SHORT)
-				lnum = (long)(short)VA(int);
+#ifdef MKSH_HAVE_HUGE
+			if (HAS(flags, FL_HUGE))
+				s = ksHfmt(VA(ksH), flags | FL_SGN, numbuf);
 			else
-				lnum = (long)VA(int);
+#endif
+			  s = kslfmt(HAS(flags, FL_SIZET) ? (ksl)VA(ssize_t) :
+			    HAS(flags, FL_LONG) ? (ksl)VA(long) :
+			    HAS(flags, FL_SHORT) ? (ksl)(short)VA(int) :
+			    (ksl)VA(int), flags | FL_SGN, numbuf);
 			goto integral;
 
 		case 'o':
+			flags |= FL_OCT;
+			if (0)
+				/* FALLTHROUGH */
 		case 'u':
+			  flags |= FL_DEC;
+			if (0)
+				/* FALLTHROUGH */
 		case 'x':
-			if (flags & FL_SIZET)
-				lnum = VA(size_t);
-			else if (flags & FL_LONG)
-				lnum = VA(unsigned long);
-			else if (flags & FL_SHORT)
-				lnum = (unsigned long)(unsigned short)VA(int);
+			  flags |= FL_HEX;
+#ifdef MKSH_HAVE_HUGE
+			if (HAS(flags, FL_HUGE))
+				s = kuHfmt(VA(kuH), flags, numbuf);
 			else
-				lnum = (unsigned long)VA(unsigned int);
-
+#endif
+			  s = kulfmt(HAS(flags, FL_SIZET) ? (kul)VA(size_t) :
+			    HAS(flags, FL_LONG) ? (kul)VA(unsigned long) :
+			    HAS(flags, FL_SHORT) ? (kul)(unsigned short)VA(int) :
+			    (kul)VA(unsigned int), flags, numbuf);
  integral:
 			flags |= FL_NUMBER;
-			cp = numbuf + sizeof(numbuf);
-			*--cp = '\0';
-
-			switch (c) {
-			case 'd':
-			case 'i':
-				if (0 > (long)lnum) {
-					lnum = -(long)lnum;
-					tmp = 1;
-				} else
-					tmp = 0;
-				/* FALLTHROUGH */
-			case 'u':
-				do {
-					*--cp = digits_lc[lnum % 10];
-					lnum /= 10;
-				} while (lnum);
-
-				if (c != 'u') {
-					if (tmp)
-						*--cp = '-';
-					else if (flags & FL_PLUS)
-						*--cp = '+';
-					else if (flags & FL_BLANK)
-						*--cp = ' ';
-				}
-				break;
-
-			case 'o':
-				do {
-					*--cp = digits_lc[lnum & 0x7];
-					lnum >>= 3;
-				} while (lnum);
-
-				if ((flags & FL_HASH) && *cp != '0')
-					*--cp = '0';
-				break;
-
-			case 'x': {
-				const char *digits = (flags & FL_UPPER) ?
-				    digits_uc : digits_lc;
-				do {
-					*--cp = digits[lnum & 0xF];
-					lnum >>= 4;
-				} while (lnum);
-
-				if (flags & FL_HASH) {
-					*--cp = (flags & FL_UPPER) ? 'X' : 'x';
-					*--cp = '0';
-				}
-			    }
-			}
-			len = numbuf + sizeof(numbuf) - 1 - (s = cp);
+			len = NUMBUFLEN(numbuf, s);
 			if (flags & FL_DOT) {
 				if (precision > len) {
 					field = precision;
@@ -999,7 +1140,7 @@ shf_vfprintf(struct shf *shf, const char
 
 		case 's':
 			if ((s = VA(const char *)) == NULL)
-				s = "(null)";
+				s = Tnil;
 			else if (flags & FL_HASH) {
 				print_value_quoted(shf, s);
 				continue;
@@ -1027,11 +1168,30 @@ shf_vfprintf(struct shf *shf, const char
 		 */
 		if (!(flags & FL_DOT) || len < precision)
 			precision = len;
+		/* determine whether we can indeed write precision columns */
+		len = 0;
+		lp = s;
+		while (*lp) {
+			int w = utf_widthadj(lp, &np);
+
+			if ((len + w) > precision)
+				break;
+			lp = np;
+			len += w;
+		}
+		/* trailing combining characters */
+		if (UTFMODE)
+			while (*lp && utf_widthadj(lp, &np) == 0)
+				lp = np;
+		/* how much we can actually output */
+		precision = len;
+
+		/* output leading padding */
 		if (field > precision) {
 			field -= precision;
 			if (!(flags & FL_RIGHT)) {
 				/* skip past sign or 0x when padding with 0 */
-				if ((flags & FL_ZERO) && (flags & FL_NUMBER)) {
+				if ((flags & (FL_ZERO | FL_NUMBER)) == (FL_ZERO | FL_NUMBER)) {
 					if (ctype(*s, C_SPC | C_PLUS | C_MINUS)) {
 						shf_putc(*s, shf);
 						s++;
@@ -1042,7 +1202,7 @@ shf_vfprintf(struct shf *shf, const char
 						s++;
 						nwritten++;
 						if (--precision &&
-						    ksh_eq(*s, 'X', 'x')) {
+						    isCh(*s, 'X', 'x')) {
 							shf_putc(*s, shf);
 							s++;
 							precision--;
@@ -1061,11 +1221,11 @@ shf_vfprintf(struct shf *shf, const char
 		} else
 			field = 0;
 
-		nwritten += precision;
-		precision = utf_skipcols(s, precision, &tmp) - s;
-		while (precision--)
-			shf_putc(*s++, shf);
+		/* output string */
+		nwritten += (lp - s);
+		shf_write(s, lp - s, shf);
 
+		/* output trailing padding */
 		nwritten += field;
 		while (field--)
 			shf_putc(c, shf);
@@ -1088,34 +1248,38 @@ shf_putc(int c, struct shf *shf)
 }
 #endif
 
-#ifdef DEBUG
-const char *
-cstrerror(int errnum)
-{
-#undef strerror
-	return (strerror(errnum));
-#define strerror dontuse_strerror /* poisoned */
-}
-#elif !HAVE_STRERROR
+#if !HAVE_STRERROR
 
-#if HAVE_SYS_ERRLIST
+#if HAVE_STRERRORDESC_NP
+/* assume prototype, _GNU_SOURCE may be needed */
+#elif HAVE_SYS_ERRLIST
 #if !HAVE_SYS_ERRLIST_DECL
 extern const int sys_nerr;
 extern const char * const sys_errlist[];
 #endif
 #endif
 
+/* pre-initio() */
 const char *
 cstrerror(int errnum)
 {
-	/* "Unknown error: " + sign + rough estimate + NUL */
-	static char errbuf[15 + 1 + (8 * sizeof(int) + 2) / 3 + 1];
+#define unkerrstr "Unknown error: "
+#define unkerrlen (sizeof(unkerrstr) - 1U)
+	static char errbuf[unkerrlen + NUMBUFSZ];
+#if HAVE_STRERRORDESC_NP
+	const char *ccp;
+#endif
+	char *cp;
 
-#if HAVE_SYS_ERRLIST
+#if HAVE_STRERRORDESC_NP
+	if ((ccp = strerrordesc_np(errnum)))
+		return (ccp);
+#elif HAVE_SYS_ERRLIST
 	if (errnum > 0 && errnum < sys_nerr && sys_errlist[errnum])
 		return (sys_errlist[errnum]);
 #endif
 
+	/* do not add ERANGE, might be EOVERFLOW */
 	switch (errnum) {
 	case 0:
 		return ("Undefined error: 0");
@@ -1127,10 +1291,8 @@ cstrerror(int errnum)
 	case ESRCH:
 		return ("No such process");
 #endif
-#ifdef E2BIG
 	case E2BIG:
 		return ("Argument list too long");
-#endif
 	case ENOEXEC:
 		return ("Exec format error");
 	case EBADF:
@@ -1145,24 +1307,36 @@ cstrerror(int errnum)
 		return ("File exists");
 	case ENOTDIR:
 		return ("Not a directory");
-#ifdef EINVAL
 	case EINVAL:
 		return ("Invalid argument");
-#endif
 #ifdef ELOOP
 	case ELOOP:
 		return ("Too many levels of symbolic links");
 #endif
+	case EOVERFLOW:
+		return ("Value too large");
 	default:
-		shf_snprintf(errbuf, sizeof(errbuf),
-		    "Unknown error: %d", errnum);
-		return (errbuf);
+		cp = kslfmt(errnum, FL_SGN, errbuf + unkerrlen);
+		cp -= unkerrlen;
+		memcpy(cp, unkerrstr, unkerrlen);
+		return (cp);
 	}
+#undef unkerrlen
+#undef unkerrstr
+}
+#elif defined(DEBUG)
+/* pre-initio() */
+const char *
+cstrerror(int errnum)
+{
+#undef strerror
+	return (strerror(errnum));
+#define strerror dontuse_strerror /* poisoned */
 }
 #endif
 
 /* fast character classes */
-const uint32_t tpl_ctypes[128] = {
+const kui tpl_ctypes[128] = {
 	/* 0x00 */
 	CiNUL,		CiCNTRL,	CiCNTRL,	CiCNTRL,
 	CiCNTRL,	CiCNTRL,	CiCNTRL,	CiCNTRL,
@@ -1206,11 +1380,16 @@ const uint32_t tpl_ctypes[128] = {
 	CiLOWER,	CiLOWER,	CiLOWER,	CiLOWER,
 	CiLOWER,	CiLOWER,	CiLOWER,	CiLOWER,
 	CiLOWER,	CiLOWER,	CiLOWER,	CiCURLY,
-	CiQCL,		CiCURLY,	CiQCM,		CiCNTRL
+	CiQCL,		CiCURLY,	CiQCX,		CiCNTRL
 };
 
-void
-set_ifs(const char *s)
+#ifdef MKSH__DEBUG_CCLASSES
+static int debug_ccls(void);
+#endif
+
+/* pre-initio() */
+static void
+set_ccls(void)
 {
 #if defined(MKSH_EBCDIC) || defined(MKSH_FAUX_EBCDIC)
 	int i = 256;
@@ -1224,13 +1403,28 @@ set_ifs(const char *s)
 	memset((char *)ksh_ctypes + sizeof(tpl_ctypes), '\0',
 	    sizeof(ksh_ctypes) - sizeof(tpl_ctypes));
 #endif
+}
+
+/* pre-initio() */
+void
+set_ifs(const char *s)
+{
+	set_ccls();
 	ifs0 = *s;
 	while (*s)
 		ksh_ctypes[ord(*s++)] |= CiIFS;
+#ifdef MKSH__DEBUG_CCLASSES
+	if (debug_ccls())
+		exit(254);
+#endif
 }
 
 #if defined(MKSH_EBCDIC) || defined(MKSH_FAUX_EBCDIC)
-#include <locale.h>
+#if !HAVE_SETLOCALE_LCALL && !defined(MKSH_FAUX_EBCDIC)
+# error EBCDIC support requires use of the system locale
+#endif
+
+static void ebcdic_initerr(const char *, size_t, int, int, int) MKSH_A_NORETURN;
 
 /*
  * Many headaches with EBCDIC:
@@ -1239,8 +1433,8 @@ set_ifs(const char *s)
  *    contain all (most?) of the characters in ASCII, and these
  *    usually tend to agree on the code points assigned to the ASCII
  *    subset. If you need a representative example, look at EBCDIC 1047,
- *    which is first among equals in the IBM MVS development
- *    environment: https://en.wikipedia.org/wiki/EBCDIC_1047
+ *    which is first among equals in the IBM MVS development environment:
+ * https://web.archive.org/web/20200810035140/https://en.wikipedia.org/wiki/EBCDIC_1047
  *    Unfortunately, the square brackets are not consistently mapped,
  *    and for certain reasons, we need an unambiguous bijective
  *    mapping between EBCDIC and "extended ASCII".
@@ -1262,24 +1456,32 @@ set_ifs(const char *s)
  *    mainframe systems, using the -qascii option to the XL C compiler.
  *    We can determine the build mode by looking at __CHARSET_LIB:
  *    0 == EBCDIC, 1 == ASCII
+ *
+ * UTF-8 is not used, nor is UTF-EBCDIC really. We solve this problem
+ * by treating it as "nega-UTF-8": on EBCDIC systems, the output is
+ * converted to the "extended ASCII" codepage from the current EBCDIC
+ * codepage always so we convert UTF-8 backwards so the conversion
+ * will result in valid UTF-8. This may introduce fun on the EBCDIC
+ * side, but as it's not really used anyway we decided to take the risk.
  */
 
+/* pre-initio() */
 void
 ebcdic_init(void)
 {
 	int i = 256;
 	unsigned char t;
-	bool mapcache[256];
+	Wahr mapcache[256];
 
 	while (i--)
 		ebcdic_rtt_toascii[i] = i;
 	memset(ebcdic_rtt_fromascii, 0xFF, sizeof(ebcdic_rtt_fromascii));
 	setlocale(LC_ALL, "");
 #ifdef MKSH_EBCDIC
-	if (__etoa_l(ebcdic_rtt_toascii, 256) != 256) {
-		write(2, "mksh: could not map EBCDIC to ASCII\n", 36);
-		exit(255);
-	}
+	errno = ENOTDIR;
+	if ((i = __etoa_l(ebcdic_rtt_toascii, 256)) != 256)
+		ebcdic_initerr(SC("mksh: could not map EBCDIC to ASCII"),
+		    -1, i, errno);
 #endif
 
 	memset(mapcache, 0, sizeof(mapcache));
@@ -1287,15 +1489,14 @@ ebcdic_init(void)
 	while (i--) {
 		t = ebcdic_rtt_toascii[i];
 		/* ensure unique round-trip capable mapping */
-		if (mapcache[t]) {
-			write(2, "mksh: duplicate EBCDIC to ASCII mapping\n", 40);
-			exit(255);
-		}
+		if (mapcache[t])
+			ebcdic_initerr(SC("mksh: duplicate EBCDIC to ASCII mapping"),
+			    -2, i, ebcdic_rtt_fromascii[t]);
 		/*
 		 * since there are 256 input octets, this also ensures
 		 * the other mapping direction is completely filled
 		 */
-		mapcache[t] = true;
+		mapcache[t] = Ja;
 		/* fill the complete round-trip map */
 		ebcdic_rtt_fromascii[t] = i;
 		/*
@@ -1314,9 +1515,663 @@ ebcdic_init(void)
 		else
 			ebcdic_map[i] = (unsigned short)(0x100U | ord(i));
 	}
-	if (ebcdic_rtt_toascii[0] || ebcdic_rtt_fromascii[0] || ebcdic_map[0]) {
-		write(2, "mksh: NUL not at position 0\n", 28);
+	if (ebcdic_rtt_toascii[0] || ebcdic_rtt_fromascii[0] || ebcdic_map[0])
+		ebcdic_initerr(SC("mksh: NUL not at position 0"),
+		    ebcdic_rtt_toascii[0], ebcdic_rtt_fromascii[0],
+		    ebcdic_map[0]);
+	/* ensure control characters, i.e. 0x00‥0x3F and 0xFF, map sanely */
+	for (i = 0x00; i < 0x20; ++i)
+		if (!ksh_isctrl(asc2rtt(i)))
+			goto ebcdic_ctrlmis;
+	for (i = 0x7F; i < 0xA0; ++i)
+		if (!ksh_isctrl(asc2rtt(i))) {
+ ebcdic_ctrlmis:
+			ebcdic_initerr(SC("mksh: control character mismapping"),
+			    -2, i, asc2rtt(i));
+		}
+	/* validate character literals used in the code */
+#define litcheck(c,v) \
+	if (rtt2asc(c) != v) \
+		ebcdic_initerr(SC("mksh: compiler vs. runtime codepage mismatch"), \
+		    -3, c, rtt2asc(c))
+	litcheck('\n', 0x0AU);
+	litcheck('\r', 0x0DU);
+	litcheck(' ', 0x20U);
+	litcheck('!', 0x21U);
+	litcheck('"', 0x22U);
+	litcheck('#', 0x23U);
+	litcheck('$', 0x24U);
+	litcheck('%', 0x25U);
+	litcheck('&', 0x26U);
+	litcheck('\'', 0x27U);
+	litcheck('(', 0x28U);
+	litcheck(')', 0x29U);
+	litcheck('*', 0x2AU);
+	litcheck('+', 0x2BU);
+	litcheck(',', 0x2CU);
+	litcheck('-', 0x2DU);
+	litcheck('.', 0x2EU);
+	litcheck('/', 0x2FU);
+	litcheck('0', 0x30U);
+	litcheck(':', 0x3AU);
+	litcheck(';', 0x3BU);
+	litcheck('<', 0x3CU);
+	litcheck('=', 0x3DU);
+	litcheck('>', 0x3EU);
+	litcheck('?', 0x3FU);
+	litcheck('@', 0x40U);
+	litcheck('A', 0x41U);
+	litcheck('B', 0x42U);
+	litcheck('C', 0x43U);
+	litcheck('D', 0x44U);
+	litcheck('E', 0x45U);
+	litcheck('F', 0x46U);
+	litcheck('G', 0x47U);
+	litcheck('H', 0x48U);
+	litcheck('I', 0x49U);
+	litcheck('N', 0x4EU);
+	litcheck('O', 0x4FU);
+	litcheck('P', 0x50U);
+	litcheck('Q', 0x51U);
+	litcheck('R', 0x52U);
+	litcheck('S', 0x53U);
+	litcheck('T', 0x54U);
+	litcheck('U', 0x55U);
+	litcheck('W', 0x57U);
+	litcheck('X', 0x58U);
+	litcheck('Y', 0x59U);
+	litcheck('[', 0x5BU);
+	litcheck('\\', 0x5CU);
+	litcheck(']', 0x5DU);
+	litcheck('^', 0x5EU);
+	litcheck('_', 0x5FU);
+	litcheck('`', 0x60U);
+	litcheck('a', 0x61U);
+	litcheck('b', 0x62U);
+	litcheck('c', 0x63U);
+	litcheck('d', 0x64U);
+	litcheck('e', 0x65U);
+	litcheck('f', 0x66U);
+	litcheck('g', 0x67U);
+	litcheck('h', 0x68U);
+	litcheck('i', 0x69U);
+	litcheck('j', 0x6AU);
+	litcheck('k', 0x6BU);
+	litcheck('l', 0x6CU);
+	litcheck('n', 0x6EU);
+	litcheck('p', 0x70U);
+	litcheck('r', 0x72U);
+	litcheck('s', 0x73U);
+	litcheck('t', 0x74U);
+	litcheck('u', 0x75U);
+	litcheck('v', 0x76U);
+	litcheck('w', 0x77U);
+	litcheck('x', 0x78U);
+	litcheck('y', 0x79U);
+	litcheck('{', 0x7BU);
+	litcheck('|', 0x7CU);
+	litcheck('}', 0x7DU);
+	litcheck('~', 0x7EU);
+#undef litcheck
+	/* validate sh.h control character literals */
+#define ctlcheck(n,c,v) \
+	if (rtt2asc(c) != v) \
+		ebcdic_initerr(SC("mksh: control character mismapping"), \
+		    -3, n, rtt2asc(c))
+	ctlcheck('@', CTRL_AT, 0x00U);
+	ctlcheck('A', CTRL_A, 0x01U);
+	ctlcheck('B', CTRL_B, 0x02U);
+	ctlcheck('C', CTRL_C, 0x03U);
+	ctlcheck('D', CTRL_D, 0x04U);
+	ctlcheck('E', CTRL_E, 0x05U);
+	ctlcheck('F', CTRL_F, 0x06U);
+	ctlcheck('G', CTRL_G, 0x07U);
+	ctlcheck('H', CTRL_H, 0x08U);
+	ctlcheck('I', CTRL_I, 0x09U);
+	ctlcheck('J', CTRL_J, 0x0AU);
+	ctlcheck('K', CTRL_K, 0x0BU);
+	ctlcheck('L', CTRL_L, 0x0CU);
+	ctlcheck('M', CTRL_M, 0x0DU);
+	ctlcheck('N', CTRL_N, 0x0EU);
+	ctlcheck('O', CTRL_O, 0x0FU);
+	ctlcheck('P', CTRL_P, 0x10U);
+	ctlcheck('Q', CTRL_Q, 0x11U);
+	ctlcheck('R', CTRL_R, 0x12U);
+	ctlcheck('S', CTRL_S, 0x13U);
+	ctlcheck('T', CTRL_T, 0x14U);
+	ctlcheck('U', CTRL_U, 0x15U);
+	ctlcheck('V', CTRL_V, 0x16U);
+	ctlcheck('W', CTRL_W, 0x17U);
+	ctlcheck('X', CTRL_X, 0x18U);
+	ctlcheck('Y', CTRL_Y, 0x19U);
+	ctlcheck('Z', CTRL_Z, 0x1AU);
+	ctlcheck('[', CTRL_BO, 0x1BU);
+	ctlcheck('\\', CTRL_BK, 0x1CU);
+	ctlcheck(']', CTRL_BC, 0x1DU);
+	ctlcheck('^', CTRL_CA, 0x1EU);
+	ctlcheck('_', CTRL_US, 0x1FU);
+	ctlcheck('?', CTRL_QM, 0x7FU);
+#undef ctlcheck
+}
+
+/* pre-initio() */
+static void
+ebcdic_initerr(const char *s, size_t n, int a, int b, int c)
+{
+	char buf[NUMBUFSZ + 3];
+	char *cp;
+	const char *ccp;
+
+	SHIKATANAI write(2, s, n);
+	/*
+	 * a>=0: a,b,c=hex
+	 * a=-1: b=sgn c=errno
+	 * a=-2: b=hex c=hex
+	 * a=-3: b=chr c=hex
+	 */
+	if (a == -1) {
+		ccp = cstrerror(c);
+		cp = kslfmt(b, FL_SGN, buf + 1U);
+		*--cp = '<';
+		buf[NUMBUFSZ] = '>';
+		buf[NUMBUFSZ + 1U] = ccp ? '<' : '(';
+		SHIKATANAI write(2, cp, NUMBUFLEN(buf + 1U, cp) + 2U);
+		if (ccp) {
+			SHIKATANAI write(2, SZ(ccp));
+			SHIKATANAI write(2, SC(">\n"));
+		} else
+			SHIKATANAI write(2, SC("unknown error)\n"));
 		exit(255);
 	}
+	if (a == -3) {
+		buf[0] = '<';
+		buf[1] = b;
+		buf[2] = '>';
+		SHIKATANAI write(2, buf, 3);
+	} else {
+		if (a != -2) {
+			cp = kslfmt(a, FL_HEX | FL_UCASE | FL_HASH, buf + 1);
+			*--cp = '<';
+			buf[NUMBUFSZ] = '>';
+			SHIKATANAI write(2, cp, NUMBUFLEN(buf + 1U, cp) + 1U);
+		}
+		cp = kslfmt(b, FL_HEX | FL_UCASE | FL_HASH, buf + 1);
+		*--cp = '<';
+		buf[NUMBUFSZ] = '>';
+		SHIKATANAI write(2, cp, NUMBUFLEN(buf + 1U, cp) + 1U);
+	}
+	cp = kslfmt(c, FL_HEX | FL_UCASE | FL_HASH, buf + 1);
+	*--cp = '<';
+	buf[NUMBUFSZ] = '>';
+	buf[NUMBUFSZ + 1U] = '\n';
+	SHIKATANAI write(2, cp, NUMBUFLEN(buf + 1U, cp) + 2U);
+	exit(255);
+}
+#endif
+
+#ifdef MKSH__DEBUG_CCLASSES
+/*
+ * This is developer debugging code. It makes no attempt
+ * at being performant, not redundant, have acceptable
+ * style, or anything really.
+ */
+
+/* pre-initio() */
+static unsigned int
+v(unsigned int c)
+{
+	if (ord(c) == ORD('\\')) {
+		printf("\\\\");
+		return (2);
+	} else if (c < 0x21U || c > 0x7EU) {
+		printf("\\x%02X", c);
+		return (4);
+	} else {
+		putchar(c);
+		return (1);
+	}
+}
+
+#define tabto(len,to) do {		\
+	while (len < to) {		\
+		putchar('\t');		\
+		len = (len | 7) + 1;	\
+	}				\
+} while (/* CONSTCOND */ 0)
+
+static char vert[40][40];
+
+static struct ciname {
+	const char *name;
+	kui val;
+	kui bit;
+} ci[32], *cibit[32];
+
+/* pre-initio() */
+static int
+cicomp(const void *a_, const void *b_)
+{
+	const struct ciname *a = a_;
+	const struct ciname *b = b_;
+	return (strcmp(a->name, b->name));
+}
+
+/* pre-initio() */
+static int
+debug_ccls(void)
+{
+	unsigned int i, j, k, x, y, z;
+
+	printf("\t0               1               2               3               4               5               6               7            ->7\n");
+	printf("\t0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF\n");
+#define D(x) do { \
+	printf("%s\t", #x); \
+	for (i = 0; i <= 0x7F; ++i) \
+		putchar(tpl_ctypes[i] & x ? '#' : '-'); \
+	putchar('\n'); \
+} while (/* CONSTCOND */ 0)
+#define DCi() do {	\
+	D(CiIFS);	\
+	D(CiCNTRL);	\
+	D(CiUPPER);	\
+	D(CiLOWER);	\
+	D(CiHEXLT);	\
+	D(CiOCTAL);	\
+	D(CiQCL);	\
+	D(CiALIAS);	\
+	D(CiQCX);	\
+	D(CiVAR1);	\
+	D(CiQCM);	\
+	D(CiDIGIT);	\
+	D(CiQC);	\
+	D(CiSPX);	\
+	D(CiCURLY);	\
+	D(CiANGLE);	\
+	D(CiNUL);	\
+	D(CiTAB);	\
+	D(CiNL);	\
+	D(CiCR);	\
+	D(CiSP);	\
+	D(CiHASH);	\
+	D(CiSS);	\
+	D(CiPERCT);	\
+	D(CiPLUS);	\
+	D(CiMINUS);	\
+	D(CiCOLON);	\
+	D(CiEQUAL);	\
+	D(CiQUEST);	\
+	D(CiBRACK);	\
+	D(CiUNDER);	\
+	D(CiGRAVE);	\
+} while (/* CONSTCOND */ 0)
+	DCi();
+#undef D
+	putchar('\n');
+
+	printf("\t  i i i i i   i       i     i i               i   i i i i i i i\n");
+	printf("\tC C U L H O   A   i   D     C A           i   P i M C E Q B U G\n");
+	printf("\ti N P O E C i L i V i I   i U N i i       H   E P I O Q U R N R\n");
+	printf("\tI T P W X T Q I Q A Q G i S R G N T i i i A i R L N L U E A D A\n");
+	printf("\tF R E E L A C A C R C I Q P L L U A N C S S S C U U O A S C E V\n");
+	printf("\tS L R R T L L S X 1 M T C X Y E L B L R P H S T S S N L T K R E\n");
+	j = 0;
+#define D(x,i1,i2,i3) do { \
+	printf("%s\t", #x); \
+	for (i = 0; i <= 31; ++i) { \
+		printf(x & BIT(i) ? "**" : "- "); \
+		vert[i][j] = (x & BIT(i) ? '#' : '-'); \
+	} \
+	printf("\t%08X\n", x); \
+	++j; \
+} while (/* CONSTCOND */ 0)
+#define DC_() do {	\
+	D(C_ALIAS, 2, 24, "valid characters in alias names"); \
+	D(C_ALNUM, 1, 24, "alphanumerical"); \
+	D(C_ALNUX, 1, 24, "alphanumerical plus underscore (“word character”)"); \
+	D(C_ALPHA, 1, 24, "alphabetical (upper plus lower)"); \
+	D(C_ALPHX, 1, 24, "alphabetical plus underscore (identifier lead)"); \
+	D(C_ASCII, 1, 24, "7-bit ASCII except NUL"); \
+	D(C_BLANK, 0, 24, "tab and space"); \
+	D(C_CNTRL, 1, 24, "POSIX control characters"); \
+	D(C_DIGIT, 1, 24, "decimal digits"); \
+	D(C_EDCMD, 0, 32, "editor x_locate_word() command"); \
+	D(C_EDGLB, 0, 32, "escape for globbing"); \
+	D(C_EDNWC, 0, 32, "editor non-word characters"); \
+	D(C_EDQ, 0, 32, "editor quotes for tab completion"); \
+	D(C_GRAPH, 1, 24, "POSIX graphical (alphanumerical plus punctuation)"); \
+	D(C_HEXLT, 1, 24, "hex letter"); \
+	D(C_IFS, 0, 24, "IFS whitespace, IFS non-whitespace, NUL"); \
+	D(C_IFSWS, 0, 24, "IFS whitespace candidates"); \
+	D(C_LEX1, 0, 24, "(for the lexer)"); \
+	D(C_LOWER, 1, 24, "lowercase letters"); \
+	D(C_MFS, 3, 24, "separator for motion"); \
+	D(C_OCTAL, 1, 24, "octal digit"); \
+	D(C_PATMO, 0, 24, "pattern magical operator, except space"); \
+	D(C_PRINT, 1, 24, "POSIX printable characters (graph plus space)"); \
+	D(C_PUNCT, 0, 40, "POSIX punctuation"); \
+	D(C_QUOTE, 0, 40, "characters requiring quoting, minus space"); \
+	D(C_SEDEC, 1, 24, "hexadecimal digit"); \
+	D(C_SPACE, 1, 24, "POSIX space class"); \
+	D(C_SUB1, 0, 24, "substitution operations with word"); \
+	D(C_SUB2, 0, 24, "substitution operations with pattern"); \
+	D(C_UPPER, 1, 24, "uppercase letters"); \
+	D(C_VAR1, 0, 24, "substitution parameters, other than positional"); \
+} while (/* CONSTCOND */ 0)
+	DC_();
+#undef D
+	putchar('\n');
+
+	for (i = 0; i <= 31; ++i)
+		vert[i][j] = 0;
+	j = 0;
+#define D(x) do { \
+	printf("%s\t%s\n", #x, vert[j++]); \
+} while (/* CONSTCOND */ 0)
+	DCi();
+#undef D
+	putchar('\n');
+
+#define D(x) do {					\
+	y = 0;						\
+	while (BIT(y) != x)				\
+		if (y++ == 31) {			\
+			printf("E: %s=%X\n", #x, x);	\
+			exit(255);			\
+		}					\
+	ci[y].name = #x;				\
+	ci[y].val = x;				\
+	ci[y].bit = y;					\
+} while (/* CONSTCOND */ 0)
+	DCi();
+#undef D
+	qsort(ci, NELEM(ci), sizeof(struct ciname), &cicomp);
+	for (i = 0; i < NELEM(ci); ++i) {
+		cibit[ci[i].bit] = &ci[i];
+		printf("BIT(%d)\t%08X  %s\n", ci[i].bit, ci[i].val, ci[i].name);
+	}
+	putchar('\n');
+
+#define D(x) do { \
+	if (x != CiIFS && (ksh_ctypes[i] & x)) { \
+		if (z) { \
+			printf(" | "); \
+			z += 3; \
+		} \
+		printf("%s", #x); \
+		z += strlen(#x); \
+	} \
+} while (/* CONSTCOND */ 0)
+	printf("// shf.c begin {{{\n/* fast character classes */\n");
+	printf("const kui tpl_ctypes[128] = {\n");
+	x = 0, y = 0; /* fsck GCC */
+	for (i = 0; i <= 0x7F; ++i) {
+		if (!(i & 0x0F)) {
+			printf("\t/* 0x%02X */\n", i);
+			x = 1; /* did newline */
+		}
+		if (x) {
+			printf("\t");
+			x = 0;
+			y = 16;
+		}
+		z = 0;
+		DCi();
+		if (i != 0x7F) {
+			putchar(',');
+			++z;
+		}
+		if (((i & 0x03) == 0x03) || ((i & 0x59) == 0x41)) {
+			putchar('\n');
+			x = 1;
+		} else {
+			if ((i & 0x58) == 0x40)
+				y = 24;
+			tabto(z, y);
+			if (z > 16) {
+				y = 8;
+				tabto(z, 24);
+			}
+		}
+	}
+#undef D
+	printf("};\n// shf.c end }}}\n\n");
+
+#define putrangef(len,cond,count) do {			\
+	for (count = 0; count <= 0xFF; ++count)		\
+		if (ksh_ctypes[count] & cond)		\
+			len += v(count);		\
+} while (/* CONSTCOND */ 0)
+#define putranget(len,cond,count,hold,flag) do {	\
+	flag = 0;					\
+	count = -1;					\
+	while (1) {					\
+		++count;				\
+		if (!flag) {				\
+			if (count > 0xFF)		\
+				break;			\
+			if (ksh_ctypes[count] & cond) {	\
+				hold = count;		\
+				flag = 1;		\
+			}				\
+		} else if (count > 0xFF ||		\
+		    !(ksh_ctypes[count] & cond)) {	\
+			flag = count - 1;		\
+			len += v(hold);			\
+			if (flag == hold + 1) {		\
+				len += v(flag);		\
+			} else if (flag > hold) {	\
+				printf("‥");		\
+				len += 1 + v(flag);	\
+			}				\
+			if (count > 0xFF)		\
+				break;			\
+			flag = 0;			\
+		}					\
+	}						\
+} while (/* CONSTCOND */ 0)
+#define putrangea(len,cond,count,hold,flag) do {	\
+	flag = 0;					\
+	count = -1;					\
+	while (1) {					\
+		++count;				\
+		if (!flag) {				\
+			if (count > 0xFF)		\
+				break;			\
+			if (ksh_ctypes[count] & cond) {	\
+				len += v(count);	\
+				hold = count;		\
+				flag = count == '0' ||	\
+				    count == 'A' ||	\
+				    count == 'a';	\
+			}				\
+		} else if (count > 0xFF ||		\
+		    !(ksh_ctypes[count] & cond)) {	\
+			flag = count - 1;		\
+			if (flag == hold + 1) {		\
+				len += v(flag);		\
+			} else if (flag > hold) {	\
+				printf("‥");		\
+				len += 1 + v(flag);	\
+			}				\
+			if (count > 0xFF)		\
+				break;			\
+			flag = 0;			\
+		} else if ((count - 1) == '9' ||	\
+		    (count - 1) == 'Z' ||		\
+		    (count - 1) == 'z') {		\
+			flag = count - 1;		\
+			if (flag == hold + 1) {		\
+				len += v(flag);		\
+			} else if (flag > hold) {	\
+				printf("‥");		\
+				len += 1 + v(flag);	\
+			}				\
+			len += v(count);		\
+			flag = 0;			\
+		}					\
+	}						\
+} while (/* CONSTCOND */ 0)
+
+#define DD(n,x,ign) do {				\
+	y = 0;						\
+	while (BIT(y) != x)				\
+		if (y++ == 31) {			\
+			printf("E: %s=%X\n", n, x);	\
+			exit(255);			\
+		}					\
+	printf("#define %s\tBIT(%d)", n, y);		\
+	if (x != ign) {					\
+		printf("\t/* ");			\
+		y = 3;					\
+		switch (x) {				\
+		case CiCNTRL:				\
+		case CiUPPER: case CiLOWER:		\
+		case CiHEXLT: case CiOCTAL:		\
+			putranget(y, x, i, j, k);	\
+			break;				\
+		default:				\
+			putrangef(y, x, i);		\
+		}					\
+		tabto(y, 32);				\
+		printf("*/");				\
+	}						\
+	putchar('\n');					\
+} while (/* CONSTCOND */ 0)
+	DD("??IFS", CiIFS, CiCNTRL);
+
+	printf("// sh.h begin {{{\n/*\n * fast character classes\n */\n\n");
+	printf("/* internal types, do not reference */\n\n");
+
+#define D(x) DD(#x, x, CiIFS)
+	printf("/* initially empty — filled at runtime from $IFS */\n");
+	DCi();
+#undef DD
+#undef D
+	printf("/* out of space, but one for *@ would make sense, possibly others */\n\n");
+
+	printf("/* compile-time initialised, ASCII only */\n"
+		"extern const kui tpl_ctypes[128];\n"
+		"/* run-time, contains C_IFS as well, full 2⁸ octet range */\n"
+		"EXTERN kui ksh_ctypes[256];\n"
+		"/* first octet of $IFS, for concatenating \"$*\" */\n"
+		"EXTERN char ifs0;\n"
+		"\n");
+
+#define expcond(cond,len,cnt,flg,fnd,cnd) do {		\
+	flg = 1;					\
+	for (cnt = 0; cnt < NELEM(ci); ++cnt)		\
+		if (cond == ci[cnt].val) {		\
+			len += printf("%s",		\
+			    ci[cnt].name);		\
+			flg = 0;			\
+			break;				\
+		}					\
+	if (flg) {					\
+		cnd = cond;				\
+		fnd = 0;				\
+		if (cnd != C_GRAPH &&			\
+		    (cnd & C_GRAPH) == C_GRAPH) {	\
+			len += printf("%s%s",		\
+			    fnd ? " | " : "(",		\
+			    "C_GRAPH");			\
+			fnd = 1;			\
+			cnd &= ~C_GRAPH;		\
+		}					\
+		if (cnd != C_PUNCT &&			\
+		    (cnd & C_PUNCT) == C_PUNCT) {	\
+			len += printf("%s%s",		\
+			    fnd ? " | " : "(",		\
+			    "C_PUNCT");			\
+			fnd = 1;			\
+			cnd &= ~C_PUNCT;		\
+		}					\
+		for (cnt = 0; cnt < NELEM(ci); ++cnt)	\
+		   if (cnd & ci[cnt].val) {		\
+			len += printf("%s%s",		\
+			    fnd ? " | " : "(",		\
+			    ci[cnt].name);		\
+			fnd = 1;			\
+		}					\
+		if (!fnd) {				\
+			printf("<ERR>\n");		\
+			exit(255);			\
+		}					\
+		putchar(')');				\
+		++len;					\
+	}						\
+} while (/* CONSTCOND */ 0)
+
+	set_ccls(); /* drop CiIFS from ksh_ctypes */
+#define D(cond,rng,tabstop,lbl) do {			\
+	printf("/* ");					\
+	y = 3;						\
+	switch (rng) {					\
+	case 0:						\
+		putrangef(y, cond, i);			\
+		break;					\
+	case 1:						\
+		putranget(y, cond, i, j, k);		\
+		break;					\
+	case 2:						\
+		putrangea(y, cond, i, j, k);		\
+		break;					\
+	case 3:						\
+		for (i = 0; i <= 0x7F; ++i) {		\
+			if (!!(ksh_ctypes[i] & cond) ^	\
+			    !!(ksh_ctypes[i] & (	\
+			    C_ALNUX | CiSS)))		\
+				continue;		\
+			printf("<ERR(%02X)>\n", i);	\
+			exit(255);			\
+		}					\
+		y += printf("not alnux or dollar");	\
+		break;					\
+	}						\
+	if (cond & CiIFS)				\
+		y += printf(" + $IFS");			\
+	tabto(y, tabstop);				\
+	printf("%s */\n#define %s\t", lbl, #cond);	\
+	expcond(cond, y, i, z, j, k);			\
+	putchar('\n');					\
+} while (/* CONSTCOND */ 0)
+	printf("/* external types */\n\n");
+	DC_();
+#undef D
+
+#define D(x,lbl) do {			\
+	y = printf("#define %s", #x);	\
+	tabto(y, 16);			\
+	expcond(x, y, i, z, j, k);	\
+	tabto(y, 32);			\
+	y += printf("/* ");		\
+	putrangef(y, x, i);		\
+	tabto(y, 40);			\
+	printf("%s */\n", lbl);		\
+} while (/* CONSTCOND */ 0)
+	printf("\n/* individual chars you might like */\n");
+	D(C_ANGLE, "angle brackets");
+	D(C_COLON, "colon");
+	D(C_CR, "ASCII carriage return");
+	D(C_DOLAR, "dollar sign");
+	D(C_EQUAL, "equals sign");
+	D(C_GRAVE, "accent gravis");
+	D(C_HASH, "hash sign");
+	D(C_LF, "ASCII line feed");
+	D(C_MINUS, "hyphen-minus");
+	printf("#ifdef MKSH_WITH_TEXTMODE\n"
+		"#define C_NL\t(CiNL | CiCR)\t/*\tCR or LF under OS/2 TEXTMODE */\n"
+		"#else\n"
+		"#define C_NL\tCiNL\t\t/*\tLF only like under Unix */\n"
+		"#endif\n");
+	D(C_NUL, "ASCII NUL");
+	D(C_PLUS, "plus sign");
+	D(C_QC, "quote characters");
+	D(C_QUEST, "question mark");
+	D(C_SPC, "ASCII space");
+	D(C_TAB, "ASCII horizontal tabulator");
+	D(C_UNDER, "underscore");
+
+	printf("// sh.h end }}}\n");
+	return (ksh_ctypes[0] == CiNUL);
 }
 #endif
--- mksh-59c.orig/strlcpy.c
+++ mksh-59c/strlcpy.c
@@ -1,6 +1,6 @@
 /*-
  * Copyright (c) 2006, 2008, 2009, 2013
- *	mirabilos <m@mirbsd.org>
+ *	mirabilos <m$(date +%Y)@mirbsd.de>
  * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>
  *
  * Permission to use, copy, modify, and distribute this software for any
@@ -18,7 +18,7 @@
 
 #include "sh.h"
 
-__RCSID("$MirOS: src/bin/mksh/strlcpy.c,v 1.10 2015/11/29 17:05:02 tg Exp $");
+__RCSID("$MirOS: src/bin/mksh/strlcpy.c,v 1.11 2025/04/25 23:15:01 tg Exp $");
 
 /*
  * Copy src to string dst of size siz. At most siz-1 characters
--- mksh-59c.orig/syn.c
+++ mksh-59c/syn.c
@@ -3,8 +3,8 @@
 /*-
  * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009,
  *		 2011, 2012, 2013, 2014, 2015, 2016, 2017,
- *		 2018, 2020
- *	mirabilos <m@mirbsd.org>
+ *		 2018, 2020, 2021, 2023, 2024, 2025
+ *	mirabilos <m$(date +%Y)@mirbsd.de>
  *
  * Provided that these terms and disclaimer and all copyright notices
  * are retained or reproduced in an accompanying document, permission
@@ -22,9 +22,11 @@
  * of said person's immediate fault when using the work as intended.
  */
 
+/* to avoid -Wmissing-format-attribute on vwarnf(), which is no candidate */
+#define MKSH_SHF_VFPRINTF_NO_GCC_FORMAT_ATTRIBUTE
 #include "sh.h"
 
-__RCSID("$MirOS: src/bin/mksh/syn.c,v 1.129 2020/10/31 01:21:58 tg Exp $");
+__RCSID("$MirOS: src/bin/mksh/syn.c,v 1.158 2025/12/24 04:51:56 tg Exp $");
 
 struct nesting_state {
 	int start_token;	/* token than began nesting (eg, FOR) */
@@ -37,46 +39,54 @@ struct yyrecursive_state {
 	struct ioword **old_herep;
 	int old_symbol;
 	unsigned int old_nesting_type;
-	bool old_reject;
+	Wahr old_reject;
 };
 
-static void yyparse(bool);
+static void yyparse(Wahr);
 static struct op *pipeline(int, int);
 static struct op *andor(int);
-static struct op *c_list(int, bool);
+static struct op *c_list(int, Wahr);
 static struct ioword *synio(int);
-static struct op *nested(int, int, int, int);
+static struct op *nested(int, unsigned int, unsigned int, int);
 static struct op *get_command(int, int);
 static struct op *dogroup(int);
 static struct op *thenpart(int);
 static struct op *elsepart(int);
 static struct op *caselist(int);
 static struct op *casepart(int, int);
-static struct op *function_body(char *, int, bool);
+static struct op *function_body(char *, int, int);
 static char **wordlist(int);
 static struct op *block(int, struct op *, struct op *);
 static struct op *newtp(int);
 static void syntaxerr(const char *) MKSH_A_NORETURN;
 static void nesting_push(struct nesting_state *, int);
 static void nesting_pop(struct nesting_state *);
-static int inalias(struct source *) MKSH_A_PURE;
+static int inalias(struct source *);
 static Test_op dbtestp_isa(Test_env *, Test_meta);
-static const char *dbtestp_getopnd(Test_env *, Test_op, bool);
+static const char *dbtestp_getopnd(Test_env *, Test_op, Wahr);
 static int dbtestp_eval(Test_env *, Test_op, const char *,
-    const char *, bool);
+    const char *, Wahr);
 static void dbtestp_error(Test_env *, int, const char *) MKSH_A_NORETURN;
 
+static void vwarnf(unsigned int, int, const char *, va_list);
+#ifndef MKSH_SMALL
+static void vwarnf0(unsigned int, int, const char *, va_list)
+    MKSH_A_FORMAT(__printf__, 3, 0);
+#else
+#define vwarnf0 vwarnf
+#endif
+
 static struct op *outtree;		/* yyparse output */
 static struct nesting_state nesting;	/* \n changed to ; */
 
-static bool reject;			/* token(cf) gets symbol again */
+static Wahr reject;			/* token(cf) gets symbol again */
 static int symbol;			/* yylex value */
 
-#define REJECT		(reject = true)
-#define ACCEPT		(reject = false)
-#define token(cf)	((reject) ? (ACCEPT, symbol) : (symbol = yylex(cf)))
-#define tpeek(cf)	((reject) ? (symbol) : (REJECT, symbol = yylex(cf)))
-#define musthave(c,cf)	do { 					\
+#define REJECT		(reject = Ja)
+#define ACCEPT		(reject = Nee)
+#define token(cf)	((reject ? 0 : (symbol = yylex(cf))), ACCEPT, symbol)
+#define tpeek(cf)	((reject ? 0 : (symbol = yylex(cf))), REJECT, symbol)
+#define musthave(c,cf)	do {					\
 	if ((unsigned int)token(cf) != (unsigned int)(c))	\
 		syntaxerr(NULL);				\
 } while (/* CONSTCOND */ 0)
@@ -85,7 +95,7 @@ static const char Tcbrace[] = "}";
 static const char Tesac[] = "esac";
 
 static void
-yyparse(bool doalias)
+yyparse(Wahr doalias)
 {
 	int c;
 
@@ -138,11 +148,11 @@ andor(int sALIAS)
 }
 
 static struct op *
-c_list(int sALIAS, bool multi)
+c_list(int sALIAS, Wahr multi)
 {
 	struct op *t = NULL, *p, *tl = NULL;
 	int c;
-	bool have_sep;
+	Wahr have_sep;
 
 	while (/* CONSTCOND */ 1) {
 		p = andor(sALIAS);
@@ -151,7 +161,7 @@ c_list(int sALIAS, bool multi)
 		 * we don't worry about what flags to pass token()
 		 */
 		c = token(0);
-		have_sep = true;
+		have_sep = Ja;
 		if (c == '\n' && (multi || inalias(source))) {
 			if (!p)
 				/* ignore blank lines */
@@ -161,7 +171,7 @@ c_list(int sALIAS, bool multi)
 		else if (c == '&' || c == COPROC)
 			p = block(c == '&' ? TASYNC : TCOPROC, p, NULL);
 		else if (c != ';')
-			have_sep = false;
+			have_sep = Nee;
 		if (!t)
 			t = p;
 		else if (!tl)
@@ -181,19 +191,16 @@ static struct ioword *
 synio(int cf)
 {
 	struct ioword *iop;
-	static struct ioword *nextiop;
-	bool ishere;
-
-	if (nextiop != NULL) {
-		iop = nextiop;
-		nextiop = NULL;
-		return (iop);
-	}
+	Wahr ishere;
 
 	if (tpeek(cf) != REDIR)
 		return (NULL);
 	ACCEPT;
 	iop = yylval.iop;
+	if (iop->ioflag & IOSYNIONEXT) {
+		iop->ioflag &= ~IOSYNIONEXT;
+		return (iop);
+	}
 	ishere = (iop->ioflag & IOTYPE) == IOHERE;
 	if (iop->ioflag & IOHERESTR) {
 		musthave(LWORD, 0);
@@ -216,31 +223,31 @@ synio(int cf)
 		iop->ioname = yylval.cp;
 
 	if (iop->ioflag & IOBASH) {
-		char *cp;
-
-		nextiop = alloc(sizeof(*iop), ATEMP);
-		nextiop->ioname = cp = alloc(3, ATEMP);
-		*cp++ = CHAR;
-		*cp++ = digits_lc[iop->unit % 10];
-		*cp = EOS;
-
 		iop->ioflag &= ~IOBASH;
-		nextiop->unit = 2;
-		nextiop->ioflag = IODUP;
-		nextiop->delim = NULL;
-		nextiop->heredoc = NULL;
+
+		yylval.iop = alloc(sizeof(struct ioword), ATEMP);
+		yylval.iop->ioname = alloc(3U, ATEMP);
+		yylval.iop->ioname[0] = CHAR;
+		yylval.iop->ioname[1] = digits_lc[iop->unit];
+		yylval.iop->ioname[2] = EOS;
+		yylval.iop->delim = NULL;
+		yylval.iop->heredoc = NULL;
+		yylval.iop->ioflag = IODUP | IOSYNIONEXT;
+		yylval.iop->unit = 2;
+		REJECT;
+		symbol = REDIR;
 	}
 	return (iop);
 }
 
 static struct op *
-nested(int type, int smark, int emark, int sALIAS)
+nested(int type, unsigned int smark, unsigned int emark, int sALIAS)
 {
 	struct op *t;
 	struct nesting_state old_nesting;
 
-	nesting_push(&old_nesting, smark);
-	t = c_list(sALIAS, true);
+	nesting_push(&old_nesting, (int)smark);
+	t = c_list(sALIAS, Ja);
 	musthave(emark, KEYWORD|sALIAS);
 	nesting_pop(&old_nesting);
 	return (block(type, t, NULL));
@@ -271,8 +278,8 @@ get_command(int cf, int sALIAS)
 	struct ioword *iop;
 	XPtrV args, vars;
 	struct nesting_state old_nesting;
-	bool check_decl_utility;
-	static struct ioword *iops[NUFILE + 1];
+	Wahr check_decl_utility;
+	struct ioword *iops[NUFILE + 1];
 
 	XPinit(args, 16);
 	XPinit(vars, 16);
@@ -297,7 +304,7 @@ get_command(int cf, int sALIAS)
  get_command_loop:
 		if (XPsize(args) == 0) {
  get_command_start:
-			check_decl_utility = true;
+			check_decl_utility = Ja;
 			cf = sALIAS | CMDASN;
 		} else if (t->u.evalflags)
 			cf = CMDWORD | CMDASN;
@@ -317,16 +324,16 @@ get_command(int cf, int sALIAS)
 			ACCEPT;
 			if (check_decl_utility) {
 				struct tbl *tt = get_builtin(ident);
-				uint32_t flag;
+				kui flag;
 
 				flag = tt ? tt->flag : 0;
 				if (flag & DECL_UTIL)
 					t->u.evalflags = DOVACHECK;
 				if (!(flag & DECL_FWDR))
-					check_decl_utility = false;
+					check_decl_utility = Nee;
 			}
 			if ((XPsize(args) == 0 || Flag(FKEYWORD)) &&
-			    is_wdvarassign(yylval.cp))
+			    is_wdvarassign(yylval.cp, Nee))
 				XPput(vars, yylval.cp);
 			else
 				XPput(args, yylval.cp);
@@ -334,7 +341,7 @@ get_command(int cf, int sALIAS)
 
 		case ORD('(' /*)*/):
 			if (XPsize(args) == 0 && XPsize(vars) == 1 &&
-			    is_wdvarassign(yylval.cp)) {
+			    is_wdvarassign(yylval.cp, Ja)) {
 				char *tcp;
 
 				/* wdarrassign: foo=(bar) */
@@ -376,8 +383,7 @@ get_command(int cf, int sALIAS)
 				syntaxerr(NULL);
 			ACCEPT;
 			musthave(/*(*/ ')', 0);
-			t = function_body(XPptrv(args)[0],
-			    sALIAS, false);
+			t = function_body(XPptrv(args)[0], sALIAS, 0);
 			break;
 		}
 		break;
@@ -438,10 +444,10 @@ get_command(int cf, int sALIAS)
 	case SELECT:
 		t = newtp((c == FOR) ? TFOR : TSELECT);
 		musthave(LWORD, CMDASN);
-		if (!is_wdvarname(yylval.cp, true))
+		if (!is_wdvarname(yylval.cp, Ja))
 			yyerror("%s: bad identifier",
 			    c == FOR ? "for" : Tselect);
-		strdupx(t->str, ident, ATEMP);
+		strdupx(t->op_str, ident, ATEMP);
 		nesting_push(&old_nesting, c);
 		t->vars = wordlist(sALIAS);
 		t->left = dogroup(sALIAS);
@@ -452,15 +458,21 @@ get_command(int cf, int sALIAS)
 	case UNTIL:
 		nesting_push(&old_nesting, c);
 		t = newtp((c == WHILE) ? TWHILE : TUNTIL);
-		t->left = c_list(sALIAS, true);
+		t->left = c_list(sALIAS, Ja);
+		if (!t->left)
+			syntaxerr(NULL);
 		t->right = dogroup(sALIAS);
+#ifndef MKSH_SMALL
+		if (!t->right)
+			syntaxerr(NULL);
+#endif
 		nesting_pop(&old_nesting);
 		break;
 
 	case CASE:
 		t = newtp(TCASE);
 		musthave(LWORD, 0);
-		t->str = yylval.cp;
+		t->op_str = yylval.cp;
 		nesting_push(&old_nesting, c);
 		t->left = caselist(sALIAS);
 		nesting_pop(&old_nesting);
@@ -469,7 +481,7 @@ get_command(int cf, int sALIAS)
 	case IF:
 		nesting_push(&old_nesting, c);
 		t = newtp(TIF);
-		t->left = c_list(sALIAS, true);
+		t->left = c_list(sALIAS, Ja);
 		t->right = thenpart(sALIAS);
 		musthave(FI, KEYWORD|sALIAS);
 		nesting_pop(&old_nesting);
@@ -486,18 +498,29 @@ get_command(int cf, int sALIAS)
 	case TIME:
 		syniocf &= ~(KEYWORD|sALIAS);
 		t = pipeline(0, sALIAS);
-		if (t && t->type == TCOM) {
-			t->str = alloc(2, ATEMP);
-			/* TF_* flags */
-			t->str[0] = '\0';
-			t->str[1] = '\0';
-		}
 		t = block(TTIME, t, NULL);
 		break;
 
 	case FUNCTION:
+		XPsize(args) = 0;
+		if (tpeek(0) == '(') {
+			const char *p;
+
+			ACCEPT;
+			while (tpeek(CONTIN) != ')') {
+				musthave(LWORD, CONTIN);
+				p = skip_wdvarname(yylval.cp, Nee);
+				if (p == yylval.cp || (*p != EOS &&
+				    (*p != CHAR || p[1] != '=')))
+					syntaxerr("expected parameter, not");
+				ACCEPT;
+				XPput(args, yylval.cp);
+			}
+			ACCEPT;
+			XPput(args, NULL);
+		}
 		musthave(LWORD, 0);
-		t = function_body(yylval.cp, sALIAS, true);
+		t = function_body(yylval.cp, sALIAS, XPsize(args) > 0 ? 2 : 1);
 		break;
 	}
 
@@ -520,6 +543,15 @@ get_command(int cf, int sALIAS)
 		t->args = (const char **)XPclose(args);
 		XPput(vars, NULL);
 		t->vars = (char **)XPclose(vars);
+	} else if (t->type == TFUNCT && t->u.charflag && XPsize(args) > 0) {
+		struct op *xt;
+
+		xt = newtp(TEXFUNC);
+		xt->args = (const char **)XPclose(args);
+		XPfree(vars);
+		xt->left = t->left;
+		xt->lineno = t->lineno;
+		t->left = xt;
 	} else {
 		XPfree(args);
 		XPfree(vars);
@@ -553,7 +585,7 @@ dogroup(int sALIAS)
 		c = ORD('}');
 	else
 		syntaxerr(NULL);
-	list = c_list(sALIAS, true);
+	list = c_list(sALIAS, Ja);
 	musthave(c, KEYWORD|sALIAS);
 	return (list);
 }
@@ -565,7 +597,7 @@ thenpart(int sALIAS)
 
 	musthave(THEN, KEYWORD|sALIAS);
 	t = newtp(0);
-	t->left = c_list(sALIAS, true);
+	t->left = c_list(sALIAS, Ja);
 	if (t->left == NULL)
 		syntaxerr(NULL);
 	t->right = elsepart(sALIAS);
@@ -579,13 +611,13 @@ elsepart(int sALIAS)
 
 	switch (token(KEYWORD|sALIAS|CMDASN)) {
 	case ELSE:
-		if ((t = c_list(sALIAS, true)) == NULL)
+		if ((t = c_list(sALIAS, Ja)) == NULL)
 			syntaxerr(NULL);
 		return (t);
 
 	case ELIF:
 		t = newtp(TELIF);
-		t->left = c_list(sALIAS, true);
+		t->left = c_list(sALIAS, Ja);
 		t->right = thenpart(sALIAS);
 		return (t);
 
@@ -655,7 +687,7 @@ casepart(int endtok, int sALIAS)
 	t->vars = (char **)XPclose(ptns);
 	musthave(ORD(')'), 0);
 
-	t->left = c_list(sALIAS, true);
+	t->left = c_list(sALIAS, Ja);
 
 	/* initialise to default for ;; or omitted */
 	t->u.charflag = ORD(';');
@@ -680,8 +712,8 @@ casepart(int endtok, int sALIAS)
 
 static struct op *
 function_body(char *name, int sALIAS,
-    /* function foo { ... } vs foo() { .. } */
-    bool ksh_func)
+    /* 0=foo() { … }; 1=function foo { … }; 2=function () foo { … } */
+    int ksh_func)
 {
 	char *sname, *p;
 	struct op *t;
@@ -693,9 +725,10 @@ function_body(char *name, int sALIAS,
 	 * have allowed more; the following were never allowed:
 	 *	NUL TAB NL SP " $ & ' ( ) ; < = > \ ` |
 	 * C_QUOTE|C_SPC covers all but adds # * ? [ ]
+	 * CiQCM, as desired, adds / but also ^ (as collateral)
 	 */
 	for (p = sname; *p; p++)
-		if (ctype(*p, C_QUOTE | C_SPC))
+		if (ctype(*p, C_QUOTE | C_SPC | CiQCM))
 			yyerror(Tinvname, sname, Tfunction);
 
 	/*
@@ -704,21 +737,25 @@ function_body(char *name, int sALIAS,
 	 * shouldn't break anything. However, for function foo, AT&T ksh
 	 * only accepts an open-brace.
 	 */
-	if (ksh_func) {
+	switch (ksh_func) {
+	case 1:
 		if ((unsigned int)tpeek(CONTIN|KEYWORD|sALIAS) == ORD('(' /*)*/)) {
 			/* function foo () { //}*/
 			ACCEPT;
 			musthave(ORD(/*(*/ ')'), 0);
 			/* degrade to POSIX function */
-			ksh_func = false;
+			ksh_func = Nee;
 		}
+		/* FALLTHROUGH */
+	case 2:
 		musthave(ORD('{' /*}*/), CONTIN|KEYWORD|sALIAS);
 		REJECT;
+		break;
 	}
 
 	t = newtp(TFUNCT);
-	t->str = sname;
-	t->u.ksh_func = tobool(ksh_func);
+	t->op_str = sname;
+	t->u.charflag = ksh_func ? 1 : 0;
 	t->lineno = source->line;
 
 	if ((t->left = get_command(CONTIN, sALIAS)) == NULL) {
@@ -788,37 +825,37 @@ static const struct tokeninfo {
 	short reserved;
 } tokentab[] = {
 	/* Reserved words */
-	{ "if",		IF,	true },
-	{ "then",	THEN,	true },
-	{ "else",	ELSE,	true },
-	{ "elif",	ELIF,	true },
-	{ "fi",		FI,	true },
-	{ "case",	CASE,	true },
-	{ Tesac,	ESAC,	true },
-	{ "for",	FOR,	true },
-	{ Tselect,	SELECT,	true },
-	{ "while",	WHILE,	true },
-	{ "until",	UNTIL,	true },
-	{ "do",		DO,	true },
-	{ "done",	DONE,	true },
-	{ "in",		IN,	true },
-	{ Tfunction,	FUNCTION, true },
-	{ Ttime,	TIME,	true },
-	{ "{",		ORD('{'), true },
-	{ Tcbrace,	ORD('}'), true },
-	{ "!",		BANG,	true },
-	{ "[[",		DBRACKET, true },
+	{ "if",		IF,		Ja },
+	{ "then",	THEN,		Ja },
+	{ "else",	ELSE,		Ja },
+	{ "elif",	ELIF,		Ja },
+	{ "fi",		FI,		Ja },
+	{ "case",	CASE,		Ja },
+	{ Tesac,	ESAC,		Ja },
+	{ "for",	FOR,		Ja },
+	{ Tselect,	SELECT,		Ja },
+	{ "while",	WHILE,		Ja },
+	{ "until",	UNTIL,		Ja },
+	{ "do",		DO,		Ja },
+	{ "done",	DONE,		Ja },
+	{ "in",		IN,		Ja },
+	{ Tfunction,	FUNCTION,	Ja },
+	{ Ttime,	TIME,		Ja },
+	{ "{",		ORD('{'),	Ja },
+	{ Tcbrace,	ORD('}'),	Ja },
+	{ "!",		BANG,		Ja },
+	{ "[[",		DBRACKET,	Ja },
 	/* Lexical tokens (0[EOF], LWORD and REDIR handled specially) */
-	{ "&&",		LOGAND,	false },
-	{ "||",		LOGOR,	false },
-	{ ";;",		BREAK,	false },
-	{ ";|",		BRKEV,	false },
-	{ ";&",		BRKFT,	false },
-	{ "((",		MDPAREN, false },
-	{ "|&",		COPROC,	false },
+	{ "&&",		LOGAND,		Nee },
+	{ "||",		LOGOR,		Nee },
+	{ ";;",		BREAK,		Nee },
+	{ ";|",		BRKEV,		Nee },
+	{ ";&",		BRKFT,		Nee },
+	{ "((",		MDPAREN,	Nee },
+	{ "|&",		COPROC,		Nee },
 	/* and some special cases... */
-	{ "newline",	ORD('\n'), false },
-	{ NULL,		0,	false }
+	{ "newline",	ORD('\n'),	Nee },
+	{ NULL,		0,		Nee }
 };
 
 void
@@ -843,8 +880,6 @@ initkeywords(void)
 static void
 syntaxerr(const char *what)
 {
-	/* 23<<- is the longest redirection, I think */
-	char redir[8];
 	const char *s;
 	struct tokeninfo const *tt;
 	int c;
@@ -871,7 +906,7 @@ syntaxerr(const char *what)
 		break;
 
 	case REDIR:
-		s = snptreef(redir, sizeof(redir), Tft_R, yylval.iop);
+		s = stripioact(yylval.iop);
 		break;
 
 	default:
@@ -880,15 +915,10 @@ syntaxerr(const char *what)
 			    break;
 		if (tt->name)
 			s = tt->name;
-		else {
-			if (c > 0 && c < 256) {
-				redir[0] = c;
-				redir[1] = '\0';
-			} else
-				shf_snprintf(redir, sizeof(redir),
-					"?%d", c);
-			s = redir;
-		}
+		else if (c > 0 && c < 256)
+			s = shf_smprintf("%c", c);
+		else
+			s = shf_smprintf("?%d", c);
 	}
 	yyerror(Tf_sD_s_qs, Tsynerr, what, s);
 }
@@ -913,25 +943,27 @@ newtp(int type)
 	struct op *t;
 
 	t = alloc(sizeof(struct op), ATEMP);
-	t->type = type;
-	t->u.evalflags = 0;
 	t->args = NULL;
 	t->vars = NULL;
 	t->ioact = NULL;
 	t->left = t->right = NULL;
-	t->str = NULL;
+	if (type == TCOM)
+		t->op_flag = 0;
+	else
+		t->op_str = NULL;
+	t->lineno = 0;
+	t->type = type;
+	t->u.evalflags = 0;
 	return (t);
 }
 
 struct op *
-compile(Source *s, bool skiputf8bom, bool doalias)
+compile(Source *s, Wahr doalias)
 {
 	nesting.start_token = 0;
 	nesting.start_line = 0;
 	herep = heres;
 	source = s;
-	if (skiputf8bom)
-		yyskiputf8bom();
 	yyparse(doalias);
 	return (outtree);
 }
@@ -948,7 +980,6 @@ inalias(struct source *s)
 	return (0);
 }
 
-
 /*
  * Order important - indexed by Test_meta values
  * Note that ||, &&, ( and ) can't appear in as unquoted strings
@@ -977,7 +1008,7 @@ static Test_op
 dbtestp_isa(Test_env *te, Test_meta meta)
 {
 	int c = tpeek(CMDASN | (meta == TM_BINOP ? 0 : CONTIN));
-	bool uqword;
+	Wahr uqword;
 	char *save = NULL;
 	Test_op ret = TO_NONOP;
 
@@ -1020,7 +1051,7 @@ dbtestp_isa(Test_env *te, Test_meta meta
 
 static const char *
 dbtestp_getopnd(Test_env *te, Test_op op MKSH_A_UNUSED,
-    bool do_eval MKSH_A_UNUSED)
+    Wahr do_eval MKSH_A_UNUSED)
 {
 	int c = tpeek(CMDASN);
 
@@ -1036,7 +1067,7 @@ dbtestp_getopnd(Test_env *te, Test_op op
 static int
 dbtestp_eval(Test_env *te MKSH_A_UNUSED, Test_op op MKSH_A_UNUSED,
     const char *opnd1 MKSH_A_UNUSED, const char *opnd2 MKSH_A_UNUSED,
-    bool do_eval MKSH_A_UNUSED)
+    Wahr do_eval MKSH_A_UNUSED)
 {
 	return (1);
 }
@@ -1057,41 +1088,49 @@ dbtestp_error(Test_env *te, int offset,
 }
 
 #if HAVE_SELECT
-
-#ifndef EOVERFLOW
-#ifdef ERANGE
-#define EOVERFLOW	ERANGE
-#else
-#define EOVERFLOW	EINVAL
-#endif
-#endif
-
-bool
+Wahr
 parse_usec(const char *s, struct timeval *tv)
 {
-	struct timeval tt;
 	int i;
 
 	tv->tv_sec = 0;
 	/* parse integral part */
-	while (ctype(*s, C_DIGIT)) {
-		tt.tv_sec = tv->tv_sec * 10 + ksh_numdig(*s++);
-		/*XXX this overflow check maybe UB */
-		if (tt.tv_sec / 10 != tv->tv_sec) {
-			errno = EOVERFLOW;
-			return (true);
+#define mbiCfail do { errno = EOVERFLOW; return (Ja); } while (/* CONSTCOND */ 0)
+	if (mbiTYPE_ISF(time_t)) {
+		time_t tt = 0;
+
+		while (ctype(*s, C_DIGIT))
+			tt = tt * 10 + ksh_numdig(*s++);
+		mbiCAAlet(tv->tv_sec, time_t, tt);
+	} else if (mbiTYPE_ISU(time_t)) {
+		time_t tt = 0;
+
+		while (ctype(*s, C_DIGIT)) {
+			mbiCAUmul(time_t, tt, 10);
+			mbiCAUadd(tt, ksh_numdig(*s));
+			++s;
+		}
+		mbiCAAlet(tv->tv_sec, time_t, tt);
+	} else {
+		mbiHUGE_S tt = 0;
+
+		while (ctype(*s, C_DIGIT)) {
+			mbiCAPmul(mbiHUGE_S, tt, 10);
+			mbiCAPadd(mbiHUGE_S, tt, ksh_numdig(*s));
+			++s;
 		}
-		tv->tv_sec = tt.tv_sec;
+		mbiCASlet(time_t, tv->tv_sec, mbiHUGE_S, tt);
 	}
+#undef mbiCfail
 
 	tv->tv_usec = 0;
 	if (!*s)
 		/* no decimal fraction */
-		return (false);
+		return (Nee);
 	else if (*s++ != '.') {
 		/* junk after integral part */
 		errno = EINVAL;
-		return (true);
+		return (Ja);
 	}
 
 	/* parse decimal fraction */
@@ -1107,11 +1146,11 @@ parse_usec(const char *s, struct timeval
 		++s;
 	if (*s) {
 		errno = EINVAL;
-		return (true);
+		return (Ja);
 	}
 
 	/* end of input string reached, no errors */
-	return (false);
+	return (Nee);
 }
 #endif
 
@@ -1152,7 +1191,7 @@ yyrecursive(int subtype)
 	e->yyrecursive_statep = ys;
 	/* we use TPAREN as a helper container here */
 	t = nested(TPAREN, stok, etok, ALIAS);
-	yyrecursive_pop(false);
+	yyrecursive_pop(Nee);
 
 	/* t->left because nested(TPAREN, ...) hides our goodies there */
 	cp = snptreef(NULL, 0, Tf_T, t->left);
@@ -1162,7 +1201,7 @@ yyrecursive(int subtype)
 }
 
 void
-yyrecursive_pop(bool popall)
+yyrecursive_pop(Wahr popall)
 {
 	struct yyrecursive_state *ys;
 
@@ -1182,3 +1221,284 @@ yyrecursive_pop(bool popall)
 	if (popall)
 		goto popnext;
 }
+
+void
+yyerror(const char *fmt, ...)
+{
+	va_list ap;
+
+	/* pop aliases and re-reads */
+	while (source->type == SALIAS || source->type == SREREAD)
+		source = source->next;
+	/* zap pending input */
+	source->str = null;
+
+	va_start(ap, fmt);
+	vwarnf0(KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE | KWF_NOERRNO,
+	    0, fmt, ap);
+	va_end(ap);
+	unwind(LSHELL);
+}
+
+/* used by error reporting functions to print "ksh: .kshrc[25]: " */
+Wahr
+error_prefix(Wahr fileline)
+{
+	Wahr kshname_shown = Nee;
+
+	/* Avoid foo: foo[2]: ... */
+	if (!fileline || !source || !source->file ||
+	    strcmp(source->file, kshname) != 0) {
+		kshname_shown = Ja;
+		shf_puts(kshname + (isch(*kshname, '-') ? 1 : 0), shl_out);
+		shf_putc_i(':', shl_out);
+		shf_putc_i(' ', shl_out);
+	}
+	if (fileline && source && source->file != NULL) {
+		shf_fprintf(shl_out, "%s[%d]: ", source->file, source->errline ?
+		    source->errline : source->line);
+		source->errline = 0;
+	}
+	return (kshname_shown);
+}
+
+/* error reporting functions */
+
+static void
+vwarnf(unsigned int flags, int verrno, const char *fmt, va_list ap)
+{
+	int rept = 0;
+	Wahr show_builtin_argv0 = Nee;
+
+	if (HAS(flags, KWF_ERROR)) {
+		if (HAS(flags, KWF_INTERNAL))
+			shf_write(SC("internal error: "), shl_out);
+		else
+			shf_write(SC("E: "), shl_out);
+		/* additional things to do on error */
+		exstat = flags & KWF_EXSTAT;
+		if (HAS(flags, KWF_INTERNAL) && trap_exstat != -1)
+			trap_exstat = exstat;
+		/* debugging: note that stdout not valid */
+		shl_stdout_ok = Nee;
+	} else {
+		if (HAS(flags, KWF_INTERNAL))
+			shf_write(SC("internal warning: "), shl_out);
+		else
+			shf_write(SC("W: "), shl_out);
+	}
+	if (HAS(flags, KWF_BUILTIN) &&
+	    /* not set when main() calls parse_args() */
+	    builtin_argv0 && builtin_argv0 != kshname)
+		show_builtin_argv0 = Ja;
+	if (HAS(flags, KWF_PREFIX) && error_prefix(HAS(flags, KWF_FILELINE)) &&
+	    show_builtin_argv0) {
+		const char *kshbasename;
+
+		kshname_islogin(&kshbasename);
+		show_builtin_argv0 = strcmp(builtin_argv0, kshbasename) != 0;
+	}
+	if (show_builtin_argv0) {
+		shf_puts(builtin_argv0, shl_out);
+		shf_putc_i(':', shl_out);
+		shf_putc_i(' ', shl_out);
+	}
+	switch (flags & KWF_MSGMASK) {
+	default:
+#undef shf_vfprintf
+		shf_vfprintf(shl_out, fmt, ap);
+#define shf_vfprintf poisoned_shf_vfprintf
+		break;
+	case KWF_THREEMSG:
+		rept = 2;
+		if (0)
+			/* FALLTHROUGH */
+	case KWF_TWOMSG:
+		  rept = 1;
+		/* FALLTHROUGH */
+	case KWF_ONEMSG:
+		while (/* CONSTCOND */ 1) {
+			shf_puts(fmt ? fmt : Tnil, shl_out);
+			if (!rept--)
+				break;
+			shf_putc_i(':', shl_out);
+			shf_putc_i(' ', shl_out);
+			fmt = va_arg(ap, const char *);
+		}
+		break;
+	}
+	if (!HAS(flags, KWF_NOERRNO)) {
+		/* compare shf.c */
+#if !HAVE_STRERROR
+		shf_putc_i(':', shl_out);
+		shf_putc_i(' ', shl_out);
+		shf_putsv(cstrerror(verrno), shl_out);
+#else
+		/* may be nil */
+		shf_fprintf(shl_out, ": %s", cstrerror(verrno));
+#endif
+	}
+	shf_putc_i('\n', shl_out);
+	shf_flush(shl_out);
+}
+
+#ifndef MKSH_SMALL
+static void
+vwarnf0(unsigned int flags, int verrno, const char *fmt, va_list ap)
+{
+	vwarnf(flags, verrno, fmt, ap);
+}
+#endif
+
+void
+kwarnf(unsigned int flags, ...)
+{
+	const char *fmt;
+	va_list ap;
+	int verrno;
+
+	verrno = errno;
+
+	va_start(ap, flags);
+	if (HAS(flags, KWF_VERRNO))
+		verrno = va_arg(ap, int);
+	fmt = va_arg(ap, const char *);
+	vwarnf(flags, verrno, fmt, ap);
+	va_end(ap);
+	if (HAS(flags, KWF_BIUNWIND))
+		bi_unwind(0);
+}
+
+#ifndef MKSH_SMALL
+void
+kwarnf0(unsigned int flags, const char *fmt, ...)
+{
+	va_list ap;
+	int verrno;
+
+	verrno = errno;
+
+	va_start(ap, fmt);
+	vwarnf0(flags, verrno, fmt, ap);
+	va_end(ap);
+	if (HAS(flags, KWF_BIUNWIND))
+		bi_unwind(0);
+}
+
+void
+kwarnf1(unsigned int flags, int verrno, const char *fmt, ...)
+{
+	va_list ap;
+
+	va_start(ap, fmt);
+	vwarnf0(flags, verrno, fmt, ap);
+	va_end(ap);
+	if (HAS(flags, KWF_BIUNWIND))
+		bi_unwind(0);
+}
+#endif
+
+/* presented by lack of portable variadic macros in early C */
+
+void
+kerrf(unsigned int flags, ...)
+{
+	const char *fmt;
+	va_list ap;
+	int verrno;
+
+	verrno = errno;
+
+	va_start(ap, flags);
+	if (HAS(flags, KWF_VERRNO))
+		verrno = va_arg(ap, int);
+	fmt = va_arg(ap, const char *);
+	vwarnf(flags, verrno, fmt, ap);
+	va_end(ap);
+	unwind(LERROR);
+}
+
+#ifndef MKSH_SMALL
+void
+kerrf0(unsigned int flags, const char *fmt, ...)
+{
+	va_list ap;
+	int verrno;
+
+	verrno = errno;
+
+	va_start(ap, fmt);
+	vwarnf0(flags, verrno, fmt, ap);
+	va_end(ap);
+	unwind(LERROR);
+}
+
+#if 0 /* not used */
+void
+kerrf1(unsigned int flags, int verrno, const char *fmt, ...)
+{
+	va_list ap;
+
+	va_start(ap, fmt);
+	vwarnf0(flags, verrno, fmt, ap);
+	va_end(ap);
+	unwind(LERROR);
+}
+#endif
+#endif
+
+/* maybe error, maybe builtin error; use merrf() macro */
+void
+merrF(int *ep, unsigned int flags, ...)
+{
+	const char *fmt;
+	va_list ap;
+	int verrno;
+
+	verrno = errno;
+
+	if (ep)
+		flags |= KWF_BUILTIN;
+
+	va_start(ap, flags);
+	if (HAS(flags, KWF_VERRNO))
+		verrno = va_arg(ap, int);
+	fmt = va_arg(ap, const char *);
+	vwarnf(flags, verrno, fmt, ap);
+	va_end(ap);
+
+	if (ep) {
+		*ep = exstat;
+		bi_unwind(0);
+	} else
+		unwind(LERROR);
+}
+
+/* transform warning into bi_errorf */
+void
+bi_unwind(int rc)
+{
+	if (rc)
+		exstat = rc;
+	/* debugging: note that stdout not valid */
+	shl_stdout_ok = Nee;
+
+	/* POSIX special builtins cause non-interactive shells to exit */
+	if (builtin_spec) {
+		builtin_argv0 = NULL;
+		/* may not want to use LERROR here */
+		unwind(LERROR);
+	}
+}
+
+/*XXX old */
+void
+bi_errorf(const char *fmt, ...)
+{
+	va_list ap;
+
+	va_start(ap, fmt);
+	vwarnf0(/*XXX*/ KWF_BIERR | KWF_NOERRNO, /*XXX*/ 0, fmt, ap);
+	va_end(ap);
+	bi_unwind(0);
+}
--- mksh-59c.orig/tree.c
+++ mksh-59c/tree.c
@@ -2,8 +2,8 @@
 
 /*-
  * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
- *		 2011, 2012, 2013, 2015, 2016, 2017
- *	mirabilos <m@mirbsd.org>
+ *		 2011, 2012, 2013, 2015, 2016, 2017, 2021, 2025
+ *	mirabilos <m$(date +%Y)@mirbsd.de>
  *
  * Provided that these terms and disclaimer and all copyright notices
  * are retained or reproduced in an accompanying document, permission
@@ -23,30 +23,33 @@
 
 #include "sh.h"
 
-__RCSID("$MirOS: src/bin/mksh/tree.c,v 1.100 2020/10/31 04:28:54 tg Exp $");
+__RCSID("$MirOS: src/bin/mksh/tree.c,v 1.118 2025/12/24 04:51:56 tg Exp $");
 
 #define INDENT	8
 
 static void ptree(struct op *, int, struct shf *);
-static void pioact(struct shf *, struct ioword *);
 static const char *wdvarput(struct shf *, const char *, int, int);
 static void vfptreef(struct shf *, int, const char *, va_list);
 static struct ioword **iocopy(struct ioword **, Area *);
 static void iofree(struct ioword **, Area *);
 
 /* "foo& ; bar" and "foo |& ; bar" are invalid */
-static bool prevent_semicolon;
+static Wahr prevent_semicolon;
 
 /* here document diversion */
 static unsigned short ptree_nest;
-static bool ptree_hashere;
+static Wahr ptree_hashere;
 static struct shf ptree_heredoc;
 #define ptree_outhere(shf) do {					\
 	if (ptree_hashere) {					\
-		shf_puts(shf_sclose(&ptree_heredoc), (shf));	\
+		char *ptree_thehere;				\
+								\
+		ptree_thehere = shf_sclose(&ptree_heredoc);	\
+		shf_puts(ptree_thehere, (shf));			\
 		shf_putc('\n', (shf));				\
-		ptree_hashere = false;				\
-		/*prevent_semicolon = true;*/			\
+		afree(ptree_thehere, ATEMP);			\
+		ptree_hashere = Nee;				\
+		/*prevent_semicolon = Ja;*/			\
 	}							\
 } while (/* CONSTCOND */ 0)
 
@@ -69,7 +72,7 @@ ptree(struct op *t, int indent, struct s
 		return;
 	switch (t->type) {
 	case TCOM:
-		prevent_semicolon = false;
+		prevent_semicolon = Nee;
 		/* special-case 'var=<<EOF' (cf. exec.c:execute) */
 		if (t->args &&
 		    /* we have zero arguments, i.e. no program to run */
@@ -82,7 +85,7 @@ ptree(struct op *t, int indent, struct s
 		    /* of type "here document" (or "here string") */
 		    (t->ioact[0]->ioflag & IOTYPE) == IOHERE &&
 		    /* the variable assignment begins with a valid varname */
-		    (ccp = skip_wdvarname(t->vars[0], true)) != t->vars[0] &&
+		    (ccp = skip_wdvarname(t->vars[0], Ja)) != t->vars[0] &&
 		    /* and has no right-hand side (i.e. "varname=") */
 		    ccp[0] == CHAR && ((ccp[1] == '=' && ccp[2] == EOS) ||
 		    /* or "varname+=" */ (ccp[1] == '+' && ccp[2] == CHAR &&
@@ -140,7 +143,7 @@ ptree(struct op *t, int indent, struct s
 		break;
 	case TBANG:
 		shf_puts("! ", shf);
-		prevent_semicolon = false;
+		prevent_semicolon = Nee;
 		t = t->right;
 		goto Chain;
 	case TDBRACKET:
@@ -153,7 +156,7 @@ ptree(struct op *t, int indent, struct s
 	case TSELECT:
 	case TFOR:
 		fptreef(shf, indent, "%s %s ",
-		    (t->type == TFOR) ? "for" : Tselect, t->str);
+		    (t->type == TFOR) ? "for" : Tselect, t->op_str);
 		if (t->vars != NULL) {
 			shf_puts("in ", shf);
 			w = (const char **)t->vars;
@@ -165,7 +168,7 @@ ptree(struct op *t, int indent, struct s
 		fptreef(shf, indent, "%;done ");
 		break;
 	case TCASE:
-		fptreef(shf, indent, "case %S in", t->str);
+		fptreef(shf, indent, "case %S in", t->op_str);
 		for (t1 = t->left; t1 != NULL; t1 = t1->right) {
 			fptreef(shf, indent, "%N(");
 			w = (const char **)t1->vars;
@@ -180,7 +183,8 @@ ptree(struct op *t, int indent, struct s
 		fptreef(shf, indent, "%Nesac ");
 		break;
 	case TELIF:
-		internal_errorf(TELIF_unexpected);
+		kerrf(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_ONEMSG | KWF_NOERRNO,
+		    TELIF_unexpected);
 		/* FALLTHROUGH */
 	case TIF:
 		i = 2;
@@ -223,29 +227,41 @@ ptree(struct op *t, int indent, struct s
 		break;
 	case TCOPROC:
 		fptreef(shf, indent, "%T|& ", t->left);
-		prevent_semicolon = true;
+		prevent_semicolon = Ja;
 		break;
 	case TASYNC:
 		fptreef(shf, indent, "%T& ", t->left);
-		prevent_semicolon = true;
+		prevent_semicolon = Ja;
 		break;
 	case TFUNCT:
-		fpFUNCTf(shf, indent, tobool(t->u.ksh_func), t->str, t->left);
+		fpFUNCTf(t->op_str, t->left, shf, indent, isWahr(t->u.charflag));
 		break;
 	case TTIME:
 		fptreef(shf, indent, Tf_s_T, Ttime, t->left);
 		break;
 	default:
 		shf_puts("<botch>", shf);
-		prevent_semicolon = false;
+		prevent_semicolon = Nee;
 		break;
 	}
 	if ((ioact = t->ioact) != NULL)
-		while (*ioact != NULL)
+		while (*ioact != NULL) {
 			pioact(shf, *ioact++);
+			shf_putc(' ', shf);
+		}
 }
 
-static void
+char *
+stripioact(struct ioword *iop)
+{
+	struct shf shf;
+
+	shf_sopen(NULL, 32, SHF_WR | SHF_DYNAMIC, &shf);
+	pioact(&shf, iop);
+	return (shf_sclose(&shf));
+}
+
+void
 pioact(struct shf *shf, struct ioword *iop)
 {
 	unsigned short flag = iop->ioflag;
@@ -276,12 +292,12 @@ pioact(struct shf *shf, struct ioword *i
 			if (!ptree_hashere) {
 				shf_sopen(NULL, 0, SHF_WR | SHF_DYNAMIC,
 				    &ptree_heredoc);
-				ptree_hashere = true;
+				ptree_hashere = Ja;
 			}
 			shf_putc('\n', &ptree_heredoc);
 			shf_puts(iop->heredoc, &ptree_heredoc);
 			/* iop->delim is set before iop->heredoc */
-			shf_puts(evalstr(iop->delim, 0), &ptree_heredoc);
+			shf_putsv(evalstr(iop->delim, 0), &ptree_heredoc);
 		}
  ioheredelim:
 		/* delim is NULL during syntax error printing */
@@ -300,7 +316,8 @@ pioact(struct shf *shf, struct ioword *i
 		shf_puts("<>", shf);
 		break;
 	case IODUP:
-		shf_puts(flag & IORDUP ? "<&" : ">&", shf);
+		shf_putc(flag & IORDUP ? '<' : '>', shf);
+		shf_putc('&', shf);
 		break;
 	}
 	/* name is NULL for IOHERE or when printing syntax errors */
@@ -310,8 +327,7 @@ pioact(struct shf *shf, struct ioword *i
 		else
 			wdvarput(shf, iop->ioname, 0, WDS_TPUTS);
 	}
-	shf_putc(' ', shf);
-	prevent_semicolon = false;
+	prevent_semicolon = Nee;
 }
 
 /* variant of fputs for ptreef and wdstrip */
@@ -416,7 +432,8 @@ wdvarput(struct shf *shf, const char *wp
 			}
 			return (wp);
 		case OPAT:
-			shf_putchar(*wp++, shf);
+			c = *wp++;
+			shf_putc(c, shf);
 			shf_putc('(', shf);
 			break;
 		case SPAT:
@@ -468,18 +485,14 @@ vfptreef(struct shf *shf, int indent, co
 	int c;
 
 	if (!ptree_nest++)
-		ptree_hashere = false;
+		ptree_hashere = Nee;
 
 	while ((c = ord(*fmt++))) {
 		if (c == '%') {
 			switch ((c = ord(*fmt++))) {
-			case ORD('c'):
-				/* character (octet, probably) */
-				shf_putchar(va_arg(va, int), shf);
-				break;
 			case ORD('s'):
 				/* string */
-				shf_puts(va_arg(va, char *), shf);
+				shf_putsv(va_arg(va, char *), shf);
 				break;
 			case ORD('S'):
 				/* word */
@@ -522,14 +535,19 @@ vfptreef(struct shf *shf, int indent, co
 			case ORD('R'):
 				/* I/O redirection */
 				pioact(shf, va_arg(va, struct ioword *));
+				shf_putc(' ', shf);
 				break;
+			case ORD('c'):
+				/* character (octet, probably) */
+				c = va_arg(va, int);
+				/* FALLTHROUGH */
 			default:
 				shf_putc(c, shf);
 				break;
 			}
 		} else
 			shf_putc(c, shf);
-		prevent_semicolon = false;
+		prevent_semicolon = Nee;
  dont_trash_prevent_semicolon:
 		;
 	}
@@ -553,47 +571,62 @@ tcopy(struct op *t, Area *ap)
 
 	r = alloc(sizeof(struct op), ap);
 
-	r->type = t->type;
-	r->u.evalflags = t->u.evalflags;
-
-	if (t->type == TCASE)
-		r->str = wdcopy(t->str, ap);
-	else
-		strdupx(r->str, t->str, ap);
-
-	if (t->vars == NULL)
-		r->vars = NULL;
+	if (t->args == NULL)
+		r->args = NULL;
 	else {
-		tw = (const char **)t->vars;
+		tw = t->args;
 		while (*tw)
 			++tw;
-		rw = r->vars = alloc2(tw - (const char **)t->vars + 1,
-		    sizeof(*tw), ap);
-		tw = (const char **)t->vars;
+		r->args = (const char **)(rw = alloc2(tw - t->args + 1,
+		    sizeof(*tw), ap));
+		tw = t->args;
 		while (*tw)
 			*rw++ = wdcopy(*tw++, ap);
 		*rw = NULL;
 	}
 
-	if (t->args == NULL)
-		r->args = NULL;
+	if (t->vars == NULL)
+		r->vars = NULL;
 	else {
-		tw = t->args;
+		tw = (const char **)t->vars;
 		while (*tw)
 			++tw;
-		r->args = (const char **)(rw = alloc2(tw - t->args + 1,
-		    sizeof(*tw), ap));
-		tw = t->args;
+		rw = r->vars = alloc2(tw - (const char **)t->vars + 1,
+		    sizeof(*tw), ap);
+		tw = (const char **)t->vars;
 		while (*tw)
 			*rw++ = wdcopy(*tw++, ap);
 		*rw = NULL;
 	}
 
 	r->ioact = (t->ioact == NULL) ? NULL : iocopy(t->ioact, ap);
-
 	r->left = tcopy(t->left, ap);
 	r->right = tcopy(t->right, ap);
+
+	switch (t->type) {
+	case TCOM:
+		r->op_flag = t->op_flag;
+		break;
+	case TCASE:
+		r->op_str = wdcopy(t->op_str, ap);
+		break;
+	default:
+		strdupx(r->op_str, t->op_str, ap);
+		break;
+	}
+
 	r->lineno = t->lineno;
+	r->type = t->type;
+
+	switch (t->type) {
+	case TFUNCT:
+	case TPAT:
+		r->u.charflag = t->u.charflag;
+		break;
+	default:
+		r->u.evalflags = t->u.evalflags;
+		break;
+	}
 
 	return (r);
 }
@@ -663,9 +696,9 @@ wdscan(const char *wp, int c)
 				nest--;
 			break;
 		default:
-			internal_warningf(
+			kwarnf0(KWF_INTERNAL | KWF_WARNING | KWF_NOERRNO,
 			    "wdscan: unknown char 0x%X (carrying on)",
-			    (unsigned char)wp[-1]);
+			    KBI(wp[-1]));
 		}
 }
 
@@ -725,7 +758,8 @@ tfree(struct op *t, Area *ap)
 	if (t == NULL)
 		return;
 
-	afree(t->str, ap);
+	if (t->type != TCOM)
+		afree(t->op_str, ap);
 
 	if (t->vars != NULL) {
 		for (w = t->vars; *w != NULL; w++)
@@ -769,9 +803,21 @@ iofree(struct ioword **iow, Area *ap)
 }
 
 void
-fpFUNCTf(struct shf *shf, int i, bool isksh, const char *k, struct op *v)
+fpFUNCTf(const char *k, struct op *v, struct shf *shf, int i, Wahr isksh)
 {
-	if (isksh)
+	if (v->type == TEXFUNC && v->args) {
+		const char **arg = v->args;
+
+		shf_puts(Tfunction, shf);
+		shf_putc(' ', shf);
+		shf_putc('(', shf); /*)*/
+		while (*arg) {
+			if (arg != v->args)
+				shf_putc(' ', shf);
+			wdvarput(shf, *arg++, 0, WDS_TPUTS);
+		}
+		fptreef(shf, i, /*(*/") %s %T", k, v->left);
+	} else if (isksh)
 		fptreef(shf, i, "%s %s %T", Tfunction, k, v);
 	else if (ktsearch(&keywords, k, hash(k)))
 		fptreef(shf, i, "%s %s() %T", Tfunction, k, v);
@@ -779,64 +825,300 @@ fpFUNCTf(struct shf *shf, int i, bool is
 		fptreef(shf, i, "%s() %T", k, v);
 }
 
-
-/* for jobs.c */
 void
-vistree(char *dst, size_t sz, struct op *t)
+uprntc(unsigned char c, struct shf *shf)
+{
+	unsigned char a;
+
+	if (ctype(c, C_PRINT)) {
+ doprnt:
+		shf_putc(c, shf);
+		return;
+	}
+
+	if (!UTFMODE) {
+		if (!ksh_isctrl8(c))
+			goto doprnt;
+		if ((a = rtt2asc(c)) >= 0x80U) {
+			shf_scheck(3, shf);
+			shf_putc('^', shf);
+			shf_putc('!', shf);
+			a &= 0x7FU;
+			goto unctrl;
+		}
+	} else if ((a = rtt2asc(c)) >= 0x80U) {
+		shf_scheck(4, shf);
+		shf_putc('\\', shf);
+		shf_putc('x', shf);
+		shf_putc(digits_uc[(a >> 4) & 0x0F], shf);
+		shf_putc(digits_uc[a & 0x0F], shf);
+		return;
+	}
+	shf_scheck(2, shf);
+	shf_putc('^', shf);
+ unctrl:
+	shf_putc(asc2rtt(a ^ 0x40U), shf);
+}
+
+#ifndef MKSH_NO_CMDLINE_EDITING
+/*
+ * For now, these are only used by the edit code, which requires
+ * a difference: tab is output as three spaces, not as control
+ * character in caret notation. If these will ever be used else‐
+ * where split them up.
+ */
+/*size_t*/ void
+uescmbT(unsigned char *dst, const char **cpp)
 {
-	unsigned int c;
-	char *cp, *buf;
+	unsigned char c;
+	unsigned int wc;
+	size_t n, dstsz = 0;
+	const char *cp = *cpp;
+
+	c = *cp++;
+	/* test cheap first (easiest) */
+	if (ctype(c, C_PRINT)) {
+ prntb:
+		dst[dstsz++] = c;
+		goto out;
+	}
+	/* differently from uprntc, note tab as three spaces */
+	if (ord(c) == CTRL_I) {
+		dst[dstsz++] = ' ';
+		dst[dstsz++] = ' ';
+		dst[dstsz++] = ' ';
+		goto out;
+	}
+
+	/* more specialised tests depend on shell state */
+	if (UTFMODE) {
+		/* wc = rtt2asc(c) except UTF-8 is decoded */
+		if ((n = utf_mbtowc(&wc, cp - 1)) == (size_t)-1) {
+			/* failed: invalid UTF-8 */
+			wc = rtt2asc(c);
+			dst[dstsz++] = '\\';
+			dst[dstsz++] = 'x';
+			dst[dstsz++] = digits_uc[(wc >> 4) & 0x0F];
+			dst[dstsz++] = digits_uc[wc & 0x0F];
+			goto out;
+		}
+		/*
+		 * printable as-is? U+0020‥U+007E already handled
+		 * above as they are C_PRINT, U+00A0 or higher are
+		 * not escaped either, anything in between is special
+		 */
+		if (wc >= 0xA0U) {
+			dst[dstsz++] = c;
+			switch (n) {
+#ifdef notyet
+			case 4:
+				dst[dstsz++] = *cp++;
+				/* FALLTHROUGH */
+#endif
+			case 3:
+				dst[dstsz++] = *cp++;
+				/* FALLTHROUGH */
+			default:
+				dst[dstsz++] = *cp++;
+				break;
+			}
+			goto out;
+		}
+		/* and encoded with either 1 or 2 octets */
+
+		/* C1 control character, UTF-8 encoded */
+		if (wc >= 0x80U) {
+			/* n == 2 so we miss one out */
+			++cp;
+
+			c = '+';
+			goto prntC1;
+		}
+		/* nope, must be C0 or DEL */
+		/* n == 1 so cp needs no adjustment */
+		goto prntC0;
+	}
+
+	/* not UTFMODE allows more but the test is more expensive */
+	if (!ksh_isctrl8(c))
+		goto prntb;
+	/* UTF-8 is not decoded, we just transfer an octet to ASCII */
+	wc = rtt2asc(c);
+	/* C1 control character octet? */
+	if (wc >= 0x80U) {
+		c = '!';
+ prntC1:
+		dst[dstsz++] = '^';
+		dst[dstsz++] = c;
+		wc &= 0x7FU;
+	} else {
+		/* nope, so C0 or DEL, anything else went to prntb */
+ prntC0:
+		dst[dstsz++] = '^';
+	}
+	dst[dstsz++] = asc2rtt(wc ^ 0x40U);
+
+ out:
+	*cpp = cp;
+	dst[dstsz] = '\0';
+#ifdef usedoutsideofedit
+	return (dstsz);
+#endif
+}
+
+int
+uwidthmbT(char *cp, char **dcp)
+{
+	unsigned char c;
+	unsigned int wc;
+	int w;
 	size_t n;
 
-	buf = alloc(sz + 16, ATEMP);
-	snptreef(buf, sz + 16, Tf_T, t);
-	cp = buf;
- vist_loop:
-	if (UTFMODE && (n = utf_mbtowc(&c, cp)) != (size_t)-1) {
-		if (c == 0 || n >= sz)
-			/* NUL or not enough free space */
-			goto vist_out;
-		/* copy multibyte char */
-		sz -= n;
-		while (n--)
-			*dst++ = *cp++;
-		goto vist_loop;
-	}
-	if (--sz == 0 || (c = ord(*cp++)) == 0)
-		/* NUL or not enough free space */
-		goto vist_out;
-	if (ksh_isctrl(c)) {
-		/* C0 or C1 control character or DEL */
-		if (--sz == 0)
-			/* not enough free space for two chars */
-			goto vist_out;
-		*dst++ = '^';
-		c = ksh_unctrl(c);
-	} else if (UTFMODE && rtt2asc(c) > 0x7F) {
-		/* better not try to display broken multibyte chars */
-		/* also go easy on the UCS: no U+FFFD here */
-		c = ORD('?');
-	}
-	*dst++ = c;
-	goto vist_loop;
-
- vist_out:
-	*dst = '\0';
-	afree(buf, ATEMP);
+	c = *cp++;
+	/* test cheap first (easiest) */
+	if (ctype(c, C_PRINT)) {
+ prntb:
+		w = 1;
+		goto out;
+	}
+	/* differently from uprntc, note tab as three spaces */
+	if (ord(c) == CTRL_I) {
+		w = 3;
+		goto out;
+	}
+
+	/* more specialised tests depend on shell state */
+	if (UTFMODE) {
+		/* wc = rtt2asc(c) except UTF-8 is decoded */
+		if ((n = utf_mbtowc(&wc, cp - 1)) == (size_t)-1) {
+			/* \x## */
+			w = 4;
+			goto out;
+		}
+		cp += n - 1;
+		/*
+		 * printable as-is? U+0020‥U+007E already handled
+		 * above as they are C_PRINT, U+00A0 or higher are
+		 * not escaped either, anything in between is special
+		 */
+		if (wc >= 0xA0U) {
+			w = utf_wcwidth(wc);
+			goto out;
+		}
+		/* and encoded with either 1 or 2 octets */
+
+		/* C1 control character, UTF-8 encoded */
+		if (wc >= 0x80U)
+			goto prntC1;
+		/* nope, must be C0 or DEL */
+		goto prntC0;
+	}
+
+	/* not UTFMODE allows more but the test is more expensive */
+	if (!ksh_isctrl8(c))
+		goto prntb;
+	/* UTF-8 is not decoded, we just transfer an octet to ASCII */
+	wc = rtt2asc(c);
+	/* C1 control character octet? */
+	if (wc >= 0x80U) {
+ prntC1:
+		w = 3;
+	} else {
+		/* nope, so C0 or DEL, anything else went to prntb */
+ prntC0:
+		w = 2;
+	}
+
+ out:
+	if (dcp)
+		*dcp = cp;
+	return (w);
 }
+#endif
 
-#ifdef DEBUG
-void
-dumpchar(struct shf *shf, unsigned char c)
+const char *
+uprntmbs(const char *cp, Wahr esc_caret, struct shf *shf)
 {
-	if (ksh_isctrl(c)) {
-		/* C0 or C1 control character or DEL */
-		shf_putc('^', shf);
-		c = ksh_unctrl(c);
+	unsigned char c;
+	unsigned int wc;
+	size_t n;
+
+	while ((c = *cp++) != 0) {
+		/* test cheap first (easiest) */
+		if (ctype(c, C_PRINT)) {
+			if (esc_caret && (c == ORD('\\') || c == ORD('^'))) {
+				shf_scheck(2, shf);
+				shf_putc('\\', shf);
+			}
+ prntb:
+			shf_putc(c, shf);
+			continue;
+		}
+
+		/* more specialised tests depend on shell state */
+		if (UTFMODE) {
+			/* wc = rtt2asc(c) except UTF-8 is decoded */
+			if ((n = utf_mbtowc(&wc, cp - 1)) == (size_t)-1) {
+				/* failed: invalid UTF-8 */
+				wc = rtt2asc(c);
+				shf_scheck(4, shf);
+				shf_putc('\\', shf);
+				shf_putc('x', shf);
+				shf_putc(digits_uc[(wc >> 4) & 0x0F], shf);
+				shf_putc(digits_uc[wc & 0x0F], shf);
+				continue;
+			}
+			/*
+			 * printable as-is? U+0020‥U+007E already handled
+			 * above as they are C_PRINT, U+00A0 or higher are
+			 * not escaped either, anything in between is special
+			 */
+			if (wc >= 0xA0U) {
+				--cp;
+				shf_wr_sm(cp, n, shf);
+				continue;
+			}
+			/* and encoded with either 1 or 2 octets */
+
+			/* C1 control character, UTF-8 encoded */
+			if (wc >= 0x80U) {
+				/* n == 2 so we miss one out */
+				++cp;
+
+				c = '+';
+				goto prntC1;
+			}
+			/* nope, must be C0 or DEL */
+			/* n == 1 so cp needs no adjustment */
+			goto prntC0;
+		}
+
+		/* not UTFMODE allows more but the test is more expensive */
+		if (!ksh_isctrl8(c))
+			goto prntb;
+		/* UTF-8 is not decoded, we just transfer an octet to ASCII */
+		wc = rtt2asc(c);
+		/* C1 control character octet? */
+		if (wc >= 0x80U) {
+			c = '!';
+ prntC1:
+			shf_scheck(3, shf);
+			shf_putc('^', shf);
+			shf_putc(c, shf);
+			wc &= 0x7FU;
+		} else {
+			/* nope, so C0 or DEL, anything else went to prntb */
+ prntC0:
+			shf_scheck(2, shf);
+			shf_putc('^', shf);
+		}
+		shf_putc(asc2rtt(wc ^ 0x40U), shf);
 	}
-	shf_putc(c, shf);
+	/* point to the trailing NUL for continuation */
+	return ((const void *)(cp - 1));
 }
 
+#ifdef DEBUG
 /* see: wdvarput */
 static const char *
 dumpwdvar_i(struct shf *shf, const char *wp, int quotelevel)
@@ -844,7 +1126,7 @@ dumpwdvar_i(struct shf *shf, const char
 	int c;
 
 	while (/* CONSTCOND */ 1) {
-		switch(*wp++) {
+		switch (*wp++) {
 		case EOS:
 			shf_puts("EOS", shf);
 			return (--wp);
@@ -858,7 +1140,7 @@ dumpwdvar_i(struct shf *shf, const char
 				/* FALLTHROUGH */
 		case CHAR:
 			  shf_puts("CHAR=", shf);
-			dumpchar(shf, *wp++);
+			uprntc(*wp++, shf);
 			break;
 		case QCHAR:
 			shf_puts("QCHAR<", shf);
@@ -866,7 +1148,7 @@ dumpwdvar_i(struct shf *shf, const char
 			if (quotelevel == 0 || c == ORD('"') ||
 			    c == ORD('\\') || ctype(c, C_DOLAR | C_GRAVE))
 				shf_putc('\\', shf);
-			dumpchar(shf, c);
+			uprntc(c, shf);
 			goto closeandout;
 		case COMASUB:
 			shf_puts("COMASUB<", shf);
@@ -874,8 +1156,7 @@ dumpwdvar_i(struct shf *shf, const char
 		case COMSUB:
 			shf_puts("COMSUB<", shf);
  dumpsub:
-			while ((c = *wp++) != 0)
-				dumpchar(shf, c);
+			wp = uprntmbs(wp, Nee, shf) + 1;
  closeandout:
 			shf_putc('>', shf);
 			break;
@@ -903,21 +1184,20 @@ dumpwdvar_i(struct shf *shf, const char
 			break;
 		case OSUBST:
 			shf_puts("OSUBST(", shf);
-			dumpchar(shf, *wp++);
+			uprntc(*wp++, shf);
 			shf_puts(")[", shf);
-			while ((c = *wp++) != 0)
-				dumpchar(shf, c);
+			wp = uprntmbs(wp, Nee, shf) + 1;
 			shf_putc('|', shf);
 			wp = dumpwdvar_i(shf, wp, 0);
 			break;
 		case CSUBST:
 			shf_puts("]CSUBST(", shf);
-			dumpchar(shf, *wp++);
+			uprntc(*wp++, shf);
 			shf_putc(')', shf);
 			return (wp);
 		case OPAT:
 			shf_puts("OPAT=", shf);
-			dumpchar(shf, *wp++);
+			uprntc(*wp++, shf);
 			break;
 		case SPAT:
 			shf_puts("SPAT", shf);
@@ -926,7 +1206,7 @@ dumpwdvar_i(struct shf *shf, const char
 			shf_puts("CPAT", shf);
 			break;
 		default:
-			shf_fprintf(shf, "INVAL<%u>", (uint8_t)wp[-1]);
+			shf_fprintf(shf, "INVAL<%u>", (kby)wp[-1]);
 			break;
 		}
 		shf_putc(' ', shf);
@@ -1010,7 +1290,7 @@ dumptree(struct shf *shf, struct op *t)
 	++nesting;
 	shf_puts("{tree:" /*}*/, shf);
 	if (t == NULL) {
-		name = "(null)";
+		name = Tnil;
 		goto out;
 	}
 	dumpioact(shf, t);
@@ -1059,7 +1339,7 @@ dumptree(struct shf *shf, struct op *t)
 		shf_putc('\n', shf);
 		dumptree(shf, t->left);
 /* middumprightandout: (unused) */
-		shf_fprintf(shf, "/%s:", name);
+		shf_fprintf(shf, " /%s:", name);
  dumprightandout:
 		t = t->right;
 		goto dumpandout;
@@ -1085,7 +1365,7 @@ dumptree(struct shf *shf, struct op *t)
 		break;
 	OPEN(TFOR)
  dumpfor:
-		shf_fprintf(shf, " str<%s>", t->str);
+		shf_fprintf(shf, " str<%s>", t->op_str);
 		if (t->vars != NULL) {
 			i = 0;
 			w = (const char **)t->vars;
@@ -1102,7 +1382,7 @@ dumptree(struct shf *shf, struct op *t)
 	OPEN(TSELECT)
 		goto dumpfor;
 	OPEN(TCASE)
-		shf_fprintf(shf, " str<%s>", t->str);
+		shf_fprintf(shf, " str<%s>", t->op_str);
 		i = 0;
 		for (t1 = t->left; t1 != NULL; t1 = t1->right) {
 			shf_putc('\n', shf);
@@ -1134,8 +1414,22 @@ dumptree(struct shf *shf, struct op *t)
 	OPEN(TASYNC)
 		goto dumpleftandout;
 	OPEN(TFUNCT)
-		shf_fprintf(shf, " str<%s> ksh<%s>", t->str,
-		    t->u.ksh_func ? Ttrue : Tfalse);
+		shf_fprintf(shf, " str<%s> ksh<%s>", t->op_str,
+		    t->u.charflag ? Ttrue : Tfalse);
+		if (t->left && t->left->type == TEXFUNC)
+			t = t->left;
+		if (t->args) {
+			i = 0;
+			w = t->args;
+			while (*w) {
+				shf_putc('\n', shf);
+				for (j = 0; j < nesting; ++j)
+					shf_putc('\t', shf);
+				shf_fprintf(shf, " arg%d<", i++);
+				dumpwdvar(shf, *w++);
+				shf_putc('>', shf);
+			}
+		}
 		goto dumpleftandout;
 	OPEN(TTIME)
 		goto dumpleftandout;
@@ -1179,4 +1473,47 @@ dumptree(struct shf *shf, struct op *t)
 	shf_fprintf(shf, /*{*/ " /%s}\n", name);
 	--nesting;
 }
+
+void
+dumphex(struct shf *shf, const void *buf, size_t len)
+{
+	const kby *s = buf;
+	size_t i = 0;
+
+	if (!len--) {
+		shf_puts("00000000  <\n", shf);
+		goto out;
+	}
+
+ loop:
+	if ((i & 0xFU) == 0x0U)
+		shf_fprintf(shf, "%08zX  ", i);
+	else if ((i & 0xFU) == 0x8U)
+		shf_puts("- ", shf);
+	shf_fprintf(shf, "%02X%c", ord(s[i]), i == len ? '<' : ' ');
+	if (i < len && (i & 0xFU) != 0xFU) {
+		++i;
+		goto loop;
+	}
+	while ((i & 0xFU) != 0xFU) {
+		++i;
+		if ((i & 0xFU) == 0x8U)
+			shf_puts("  ", shf);
+		shf_puts("   ", shf);
+	}
+	shf_puts(" |", shf);
+	i &= (size_t)~(size_t)0xFU;
+ visloop:
+	if (i <= len) {
+		shf_putc(ctype(s[i], C_PRINT) ? ord(s[i]) : '.', shf);
+		++i;
+		if ((i & 0xFU) != 0x0U)
+			goto visloop;
+	}
+	shf_puts("|\n", shf);
+	if (i <= len)
+		goto loop;
+ out:
+	shf_flush(shf);
+}
 #endif
--- mksh-59c.orig/ulimit.c
+++ mksh-59c/ulimit.c
@@ -3,8 +3,8 @@
 /*-
  * Copyright (c) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
  *		 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017,
- *		 2019, 2020
- *	mirabilos <m@mirbsd.org>
+ *		 2019, 2020, 2021, 2022, 2023
+ *	mirabilos <m$(date +%Y)@mirbsd.de>
  *
  * Provided that these terms and disclaimer and all copyright notices
  * are retained or reproduced in an accompanying document, permission
@@ -24,68 +24,76 @@
 
 #include "sh.h"
 
-__RCSID("$MirOS: src/bin/mksh/ulimit.c,v 1.3 2020/07/24 21:08:26 tg Exp $");
+__RCSID("$MirOS: src/bin/mksh/ulimit.c,v 1.19 2025/06/01 01:10:32 tg Exp $");
 
 #define SOFT	0x1
 #define HARD	0x2
 
 #if HAVE_RLIMIT
 
-#if !HAVE_RLIM_T
-typedef unsigned long rlim_t;
-#endif
-
 /* Magic to divine the 'm' and 'v' limits */
 
+#undef MKHL_AS
+#undef MKHL_VMEM
+#undef MKHL_RSS
+
 #ifdef RLIMIT_AS
-#if !defined(RLIMIT_VMEM) || (RLIMIT_VMEM == RLIMIT_AS) || \
-    !defined(RLIMIT_RSS) || (RLIMIT_VMEM == RLIMIT_RSS)
-#define ULIMIT_V_IS_AS
-#elif defined(RLIMIT_VMEM)
-#if !defined(RLIMIT_RSS) || (RLIMIT_RSS == RLIMIT_AS)
-#define ULIMIT_V_IS_AS
-#else
-#define ULIMIT_V_IS_VMEM
-#endif
+#define MKHL_AS
 #endif
+
+#ifdef RLIMIT_VMEM
+#define MKHL_VMEM
 #endif
 
 #ifdef RLIMIT_RSS
-#ifdef ULIMIT_V_IS_VMEM
-#define ULIMIT_M_IS_RSS
-#elif defined(RLIMIT_VMEM) && (RLIMIT_VMEM == RLIMIT_RSS)
-#define ULIMIT_M_IS_VMEM
-#else
-#define ULIMIT_M_IS_RSS
-#endif
-#if defined(ULIMIT_M_IS_RSS) && defined(RLIMIT_AS) && \
-    !defined(__APPLE__) && (RLIMIT_RSS == RLIMIT_AS)
-/* On Mac OSX keep -m as -v alias for pkgsrc and other software expecting it */
-#undef ULIMIT_M_IS_RSS
+#define MKHL_RSS
 #endif
+
+#if defined(MKHL_AS) && defined(MKHL_VMEM) && (RLIMIT_AS == RLIMIT_VMEM)
+#undef MKHL_VMEM
 #endif
 
-#if !defined(RLIMIT_AS) && !defined(ULIMIT_M_IS_VMEM) && defined(RLIMIT_VMEM)
-#define ULIMIT_V_IS_VMEM
+#if defined(MKHL_AS) && defined(MKHL_RSS) && (RLIMIT_AS == RLIMIT_RSS)
+#undef MKHL_RSS
 #endif
 
-#if !defined(ULIMIT_V_IS_VMEM) && defined(RLIMIT_VMEM) && \
-    (!defined(RLIMIT_RSS) || (defined(RLIMIT_AS) && (RLIMIT_RSS == RLIMIT_AS)))
-#define ULIMIT_M_IS_VMEM
+#if defined(MKHL_VMEM) && defined(MKHL_RSS) && (RLIMIT_VMEM == RLIMIT_RSS)
+#undef MKHL_VMEM
 #endif
 
-#if defined(ULIMIT_M_IS_VMEM) && defined(RLIMIT_AS) && \
-    (RLIMIT_VMEM == RLIMIT_AS)
+#undef ULIMIT_V_IS_AS
+#undef ULIMIT_V_IS_VMEM
+#undef ULIMIT_M_IS_RSS
 #undef ULIMIT_M_IS_VMEM
-#endif
 
-#if defined(ULIMIT_M_IS_RSS) && defined(ULIMIT_M_IS_VMEM)
-# error nonsensical m ulimit
+#ifdef MKHL_AS
+#define ULIMIT_V_IS_AS
+#if defined(MKHL_RSS)
+#define ULIMIT_M_IS_RSS
+#elif defined(MKHL_VMEM)
+#define ULIMIT_M_IS_VMEM
+#endif
+#else /* !MKHL_AS */
+#ifdef MKHL_VMEM
+#define ULIMIT_V_IS_VMEM
+#endif
+#ifdef MKHL_RSS
+#define ULIMIT_M_IS_RSS
 #endif
+#endif /* !MKHL_AS */
 
-#if defined(ULIMIT_V_IS_VMEM) && defined(ULIMIT_V_IS_AS)
-# error nonsensical v ulimit
+/* pkgsrc® at least on Mac OSX expects -m as -v alias */
+#if !defined(ULIMIT_M_IS_RSS) && !defined(ULIMIT_M_IS_VMEM)
+#if defined(RLIMIT_VMEM)
+#define ULIMIT_M_IS_VMEM
+#elif defined(RLIMIT_RSS)
+#define ULIMIT_M_IS_RSS
 #endif
+#endif
+
+#undef MKHL_AS
+#undef MKHL_VMEM
+#undef MKHL_RSS
 
 #define LIMITS_GEN	"rlimits.gen"
 
@@ -110,9 +118,9 @@ typedef unsigned long rlim_t;
 #endif
 
 #if defined(KSH_UL_SFIL)
-#define KSH_UL_WFIL	true
+#define KSH_UL_WFIL	Ja
 #else
-#define KSH_UL_WFIL	false
+#define KSH_UL_WFIL	Nee
 #define KSH_UL_SFIL	0
 #endif
 
@@ -147,7 +155,7 @@ struct limits {
 	/* write command */
 	int wesource;
 	/* writable? */
-	bool writable;
+	Wahr writable;
 #endif
 	/* getopts char */
 	char optchar;
@@ -171,7 +179,7 @@ struct limits {
 	static const struct {				\
 		int rcmd;				\
 		int wcmd;				\
-		bool writable;				\
+		Wahr writable;				\
 		char optchar;				\
 		char name[sizeof(lname)];		\
 	} rlimits_ ## lg = {				\
@@ -183,6 +191,12 @@ struct limits {
 static void print_ulimit(const struct limits *, int);
 static int set_ulimit(const struct limits *, const char *, int);
 
+/*
+ * UGH! Strictly speaking this is UB in C. Need to figure out whether
+ * it is worth the botherance to fix this (union) or to test for C99+
+ * flexible array member using it when present, maybe keeping this if
+ * not… :~
+ */
 static const struct limits * const rlimits[] = {
 #define RLIMITS_ITEMS
 #include LIMITS_GEN
@@ -202,7 +216,7 @@ c_ulimit(const char **wp)
 	size_t i = 0;
 	int how = SOFT | HARD, optc;
 	char what = 'f';
-	bool all = false;
+	Wahr all = Nee;
 
 	while ((optc = ksh_getopt(wp, &builtin_opt, rlimits_opts)) != -1)
 		switch (optc) {
@@ -213,15 +227,33 @@ c_ulimit(const char **wp)
 			how = SOFT;
 			break;
 		case ORD('a'):
-			all = true;
+			all = Ja;
 			break;
 		case ORD('?'):
-			bi_errorf("usage: ulimit [-%s] [value]", rlimits_opts);
+ unknown_opt:
+			kwarnf0(KWF_BIERR | KWF_NOERRNO,
+			    "usage: ulimit [-%s] [value]", rlimits_opts);
 			return (1);
 		default:
 			what = optc;
 		}
 
+	if (all) {
+		if (wp[builtin_opt.optind]) {
+ unexpected_args:
+			kwarnf(KWF_BIERR | KWF_ONEMSG | KWF_NOERRNO,
+			    Ttoo_many_args);
+			return (1);
+		}
+		while (i < NELEM(rlimits)) {
+			shprintf("-%c: %-20s  ", rlimits[i]->optchar,
+			    rlimits[i]->name);
+			print_ulimit(rlimits[i], how);
+			++i;
+		}
+		return (0);
+	}
+
 	while (i < NELEM(rlimits)) {
 		if (rlimits[i]->optchar == what)
 			goto found;
@@ -230,30 +262,38 @@ c_ulimit(const char **wp)
 #ifndef RLIMIT_CORE
 	if (what == ORD('c'))
 		/* silently accept */
-		return 0;
+		return (0);
 #endif
-	internal_warningf("ulimit: %c", what);
-	return (1);
+	ksh_getopt_opterr(what, wp[0], Tunknown_option);
+	goto unknown_opt;
+
  found:
 	if (wp[builtin_opt.optind]) {
-		if (all || wp[builtin_opt.optind + 1]) {
-			bi_errorf(Ttoo_many_args);
-			return (1);
-		}
+		if (wp[builtin_opt.optind + 1])
+			goto unexpected_args;
 		return (set_ulimit(rlimits[i], wp[builtin_opt.optind], how));
 	}
-	if (!all)
-		print_ulimit(rlimits[i], how);
-	else for (i = 0; i < NELEM(rlimits); ++i) {
-		shprintf("-%c: %-20s  ", rlimits[i]->optchar, rlimits[i]->name);
-		print_ulimit(rlimits[i], how);
-	}
+	print_ulimit(rlimits[i], how);
 	return (0);
 }
 
 #if HAVE_RLIMIT
-#define RL_T rlim_t
-#define RL_U (rlim_t)RLIM_INFINITY
+#ifndef MKSH_RLIM_T
+#define MKSH_RLIM_T rlim_t
+#else
+/* because add_cppflags does not handle spaces */
+#define RLT_SI signed int
+#define RLT_UI unsigned int
+#define RLT_SL signed long
+#define RLT_UL unsigned long
+#define RLT_SQ signed long long
+#define RLT_UQ unsigned long long
+#endif
+#define RL_T MKSH_RLIM_T
+#define RL_U (MKSH_RLIM_T)RLIM_INFINITY
+mbCTA_BEG(ulimit_c);
+ mbCTA(rlinf_fits, (RLIM_INFINITY) == (RL_U));
+mbCTA_END(ulimit_c);
 #else
 #define RL_T long
 #define RL_U LONG_MAX
@@ -263,16 +303,22 @@ static int
 set_ulimit(const struct limits *l, const char *v, int how MKSH_A_UNUSED)
 {
 	RL_T val = (RL_T)0;
+	mbiHUGE_U hval;
 #if HAVE_RLIMIT
 	struct rlimit limit;
 #endif
 
-	if (strcmp(v, "unlimited") == 0)
+	if (strcmp(v, "unlimited") == 0) {
 		val = RL_U;
-	else {
+		goto got_val;
+	}
+	if (!getnh(v, &hval)) {
 		mksh_uari_t rval;
 
-		if (!evaluate(v, (mksh_ari_t *)&rval, KSH_RETURN_ERROR, false))
+		if (errno != EINVAL)
+			goto inv_val;
+
+		if (!evaluate(v, (mksh_ari_t *)&rval, KSH_RETURN_ERROR, Nee))
 			return (1);
 		/*
 		 * Avoid problems caused by typos that evaluate misses due
@@ -281,21 +327,43 @@ set_ulimit(const struct limits *l, const
 		 * evaluate() to control if unset params are 0 or an error.
 		 */
 		if (!rval && !ctype(v[0], C_DIGIT)) {
-			bi_errorf("invalid %s limit: %s", l->name, v);
+			errno = EINVAL;
+ inv_val:
+			kwarnf0(KWF_BIERR, "invalid %s limit: %s", l->name, v);
 			return (1);
 		}
+		hval = rval;
+	}
+	errno = EOVERFLOW;
+#define mbiCfail goto inv_val
 #if HAVE_RLIMIT
-		val = (rlim_t)((rlim_t)rval * l->factor);
-#else
-		val = (RL_T)rval;
+	mbiCAUmul(mbiHUGE_U, hval, l->factor);
 #endif
+	if (mbiTYPE_ISU(RL_T))
+		mbiCASlet(RL_T, val, mbiHUGE_U, hval);
+	else {
+		/* huh, rlim_t is supposed to be unsigned! */
+		mbiHUGE_S hsval;
+
+		mbiCAsafeU2S(mbiHUGE_S, mbiHUGE_U, hval);
+		hsval = mbiA_U2S(mbiHUGE_U, mbiHUGE_S, mbiHUGE_S_MAX, hval);
+		mbiCASlet(RL_T, val, mbiHUGE_S, hsval);
 	}
+#undef mbiCfail
+	/* do not numerically apprehend magic values */
+	if (
+#if HAVE_RLIMIT && (defined(RLIM_SAVED_CUR) || defined(RLIM_SAVED_MAX))
+	    val == RLIM_SAVED_CUR || val == RLIM_SAVED_MAX ||
+#endif
+	    val == RL_U)
+		goto inv_val;
+ got_val:
 
 #if HAVE_RLIMIT
 	if (getrlimit(l->resource, &limit) < 0) {
 #ifndef MKSH_SMALL
-		bi_errorf("limit %s could not be read, contact the mksh developers: %s",
-		    l->name, cstrerror(errno));
+		kwarnf(KWF_BIERR | KWF_TWOMSG, l->name,
+		    "limit could not be read, contact the mksh developers");
 #endif
 		/* some can't be read */
 		limit.rlim_cur = RLIM_INFINITY;
@@ -308,9 +376,10 @@ set_ulimit(const struct limits *l, const
 	if (!setrlimit(l->resource, &limit))
 		return (0);
 #else
-	if (l->writable == false) {
+	if (l->writable == Nee) {
 	    /* check.t:ulimit-2 fails if we return 1 and/or do:
-		bi_errorf(Tf_ro, l->name);
+		kwarnf(KWF_BIERR | KWF_TWOMSG | KWF_NOERRNO,
+		    l->name, Tread_only);
 	    */
 		return (0);
 	}
@@ -318,9 +387,10 @@ set_ulimit(const struct limits *l, const
 		return (0);
 #endif
 	if (errno == EPERM)
-		bi_errorf("%s exceeds allowable %s limit", v, l->name);
+		kwarnf0(KWF_BIERR | KWF_NOERRNO,
+		    "%s exceeds allowable %s limit", v, l->name);
 	else
-		bi_errorf("bad %s limit: %s", l->name, cstrerror(errno));
+		kwarnf0(KWF_BIERR, "%s: bad %s limit", v, l->name);
 	return (1);
 }
 
@@ -328,6 +398,7 @@ static void
 print_ulimit(const struct limits *l, int how MKSH_A_UNUSED)
 {
 	RL_T val = (RL_T)0;
+	char numbuf[NUMBUFSZ];
 #if HAVE_RLIMIT
 	struct rlimit limit;
 
@@ -336,17 +407,17 @@ print_ulimit(const struct limits *l, int
 	if ((val = ulimit(l->resource, 0)) < 0)
 #endif
 	    {
-		shf_puts("unknown\n", shl_stdout);
-		return;
+		shf_puts("unknown", shl_stdout);
+		goto out;
 	}
 #if HAVE_RLIMIT
 	if (how & SOFT)
 		val = limit.rlim_cur;
-	else if (how & HARD)
+	else
 		val = limit.rlim_max;
 #endif
 	if (val == RL_U)
-		shf_puts("unlimited\n", shl_stdout);
+		shf_puts("unlimited", shl_stdout);
 	else {
 #if HAVE_RLIMIT
 		val /= l->factor;
@@ -355,6 +426,10 @@ print_ulimit(const struct limits *l, int
 			val = (RL_T)(((size_t)val - (size_t)&etext) /
 			    (size_t)1024);
 #endif
-		shprintf("%lu\n", (unsigned long)val);
+		shf_puts(mbiTYPE_ISU(RL_T) ?
+		    kuHfmt((kuH)val, FL_DEC, numbuf) :
+		    ksHfmt((ksH)val, FL_DEC, numbuf), shl_stdout);
 	}
+ out:
+	shf_putc('\n', shl_stdout);
 }
--- mksh-59c.orig/ulimits.opt
+++ mksh-59c/ulimits.opt
@@ -1,6 +1,6 @@
 /*-
  * Copyright (c) 2013, 2015, 2020
- *	mirabilos <m@mirbsd.org>
+ *	mirabilos <m$(date +%Y)@mirbsd.de>
  *
  * Provided that these terms and disclaimer and all copyright notices
  * are retained or reproduced in an accompanying document, permission
@@ -21,7 +21,7 @@
  */
 
 @RLIMITS_DEFNS
-__RCSID("$MirOS: src/bin/mksh/ulimits.opt,v 1.2 2020/07/24 20:50:11 tg Exp $");
+__RCSID("$MirOS: src/bin/mksh/ulimits.opt,v 1.4 2025/04/25 23:15:02 tg Exp $");
 @RLIMITS_ITEMS
 #define FN(lname,lg,ls,lw,lopt) (const struct limits *)(&rlimits_ ## lg),
 @@
@@ -38,9 +38,9 @@ __RCSID("$MirOS: src/bin/mksh/ulimits.op
 FN("file(blocks)", KSH_UL_GFIL, KSH_UL_SFIL, KSH_UL_WFIL
 
 >d|KSH_UL_GBRK
-FN("data(KiB)", KSH_UL_GBRK, 0, false
+FN("data(KiB)", KSH_UL_GBRK, 0, Nee
 
 >n|KSH_UL_GDES
-FN("nofiles(descriptors)", KSH_UL_GDES, 0, false
+FN("nofiles(descriptors)", KSH_UL_GDES, 0, Nee
 
 |RLIMITS_OPTCS
--- mksh-59c.orig/var.c
+++ mksh-59c/var.c
@@ -3,8 +3,8 @@
 /*-
  * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
  *		 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018,
- *		 2019
- *	mirabilos <m@mirbsd.org>
+ *		 2019, 2021, 2022, 2023
+ *	mirabilos <m$(date +%Y)@mirbsd.de>
  *
  * Provided that these terms and disclaimer and all copyright notices
  * are retained or reproduced in an accompanying document, permission
@@ -25,11 +25,7 @@
 #include "sh.h"
 #include "mirhash.h"
 
-#if defined(__OpenBSD__)
-#include <sys/sysctl.h>
-#endif
-
-__RCSID("$MirOS: src/bin/mksh/var.c,v 1.237 2020/06/22 17:11:03 tg Exp $");
+__RCSID("$MirOS: src/bin/mksh/var.c,v 1.288 2025/12/24 04:51:57 tg Exp $");
 
 /*-
  * Variables
@@ -42,33 +38,43 @@ __RCSID("$MirOS: src/bin/mksh/var.c,v 1.
  */
 
 static struct table specials;
-static uint32_t lcg_state = 5381, qh_state = 4711;
+static k32 lcg_state = 5381U, qh_state = 4711U;
 /* may only be set by typeset() just before call to array_index_calc() */
 static enum namerefflag innermost_refflag = SRF_NOP;
 
-static void c_typeset_vardump(struct tbl *, uint32_t, int, int, bool, bool);
-static void c_typeset_vardump_recursive(struct block *, uint32_t, int, bool,
-    bool);
+/*
+ * Evil hack since casting uint to sint is implementation-defined
+ */
+typedef union {
+	mksh_ari_t i;
+	mksh_uari_t u;
+} mksh_ari_u;
+
+static void c_typeset_vardump(struct tbl *, kui, int, int, Wahr, Wahr);
+static void c_typeset_vardump_recursive(struct block *, kui, int, Wahr,
+    Wahr);
 static char *formatstr(struct tbl *, const char *);
 static void exportprep(struct tbl *, const char *, size_t);
 static int special(const char *);
 static void unspecial(const char *);
 static void getspec(struct tbl *);
 static void setspec(struct tbl *);
-static void unsetspec(struct tbl *, bool);
-static int getint(struct tbl *, mksh_ari_u *, bool);
-static const char *array_index_calc(const char *, bool *, uint32_t *);
-static struct tbl *vtypeset(int *, const char *, uint32_t, uint32_t, int, int);
+static void unsetspec(struct tbl *, Wahr);
+static int getint(struct tbl *, mksh_ari_u *, Wahr);
+static int getnum(const char *, mksh_ari_u *, Wahr, Wahr);
+static const char *array_index_calc(const char *, Wahr *, k32 *);
+static struct tbl *vtypeset(int *, const char *, kui, kui, int, int);
 
 /*
  * create a new block for function calls and simple commands
  * assume caller has allocated and set up e->loc
  */
+/* pre-initio() */
 void
 newblock(void)
 {
 	struct block *l;
-	static const char *empty[] = { null };
+	static const char *empty[] = { null, NULL };
 
 	l = alloc(sizeof(struct block), ATEMP);
 	l->flags = 0;
@@ -107,7 +113,7 @@ popblock(void)
 			if ((vq = global(vp->name))->flag & ISSET)
 				setspec(vq);
 			else
-				unsetspec(vq, false);
+				unsetspec(vq, Nee);
 		}
 	if (l->flags & BF_DOGETOPTS)
 		user_opt = l->getopts_state;
@@ -150,7 +156,7 @@ initvar(void)
 
 /* common code for several functions below and c_typeset() */
 struct block *
-varsearch(struct block *l, struct tbl **vpp, const char *vn, uint32_t h)
+varsearch(struct block *l, struct tbl **vpp, const char *vn, k32 h)
 {
 	register struct tbl *vp;
 
@@ -171,20 +177,23 @@ varsearch(struct block *l, struct tbl **
 
 /*
  * Used to calculate an array index for global()/local(). Sets *arrayp
- * to true if this is an array, sets *valp to the array index, returns
+ * to true if this is an array, sets *idxp to the array index, returns
  * the basename of the array. May only be called from global()/local()
  * and must be their first callee.
  */
 static const char *
-array_index_calc(const char *n, bool *arrayp, uint32_t *valp)
+array_index_calc(const char *n, Wahr *arrayp, k32 *idxp)
 {
 	const char *p;
 	size_t len;
 	char *ap = NULL;
 
-	*arrayp = false;
+	*arrayp = Nee;
  redo_from_ref:
-	p = skip_varname(n, false);
+	p = skip_varname(n, Nee);
+	if ((size_t)(p - n) > (size_t)(INT_MAX - X_EXTRA))
+		kerrf(KWF_ERR(255) | KWF_PREFIX | KWF_FILELINE | KWF_ONEMSG |
+		    KWF_NOERRNO, "parameter name too long");
 	if (innermost_refflag == SRF_NOP && (p != n) && ctype(n[0], C_ALPHX)) {
 		struct tbl *vp;
 		char *vn;
@@ -208,18 +217,18 @@ array_index_calc(const char *n, bool *ar
 
 	if (p != n && ord(*p) == ORD('[') && (len = array_ref_len(p))) {
 		char *sub, *tmp;
-		mksh_ari_t rval;
+		mksh_ari_u rval;
 		size_t tmplen = p - n;
 
 		/* calculate the value of the subscript */
-		*arrayp = true;
+		*arrayp = Ja;
 		len -= 2;
 		tmp = alloc((len > tmplen ? len : tmplen) + 1, ATEMP);
 		memcpy(tmp, p + 1, len);
 		tmp[len] = '\0';
 		sub = substitute(tmp, 0);
-		evaluate(sub, &rval, KSH_UNWIND_ERROR, true);
-		*valp = (uint32_t)rval;
+		evaluate(sub, &rval.i, KSH_UNWIND_ERROR, Ja);
+		*idxp = mbiMM(k32, K32_FM, rval.u);
 		afree(sub, ATEMP);
 		memcpy(tmp, n, tmplen);
 		tmp[tmplen] = '\0';
@@ -235,30 +244,32 @@ array_index_calc(const char *n, bool *ar
 struct tbl *
 global(const char *n)
 {
-	return (isglobal(n, true));
+	return (isglobal(n, Ja));
 }
 
 /* search for variable; if not found, return NULL or create globally */
 struct tbl *
-isglobal(const char *n, bool docreate)
+isglobal(const char *n, Wahr docreate)
 {
 	struct tbl *vp;
 	union mksh_cchack vname;
 	struct block *l = e->loc;
 	int c;
-	bool array;
-	uint32_t h, val;
+	Wahr array;
+	k32 h;
+	k32 idx;
 
 	/*
 	 * check to see if this is an array;
 	 * dereference namerefs; must come first
 	 */
-	vn = array_index_calc(n, &array, &val);
+	vn = array_index_calc(n, &array, &idx);
 	h = hash(vn);
 	c = (unsigned char)vn[0];
 	if (!ctype(c, C_ALPHX)) {
 		if (array)
-			errorf(Tbadsubst);
+			kerrf(KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE |
+			    KWF_ONEMSG | KWF_NOERRNO, Tbadsubst);
 		vp = vtemp;
 		vp->flag = DEFINED;
 		vp->type = 0;
@@ -311,10 +322,10 @@ isglobal(const char *n, bool docreate)
 	if (vp == NULL && docreate)
 		vp = ktenter(&l->vars, vn, h);
 	else
-		docreate = false;
+		docreate = Nee;
 	if (vp != NULL) {
 		if (array)
-			vp = arraysearch(vp, val);
+			vp = arraysearch(vp, idx);
 		if (docreate) {
 			vp->flag |= DEFINED;
 			if (special(vn))
@@ -332,19 +343,20 @@ isglobal(const char *n, bool docreate)
  * Search for local variable, if not found create locally.
  */
 struct tbl *
-local(const char *n, bool copy)
+local(const char *n, Wahr copy)
 {
 	struct tbl *vp;
 	union mksh_cchack vname;
 	struct block *l = e->loc;
-	bool array;
-	uint32_t h, val;
+	Wahr array;
+	k32 h;
+	k32 idx;
 
 	/*
 	 * check to see if this is an array;
 	 * dereference namerefs; must come first
 	 */
-	vn = array_index_calc(n, &array, &val);
+	vn = array_index_calc(n, &array, &idx);
 	h = hash(vn);
 	if (!ctype(*vn, C_ALPHX)) {
 		vp = vtemp;
@@ -368,7 +380,7 @@ local(const char *n, bool copy)
 		}
 	}
 	if (array)
-		vp = arraysearch(vp, val);
+		vp = arraysearch(vp, idx);
 	vp->flag |= DEFINED;
 	if (special(vn))
 		vp->flag |= SPECIAL;
@@ -414,21 +426,17 @@ str_val(struct tbl *vp)
 			n = (vp->val.i < 0) ? -vp->val.u : vp->val.u;
 		base = (vp->type == 0) ? 10U : (unsigned int)vp->type;
 
-		if (base == 1 && n == 0)
-			base = 2;
 		if (base == 1) {
-			size_t sz = 1;
-
-			*(s = strbuf) = '1';
+			s = strbuf;
 			s[1] = '#';
-			if (!UTFMODE)
-				s[2] = (unsigned char)n;
-			else if ((n & 0xFF80) == 0xEF80)
-				/* OPTU-16 -> raw octet */
-				s[2] = asc2rtt(n & 0xFF);
-			else
-				sz = utf_wctomb(s + 2, n);
-			s[2 + sz] = '\0';
+			if (n == 0) {
+				s[0] = '2';
+				s[2] = '0';
+				s[3] = '\0';
+			} else {
+				s[0] = '1';
+				s[2 + ez_ctomb(s + 2, n)] = '\0';
+			}
 		} else {
 			*--s = '\0';
 			do {
@@ -457,25 +465,34 @@ str_val(struct tbl *vp)
 int
 setstr(struct tbl *vq, const char *s, int error_ok)
 {
-	bool no_ro_check = tobool(error_ok & 0x4);
+	Wahr no_ro_check = isWahr(error_ok & 0x4);
 
 	error_ok &= ~0x4;
 	if ((vq->flag & RDONLY) && !no_ro_check) {
-		warningf(true, Tf_ro, vq->name);
+		kwarnf((error_ok ? KWF_WARNING : KWF_ERR(2)) | KWF_PREFIX |
+		    KWF_FILELINE | KWF_TWOMSG | KWF_NOERRNO,
+		    vq->name, Tread_only);
 		if (!error_ok)
-			errorfxz(2);
+			unwind(LERROR);
 		return (0);
 	}
 	if (!(vq->flag&INTEGER)) {
 		/* string dest */
 		char *salloc = NULL;
 		size_t cursz;
+#ifndef MKSH_SMALL
+		mbiPTR_U cmp_s, cmp_b, cmp_e;
+#endif
+
 		if ((vq->flag&ALLOC)) {
 			cursz = strlen(vq->val.s) + 1;
 #ifndef MKSH_SMALL
 			/* debugging */
-			if (s >= vq->val.s && s < (vq->val.s + cursz)) {
-				internal_errorf(
+			cmp_s = (mbiPTR_U)(const void *)s;
+			cmp_b = (mbiPTR_U)(void *)vq->val.s;
+			cmp_e = (mbiPTR_U)(void *)(vq->val.s + cursz);
+			if (cmp_s >= cmp_b && cmp_s < cmp_e) {
+				kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,
 				    "setstr: %s=%s: assigning to self",
 				    vq->name, s);
 			}
@@ -494,10 +511,11 @@ setstr(struct tbl *vq, const char *s, in
 			vq->flag |= ALLOC;
 			vq->type = 0;
 		}
+		vq->flag &= ~IMPORT;
 		afree(salloc, ATEMP);
 	} else {
 		/* integer dest */
-		if (!v_evaluate(vq, s, error_ok, true))
+		if (!v_evaluate(vq, s, error_ok, Ja))
 			return (0);
 	}
 	vq->flag |= ISSET;
@@ -525,22 +543,28 @@ setint(struct tbl *vq, mksh_ari_t n)
 }
 
 static int
-getint(struct tbl *vp, mksh_ari_u *nump, bool arith)
+getint(struct tbl *vp, mksh_ari_u *nump, Wahr arith)
 {
-	mksh_uari_t c, num = 0, base = 10;
-	const char *s;
-	bool have_base = false, neg = false;
-
 	if (vp->flag & SPECIAL)
 		getspec(vp);
 	/* XXX is it possible for ISSET to be set and val.s to be NULL? */
-	if (!(vp->flag & ISSET) || (!(vp->flag & INTEGER) && vp->val.s == NULL))
+	if (!(vp->flag & ISSET) || (!(vp->flag & INTEGER) && vp->val.s == NULL)) {
+		errno = EINVAL;
 		return (-1);
+	}
 	if (vp->flag & INTEGER) {
 		nump->i = vp->val.i;
 		return (vp->type);
 	}
-	s = vp->val.s + vp->type;
+	return (getnum(vp->val.s + vp->type, nump, arith,
+	    Flag(FPOSIX) && !(vp->flag & ZEROFIL)));
+}
+
+static int
+getnum(const char *s, mksh_ari_u *nump, Wahr arith, Wahr psxoctal)
+{
+	mksh_uari_t c, num = 0, base = 10;
+	Wahr have_base = Nee, neg = Nee;
 
 	do {
 		c = (unsigned char)*s++;
@@ -548,7 +572,7 @@ getint(struct tbl *vp, mksh_ari_u *nump,
 
 	switch (c) {
 	case '-':
-		neg = true;
+		neg = Ja;
 		/* FALLTHROUGH */
 	case '+':
 		c = (unsigned char)*s++;
@@ -556,17 +580,16 @@ getint(struct tbl *vp, mksh_ari_u *nump,
 	}
 
 	if (c == '0' && arith) {
-		if (ksh_eq(s[0], 'X', 'x')) {
+		if (isCh(s[0], 'X', 'x')) {
 			/* interpret as hexadecimal */
 			base = 16;
 			++s;
 			goto getint_c_style_base;
-		} else if (Flag(FPOSIX) && ctype(s[0], C_DIGIT) &&
-		    !(vp->flag & ZEROFIL)) {
+		} else if (psxoctal && ctype(s[0], C_DIGIT)) {
 			/* interpret as octal (deprecated) */
 			base = 8;
  getint_c_style_base:
-			have_base = true;
+			have_base = Ja;
 			c = (unsigned char)*s++;
 		}
 	}
@@ -574,28 +597,21 @@ getint(struct tbl *vp, mksh_ari_u *nump,
 	do {
 		if (c == '#') {
 			/* ksh-style base determination */
-			if (have_base || num < 1)
+			if (have_base || num < 1) {
+				errno = EINVAL;
 				return (-1);
+			}
 			if ((base = num) == 1) {
 				/* mksh-specific extension */
 				unsigned int wc;
 
-				if (!UTFMODE)
-					wc = *(const unsigned char *)s;
-				else if (utf_mbtowc(&wc, s) == (size_t)-1)
-					/* OPTU-8 -> OPTU-16 */
-					/*
-					 * (with a twist: 1#\uEF80 converts
-					 * the same as 1#\x80 does, thus is
-					 * not round-tripping correctly XXX)
-					 */
-					wc = 0xEF00 + rtt2asc(*s);
+				ez_mbtoc(&wc, s);
 				nump->u = (mksh_uari_t)wc;
 				return (1);
 			} else if (base > 36)
 				base = 10;
 			num = 0;
-			have_base = true;
+			have_base = Ja;
 			continue;
 		}
 		if (ctype(c, C_DIGIT))
@@ -604,10 +620,14 @@ getint(struct tbl *vp, mksh_ari_u *nump,
 			c = ksh_numuc(c) + 10;
 		else if (ctype(c, C_LOWER))
 			c = ksh_numlc(c) + 10;
-		else
+		else {
+			errno = EINVAL;
 			return (-1);
-		if (c >= base)
+		}
+		if (c >= base) {
+			errno = EINVAL;
 			return (-1);
+		}
 		/* handle overflow as truncation */
 		num = num * base + c;
 	} while ((c = (unsigned char)*s++));
@@ -623,7 +643,7 @@ getint(struct tbl *vp, mksh_ari_u *nump,
  * (vq and vp may be the same)
  */
 struct tbl *
-setint_v(struct tbl *vq, struct tbl *vp, bool arith)
+setint_v(struct tbl *vq, struct tbl *vp, Wahr arith)
 {
 	int base;
 	mksh_ari_u num;
@@ -641,10 +661,11 @@ setint_v(struct tbl *vq, struct tbl *vp,
 void
 setint_n(struct tbl *vq, mksh_ari_t num, int newbase)
 {
-	if (!(vq->flag & INTEGER) && (vq->flag & ALLOC)) {
-		vq->flag &= ~ALLOC;
+	if (!(vq->flag & INTEGER)) {
+		if (vq->flag & ALLOC)
+			afree(vq->val.s, vq->areap);
+		vq->flag &= ~(ALLOC | IMPORT);
 		vq->type = 0;
-		afree(vq->val.s, vq->areap);
 	}
 	vq->val.i = num;
 	if (newbase != 0)
@@ -657,36 +678,39 @@ setint_n(struct tbl *vq, mksh_ari_t num,
 static char *
 formatstr(struct tbl *vp, const char *s)
 {
-	int olen, nlen;
 	char *p, *q;
-	size_t psiz;
-
-	olen = (int)utf_mbswidth(s);
 
-	if (vp->flag & (RJUST|LJUST)) {
+	if (vp->flag & (RJUST | LJUST)) {
+		int slen, nlen;
+		size_t psiz;
+
+		psiz = utf_mbswidth(s);
+		if (psiz > (size_t)INT_MAX) {
+			errno = EOVERFLOW;
+			kerrf0(KWF_ERR(0xFF) | KWF_PREFIX | KWF_FILELINE,
+			    "string width %zu", psiz);
+		}
+		slen = (int)psiz;
 		if (!vp->u2.field)
 			/* default field width */
-			vp->u2.field = olen;
+			vp->u2.field = slen;
 		nlen = vp->u2.field;
-	} else
-		nlen = olen;
 
-	p = alloc((psiz = nlen * /* MB_LEN_MAX */ 3 + 1), ATEMP);
-	if (vp->flag & (RJUST|LJUST)) {
-		int slen = olen;
+		p = alloc2(nlen + 1, /* MB_LEN_MAX */ 4, ATEMP);
+		psiz = ((size_t)nlen + 1U) * 4U;
 
 		if (vp->flag & RJUST) {
 			const char *qq;
 			int n = 0;
 
-			qq = utf_skipcols(s, slen, &slen);
+			qq = s + strlen(s);
 
 			/* strip trailing spaces (AT&T uses qq[-1] == ' ') */
 			while (qq > s && ctype(qq[-1], C_SPACE)) {
 				--qq;
 				--slen;
 			}
-			if (vp->flag & ZEROFIL && vp->flag & INTEGER) {
+			if (HAS(vp->flag, ZEROFIL | INTEGER)) {
 				if (!s[0] || !s[1])
 					goto uhm_no;
 				if (s[1] == '#')
@@ -721,7 +745,7 @@ formatstr(struct tbl *vp, const char *s)
 				vp->u2.field, vp->u2.field, s);
 		}
 	} else
-		memcpy(p, s, strlen(s) + 1);
+		strdupx(p, s, ATEMP);
 
 	if (vp->flag & UCASEV_AL) {
 		for (q = p; *q; q++)
@@ -750,7 +774,7 @@ exportprep(struct tbl *vp, const char *v
 	vp->val.s = aresizeif(cursz, cp, vp->type + vallen, vp->areap);
 	memmove(vp->val.s + vp->type, val == cp ? vp->val.s : val, vallen);
 	memcpy(vp->val.s, vp->name, namelen);
-	vp->val.s[namelen] = '=';
+	((char *)(vp->val.s))[namelen] = '=';
 }
 
 /*
@@ -759,12 +783,12 @@ exportprep(struct tbl *vp, const char *v
  * UCASEV_AL), and optionally set its value if an assignment.
  */
 struct tbl *
-typeset(const char *var, uint32_t set, uint32_t clr, int field, int base)
+typeset(const char *var, kui set, kui clr, int field, int base)
 {
 	return (vtypeset(NULL, var, set, clr, field, base));
 }
 static struct tbl *
-vtypeset(int *ep, const char *var, uint32_t set, uint32_t clr,
+vtypeset(int *ep, const char *var, kui set, kui clr,
     int field, int base)
 {
 	struct tbl *vp;
@@ -772,7 +796,7 @@ vtypeset(int *ep, const char *var, uint3
 	char *tvar, tvarbuf[32];
 	const char *val;
 	size_t len;
-	bool vappend = false;
+	Wahr vappend = Nee;
 	enum namerefflag new_refflag = SRF_NOP;
 
 	if (ep)
@@ -788,17 +812,18 @@ vtypeset(int *ep, const char *var, uint3
 	}
 
 	/* check for valid variable name, search for value */
-	val = skip_varname(var, false);
+	val = skip_varname(var, Nee);
 	if (val == var) {
 		/* no variable name given */
 		return (NULL);
 	}
 	if (ord(*val) == ORD('[')) {
 		if (new_refflag != SRF_NOP)
-			return (maybe_errorf(ep, 1, Tf_sD_s, var,
-			    "reference variable can't be an array"), NULL);
+			merrf(NULL, (ep, KWF_ERR(1) | KWF_PREFIX |
+			    KWF_FILELINE | KWF_TWOMSG | KWF_NOERRNO,
+			    var, "reference variable can't be an array"));
 		len = array_ref_len(val);
-		if (len == 0)
+		if (len < 3)
 			return (NULL);
 		/*
 		 * IMPORT is only used when the shell starts up and is
@@ -808,39 +833,39 @@ vtypeset(int *ep, const char *var, uint3
 		 * would be a major security hole.
 		 */
 		if (set & IMPORT) {
-			size_t i;
+			mksh_ari_u num;
 
-			for (i = 1; i < len - 1; i++)
-				if (!ctype(val[i], C_DIGIT))
-					return (NULL);
+			len -= 2;
+			strnbdupx(tvar, val + 1, len, ATEMP, tvarbuf);
+			if (getnum(tvar, &num, Ja, Nee) == -1)
+				len = 0;
+			if (tvar != tvarbuf)
+				afree(tvar, ATEMP);
+			if (!len)
+				return (NULL);
+			len += 2;
 		}
 		val += len;
 	}
 	if (ord(val[0]) == ORD('=')) {
 		len = val - var;
-		tvar = len < sizeof(tvarbuf) ? tvarbuf : alloc(len + 1, ATEMP);
-		memcpy(tvar, var, len);
-		tvar[len] = '\0';
+		strnbdupx(tvar, var, len, ATEMP, tvarbuf);
 		++val;
 	} else if (set & IMPORT) {
 		/* environment invalid variable name or no assignment */
 		return (NULL);
 	} else if (ord(val[0]) == ORD('+') && ord(val[1]) == ORD('=')) {
 		len = val - var;
-		tvar = len < sizeof(tvarbuf) ? tvarbuf : alloc(len + 1, ATEMP);
-		memcpy(tvar, var, len);
-		tvar[len] = '\0';
+		strnbdupx(tvar, var, len, ATEMP, tvarbuf);
 		val += 2;
-		vappend = true;
+		vappend = Ja;
 	} else if (val[0] != '\0') {
 		/* other invalid variable names (not from environment) */
 		return (NULL);
 	} else {
 		/* just varname with no value part nor equals sign */
 		len = strlen(var);
-		tvar = len < sizeof(tvarbuf) ? tvarbuf : alloc(len + 1, ATEMP);
-		memcpy(tvar, var, len);
-		tvar[len] = '\0';
+		strnbdupx(tvar, var, len, ATEMP, tvarbuf);
 		val = NULL;
 		/* handle foo[*] => foo (whole array) mapping for R39b */
 		if (len > 3 && ord(tvar[len - 3]) == ORD('[') &&
@@ -854,8 +879,9 @@ vtypeset(int *ep, const char *var, uint3
 
 		/* bail out on 'nameref foo+=bar' */
 		if (vappend)
-			return (maybe_errorf(ep, 1,
-			    "appending not allowed for nameref"), NULL);
+			merrf(NULL, (ep, KWF_ERR(1) | KWF_PREFIX |
+			    KWF_FILELINE | KWF_ONEMSG | KWF_NOERRNO,
+			    "appending not allowed for nameref"));
 		/* find value if variable already exists */
 		if ((qval = val) == NULL) {
 			varsearch(e->loc, &vp, tvar, hash(tvar));
@@ -864,7 +890,7 @@ vtypeset(int *ep, const char *var, uint3
 			qval = str_val(vp);
 		}
 		/* check target value for being a valid variable name */
-		ccp = skip_varname(qval, false);
+		ccp = skip_varname(qval, Nee);
 		if (ccp == qval) {
 			int c;
 
@@ -881,8 +907,9 @@ vtypeset(int *ep, const char *var, uint3
 				goto nameref_rhs_checked;
 			}
  nameref_empty:
-			return (maybe_errorf(ep, 1, Tf_sD_s, var,
-			    "empty nameref target"), NULL);
+			merrf(NULL, (ep, KWF_ERR(1) | KWF_PREFIX |
+			    KWF_FILELINE | KWF_TWOMSG | KWF_NOERRNO,
+			    var, Tnameref_empty));
 		}
 		len = (ord(*ccp) == ORD('[')) ? array_ref_len(ccp) : 0;
 		if (ccp[len]) {
@@ -891,15 +918,17 @@ vtypeset(int *ep, const char *var, uint3
 			 * junk after it" and "invalid array"; in the
 			 * latter case, len is also 0 and points to '['
 			 */
-			return (maybe_errorf(ep, 1, Tf_sD_s, qval,
-			    "nameref target not a valid parameter name"), NULL);
+			merrf(NULL, (ep, KWF_ERR(1) | KWF_PREFIX |
+			    KWF_FILELINE | KWF_TWOMSG | KWF_NOERRNO,
+			    qval, "nameref target not a valid parameter name"));
 		}
  nameref_rhs_checked:
 		/* prevent nameref loops */
 		while (qval) {
 			if (!strcmp(qval, tvar))
-				return (maybe_errorf(ep, 1, Tf_sD_s, qval,
-				    "expression recurses on parameter"), NULL);
+				merrf(NULL, (ep, KWF_ERR(1) | KWF_PREFIX |
+				    KWF_FILELINE | KWF_TWOMSG | KWF_NOERRNO,
+				    qval, "expression recurses on parameter"));
 			varsearch(e->loc, &vp, qval, hash(qval));
 			qval = NULL;
 			if (vp && ((vp->flag & (ARRAY | ASSOC)) == ASSOC))
@@ -908,14 +937,17 @@ vtypeset(int *ep, const char *var, uint3
 	}
 
 	/* prevent typeset from creating a local PATH/ENV/SHELL */
-	if (Flag(FRESTRICTED) && (strcmp(tvar, TPATH) == 0 ||
-	    strcmp(tvar, TENV) == 0 || strcmp(tvar, TSHELL) == 0))
-		return (maybe_errorf(ep, 1, Tf_sD_s,
-		    tvar, "restricted"), NULL);
+	if (varnamecheck(tvar))
+		merrf(NULL, (ep, KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE |
+		    KWF_TWOMSG | KWF_NOERRNO, tvar, "restricted"));
 
 	innermost_refflag = new_refflag;
-	vp = (set & LOCAL) ? local(tvar, tobool(set & LOCAL_COPY)) :
+	vp = (set & LOCAL) ? local(tvar, isWahr(set & LOCAL_COPY)) :
 	    global(tvar);
+	/* when importing environment, resolve duplicates as first-wins */
+	/* the EXPORT check is to permit overwriting the default $PATH */
+	if ((set & IMPORT) && (vp->flag & (ISSET | EXPORT)) == (ISSET | EXPORT))
+		return (NULL);
 	if (new_refflag == SRF_DISABLE && (vp->flag & (ARRAY|ASSOC)) == ASSOC)
 		vp->flag &= ~ASSOC;
 	else if (new_refflag == SRF_ENABLE) {
@@ -938,30 +970,31 @@ vtypeset(int *ep, const char *var, uint3
 
 	set &= ~(LOCAL|LOCAL_COPY);
 
-	vpbase = (vp->flag & ARRAY) ? global(arrayname(tvar)) : vp;
+	vpbase = (vp->flag & ARRAY) ? arraybase(tvar) : vp;
 
 	/*
-	 * only allow export and readonly flag to be set; AT&T ksh
+	 * only allow export and read-only flag to be set; AT&T ksh
 	 * allows any attribute to be changed which means it can be
 	 * truncated or modified (-L/-R/-Z/-i)
 	 */
 	if ((vpbase->flag & RDONLY) &&
 	    (val || clr || (set & ~(EXPORT | RDONLY))))
-		return (maybe_errorf(ep, 2, Tf_ro, tvar), NULL);
+		merrf(NULL, (ep, KWF_ERR(2) | KWF_PREFIX | KWF_FILELINE |
+		    KWF_TWOMSG | KWF_NOERRNO, tvar, Tread_only));
 	if (tvar != tvarbuf)
 		afree(tvar, ATEMP);
 
 	/* most calls are with set/clr == 0 */
 	if (set | clr) {
-		bool ok = true;
+		Wahr ok = Ja;
 
 		/*
 		 * XXX if x[0] isn't set, there will be problems: need
 		 * to have one copy of attributes for arrays...
 		 */
 		for (t = vpbase; t; t = t->u.array) {
-			bool fake_assign;
-			char *s = NULL;
+			Wahr fake_assign;
+			const char *s = NULL;
 			char *free_me = NULL;
 
 			fake_assign = (t->flag & ISSET) && (!val || t != vp) &&
@@ -983,13 +1016,27 @@ vtypeset(int *ep, const char *var, uint3
 				t->type = 0;
 				t->flag &= ~ALLOC;
 			}
+			if (set & INTEGER) {
+				/*
+				 * Don't change base if assignment is to
+				 * be done, in case assignment fails.
+				 */
+				if (base > 0 && (!val || t != vp))
+					t->type = base;
+				/*
+				 * Do not permit content from the
+				 * environment to e.g. execute commands.
+				 */
+				if ((t->flag & IMPORT) && fake_assign) {
+					mksh_ari_u num;
+
+					if (getnum(s, &num, Ja,
+					    isWahr(Flag(FPOSIX))) == -1)
+						s = "0";
+					clr |= IMPORT;
+				}
+			}
 			t->flag = (t->flag | set) & ~clr;
-			/*
-			 * Don't change base if assignment is to be
-			 * done, in case assignment fails.
-			 */
-			if ((set & INTEGER) && base > 0 && (!val || t != vp))
-				t->type = base;
 			if (set & (LJUST|RJUST|ZEROFIL))
 				t->u2.field = field;
 			if (fake_assign) {
@@ -1000,7 +1047,7 @@ vtypeset(int *ep, const char *var, uint3
 					 * variable, but keep the flag
 					 * settings.
 					 */
-					ok = false;
+					ok = Nee;
 					if (t->flag & INTEGER)
 						t->flag &= ~ISSET;
 					else {
@@ -1014,12 +1061,14 @@ vtypeset(int *ep, const char *var, uint3
 			}
 		}
 		if (!ok)
-			return (maybe_errorf(ep, 1, NULL), NULL);
+			merrf(NULL, (ep, KWF_ERR(1) | KWF_PREFIX |
+			    KWF_FILELINE | KWF_ONEMSG | KWF_NOERRNO,
+			    "failed to set string value"));
 	}
 
 	if (vappend) {
 		size_t tlen;
-		if ((vp->flag & (ISSET|ALLOC|SPECIAL|INTEGER|UCASEV_AL|LCASEV|LJUST|RJUST)) != (ISSET|ALLOC)) {
+		if ((vp->flag & (ISSET|ALLOC|SPECIAL|INTEGER|UCASEV_AL|LCASEV|LJUST|RJUST|IMPORT)) != (ISSET|ALLOC)) {
 			/* cannot special-case this */
 			strdup2x(tvar, str_val(vp), val);
 			val = tvar;
@@ -1028,7 +1077,7 @@ vtypeset(int *ep, const char *var, uint3
 		/* trivial string appending */
 		len = strlen(vp->val.s);
 		tlen = strlen(val) + 1;
-		vp->val.s = aresize(vp->val.s, len + tlen, vp->areap);
+		vp->val.s = aresize1(vp->val.s, len, tlen, vp->areap);
 		memcpy(vp->val.s + len, val, tlen);
 	} else if (val != NULL) {
  vassign:
@@ -1038,9 +1087,11 @@ vtypeset(int *ep, const char *var, uint3
 			/* done after assignment to override default */
 			if (base > 0)
 				vp->type = base;
-		} else
-			/* setstr can't fail (readonly check already done) */
+		} else {
+			/* setstr can't fail (read-only check already done) */
 			setstr(vp, val, KSH_RETURN_ERROR | 0x4);
+			vp->flag |= (set & IMPORT);
+		}
 
 		/* came here from vappend? need to free temp val */
 		if (vappend)
@@ -1087,7 +1138,7 @@ unset(struct tbl *vp, int flags)
 	vp->flag &= SPECIAL | ((flags & 1) ? 0 : ARRAY|DEFINED);
 	if (vp->flag & SPECIAL)
 		/* responsible for 'unspecial'ing var */
-		unsetspec(vp, true);
+		unsetspec(vp, Ja);
 }
 
 /*
@@ -1096,7 +1147,7 @@ unset(struct tbl *vp, int flags)
  * the terminating NUL if whole string is legal).
  */
 const char *
-skip_varname(const char *s, bool aok)
+skip_varname(const char *s, Wahr aok)
 {
 	size_t alen;
 
@@ -1110,11 +1161,20 @@ skip_varname(const char *s, bool aok)
 	return (s);
 }
 
+/* Check if plain string s is a variable name */
+int
+not_varname(const char *s, Wahr aok)
+{
+	const char *p = skip_varname(s, aok);
+
+	return (p == s || p[0] != '\0');
+}
+
 /* Return a pointer to the first character past any legal variable name */
 const char *
 skip_wdvarname(const char *s,
     /* skip array de-reference? */
-    bool aok)
+    Wahr aok)
 {
 	if (s[0] == CHAR && ctype(s[1], C_ALPHX)) {
 		do {
@@ -1145,7 +1205,7 @@ skip_wdvarname(const char *s,
 
 /* Check if coded string s is a variable name */
 int
-is_wdvarname(const char *s, bool aok)
+is_wdvarname(const char *s, Wahr aok)
 {
 	const char *p = skip_wdvarname(s, aok);
 
@@ -1154,12 +1214,37 @@ is_wdvarname(const char *s, bool aok)
 
 /* Check if coded string s is a variable assignment */
 int
-is_wdvarassign(const char *s)
+is_wdvarassign(const char *s, Wahr needEOS)
 {
-	const char *p = skip_wdvarname(s, true);
+	const char *p = skip_wdvarname(s, Ja);
 
-	return (p != s && p[0] == CHAR &&
-	    (p[1] == '=' || (p[1] == '+' && p[2] == CHAR && p[3] == '=')));
+	if (p == s || p[0] != CHAR)
+		return (0);
+	switch (ord(p[1])) {
+	case ORD('='):
+		return (!needEOS || p[2] == EOS);
+	case ORD('+'):
+		if (p[2] != CHAR || ord(p[3]) != ORD('='))
+			return (0);
+		return (!needEOS || p[4] == EOS);
+	default:
+		return (0);
+	}
+}
+
+/* don’t leak internal hash table order */
+static int
+envsort(const void *a, const void *b)
+{
+	const kby *cp1 = *(const kby * const *)a;
+	const kby *cp2 = *(const kby * const *)b;
+
+	while (*cp1 == *cp2) {
+		if (*cp1 == '=' || *cp1++ == '\0')
+			return (0);
+		++cp2;
+	}
+	return ((int)asciibetical(*cp1) - (int)asciibetical(*cp2));
 }
 
 /*
@@ -1182,7 +1267,7 @@ makenv(void)
 			    (vp->flag&(ISSET|EXPORT)) == (ISSET|EXPORT)) {
 				struct block *l2;
 				struct tbl *vp2;
-				uint32_t h = hash(vp->name);
+				k32 h = hash(vp->name);
 
 				/* unexport any redefined instances */
 				for (l2 = l->next; l2 != NULL; l2 = l2->next) {
@@ -1210,6 +1295,7 @@ makenv(void)
 		if (l->flags & BF_STOPENV)
 			break;
 	}
+	qsort(XPptrv(denv), XPsize(denv), sizeof(void *), envsort);
 	XPput(denv, NULL);
 	return ((char **)XPclose(denv));
 }
@@ -1289,9 +1375,13 @@ getspec(struct tbl *vp)
 
 		vp->flag &= ~SPECIAL;
 		mksh_TIME(tv);
-		shf_snprintf(buf, sizeof(buf), "%u.%06u",
-		    (unsigned)tv.tv_sec, (unsigned)tv.tv_usec);
-		setstr(vp, buf, KSH_RETURN_ERROR | 0x4);
+		if (vp->flag & INTEGER)
+			setint(vp, (mksh_ari_t)tv.tv_sec);
+		else {
+			shf_snprintf(buf, sizeof(buf), "%u.%06u",
+			    (unsigned)tv.tv_sec, (unsigned)tv.tv_usec);
+			setstr(vp, buf, KSH_RETURN_ERROR | 0x4);
+		}
 		vp->flag |= SPECIAL;
 		return;
 	}
@@ -1370,7 +1460,7 @@ setspec(struct tbl *vp)
 		s = str_val(vp);
 		strdupx(path, s, APERM);
 		/* clear tracked aliases */
-		flushcom(true);
+		flushcom(Ja);
 		return;
 #ifndef MKSH_NO_CMDLINE_EDITING
 	case V_TERM:
@@ -1411,10 +1501,12 @@ setspec(struct tbl *vp)
 	case V_SECONDS:
 	case V_TMOUT:
 		vp->flag &= ~SPECIAL;
-		if (getint(vp, &num, false) == -1) {
+		if (getint(vp, &num, Nee) == -1) {
 			s = str_val(vp);
 			if (st != V_RANDOM)
-				errorf(Tf_sD_sD_s, vp->name, Tbadnum, s);
+				kerrf(KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE |
+				    KWF_THREEMSG | KWF_NOERRNO,
+				    vp->name, Tbadnum, s);
 			num.u = hash(s);
 		}
 		vp->flag |= SPECIAL;
@@ -1474,7 +1566,7 @@ setspec(struct tbl *vp)
 }
 
 static void
-unsetspec(struct tbl *vp, bool dounset)
+unsetspec(struct tbl *vp, Wahr dounset)
 {
 	/*
 	 * AT&T ksh man page says OPTIND, OPTARG and _ lose special
@@ -1504,7 +1596,7 @@ unsetspec(struct tbl *vp, bool dounset)
 		afree(path, APERM);
 		strdupx(path, def_path, APERM);
 		/* clear tracked aliases */
-		flushcom(true);
+		flushcom(Ja);
 		return;
 #ifndef MKSH_NO_CMDLINE_EDITING
 	case V_TERM:
@@ -1546,38 +1638,37 @@ unsetspec(struct tbl *vp, bool dounset)
  * vp, indexed by val.
  */
 struct tbl *
-arraysearch(struct tbl *vp, uint32_t val)
+arraysearch(struct tbl *vp, k32 idx)
 {
 	struct tbl *prev, *curr, *news;
 	size_t len;
 
 	vp->flag = (vp->flag | (ARRAY | DEFINED)) & ~ASSOC;
 	/* the table entry is always [0] */
-	if (val == 0)
+	if (idx == 0)
 		return (vp);
 	prev = vp;
 	curr = vp->u.array;
-	while (curr && curr->ua.index < val) {
+	while (curr && curr->ua.index < idx) {
 		prev = curr;
 		curr = curr->u.array;
 	}
-	if (curr && curr->ua.index == val) {
+	if (curr && curr->ua.index == idx) {
 		if (curr->flag&ISSET)
 			return (curr);
 		news = curr;
 	} else
 		news = NULL;
 	if (!news) {
-		len = strlen(vp->name);
-		checkoktoadd(len, 1 + offsetof(struct tbl, name[0]));
-		news = alloc(offsetof(struct tbl, name[0]) + ++len, vp->areap);
+		len = strlen(vp->name) + 1U;
+		news = alloc(mbccFAMsz(struct tbl, name, len), vp->areap);
 		memcpy(news->name, vp->name, len);
 	}
 	news->flag = (vp->flag & ~(ALLOC|DEFINED|ISSET|SPECIAL)) | AINDEX;
 	news->type = vp->type;
 	news->areap = vp->areap;
 	news->u2.field = vp->u2.field;
-	news->ua.index = val;
+	news->ua.index = idx;
 
 	if (curr != news) {
 		/* not reusing old array entry */
@@ -1610,26 +1701,30 @@ array_ref_len(const char *cp)
 }
 
 /*
- * Make a copy of the base of an array name
+ * same effect as global(copy of the base of an array name)
  */
-char *
-arrayname(const char *str)
+struct tbl *
+arraybase(const char *str)
 {
 	const char *p;
-	char *rv;
+	char *s, sbuf[32];
+	size_t n;
+	struct tbl *rv;
 
-	if (!(p = cstrchr(str, '[')))
-		/* Shouldn't happen, but why worry? */
-		strdupx(rv, str, ATEMP);
-	else
-		strndupx(rv, str, p - str, ATEMP);
+	n = strlen(str);
+	if ((p = memchr(str, '[', n)))
+		n = p - str;
+	strnbdupx(s, str, n, ATEMP, sbuf);
+	rv = global(s);
+	if (s != sbuf)
+		afree(s, ATEMP);
 
 	return (rv);
 }
 
 /* set (or overwrite, if reset) the array variable var to the values in vals */
 mksh_uari_t
-set_array(const char *var, bool reset, const char **vals)
+set_array(const char *var, Wahr reset, const char **vals)
 {
 	struct tbl *vp, *vq;
 	mksh_uari_t i = 0, j = 0;
@@ -1641,7 +1736,7 @@ set_array(const char *var, bool reset, c
 	n = strlen(var);
 	if (n > 0 && var[n - 1] == '+') {
 		/* append mode */
-		reset = false;
+		reset = Nee;
 		strndupx(cp, var, n - 1, ATEMP);
 		ccp = cp;
 	}
@@ -1649,7 +1744,8 @@ set_array(const char *var, bool reset, c
 
 	/* Note: AT&T ksh allows set -A but not set +A of a read-only var */
 	if ((vp->flag&RDONLY))
-		errorfx(2, Tf_ro, ccp);
+		kerrf(KWF_ERR(2) | KWF_PREFIX | KWF_FILELINE | KWF_TWOMSG |
+		    KWF_NOERRNO, ccp, Tread_only);
 	/* This code is quite non-optimal */
 	if (reset) {
 		/* trash existing values and attributes */
@@ -1692,7 +1788,7 @@ set_array(const char *var, bool reset, c
 				strndupx(cp, vals[i] + 1, ccp - (vals[i] + 1),
 				    ATEMP);
 				evaluate(substitute(cp, 0), (mksh_ari_t *)&j,
-				    KSH_UNWIND_ERROR, true);
+				    KSH_UNWIND_ERROR, Ja);
 				afree(cp, ATEMP);
 				ccp += 2;
 			} else
@@ -1700,7 +1796,7 @@ set_array(const char *var, bool reset, c
 		}
 #endif
 
-		vq = arraysearch(vp, j);
+		vq = arraysearch(vp, mbiMM(k32, K32_FM, j));
 		/* would be nice to deal with errors here... (see above) */
 		setstr(vq, ccp, KSH_RETURN_ERROR);
 		i++;
@@ -1713,116 +1809,187 @@ set_array(const char *var, bool reset, c
 void
 change_winsz(void)
 {
-	struct timeval tv;
-
-	mksh_TIME(tv);
-	BAFHUpdateMem_mem(qh_state, &tv, sizeof(tv));
-
+	struct {
+		struct timeval tv;
 #ifdef TIOCGWINSZ
-	/* check if window size has changed */
-	if (tty_init_fd() < 2) {
 		struct winsize ws;
+		int tif;
+		int ioc;
+		int eno;
+#endif
+#ifdef SIGWINCH
+		sig_atomic_t gotsig;
+#endif
+	} z;
 
-		if (ioctl(tty_fd, TIOCGWINSZ, &ws) >= 0) {
-			if (ws.ws_col)
-				x_cols = ws.ws_col;
-			if (ws.ws_row)
-				x_lins = ws.ws_row;
+	memset(&z, 0, sizeof(z));
+	mksh_TIME(z.tv);
+#ifdef SIGWINCH
+	z.gotsig = got_winch;
+#endif
+
+#ifdef TIOCGWINSZ
+	if ((z.tif = tty_init_fd()) < 2) {
+		/* check if window size has changed */
+		z.ioc = ioctl(tty_fd, TIOCGWINSZ, &z.ws);
+		z.eno = errno;
+#ifdef SIGWINCH
+		got_winch = 0;
+#endif
+		if (z.ioc >= 0) {
+			if (z.ws.ws_col)
+				x_cols = z.ws.ws_col;
+			if (z.ws.ws_row)
+				x_lins = z.ws.ws_row;
 		}
 	}
+#elif defined(SIGWINCH)
+	got_winch = 0;
 #endif
+	rndpush(&z, sizeof(z));
 
 	/* bounds check for sane values, use defaults otherwise */
 	if (x_cols < MIN_COLS)
 		x_cols = 80;
 	if (x_lins < MIN_LINS)
 		x_lins = 24;
-
-#ifdef SIGWINCH
-	got_winch = 0;
-#endif
 }
 
-uint32_t
+k32
 hash(const void *s)
 {
-	register uint32_t h;
+	register k32 h;
 
 	BAFHInit(h);
-	BAFHUpdateStr_reg(h, s);
-	BAFHFinish_reg(h);
+	BAFHUpdateStr(h, s);
+	BAFHFinish(h);
 	return (h);
 }
 
-uint32_t
+void
 chvt_rndsetup(const void *bp, size_t sz)
 {
-	register uint32_t h;
+	register k32 h;
 
-	/* use LCG as seed but try to get them to deviate immediately */
 	h = lcg_state;
-	(void)rndget();
-	BAFHFinish_reg(h);
+	BAFHUpdateVLQ(h, size_t, sz);
+	BAFHFinish(h);
 	/* variation through pid, ppid, and the works */
-	BAFHUpdateMem_reg(h, &rndsetupstate, sizeof(rndsetupstate));
+	BAFHUpdateMem(h, &rndsetupstate, sizeof(rndsetupstate));
 	/* some variation, some possibly entropy, depending on OE */
-	BAFHUpdateMem_reg(h, bp, sz);
+	BAFHUpdateMem(h, bp, sz);
 	/* mix them all up */
-	BAFHFinish_reg(h);
-
-	return (h);
+	BAFHFinish(h);
+	lcg_state = h;
 }
 
-mksh_ari_t
+k32
 rndget(void)
 {
 	/*
 	 * this is the same Linear Congruential PRNG as Borland
 	 * C/C++ allegedly uses in its built-in rand() function
 	 */
-	return (((lcg_state = 22695477 * lcg_state + 1) >> 16) & 0x7FFF);
+	lcg_state = mbiMO(k32, K32_FM,
+	    mbiMO(k32, K32_FM, 22695477U, *, lcg_state), +, 1U);
+	return (mbiMO(k32, K32_FM,
+	    mbiMKshr(k32, K32_FM, lcg_state, 16), &, 0x7FFFU));
 }
 
+#ifndef KSH_USE_ARC4RANDOM
+#if HAVE_GETRANDOM || defined(arc4random_pushb_fast) || defined(MKSH_A4PB)
+#define KSH_USE_ARC4RANDOM 0
+#elif defined(__OpenBSD__)
+#define KSH_USE_ARC4RANDOM 1
+#else
+#define KSH_USE_ARC4RANDOM 0
+#endif
+#endif
+
 void
 rndset(unsigned long v)
 {
-	register uint32_t h;
+	register k32 h;
 #if defined(arc4random_pushb_fast) || defined(MKSH_A4PB)
-	register uint32_t t;
+	register k32 t;
 #endif
 	struct {
 		struct timeval tv;
 		void *sp;
-		uint32_t qh;
+		k32 qh;
+#if HAVE_GETRANDOM
+		char xby[4];
+#endif
+#if KSH_USE_ARC4RANDOM
+		unsigned int xu32;
+#endif
 		pid_t pp;
-		short r;
+		unsigned short r;
 	} z;
+#if HAVE_GETRANDOM
+#ifdef GRND_INSECURE
+	static unsigned int grnd_iflag = GRND_INSECURE;
+#define grnd_flags (GRND_NONBLOCK | grnd_iflag)
+#else /* !GRND_INSECURE */
+#define grnd_flags GRND_NONBLOCK
+#endif /* !GRND_INSECURE */
+#endif /* HAVE_GETRANDOM */
 
 	/* clear the allocated space, for valgrind and to avoid UB */
 	memset(&z, 0, sizeof(z));
 
-	h = lcg_state;
-	BAFHFinish_reg(h);
-	BAFHUpdateMem_reg(h, &v, sizeof(v));
+	h = lcg_state ? lcg_state : (k32)1U;
+	BAFHFinish(h);
+	BAFHUpdateMem(h, &v, sizeof(v));
 
 	mksh_TIME(z.tv);
-	z.sp = &lcg_state;
+	z.sp = &z;
 	z.pp = procpid;
-	z.r = (short)rndget();
+	z.r = rndget();
+	/* nōn-blocking extra bytes from OS… if cheap and available */
+#if HAVE_GETRANDOM
+ try_getrandom:
+	if (getrandom(z.xby, sizeof(z.xby), grnd_flags) == -1)
+		switch (errno) {
+		case EINVAL:
+#ifdef GRND_INSECURE
+			if (grnd_iflag) {
+				/* try without again, old kernel? */
+				grnd_iflag = 0;
+				goto try_getrandom;
+			}
+#endif
+			/* FALLTHROUGH */
+		default:
+			/* warn for other errors */
+			kwarnf(KWF_WARNING | KWF_PREFIX | KWF_ONEMSG,
+			    "getrandom");
+			/* FALLTHROUGH */
+		case EAGAIN:
+		case ENOSYS:
+			/* ignore */
+			break;
+		case EINTR:
+			/* repeat */
+			goto try_getrandom;
+		}
+	/* otherwise, use whatever we got */
+#endif
+#if KSH_USE_ARC4RANDOM
+	z.xu32 = arc4random();
+#endif
 
 #if defined(arc4random_pushb_fast) || defined(MKSH_A4PB)
-	t = qh_state;
-	BAFHFinish_reg(t);
-	z.qh = (t & 0xFFFF8000) | rndget();
-	lcg_state = (t << 15) | rndget();
+	z.qh = (qh_state & 0xFFFF8000U) | rndget();
+	lcg_state = mbiMKshl(k32, K32_FM, qh_state, 15) | rndget();
 	/*
 	 * either we have very chap entropy get and push available,
 	 * with malloc() pulling in this code already anyway, or the
 	 * user requested us to use the old functions
 	 */
 	t = h;
-	BAFHUpdateMem_reg(t, &lcg_state, sizeof(lcg_state));
-	BAFHFinish_reg(t);
+	BAFHUpdateMem(t, &lcg_state, sizeof(lcg_state));
+	BAFHFinish(t);
 	lcg_state = t;
 #if defined(arc4random_pushb_fast)
 	arc4random_pushb_fast(&lcg_state, sizeof(lcg_state));
@@ -1830,23 +1997,23 @@ rndset(unsigned long v)
 #else
 	lcg_state = arc4random_pushb(&lcg_state, sizeof(lcg_state));
 #endif
-	BAFHUpdateMem_reg(h, &lcg_state, sizeof(lcg_state));
+	BAFHUpdateMem(h, &lcg_state, sizeof(lcg_state));
 #else
 	z.qh = qh_state;
 #endif
 
-	BAFHUpdateMem_reg(h, &z, sizeof(z));
-	BAFHFinish_reg(h);
+	BAFHUpdateMem(h, &z, sizeof(z));
+	BAFHFinish(h);
 	lcg_state = h;
 }
 
 void
-rndpush(const void *s)
+rndpush(const void *s, size_t n)
 {
-	register uint32_t h = qh_state;
+	register k32 h = qh_state ? qh_state : (k32)1U;
 
-	BAFHUpdateStr_reg(h, s);
-	BAFHUpdateOctet_reg(h, 0);
+	BAFHUpdateMem(h, s, n);
+	BAFHFinish(h);
 	qh_state = h;
 }
 
@@ -1856,7 +2023,7 @@ record_match(const char *istr)
 {
 	struct tbl *vp;
 
-	vp = local("KSH_MATCH", false);
+	vp = local("KSH_MATCH", Nee);
 	unset(vp, 1);
 	vp->flag = DEFINED | RDONLY;
 	setstr(vp, istr, 0x4);
@@ -1867,12 +2034,12 @@ int
 c_typeset(const char **wp)
 {
 	struct tbl *vp, **p;
-	uint32_t fset = 0, fclr = 0, flag;
+	kui fset = 0, fclr = 0, flag;
 	int thing = 0, field = 0, base = 0, i;
 	struct block *l;
 	const char *opts;
 	const char *fieldstr = NULL, *basestr = NULL;
-	bool localv = false, func = false, pflag = false, istset = true;
+	Wahr localv = Nee, func = Nee, pflag = Nee, istset = Ja;
 	enum namerefflag new_refflag = SRF_NOP;
 
 	switch (**wp) {
@@ -1880,13 +2047,13 @@ c_typeset(const char **wp)
 	/* export */
 	case 'e':
 		fset |= EXPORT;
-		istset = false;
+		istset = Nee;
 		break;
 
 	/* readonly */
 	case 'r':
 		fset |= RDONLY;
-		istset = false;
+		istset = Nee;
 		break;
 
 	/* set */
@@ -1896,7 +2063,7 @@ c_typeset(const char **wp)
 
 	/* typeset */
 	case 't':
-		localv = true;
+		localv = Ja;
 		break;
 	}
 
@@ -1944,10 +2111,10 @@ c_typeset(const char **wp)
 			 */
 			break;
 		case 'f':
-			func = true;
+			func = Ja;
 			break;
 		case 'g':
-			localv = (builtin_opt.info & GI_PLUS) ? true : false;
+			localv = isWahr(builtin_opt.info & GI_PLUS);
 			break;
 		case 'i':
 			flag = INTEGER;
@@ -1963,7 +2130,7 @@ c_typeset(const char **wp)
 		/* export, readonly: POSIX -p flag */
 		case 'p':
 			/* typeset: show values as well */
-			pflag = true;
+			pflag = Ja;
 			if (istset)
 				continue;
 			break;
@@ -1995,12 +2162,13 @@ c_typeset(const char **wp)
 	}
 
 	if (fieldstr && !getn(fieldstr, &field)) {
-		bi_errorf(Tf_sD_s, Tbadnum, fieldstr);
+		kwarnf(KWF_BIERR | KWF_TWOMSG, Tbadnum, fieldstr);
 		return (1);
 	}
 	if (basestr) {
 		if (!getn(basestr, &base)) {
-			bi_errorf(Tf_sD_s, "bad integer base", basestr);
+			kwarnf(KWF_BIERR | KWF_TWOMSG,
+			    "bad integer base", basestr);
 			return (1);
 		}
 		if (base < 1 || base > 36)
@@ -2017,7 +2185,8 @@ c_typeset(const char **wp)
 
 	if (func && (((fset|fclr) & ~(TRACE|UCASEV_AL|EXPORT)) ||
 	    new_refflag != SRF_NOP)) {
-		bi_errorf("only -t, -u and -x options may be used with -f");
+		kwarnf(KWF_BIERR | KWF_ONEMSG | KWF_NOERRNO,
+		    "only -t, -u and -x options may be used with -f");
 		return (1);
 	}
 	if (wp[builtin_opt.optind]) {
@@ -2067,7 +2236,7 @@ c_typeset(const char **wp)
 		for (i = builtin_opt.optind; wp[i]; i++) {
 			if (func) {
 				f = findfunc(wp[i], hash(wp[i]),
-				    tobool(fset & UCASEV_AL));
+				    isWahr(fset & UCASEV_AL));
 				if (!f) {
 					/* AT&T ksh does ++rv: bogus */
 					rv = 1;
@@ -2077,16 +2246,17 @@ c_typeset(const char **wp)
 					f->flag |= fset;
 					f->flag &= ~fclr;
 				} else {
-					fpFUNCTf(shl_stdout, 0,
-					    tobool(f->flag & FKSH),
-					    wp[i], f->val.t);
+					fpFUNCTf(wp[i], f->val.t,
+					    shl_stdout, 0,
+					    isWahr(f->flag & FKSH));
 					shf_putc('\n', shl_stdout);
 				}
 			} else if (!vtypeset(&x, wp[i], fset, fclr,
 			    field, base)) {
 				if (x)
 					return (x);
-				bi_errorf(Tf_sD_s, wp[i], Tnot_ident);
+				kwarnf(KWF_BIERR | KWF_TWOMSG | KWF_NOERRNO,
+				    wp[i], Tnot_ident);
 				return (1);
 			}
 		}
@@ -2103,9 +2273,9 @@ c_typeset(const char **wp)
 				if (flag && (vp->flag & flag) == 0)
 					continue;
 				if (thing == '-')
-					fpFUNCTf(shl_stdout, 0,
-					    tobool(vp->flag & FKSH),
-					    vp->name, vp->val.t);
+					fpFUNCTf(vp->name, vp->val.t,
+					    shl_stdout, 0,
+					    isWahr(vp->flag & FKSH));
 				else
 					shf_puts(vp->name, shl_stdout);
 				shf_putc('\n', shl_stdout);
@@ -2113,7 +2283,7 @@ c_typeset(const char **wp)
 		}
 	} else if (wp[builtin_opt.optind]) {
 		for (i = builtin_opt.optind; wp[i]; i++) {
-			vp = isglobal(wp[i], false);
+			vp = isglobal(wp[i], Nee);
 			c_typeset_vardump(vp, flag, thing,
 			    last_lookup_was_array ? 4 : 0, pflag, istset);
 		}
@@ -2123,8 +2293,8 @@ c_typeset(const char **wp)
 }
 
 static void
-c_typeset_vardump_recursive(struct block *l, uint32_t flag, int thing,
-    bool pflag, bool istset)
+c_typeset_vardump_recursive(struct block *l, kui flag, int thing,
+    Wahr pflag, Wahr istset)
 {
 	struct tbl **blockvars, *vp;
 
@@ -2137,11 +2307,10 @@ c_typeset_vardump_recursive(struct block
 }
 
 static void
-c_typeset_vardump(struct tbl *vp, uint32_t flag, int thing, int any_set,
-    bool pflag, bool istset)
+c_typeset_vardump(struct tbl *vp, kui flag, int thing, int any_set,
+    Wahr pflag, Wahr istset)
 {
 	struct tbl *tvp;
-	char *s;
 
 	if (!vp)
 		return;
@@ -2173,6 +2342,8 @@ c_typeset_vardump(struct tbl *vp, uint32
 		/* optimise later conditionals */
 		any_set = 0;
 	do {
+		Wahr baseone = Nee;
+
 		/*
 		 * Ignore array elements that aren't set unless there
 		 * are no set elements, in which case the first is
@@ -2191,11 +2362,16 @@ c_typeset_vardump(struct tbl *vp, uint32
 			 * leftadj, zerofill, etc., but POSIX says must
 			 * be suitable for re-entry...
 			 */
-			shprintf(Tf_s_s, Ttypeset, "");
+			shprintf(Tf_s_, Ttypeset);
 			if (((vp->flag & (ARRAY | ASSOC)) == ASSOC))
 				shprintf(Tf__c_, 'n');
-			if ((vp->flag & INTEGER))
-				shprintf(Tf__c_, 'i');
+			if ((vp->flag & INTEGER)) {
+				if (vp->type == 1) {
+					baseone = Ja;
+					shf_puts("-i1 ", shl_stdout);
+				} else
+					shprintf(Tf__c_, 'i');
+			}
 			if ((vp->flag & EXPORT))
 				shprintf(Tf__c_, 'x');
 			if ((vp->flag & RDONLY))
@@ -2215,22 +2391,28 @@ c_typeset_vardump(struct tbl *vp, uint32
 			if ((vp->flag & INT_U))
 				shprintf(Tf__c_, 'U');
 		} else if (pflag) {
-			shprintf(Tf_s_s, istset ? Ttypeset :
-			    (flag & EXPORT) ? Texport : Treadonly, "");
+			shprintf(Tf_s_, istset ? Ttypeset :
+			    (flag & EXPORT) ? Texport : Treadonly);
 		}
+		shf_puts(vp->name, shl_stdout);
 		if (any_set)
-			shprintf("%s[%lu]", vp->name, arrayindex(vp));
-		else
-			shf_puts(vp->name, shl_stdout);
-		if ((!thing && !flag && pflag) ||
-		    (thing == '-' && (vp->flag & ISSET))) {
-			s = str_val(vp);
+			shprintf(Tf_SQlu, arrayindex(vp));
+		if (((!thing && !flag && pflag) || thing == '-') &&
+		    (vp->flag & ISSET)) {
 			shf_putc('=', shl_stdout);
-			/* AT&T ksh can't have justified integers... */
-			if ((vp->flag & (INTEGER | LJUST | RJUST)) == INTEGER)
-				shf_puts(s, shl_stdout);
-			else
-				print_value_quoted(shl_stdout, s);
+			if (baseone)
+				shprintf(vp->val.u > 0xFF ? "16#%04X" :
+				    "16#%02X", (unsigned int)vp->val.u);
+			else {
+				const char *s = str_val(vp);
+
+				/* AT&T ksh can't have justified integers... */
+				if (IS(vp->flag, INTEGER | LJUST | RJUST,
+				    INTEGER))
+					shf_puts(s, shl_stdout);
+				else
+					print_value_quoted(shl_stdout, s);
+			}
 		}
 		shf_putc('\n', shl_stdout);
 
--- mksh-59c.orig/var_spec.h
+++ mksh-59c/var_spec.h
@@ -1,6 +1,6 @@
 /*-
  * Copyright (c) 2009, 2011, 2012, 2016, 2018
- *	mirabilos <m@mirbsd.org>
+ *	mirabilos <m$(date +%Y)@mirbsd.de>
  *
  * Provided that these terms and disclaimer and all copyright notices
  * are retained or reproduced in an accompanying document, permission
@@ -19,7 +19,7 @@
  */
 
 #if defined(VARSPEC_DEFNS)
-__RCSID("$MirOS: src/bin/mksh/var_spec.h,v 1.11 2018/01/13 21:38:10 tg Exp $");
+__RCSID("$MirOS: src/bin/mksh/var_spec.h,v 1.12 2025/04/25 23:15:02 tg Exp $");
 #define FN(name)			/* nothing */
 #elif defined(VARSPEC_ENUMS)
 #define FN(name)			V_##name,