summaryrefslogtreecommitdiff
path: root/perlio.c
blob: 209af1b0f15b0a451565bf5f816033a4f5d2dbf0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
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
/*
 * perlio.c
 * Copyright (c) 1996-2006, Nick Ing-Simmons
 * Copyright (c) 2006, 2007, 2008, 2009, 2010, 2011 Larry Wall and others
 *
 * You may distribute under the terms of either the GNU General Public License
 * or the Artistic License, as specified in the README file.
 */

/*
 * Hour after hour for nearly three weary days he had jogged up and down,
 * over passes, and through long dales, and across many streams.
 *
 *     [pp.791-792 of _The Lord of the Rings_, V/iii: "The Muster of Rohan"]
 */

/* This file contains the functions needed to implement PerlIO, which
 * is Perl's private replacement for the C stdio library. This is used
 * by default unless you compile with -Uuseperlio or run with
 * PERLIO=:stdio (but don't do this unless you know what you're doing)
 */

/*
 * If we have ActivePerl-like PERL_IMPLICIT_SYS then we need a dTHX to get
 * at the dispatch tables, even when we do not need it for other reasons.
 * Invent a dSYS macro to abstract this out
 */
#ifdef PERL_IMPLICIT_SYS
#define dSYS dTHX
#else
#define dSYS dNOOP
#endif

#define PERLIO_NOT_STDIO 0
/*
 * This file provides those parts of PerlIO abstraction
 * which are not #defined in perlio.h.
 * Which these are depends on various Configure #ifdef's
 */

#include "EXTERN.h"
#define PERL_IN_PERLIO_C
#include "perl.h"

#ifdef PERL_IMPLICIT_CONTEXT
#undef dSYS
#define dSYS dTHX
#endif

#include "XSUB.h"

#ifdef __Lynx__
/* Missing proto on LynxOS */
int mkstemp(char*);
#endif

#ifdef VMS
#include <rms.h>
#endif

#define PerlIO_lockcnt(f) (((PerlIOl*)(f))->head->flags)

/* Call the callback or PerlIOBase, and return failure. */
#define Perl_PerlIO_or_Base(f, callback, base, failure, args) 	\
	if (PerlIOValid(f)) {					\
		const PerlIO_funcs * const tab = PerlIOBase(f)->tab;\
		if (tab && tab->callback)			\
			return (*tab->callback) args;		\
		else						\
			return PerlIOBase_ ## base args;	\
	}							\
	else							\
		SETERRNO(EBADF, SS_IVCHAN);			\
	return failure

/* Call the callback or fail, and return failure. */
#define Perl_PerlIO_or_fail(f, callback, failure, args) 	\
	if (PerlIOValid(f)) {					\
		const PerlIO_funcs * const tab = PerlIOBase(f)->tab;\
		if (tab && tab->callback)			\
			return (*tab->callback) args;		\
		SETERRNO(EINVAL, LIB_INVARG);			\
	}							\
	else							\
		SETERRNO(EBADF, SS_IVCHAN);			\
	return failure

/* Call the callback or PerlIOBase, and be void. */
#define Perl_PerlIO_or_Base_void(f, callback, base, args) 	\
	if (PerlIOValid(f)) {					\
		const PerlIO_funcs * const tab = PerlIOBase(f)->tab;\
		if (tab && tab->callback)			\
			(*tab->callback) args;			\
		else						\
			PerlIOBase_ ## base args;		\
	}							\
	else							\
		SETERRNO(EBADF, SS_IVCHAN)

/* Call the callback or fail, and be void. */
#define Perl_PerlIO_or_fail_void(f, callback, args) 		\
	if (PerlIOValid(f)) {					\
		const PerlIO_funcs * const tab = PerlIOBase(f)->tab;\
		if (tab && tab->callback)			\
			(*tab->callback) args;			\
		else						\
			SETERRNO(EINVAL, LIB_INVARG);		\
	}							\
	else							\
		SETERRNO(EBADF, SS_IVCHAN)

#if defined(__osf__) && _XOPEN_SOURCE < 500
extern int   fseeko(FILE *, off_t, int);
extern off_t ftello(FILE *);
#endif

#define NATIVE_0xd  CR_NATIVE
#define NATIVE_0xa  LF_NATIVE

EXTERN_C int perlsio_binmode(FILE *fp, int iotype, int mode);

int
perlsio_binmode(FILE *fp, int iotype, int mode)
{
    /*
     * This used to be contents of do_binmode in doio.c
     */
#ifdef DOSISH
    dTHX;
    PERL_UNUSED_ARG(iotype);
#ifdef NETWARE
    if (PerlLIO_setmode(fp, mode) != -1) {
#else
    if (PerlLIO_setmode(fileno(fp), mode) != -1) {
#endif
        return 1;
    }
    else
        return 0;
#else
#  if defined(USEMYBINMODE)
    dTHX;
#    if defined(__CYGWIN__)
    PERL_UNUSED_ARG(iotype);
#    endif
    if (my_binmode(fp, iotype, mode) != FALSE)
        return 1;
    else
        return 0;
#  else
    PERL_UNUSED_ARG(fp);
    PERL_UNUSED_ARG(iotype);
    PERL_UNUSED_ARG(mode);
    return 1;
#  endif
#endif
}

#ifndef O_ACCMODE
#define O_ACCMODE 3             /* Assume traditional implementation */
#endif

int
PerlIO_intmode2str(int rawmode, char *mode, int *writing)
{
    const int result = rawmode & O_ACCMODE;
    int ix = 0;
    int ptype;
    switch (result) {
    case O_RDONLY:
	ptype = IoTYPE_RDONLY;
	break;
    case O_WRONLY:
	ptype = IoTYPE_WRONLY;
	break;
    case O_RDWR:
    default:
	ptype = IoTYPE_RDWR;
	break;
    }
    if (writing)
	*writing = (result != O_RDONLY);

    if (result == O_RDONLY) {
	mode[ix++] = 'r';
    }
#ifdef O_APPEND
    else if (rawmode & O_APPEND) {
	mode[ix++] = 'a';
	if (result != O_WRONLY)
	    mode[ix++] = '+';
    }
#endif
    else {
	if (result == O_WRONLY)
	    mode[ix++] = 'w';
	else {
	    mode[ix++] = 'r';
	    mode[ix++] = '+';
	}
    }
#if O_BINARY != 0
    /* Unless O_BINARY is different from zero, bit-and:ing
     * with it won't do much good. */
    if (rawmode & O_BINARY)
	mode[ix++] = 'b';
# endif
    mode[ix] = '\0';
    return ptype;
}

#ifndef PERLIO_LAYERS
int
PerlIO_apply_layers(pTHX_ PerlIO *f, const char *mode, const char *names)
{
    if (!names || !*names
        || strEQ(names, ":crlf")
        || strEQ(names, ":raw")
        || strEQ(names, ":bytes")
       ) {
	return 0;
    }
    Perl_croak(aTHX_ "Cannot apply \"%s\" in non-PerlIO perl", names);
    /*
     * NOTREACHED
     */
    return -1;
}

void
PerlIO_destruct(pTHX)
{
}

int
PerlIO_binmode(pTHX_ PerlIO *fp, int iotype, int mode, const char *names)
{
    return perlsio_binmode(fp, iotype, mode);
}

PerlIO *
PerlIO_fdupopen(pTHX_ PerlIO *f, CLONE_PARAMS *param, int flags)
{
#if defined(PERL_MICRO) || defined(__SYMBIAN32__)
    return NULL;
#else
#ifdef PERL_IMPLICIT_SYS
    return PerlSIO_fdupopen(f);
#else
#ifdef WIN32
    return win32_fdupopen(f);
#else
    if (f) {
	const int fd = PerlLIO_dup(PerlIO_fileno(f));
	if (fd >= 0) {
	    char mode[8];
#ifdef DJGPP
	    const int omode = djgpp_get_stream_mode(f);
#else
	    const int omode = fcntl(fd, F_GETFL);
#endif
	    PerlIO_intmode2str(omode,mode,NULL);
	    /* the r+ is a hack */
	    return PerlIO_fdopen(fd, mode);
	}
	return NULL;
    }
    else {
	SETERRNO(EBADF, SS_IVCHAN);
    }
#endif
    return NULL;
#endif
#endif
}


/*
 * De-mux PerlIO_openn() into fdopen, freopen and fopen type entries
 */

PerlIO *
PerlIO_openn(pTHX_ const char *layers, const char *mode, int fd,
	     int imode, int perm, PerlIO *old, int narg, SV **args)
{
    if (narg) {
	if (narg > 1) {
	    Perl_croak(aTHX_ "More than one argument to open");
	}
	if (*args == &PL_sv_undef)
	    return PerlIO_tmpfile();
	else {
            STRLEN len;
	    const char *name = SvPV_const(*args, len);
            if (!IS_SAFE_PATHNAME(name, len, "open"))
                return NULL;

	    if (*mode == IoTYPE_NUMERIC) {
		fd = PerlLIO_open3(name, imode, perm);
		if (fd >= 0)
		    return PerlIO_fdopen(fd, mode + 1);
	    }
	    else if (old) {
		return PerlIO_reopen(name, mode, old);
	    }
	    else {
		return PerlIO_open(name, mode);
	    }
	}
    }
    else {
	return PerlIO_fdopen(fd, (char *) mode);
    }
    return NULL;
}

XS(XS_PerlIO__Layer__find); /* prototype to pass -Wmissing-prototypes */
XS(XS_PerlIO__Layer__find)
{
    dXSARGS;
    if (items < 2)
	Perl_croak(aTHX_ "Usage class->find(name[,load])");
    else {
	const char * const name = SvPV_nolen_const(ST(1));
	ST(0) = (strEQ(name, "crlf")
		 || strEQ(name, "raw")) ? &PL_sv_yes : &PL_sv_undef;
	XSRETURN(1);
    }
}


void
Perl_boot_core_PerlIO(pTHX)
{
    newXS("PerlIO::Layer::find", XS_PerlIO__Layer__find, __FILE__);
}

#endif


/*======================================================================================*/
/*
 * Implement all the PerlIO interface ourselves.
 */

#include "perliol.h"

void
PerlIO_debug(const char *fmt, ...)
{
    va_list ap;
    dSYS;

    if (!DEBUG_i_TEST)
        return;

    va_start(ap, fmt);

    if (!PL_perlio_debug_fd) {
	if (!TAINTING_get &&
	    PerlProc_getuid() == PerlProc_geteuid() &&
	    PerlProc_getgid() == PerlProc_getegid()) {
	    const char * const s = PerlEnv_getenv("PERLIO_DEBUG");
	    if (s && *s)
		PL_perlio_debug_fd
		    = PerlLIO_open3(s, O_WRONLY | O_CREAT | O_APPEND, 0666);
	    else
		PL_perlio_debug_fd = PerlLIO_dup(2); /* stderr */
	} else {
	    /* tainting or set*id, so ignore the environment and send the
               debug output to stderr, like other -D switches.  */
	    PL_perlio_debug_fd = PerlLIO_dup(2); /* stderr */
	}
    }
    if (PL_perlio_debug_fd > 0) {
#ifdef USE_ITHREADS
	const char * const s = CopFILE(PL_curcop);
	/* Use fixed buffer as sv_catpvf etc. needs SVs */
	char buffer[1024];
	const STRLEN len1 = my_snprintf(buffer, sizeof(buffer), "%.40s:%" IVdf " ", s ? s : "(none)", (IV) CopLINE(PL_curcop));
	const STRLEN len2 = my_vsnprintf(buffer + len1, sizeof(buffer) - len1, fmt, ap);
	PERL_UNUSED_RESULT(PerlLIO_write(PL_perlio_debug_fd, buffer, len1 + len2));
#else
	const char *s = CopFILE(PL_curcop);
	STRLEN len;
	SV * const sv = Perl_newSVpvf(aTHX_ "%s:%" IVdf " ", s ? s : "(none)",
				      (IV) CopLINE(PL_curcop));
	Perl_sv_vcatpvf(aTHX_ sv, fmt, &ap);

	s = SvPV_const(sv, len);
	PERL_UNUSED_RESULT(PerlLIO_write(PL_perlio_debug_fd, s, len));
	SvREFCNT_dec(sv);
#endif
    }
    va_end(ap);
}

/*--------------------------------------------------------------------------------------*/

/*
 * Inner level routines
 */

/* check that the head field of each layer points back to the head */

#ifdef DEBUGGING
#  define VERIFY_HEAD(f) PerlIO_verify_head(aTHX_ f)
static void
PerlIO_verify_head(pTHX_ PerlIO *f)
{
    PerlIOl *head, *p;
    int seen = 0;
#ifndef PERL_IMPLICIT_SYS
    PERL_UNUSED_CONTEXT;
#endif
    if (!PerlIOValid(f))
	return;
    p = head = PerlIOBase(f)->head;
    assert(p);
    do {
	assert(p->head == head);
	if (p == (PerlIOl*)f)
	    seen = 1;
	p = p->next;
    } while (p);
    assert(seen);
}
#else
#  define VERIFY_HEAD(f)
#endif


/*
 * Table of pointers to the PerlIO structs (malloc'ed)
 */
#define PERLIO_TABLE_SIZE 64

static void
PerlIO_init_table(pTHX)
{
    if (PL_perlio)
	return;
    Newxz(PL_perlio, PERLIO_TABLE_SIZE, PerlIOl);
}



PerlIO *
PerlIO_allocate(pTHX)
{
    /*
     * Find a free slot in the table, allocating new table as necessary
     */
    PerlIOl **last;
    PerlIOl *f;
    last = &PL_perlio;
    while ((f = *last)) {
	int i;
	last = (PerlIOl **) (f);
	for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
	    if (!((++f)->next)) {
		goto good_exit;
	    }
	}
    }
    Newxz(f,PERLIO_TABLE_SIZE,PerlIOl);
    if (!f) {
	return NULL;
    }
    *last = (PerlIOl*) f++;

    good_exit:
    f->flags = 0; /* lockcnt */
    f->tab = NULL;
    f->head = f;
    return (PerlIO*) f;
}

#undef PerlIO_fdupopen
PerlIO *
PerlIO_fdupopen(pTHX_ PerlIO *f, CLONE_PARAMS *param, int flags)
{
    if (PerlIOValid(f)) {
	const PerlIO_funcs * const tab = PerlIOBase(f)->tab;
	DEBUG_i( PerlIO_debug("fdupopen f=%p param=%p\n",(void*)f,(void*)param) );
	if (tab && tab->Dup)
	     return (*tab->Dup)(aTHX_ PerlIO_allocate(aTHX), f, param, flags);
	else {
	     return PerlIOBase_dup(aTHX_ PerlIO_allocate(aTHX), f, param, flags);
	}
    }
    else
	 SETERRNO(EBADF, SS_IVCHAN);

    return NULL;
}

void
PerlIO_cleantable(pTHX_ PerlIOl **tablep)
{
    PerlIOl * const table = *tablep;
    if (table) {
	int i;
	PerlIO_cleantable(aTHX_(PerlIOl **) & (table[0]));
	for (i = PERLIO_TABLE_SIZE - 1; i > 0; i--) {
	    PerlIOl * const f = table + i;
	    if (f->next) {
		PerlIO_close(&(f->next));
	    }
	}
	Safefree(table);
	*tablep = NULL;
    }
}


PerlIO_list_t *
PerlIO_list_alloc(pTHX)
{
    PerlIO_list_t *list;
    PERL_UNUSED_CONTEXT;
    Newxz(list, 1, PerlIO_list_t);
    list->refcnt = 1;
    return list;
}

void
PerlIO_list_free(pTHX_ PerlIO_list_t *list)
{
    if (list) {
	if (--list->refcnt == 0) {
	    if (list->array) {
		IV i;
		for (i = 0; i < list->cur; i++)
		    SvREFCNT_dec(list->array[i].arg);
		Safefree(list->array);
	    }
	    Safefree(list);
	}
    }
}

void
PerlIO_list_push(pTHX_ PerlIO_list_t *list, PerlIO_funcs *funcs, SV *arg)
{
    PerlIO_pair_t *p;
    PERL_UNUSED_CONTEXT;

    if (list->cur >= list->len) {
        const IV new_len = list->len + 8;
	if (list->array)
	    Renew(list->array, new_len, PerlIO_pair_t);
	else
	    Newx(list->array, new_len, PerlIO_pair_t);
	list->len = new_len;
    }
    p = &(list->array[list->cur++]);
    p->funcs = funcs;
    if ((p->arg = arg)) {
	SvREFCNT_inc_simple_void_NN(arg);
    }
}

PerlIO_list_t *
PerlIO_clone_list(pTHX_ PerlIO_list_t *proto, CLONE_PARAMS *param)
{
    PerlIO_list_t *list = NULL;
    if (proto) {
	int i;
	list = PerlIO_list_alloc(aTHX);
	for (i=0; i < proto->cur; i++) {
	    SV *arg = proto->array[i].arg;
#ifdef USE_ITHREADS
	    if (arg && param)
		arg = sv_dup(arg, param);
#else
	    PERL_UNUSED_ARG(param);
#endif
	    PerlIO_list_push(aTHX_ list, proto->array[i].funcs, arg);
	}
    }
    return list;
}

void
PerlIO_clone(pTHX_ PerlInterpreter *proto, CLONE_PARAMS *param)
{
#ifdef USE_ITHREADS
    PerlIOl **table = &proto->Iperlio;
    PerlIOl *f;
    PL_perlio = NULL;
    PL_known_layers = PerlIO_clone_list(aTHX_ proto->Iknown_layers, param);
    PL_def_layerlist = PerlIO_clone_list(aTHX_ proto->Idef_layerlist, param);
    PerlIO_init_table(aTHX);
    DEBUG_i( PerlIO_debug("Clone %p from %p\n",(void*)aTHX,(void*)proto) );
    while ((f = *table)) {
	    int i;
	    table = (PerlIOl **) (f++);
	    for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
		if (f->next) {
		    (void) fp_dup(&(f->next), 0, param);
		}
		f++;
	    }
	}
#else
    PERL_UNUSED_CONTEXT;
    PERL_UNUSED_ARG(proto);
    PERL_UNUSED_ARG(param);
#endif
}

void
PerlIO_destruct(pTHX)
{
    PerlIOl **table = &PL_perlio;
    PerlIOl *f;
#ifdef USE_ITHREADS
    DEBUG_i( PerlIO_debug("Destruct %p\n",(void*)aTHX) );
#endif
    while ((f = *table)) {
	int i;
	table = (PerlIOl **) (f++);
	for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
	    PerlIO *x = &(f->next);
	    const PerlIOl *l;
	    while ((l = *x)) {
		if (l->tab && l->tab->kind & PERLIO_K_DESTRUCT) {
		    DEBUG_i( PerlIO_debug("Destruct popping %s\n", l->tab->name) );
		    PerlIO_flush(x);
		    PerlIO_pop(aTHX_ x);
		}
		else {
		    x = PerlIONext(x);
		}
	    }
	    f++;
	}
    }
}

void
PerlIO_pop(pTHX_ PerlIO *f)
{
    const PerlIOl *l = *f;
    VERIFY_HEAD(f);
    if (l) {
	DEBUG_i( PerlIO_debug("PerlIO_pop f=%p %s\n", (void*)f,
                              l->tab ? l->tab->name : "(Null)") );
	if (l->tab && l->tab->Popped) {
	    /*
	     * If popped returns non-zero do not free its layer structure
	     * it has either done so itself, or it is shared and still in
	     * use
	     */
	    if ((*l->tab->Popped) (aTHX_ f) != 0)
		return;
	}
	if (PerlIO_lockcnt(f)) {
	    /* we're in use; defer freeing the structure */
	    PerlIOBase(f)->flags = PERLIO_F_CLEARED;
	    PerlIOBase(f)->tab = NULL;
	}
	else {
	    *f = l->next;
	    Safefree(l);
	}

    }
}

/* Return as an array the stack of layers on a filehandle.  Note that
 * the stack is returned top-first in the array, and there are three
 * times as many array elements as there are layers in the stack: the
 * first element of a layer triplet is the name, the second one is the
 * arguments, and the third one is the flags. */

AV *
PerlIO_get_layers(pTHX_ PerlIO *f)
{
    AV * const av = newAV();

    if (PerlIOValid(f)) {
	PerlIOl *l = PerlIOBase(f);

	while (l) {
	    /* There is some collusion in the implementation of
	       XS_PerlIO_get_layers - it knows that name and flags are
	       generated as fresh SVs here, and takes advantage of that to
	       "copy" them by taking a reference. If it changes here, it needs
	       to change there too.  */
	    SV * const name = l->tab && l->tab->name ?
	    newSVpv(l->tab->name, 0) : &PL_sv_undef;
	    SV * const arg = l->tab && l->tab->Getarg ?
	    (*l->tab->Getarg)(aTHX_ &l, 0, 0) : &PL_sv_undef;
	    av_push(av, name);
	    av_push(av, arg);
	    av_push(av, newSViv((IV)l->flags));
	    l = l->next;
	}
    }

    return av;
}

/*--------------------------------------------------------------------------------------*/
/*
 * XS Interface for perl code
 */

PerlIO_funcs *
PerlIO_find_layer(pTHX_ const char *name, STRLEN len, int load)
{

    IV i;
    if ((SSize_t) len <= 0)
	len = strlen(name);
    for (i = 0; i < PL_known_layers->cur; i++) {
	PerlIO_funcs * const f = PL_known_layers->array[i].funcs;
        const STRLEN this_len = strlen(f->name);
        if (this_len == len && memEQ(f->name, name, len)) {
	    DEBUG_i( PerlIO_debug("%.*s => %p\n", (int) len, name, (void*)f) );
	    return f;
	}
    }
    if (load && PL_subname && PL_def_layerlist
	&& PL_def_layerlist->cur >= 2) {
	if (PL_in_load_module) {
	    Perl_croak(aTHX_ "Recursive call to Perl_load_module in PerlIO_find_layer");
	    return NULL;
	} else {
	    SV * const pkgsv = newSVpvs("PerlIO");
	    SV * const layer = newSVpvn(name, len);
	    CV * const cv    = get_cvs("PerlIO::Layer::NoWarnings", 0);
	    ENTER;
	    SAVEBOOL(PL_in_load_module);
	    if (cv) {
		SAVEGENERICSV(PL_warnhook);
		PL_warnhook = MUTABLE_SV((SvREFCNT_inc_simple_NN(cv)));
	    }
	    PL_in_load_module = TRUE;
	    /*
	     * The two SVs are magically freed by load_module
	     */
	    Perl_load_module(aTHX_ 0, pkgsv, NULL, layer, NULL);
	    LEAVE;
	    return PerlIO_find_layer(aTHX_ name, len, 0);
	}
    }
    DEBUG_i( PerlIO_debug("Cannot find %.*s\n", (int) len, name) );
    return NULL;
}

#ifdef USE_ATTRIBUTES_FOR_PERLIO

static int
perlio_mg_set(pTHX_ SV *sv, MAGIC *mg)
{
    if (SvROK(sv)) {
	IO * const io = GvIOn(MUTABLE_GV(SvRV(sv)));
	PerlIO * const ifp = IoIFP(io);
	PerlIO * const ofp = IoOFP(io);
	Perl_warn(aTHX_ "set %" SVf " %p %p %p",
		  SVfARG(sv), (void*)io, (void*)ifp, (void*)ofp);
    }
    return 0;
}

static int
perlio_mg_get(pTHX_ SV *sv, MAGIC *mg)
{
    if (SvROK(sv)) {
	IO * const io = GvIOn(MUTABLE_GV(SvRV(sv)));
	PerlIO * const ifp = IoIFP(io);
	PerlIO * const ofp = IoOFP(io);
	Perl_warn(aTHX_ "get %" SVf " %p %p %p",
		  SVfARG(sv), (void*)io, (void*)ifp, (void*)ofp);
    }
    return 0;
}

static int
perlio_mg_clear(pTHX_ SV *sv, MAGIC *mg)
{
    Perl_warn(aTHX_ "clear %" SVf, SVfARG(sv));
    return 0;
}

static int
perlio_mg_free(pTHX_ SV *sv, MAGIC *mg)
{
    Perl_warn(aTHX_ "free %" SVf, SVfARG(sv));
    return 0;
}

MGVTBL perlio_vtab = {
    perlio_mg_get,
    perlio_mg_set,
    NULL,                       /* len */
    perlio_mg_clear,
    perlio_mg_free
};

XS(XS_io_MODIFY_SCALAR_ATTRIBUTES); /* prototype to pass -Wmissing-prototypes */
XS(XS_io_MODIFY_SCALAR_ATTRIBUTES)
{
    dXSARGS;
    SV * const sv = SvRV(ST(1));
    AV * const av = newAV();
    MAGIC *mg;
    int count = 0;
    int i;
    sv_magic(sv, MUTABLE_SV(av), PERL_MAGIC_ext, NULL, 0);
    SvRMAGICAL_off(sv);
    mg = mg_find(sv, PERL_MAGIC_ext);
    mg->mg_virtual = &perlio_vtab;
    mg_magical(sv);
    Perl_warn(aTHX_ "attrib %" SVf, SVfARG(sv));
    for (i = 2; i < items; i++) {
	STRLEN len;
	const char * const name = SvPV_const(ST(i), len);
	SV * const layer = PerlIO_find_layer(aTHX_ name, len, 1);
	if (layer) {
	    av_push(av, SvREFCNT_inc_simple_NN(layer));
	}
	else {
	    ST(count) = ST(i);
	    count++;
	}
    }
    SvREFCNT_dec(av);
    XSRETURN(count);
}

#endif                          /* USE_ATTRIBUTES_FOR_PERLIO */

SV *
PerlIO_tab_sv(pTHX_ PerlIO_funcs *tab)
{
    HV * const stash = gv_stashpvs("PerlIO::Layer", GV_ADD);
    SV * const sv = sv_bless(newRV_noinc(newSViv(PTR2IV(tab))), stash);
    return sv;
}

XS(XS_PerlIO__Layer__NoWarnings); /* prototype to pass -Wmissing-prototypes */
XS(XS_PerlIO__Layer__NoWarnings)
{
    /* This is used as a %SIG{__WARN__} handler to suppress warnings
       during loading of layers.
     */
    dXSARGS;
    PERL_UNUSED_VAR(items);
    DEBUG_i(
        if (items)
            PerlIO_debug("warning:%s\n",SvPV_nolen_const(ST(0))) );
    XSRETURN(0);
}

XS(XS_PerlIO__Layer__find); /* prototype to pass -Wmissing-prototypes */
XS(XS_PerlIO__Layer__find)
{
    dXSARGS;
    if (items < 2)
	Perl_croak(aTHX_ "Usage class->find(name[,load])");
    else {
	STRLEN len;
	const char * const name = SvPV_const(ST(1), len);
	const bool load = (items > 2) ? SvTRUE_NN(ST(2)) : 0;
	PerlIO_funcs * const layer = PerlIO_find_layer(aTHX_ name, len, load);
	ST(0) =
	    (layer) ? sv_2mortal(PerlIO_tab_sv(aTHX_ layer)) :
	    &PL_sv_undef;
	XSRETURN(1);
    }
}

void
PerlIO_define_layer(pTHX_ PerlIO_funcs *tab)
{
    if (!PL_known_layers)
	PL_known_layers = PerlIO_list_alloc(aTHX);
    PerlIO_list_push(aTHX_ PL_known_layers, tab, NULL);
    DEBUG_i( PerlIO_debug("define %s %p\n", tab->name, (void*)tab) );
}

int
PerlIO_parse_layers(pTHX_ PerlIO_list_t *av, const char *names)
{
    if (names) {
	const char *s = names;
	while (*s) {
	    while (isSPACE(*s) || *s == ':')
		s++;
	    if (*s) {
		STRLEN llen = 0;
		const char *e = s;
		const char *as = NULL;
		STRLEN alen = 0;
		if (!isIDFIRST(*s)) {
		    /*
		     * Message is consistent with how attribute lists are
		     * passed. Even though this means "foo : : bar" is
		     * seen as an invalid separator character.
		     */
		    const char q = ((*s == '\'') ? '"' : '\'');
		    Perl_ck_warner(aTHX_ packWARN(WARN_LAYER),
				   "Invalid separator character %c%c%c in PerlIO layer specification %s",
				   q, *s, q, s);
		    SETERRNO(EINVAL, LIB_INVARG);
		    return -1;
		}
		do {
		    e++;
		} while (isWORDCHAR(*e));
		llen = e - s;
		if (*e == '(') {
		    int nesting = 1;
		    as = ++e;
		    while (nesting) {
			switch (*e++) {
			case ')':
			    if (--nesting == 0)
				alen = (e - 1) - as;
			    break;
			case '(':
			    ++nesting;
			    break;
			case '\\':
			    /*
			     * It's a nul terminated string, not allowed
			     * to \ the terminating null. Anything other
			     * character is passed over.
			     */
			    if (*e++) {
				break;
			    }
			    /*
			     * Drop through
			     */
			case '\0':
			    e--;
			    Perl_ck_warner(aTHX_ packWARN(WARN_LAYER),
					   "Argument list not closed for PerlIO layer \"%.*s\"",
					   (int) (e - s), s);
			    return -1;
			default:
			    /*
			     * boring.
			     */
			    break;
			}
		    }
		}
		if (e > s) {
		    PerlIO_funcs * const layer =
			PerlIO_find_layer(aTHX_ s, llen, 1);
		    if (layer) {
			SV *arg = NULL;
			if (as)
			    arg = newSVpvn(as, alen);
			PerlIO_list_push(aTHX_ av, layer,
					 (arg) ? arg : &PL_sv_undef);
			SvREFCNT_dec(arg);
		    }
		    else {
			Perl_ck_warner(aTHX_ packWARN(WARN_LAYER), "Unknown PerlIO layer \"%.*s\"",
				       (int) llen, s);
			return -1;
		    }
		}
		s = e;
	    }
	}
    }
    return 0;
}

void
PerlIO_default_buffer(pTHX_ PerlIO_list_t *av)
{
    PERLIO_FUNCS_DECL(*tab) = &PerlIO_perlio;
#ifdef PERLIO_USING_CRLF
    tab = &PerlIO_crlf;
#else
    if (PerlIO_stdio.Set_ptrcnt)
	tab = &PerlIO_stdio;
#endif
    DEBUG_i( PerlIO_debug("Pushing %s\n", tab->name) );
    PerlIO_list_push(aTHX_ av, (PerlIO_funcs *)tab, &PL_sv_undef);
}

SV *
PerlIO_arg_fetch(PerlIO_list_t *av, IV n)
{
    return av->array[n].arg;
}

PerlIO_funcs *
PerlIO_layer_fetch(pTHX_ PerlIO_list_t *av, IV n, PerlIO_funcs *def)
{
    if (n >= 0 && n < av->cur) {
	DEBUG_i( PerlIO_debug("Layer %" IVdf " is %s\n", n,
                              av->array[n].funcs->name) );
	return av->array[n].funcs;
    }
    if (!def)
	Perl_croak(aTHX_ "panic: PerlIO layer array corrupt");
    return def;
}

IV
PerlIOPop_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
{
    PERL_UNUSED_ARG(mode);
    PERL_UNUSED_ARG(arg);
    PERL_UNUSED_ARG(tab);
    if (PerlIOValid(f)) {
	PerlIO_flush(f);
	PerlIO_pop(aTHX_ f);
	return 0;
    }
    return -1;
}

PERLIO_FUNCS_DECL(PerlIO_remove) = {
    sizeof(PerlIO_funcs),
    "pop",
    0,
    PERLIO_K_DUMMY | PERLIO_K_UTF8,
    PerlIOPop_pushed,
    NULL,
    PerlIOBase_open,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,                       /* flush */
    NULL,                       /* fill */
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,                       /* get_base */
    NULL,                       /* get_bufsiz */
    NULL,                       /* get_ptr */
    NULL,                       /* get_cnt */
    NULL,                       /* set_ptrcnt */
};

PerlIO_list_t *
PerlIO_default_layers(pTHX)
{
    if (!PL_def_layerlist) {
	const char * const s = TAINTING_get ? NULL : PerlEnv_getenv("PERLIO");
	PERLIO_FUNCS_DECL(*osLayer) = &PerlIO_unix;
	PL_def_layerlist = PerlIO_list_alloc(aTHX);
	PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_unix));
#if defined(WIN32)
	PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_win32));
#if 0
	osLayer = &PerlIO_win32;
#endif
#endif
	PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_raw));
	PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_perlio));
	PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_stdio));
	PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_crlf));
	PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_utf8));
	PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_remove));
	PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_byte));
	PerlIO_list_push(aTHX_ PL_def_layerlist, (PerlIO_funcs *)osLayer,
                         &PL_sv_undef);
	if (s) {
	    PerlIO_parse_layers(aTHX_ PL_def_layerlist, s);
	}
	else {
	    PerlIO_default_buffer(aTHX_ PL_def_layerlist);
	}
    }
    if (PL_def_layerlist->cur < 2) {
	PerlIO_default_buffer(aTHX_ PL_def_layerlist);
    }
    return PL_def_layerlist;
}

void
Perl_boot_core_PerlIO(pTHX)
{
#ifdef USE_ATTRIBUTES_FOR_PERLIO
    newXS("io::MODIFY_SCALAR_ATTRIBUTES", XS_io_MODIFY_SCALAR_ATTRIBUTES,
	  __FILE__);
#endif
    newXS("PerlIO::Layer::find", XS_PerlIO__Layer__find, __FILE__);
    newXS("PerlIO::Layer::NoWarnings", XS_PerlIO__Layer__NoWarnings, __FILE__);
}

PerlIO_funcs *
PerlIO_default_layer(pTHX_ I32 n)
{
    PerlIO_list_t * const av = PerlIO_default_layers(aTHX);
    if (n < 0)
	n += av->cur;
    return PerlIO_layer_fetch(aTHX_ av, n, PERLIO_FUNCS_CAST(&PerlIO_stdio));
}

#define PerlIO_default_top() PerlIO_default_layer(aTHX_ -1)
#define PerlIO_default_btm() PerlIO_default_layer(aTHX_ 0)

void
PerlIO_stdstreams(pTHX)
{
    if (!PL_perlio) {
	PerlIO_init_table(aTHX);
	PerlIO_fdopen(0, "Ir" PERLIO_STDTEXT);
	PerlIO_fdopen(1, "Iw" PERLIO_STDTEXT);
	PerlIO_fdopen(2, "Iw" PERLIO_STDTEXT);
    }
}

PerlIO *
PerlIO_push(pTHX_ PerlIO *f, PERLIO_FUNCS_DECL(*tab), const char *mode, SV *arg)
{
    VERIFY_HEAD(f);
    if (tab->fsize != sizeof(PerlIO_funcs)) {
	Perl_croak( aTHX_
	    "%s (%" UVuf ") does not match %s (%" UVuf ")",
	    "PerlIO layer function table size", (UV)tab->fsize,
	    "size expected by this perl", (UV)sizeof(PerlIO_funcs) );
    }
    if (tab->size) {
	PerlIOl *l;
	if (tab->size < sizeof(PerlIOl)) {
	    Perl_croak( aTHX_
		"%s (%" UVuf ") smaller than %s (%" UVuf ")",
		"PerlIO layer instance size", (UV)tab->size,
		"size expected by this perl", (UV)sizeof(PerlIOl) );
	}
	/* Real layer with a data area */
	if (f) {
	    char *temp;
	    Newxz(temp, tab->size, char);
	    l = (PerlIOl*)temp;
	    if (l) {
		l->next = *f;
		l->tab = (PerlIO_funcs*) tab;
		l->head = ((PerlIOl*)f)->head;
		*f = l;
		DEBUG_i( PerlIO_debug("PerlIO_push f=%p %s %s %p\n",
                                      (void*)f, tab->name,
                                      (mode) ? mode : "(Null)", (void*)arg) );
		if (*l->tab->Pushed &&
		    (*l->tab->Pushed)
		      (aTHX_ f, mode, arg, (PerlIO_funcs*) tab) != 0) {
		    PerlIO_pop(aTHX_ f);
		    return NULL;
		}
	    }
	    else
		return NULL;
	}
    }
    else if (f) {
	/* Pseudo-layer where push does its own stack adjust */
	DEBUG_i( PerlIO_debug("PerlIO_push f=%p %s %s %p\n", (void*)f, tab->name,
                              (mode) ? mode : "(Null)", (void*)arg) );
	if (tab->Pushed &&
	    (*tab->Pushed) (aTHX_ f, mode, arg, (PerlIO_funcs*) tab) != 0) {
	     return NULL;
	}
    }
    return f;
}

PerlIO *
PerlIOBase_open(pTHX_ PerlIO_funcs *self, PerlIO_list_t *layers,
	       IV n, const char *mode, int fd, int imode, int perm,
	       PerlIO *old, int narg, SV **args)
{
    PerlIO_funcs * const tab = PerlIO_layer_fetch(aTHX_ layers, n - 1, PerlIO_default_layer(aTHX_ 0));
    if (tab && tab->Open) {
	PerlIO* ret = (*tab->Open)(aTHX_ tab, layers, n - 1, mode, fd, imode, perm, old, narg, args);
	if (ret && PerlIO_push(aTHX_ ret, self, mode, PerlIOArg) == NULL) {
	    PerlIO_close(ret);
	    return NULL;
	}
	return ret;
    }
    SETERRNO(EINVAL, LIB_INVARG);
    return NULL;
}

IV
PerlIOBase_binmode(pTHX_ PerlIO *f)
{
   if (PerlIOValid(f)) {
	/* Is layer suitable for raw stream ? */
	if (PerlIOBase(f)->tab && PerlIOBase(f)->tab->kind & PERLIO_K_RAW) {
	    /* Yes - turn off UTF-8-ness, to undo UTF-8 locale effects */
	    PerlIOBase(f)->flags &= ~PERLIO_F_UTF8;
	}
	else {
	    /* Not suitable - pop it */
	    PerlIO_pop(aTHX_ f);
	}
	return 0;
   }
   return -1;
}

IV
PerlIORaw_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
{
    PERL_UNUSED_ARG(mode);
    PERL_UNUSED_ARG(arg);
    PERL_UNUSED_ARG(tab);

    if (PerlIOValid(f)) {
	PerlIO *t;
	const PerlIOl *l;
	PerlIO_flush(f);
	/*
	 * Strip all layers that are not suitable for a raw stream
	 */
	t = f;
	while (t && (l = *t)) {
	    if (l->tab && l->tab->Binmode) {
		/* Has a handler - normal case */
		if ((*l->tab->Binmode)(aTHX_ t) == 0) {
		    if (*t == l) {
			/* Layer still there - move down a layer */
			t = PerlIONext(t);
		    }
		}
		else {
		    return -1;
		}
	    }
	    else {
		/* No handler - pop it */
		PerlIO_pop(aTHX_ t);
	    }
	}
	if (PerlIOValid(f)) {
	    DEBUG_i( PerlIO_debug(":raw f=%p :%s\n", (void*)f,
                         PerlIOBase(f)->tab ? PerlIOBase(f)->tab->name : "(Null)") );
	    return 0;
	}
    }
    return -1;
}

int
PerlIO_apply_layera(pTHX_ PerlIO *f, const char *mode,
		    PerlIO_list_t *layers, IV n, IV max)
{
    int code = 0;
    while (n < max) {
	PerlIO_funcs * const tab = PerlIO_layer_fetch(aTHX_ layers, n, NULL);
	if (tab) {
	    if (!PerlIO_push(aTHX_ f, tab, mode, PerlIOArg)) {
		code = -1;
		break;
	    }
	}
	n++;
    }
    return code;
}

int
PerlIO_apply_layers(pTHX_ PerlIO *f, const char *mode, const char *names)
{
    int code = 0;
    ENTER;
    save_scalar(PL_errgv);
    if (f && names) {
	PerlIO_list_t * const layers = PerlIO_list_alloc(aTHX);
	code = PerlIO_parse_layers(aTHX_ layers, names);
	if (code == 0) {
	    code = PerlIO_apply_layera(aTHX_ f, mode, layers, 0, layers->cur);
	}
	PerlIO_list_free(aTHX_ layers);
    }
    LEAVE;
    return code;
}


/*--------------------------------------------------------------------------------------*/
/*
 * Given the abstraction above the public API functions
 */

int
PerlIO_binmode(pTHX_ PerlIO *f, int iotype, int mode, const char *names)
{
    PERL_UNUSED_ARG(iotype);
    PERL_UNUSED_ARG(mode);

    DEBUG_i(
        PerlIO_debug("PerlIO_binmode f=%p %s %c %x %s\n", (void*)f,
                     (PerlIOBase(f) && PerlIOBase(f)->tab) ?
                     PerlIOBase(f)->tab->name : "(Null)",
                     iotype, mode, (names) ? names : "(Null)") );

    if (names) {
	/* Do not flush etc. if (e.g.) switching encodings.
	   if a pushed layer knows it needs to flush lower layers
	   (for example :unix which is never going to call them)
	   it can do the flush when it is pushed.
	 */
	return cBOOL(PerlIO_apply_layers(aTHX_ f, NULL, names) == 0);
    }
    else {
	/* Fake 5.6 legacy of using this call to turn ON O_TEXT */
#ifdef PERLIO_USING_CRLF
	/* Legacy binmode only has meaning if O_TEXT has a value distinct from
	   O_BINARY so we can look for it in mode.
	 */
	if (!(mode & O_BINARY)) {
	    /* Text mode */
	    /* FIXME?: Looking down the layer stack seems wrong,
	       but is a way of reaching past (say) an encoding layer
	       to flip CRLF-ness of the layer(s) below
	     */
	    while (*f) {
		/* Perhaps we should turn on bottom-most aware layer
		   e.g. Ilya's idea that UNIX TTY could serve
		 */
		if (PerlIOBase(f)->tab &&
		    PerlIOBase(f)->tab->kind & PERLIO_K_CANCRLF)
		{
		    if (!(PerlIOBase(f)->flags & PERLIO_F_CRLF)) {
			/* Not in text mode - flush any pending stuff and flip it */
			PerlIO_flush(f);
			PerlIOBase(f)->flags |= PERLIO_F_CRLF;
		    }
		    /* Only need to turn it on in one layer so we are done */
		    return TRUE;
		}
		f = PerlIONext(f);
	    }
	    /* Not finding a CRLF aware layer presumably means we are binary
	       which is not what was requested - so we failed
	       We _could_ push :crlf layer but so could caller
	     */
	    return FALSE;
	}
#endif
	/* Legacy binmode is now _defined_ as being equivalent to pushing :raw
	   So code that used to be here is now in PerlIORaw_pushed().
	 */
	return cBOOL(PerlIO_push(aTHX_ f, PERLIO_FUNCS_CAST(&PerlIO_raw), NULL, NULL));
    }
}

int
PerlIO__close(pTHX_ PerlIO *f)
{
    if (PerlIOValid(f)) {
	PerlIO_funcs * const tab = PerlIOBase(f)->tab;
	if (tab && tab->Close)
	    return (*tab->Close)(aTHX_ f);
	else
	    return PerlIOBase_close(aTHX_ f);
    }
    else {
	SETERRNO(EBADF, SS_IVCHAN);
	return -1;
    }
}

int
Perl_PerlIO_close(pTHX_ PerlIO *f)
{
    const int code = PerlIO__close(aTHX_ f);
    while (PerlIOValid(f)) {
	PerlIO_pop(aTHX_ f);
	if (PerlIO_lockcnt(f))
	    /* we're in use; the 'pop' deferred freeing the structure */
	    f = PerlIONext(f);
    }
    return code;
}

int
Perl_PerlIO_fileno(pTHX_ PerlIO *f)
{
    Perl_PerlIO_or_Base(f, Fileno, fileno, -1, (aTHX_ f));
}


static PerlIO_funcs *
PerlIO_layer_from_ref(pTHX_ SV *sv)
{
    /*
     * For any scalar type load the handler which is bundled with perl
     */
    if (SvTYPE(sv) < SVt_PVAV && (!isGV_with_GP(sv) || SvFAKE(sv))) {
	PerlIO_funcs *f = PerlIO_find_layer(aTHX_ STR_WITH_LEN("scalar"), 1);
	/* This isn't supposed to happen, since PerlIO::scalar is core,
	 * but could happen anyway in smaller installs or with PAR */
	if (!f)
	    /* diag_listed_as: Unknown PerlIO layer "%s" */
	    Perl_ck_warner(aTHX_ packWARN(WARN_LAYER), "Unknown PerlIO layer \"scalar\"");
	return f;
    }

    /*
     * For other types allow if layer is known but don't try and load it
     */
    switch (SvTYPE(sv)) {
    case SVt_PVAV:
	return PerlIO_find_layer(aTHX_ STR_WITH_LEN("Array"), 0);
    case SVt_PVHV:
	return PerlIO_find_layer(aTHX_ STR_WITH_LEN("Hash"), 0);
    case SVt_PVCV:
	return PerlIO_find_layer(aTHX_ STR_WITH_LEN("Code"), 0);
    case SVt_PVGV:
	return PerlIO_find_layer(aTHX_ STR_WITH_LEN("Glob"), 0);
    default:
	return NULL;
    }
}

PerlIO_list_t *
PerlIO_resolve_layers(pTHX_ const char *layers,
		      const char *mode, int narg, SV **args)
{
    PerlIO_list_t *def = PerlIO_default_layers(aTHX);
    int incdef = 1;
    if (!PL_perlio)
	PerlIO_stdstreams(aTHX);
    if (narg) {
	SV * const arg = *args;
	/*
	 * If it is a reference but not an object see if we have a handler
	 * for it
	 */
	if (SvROK(arg) && !SvOBJECT(SvRV(arg))) {
	    PerlIO_funcs * const handler = PerlIO_layer_from_ref(aTHX_ SvRV(arg));
	    if (handler) {
		def = PerlIO_list_alloc(aTHX);
		PerlIO_list_push(aTHX_ def, handler, &PL_sv_undef);
		incdef = 0;
	    }
	    /*
	     * Don't fail if handler cannot be found :via(...) etc. may do
	     * something sensible else we will just stringfy and open
	     * resulting string.
	     */
	}
    }
    if (!layers || !*layers)
	layers = Perl_PerlIO_context_layers(aTHX_ mode);
    if (layers && *layers) {
	PerlIO_list_t *av;
	if (incdef) {
	    av = PerlIO_clone_list(aTHX_ def, NULL);
	}
	else {
	    av = def;
	}
	if (PerlIO_parse_layers(aTHX_ av, layers) == 0) {
	     return av;
	}
	else {
	    PerlIO_list_free(aTHX_ av);
	    return NULL;
	}
    }
    else {
	if (incdef)
	    def->refcnt++;
	return def;
    }
}

PerlIO *
PerlIO_openn(pTHX_ const char *layers, const char *mode, int fd,
	     int imode, int perm, PerlIO *f, int narg, SV **args)
{
    if (!f && narg == 1 && *args == &PL_sv_undef) {
	if ((f = PerlIO_tmpfile())) {
	    if (!layers || !*layers)
		layers = Perl_PerlIO_context_layers(aTHX_ mode);
	    if (layers && *layers)
		PerlIO_apply_layers(aTHX_ f, mode, layers);
	}
    }
    else {
	PerlIO_list_t *layera;
	IV n;
	PerlIO_funcs *tab = NULL;
	if (PerlIOValid(f)) {
	    /*
	     * This is "reopen" - it is not tested as perl does not use it
	     * yet
	     */
	    PerlIOl *l = *f;
	    layera = PerlIO_list_alloc(aTHX);
	    while (l) {
		SV *arg = NULL;
		if (l->tab && l->tab->Getarg)
		    arg = (*l->tab->Getarg) (aTHX_ &l, NULL, 0);
		PerlIO_list_push(aTHX_ layera, l->tab,
				 (arg) ? arg : &PL_sv_undef);
		SvREFCNT_dec(arg);
		l = *PerlIONext(&l);
	    }
	}
	else {
	    layera = PerlIO_resolve_layers(aTHX_ layers, mode, narg, args);
	    if (!layera) {
		return NULL;
	    }
	}
	/*
	 * Start at "top" of layer stack
	 */
	n = layera->cur - 1;
	while (n >= 0) {
	    PerlIO_funcs * const t = PerlIO_layer_fetch(aTHX_ layera, n, NULL);
	    if (t && t->Open) {
		tab = t;
		break;
	    }
	    n--;
	}
	if (tab) {
	    /*
	     * Found that layer 'n' can do opens - call it
	     */
	    if (narg > 1 && !(tab->kind & PERLIO_K_MULTIARG)) {
		Perl_croak(aTHX_ "More than one argument to open(,':%s')",tab->name);
	    }
	    DEBUG_i( PerlIO_debug("openn(%s,'%s','%s',%d,%x,%o,%p,%d,%p)\n",
                                  tab->name, layers ? layers : "(Null)", mode, fd,
                                  imode, perm, (void*)f, narg, (void*)args) );
	    if (tab->Open)
		 f = (*tab->Open) (aTHX_ tab, layera, n, mode, fd, imode, perm,
				   f, narg, args);
	    else {
		 SETERRNO(EINVAL, LIB_INVARG);
		 f = NULL;
	    }
	    if (f) {
		if (n + 1 < layera->cur) {
		    /*
		     * More layers above the one that we used to open -
		     * apply them now
		     */
		    if (PerlIO_apply_layera(aTHX_ f, mode, layera, n + 1, layera->cur) != 0) {
			/* If pushing layers fails close the file */
			PerlIO_close(f);
			f = NULL;
		    }
		}
	    }
	}
	PerlIO_list_free(aTHX_ layera);
    }
    return f;
}


SSize_t
Perl_PerlIO_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
{
     PERL_ARGS_ASSERT_PERLIO_READ;

     Perl_PerlIO_or_Base(f, Read, read, -1, (aTHX_ f, vbuf, count));
}

SSize_t
Perl_PerlIO_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
{
     PERL_ARGS_ASSERT_PERLIO_UNREAD;

     Perl_PerlIO_or_Base(f, Unread, unread, -1, (aTHX_ f, vbuf, count));
}

SSize_t
Perl_PerlIO_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
{
     PERL_ARGS_ASSERT_PERLIO_WRITE;

     Perl_PerlIO_or_fail(f, Write, -1, (aTHX_ f, vbuf, count));
}

int
Perl_PerlIO_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
{
     Perl_PerlIO_or_fail(f, Seek, -1, (aTHX_ f, offset, whence));
}

Off_t
Perl_PerlIO_tell(pTHX_ PerlIO *f)
{
     Perl_PerlIO_or_fail(f, Tell, -1, (aTHX_ f));
}

int
Perl_PerlIO_flush(pTHX_ PerlIO *f)
{
    if (f) {
	if (*f) {
	    const PerlIO_funcs *tab = PerlIOBase(f)->tab;

	    if (tab && tab->Flush)
		return (*tab->Flush) (aTHX_ f);
	    else
		 return 0; /* If no Flush defined, silently succeed. */
	}
	else {
	    DEBUG_i( PerlIO_debug("Cannot flush f=%p\n", (void*)f) );
	    SETERRNO(EBADF, SS_IVCHAN);
	    return -1;
	}
    }
    else {
	/*
	 * Is it good API design to do flush-all on NULL, a potentially
	 * erroneous input? Maybe some magical value (PerlIO*
	 * PERLIO_FLUSH_ALL = (PerlIO*)-1;)? Yes, stdio does similar
	 * things on fflush(NULL), but should we be bound by their design
	 * decisions? --jhi
	 */
	PerlIOl **table = &PL_perlio;
	PerlIOl *ff;
	int code = 0;
	while ((ff = *table)) {
	    int i;
	    table = (PerlIOl **) (ff++);
	    for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
		if (ff->next && PerlIO_flush(&(ff->next)) != 0)
		    code = -1;
		ff++;
	    }
	}
	return code;
    }
}

void
PerlIOBase_flush_linebuf(pTHX)
{
    PerlIOl **table = &PL_perlio;
    PerlIOl *f;
    while ((f = *table)) {
	int i;
	table = (PerlIOl **) (f++);
	for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
	    if (f->next
		&& (PerlIOBase(&(f->next))->
		    flags & (PERLIO_F_LINEBUF | PERLIO_F_CANWRITE))
		== (PERLIO_F_LINEBUF | PERLIO_F_CANWRITE))
		PerlIO_flush(&(f->next));
	    f++;
	}
    }
}

int
Perl_PerlIO_fill(pTHX_ PerlIO *f)
{
     Perl_PerlIO_or_fail(f, Fill, -1, (aTHX_ f));
}

int
PerlIO_isutf8(PerlIO *f)
{
     if (PerlIOValid(f))
	  return (PerlIOBase(f)->flags & PERLIO_F_UTF8) != 0;
     else
	  SETERRNO(EBADF, SS_IVCHAN);

     return -1;
}

int
Perl_PerlIO_eof(pTHX_ PerlIO *f)
{
     Perl_PerlIO_or_Base(f, Eof, eof, -1, (aTHX_ f));
}

int
Perl_PerlIO_error(pTHX_ PerlIO *f)
{
     Perl_PerlIO_or_Base(f, Error, error, -1, (aTHX_ f));
}

void
Perl_PerlIO_clearerr(pTHX_ PerlIO *f)
{
     Perl_PerlIO_or_Base_void(f, Clearerr, clearerr, (aTHX_ f));
}

void
Perl_PerlIO_setlinebuf(pTHX_ PerlIO *f)
{
     Perl_PerlIO_or_Base_void(f, Setlinebuf, setlinebuf, (aTHX_ f));
}

int
PerlIO_has_base(PerlIO *f)
{
     if (PerlIOValid(f)) {
	  const PerlIO_funcs * const tab = PerlIOBase(f)->tab;

	  if (tab)
	       return (tab->Get_base != NULL);
     }

     return 0;
}

int
PerlIO_fast_gets(PerlIO *f)
{
    if (PerlIOValid(f)) {
	 if (PerlIOBase(f)->flags & PERLIO_F_FASTGETS) {
	     const PerlIO_funcs * const tab = PerlIOBase(f)->tab;

	     if (tab)
		  return (tab->Set_ptrcnt != NULL);
	 }
    }

    return 0;
}

int
PerlIO_has_cntptr(PerlIO *f)
{
    if (PerlIOValid(f)) {
	const PerlIO_funcs * const tab = PerlIOBase(f)->tab;

	if (tab)
	     return (tab->Get_ptr != NULL && tab->Get_cnt != NULL);
    }

    return 0;
}

int
PerlIO_canset_cnt(PerlIO *f)
{
    if (PerlIOValid(f)) {
	  const PerlIO_funcs * const tab = PerlIOBase(f)->tab;

	  if (tab)
	       return (tab->Set_ptrcnt != NULL);
    }

    return 0;
}

STDCHAR *
Perl_PerlIO_get_base(pTHX_ PerlIO *f)
{
     Perl_PerlIO_or_fail(f, Get_base, NULL, (aTHX_ f));
}

SSize_t
Perl_PerlIO_get_bufsiz(pTHX_ PerlIO *f)
{
    /* Note that Get_bufsiz returns a Size_t */
     Perl_PerlIO_or_fail(f, Get_bufsiz, -1, (aTHX_ f));
}

STDCHAR *
Perl_PerlIO_get_ptr(pTHX_ PerlIO *f)
{
     Perl_PerlIO_or_fail(f, Get_ptr, NULL, (aTHX_ f));
}

SSize_t
Perl_PerlIO_get_cnt(pTHX_ PerlIO *f)
{
     Perl_PerlIO_or_fail(f, Get_cnt, -1, (aTHX_ f));
}

void
Perl_PerlIO_set_cnt(pTHX_ PerlIO *f, SSize_t cnt)
{
     Perl_PerlIO_or_fail_void(f, Set_ptrcnt, (aTHX_ f, NULL, cnt));
}

void
Perl_PerlIO_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, SSize_t cnt)
{
     Perl_PerlIO_or_fail_void(f, Set_ptrcnt, (aTHX_ f, ptr, cnt));
}


/*--------------------------------------------------------------------------------------*/
/*
 * utf8 and raw dummy layers
 */

IV
PerlIOUtf8_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
{
    PERL_UNUSED_CONTEXT;
    PERL_UNUSED_ARG(mode);
    PERL_UNUSED_ARG(arg);
    if (PerlIOValid(f)) {
	if (tab && tab->kind & PERLIO_K_UTF8)
	    PerlIOBase(f)->flags |= PERLIO_F_UTF8;
	else
	    PerlIOBase(f)->flags &= ~PERLIO_F_UTF8;
	return 0;
    }
    return -1;
}

PERLIO_FUNCS_DECL(PerlIO_utf8) = {
    sizeof(PerlIO_funcs),
    "utf8",
    0,
    PERLIO_K_DUMMY | PERLIO_K_UTF8 | PERLIO_K_MULTIARG,
    PerlIOUtf8_pushed,
    NULL,
    PerlIOBase_open,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,                       /* flush */
    NULL,                       /* fill */
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,                       /* get_base */
    NULL,                       /* get_bufsiz */
    NULL,                       /* get_ptr */
    NULL,                       /* get_cnt */
    NULL,                       /* set_ptrcnt */
};

PERLIO_FUNCS_DECL(PerlIO_byte) = {
    sizeof(PerlIO_funcs),
    "bytes",
    0,
    PERLIO_K_DUMMY | PERLIO_K_MULTIARG,
    PerlIOUtf8_pushed,
    NULL,
    PerlIOBase_open,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,                       /* flush */
    NULL,                       /* fill */
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,                       /* get_base */
    NULL,                       /* get_bufsiz */
    NULL,                       /* get_ptr */
    NULL,                       /* get_cnt */
    NULL,                       /* set_ptrcnt */
};

PERLIO_FUNCS_DECL(PerlIO_raw) = {
    sizeof(PerlIO_funcs),
    "raw",
    0,
    PERLIO_K_DUMMY,
    PerlIORaw_pushed,
    PerlIOBase_popped,
    PerlIOBase_open,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,                       /* flush */
    NULL,                       /* fill */
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,                       /* get_base */
    NULL,                       /* get_bufsiz */
    NULL,                       /* get_ptr */
    NULL,                       /* get_cnt */
    NULL,                       /* set_ptrcnt */
};
/*--------------------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------------------*/
/*
 * "Methods" of the "base class"
 */

IV
PerlIOBase_fileno(pTHX_ PerlIO *f)
{
    return PerlIOValid(f) ? PerlIO_fileno(PerlIONext(f)) : -1;
}

char *
PerlIO_modestr(PerlIO * f, char *buf)
{
    char *s = buf;
    if (PerlIOValid(f)) {
	const IV flags = PerlIOBase(f)->flags;
	if (flags & PERLIO_F_APPEND) {
	    *s++ = 'a';
	    if (flags & PERLIO_F_CANREAD) {
		*s++ = '+';
	    }
	}
	else if (flags & PERLIO_F_CANREAD) {
	    *s++ = 'r';
	    if (flags & PERLIO_F_CANWRITE)
		*s++ = '+';
	}
	else if (flags & PERLIO_F_CANWRITE) {
	    *s++ = 'w';
	    if (flags & PERLIO_F_CANREAD) {
		*s++ = '+';
	    }
	}
#ifdef PERLIO_USING_CRLF
	if (!(flags & PERLIO_F_CRLF))
	    *s++ = 'b';
#endif
    }
    *s = '\0';
    return buf;
}


IV
PerlIOBase_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
{
    PerlIOl * const l = PerlIOBase(f);
    PERL_UNUSED_CONTEXT;
    PERL_UNUSED_ARG(arg);

    l->flags &= ~(PERLIO_F_CANREAD | PERLIO_F_CANWRITE |
		  PERLIO_F_TRUNCATE | PERLIO_F_APPEND);
    if (tab && tab->Set_ptrcnt != NULL)
	l->flags |= PERLIO_F_FASTGETS;
    if (mode) {
	if (*mode == IoTYPE_NUMERIC || *mode == IoTYPE_IMPLICIT)
	    mode++;
	switch (*mode++) {
	case 'r':
	    l->flags |= PERLIO_F_CANREAD;
	    break;
	case 'a':
	    l->flags |= PERLIO_F_APPEND | PERLIO_F_CANWRITE;
	    break;
	case 'w':
	    l->flags |= PERLIO_F_TRUNCATE | PERLIO_F_CANWRITE;
	    break;
	default:
	    SETERRNO(EINVAL, LIB_INVARG);
	    return -1;
	}
#ifdef EBCDIC
	{
        /* The mode variable contains one positional parameter followed by
         * optional keyword parameters.  The positional parameters must be
         * passed as lowercase characters.  The keyword parameters can be
         * passed in mixed case. They must be separated by commas. Only one
         * instance of a keyword can be specified.  */
	int comma = 0;
	while (*mode) {
	    switch (*mode++) {
	    case '+':
		if(!comma)
		  l->flags |= PERLIO_F_CANREAD | PERLIO_F_CANWRITE;
		break;
	    case 'b':
		if(!comma)
		  l->flags &= ~PERLIO_F_CRLF;
		break;
	    case 't':
		if(!comma)
		  l->flags |= PERLIO_F_CRLF;
		break;
	    case ',':
		comma = 1;
		break;
	    default:
		break;
	    }
	}
	}
#else
	while (*mode) {
	    switch (*mode++) {
	    case '+':
		l->flags |= PERLIO_F_CANREAD | PERLIO_F_CANWRITE;
		break;
	    case 'b':
		l->flags &= ~PERLIO_F_CRLF;
		break;
	    case 't':
		l->flags |= PERLIO_F_CRLF;
		break;
	    default:
		SETERRNO(EINVAL, LIB_INVARG);
		return -1;
	    }
	}
#endif
    }
    else {
	if (l->next) {
	    l->flags |= l->next->flags &
		(PERLIO_F_CANREAD | PERLIO_F_CANWRITE | PERLIO_F_TRUNCATE |
		 PERLIO_F_APPEND);
	}
    }
#if 0
    DEBUG_i(
    PerlIO_debug("PerlIOBase_pushed f=%p %s %s fl=%08" UVxf " (%s)\n",
		 (void*)f, PerlIOBase(f)->tab->name, (omode) ? omode : "(Null)",
		 l->flags, PerlIO_modestr(f, temp));
    );
#endif
    return 0;
}

IV
PerlIOBase_popped(pTHX_ PerlIO *f)
{
    PERL_UNUSED_CONTEXT;
    PERL_UNUSED_ARG(f);
    return 0;
}

SSize_t
PerlIOBase_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
{
    /*
     * Save the position as current head considers it
     */
    const Off_t old = PerlIO_tell(f);
    PerlIO_push(aTHX_ f, PERLIO_FUNCS_CAST(&PerlIO_pending), "r", NULL);
    PerlIOSelf(f, PerlIOBuf)->posn = old;
    return PerlIOBuf_unread(aTHX_ f, vbuf, count);
}

SSize_t
PerlIOBase_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
{
    STDCHAR *buf = (STDCHAR *) vbuf;
    if (f) {
        if (!(PerlIOBase(f)->flags & PERLIO_F_CANREAD)) {
	    PerlIOBase(f)->flags |= PERLIO_F_ERROR;
	    SETERRNO(EBADF, SS_IVCHAN);
	    PerlIO_save_errno(f);
	    return 0;
	}
	while (count > 0) {
	 get_cnt:
	  {
	    SSize_t avail = PerlIO_get_cnt(f);
	    SSize_t take = 0;
	    if (avail > 0)
		take = (((SSize_t) count >= 0) && ((SSize_t)count < avail)) ? (SSize_t)count : avail;
	    if (take > 0) {
		STDCHAR *ptr = PerlIO_get_ptr(f);
		Copy(ptr, buf, take, STDCHAR);
		PerlIO_set_ptrcnt(f, ptr + take, (avail -= take));
		count -= take;
		buf += take;
		if (avail == 0)		/* set_ptrcnt could have reset avail */
		    goto get_cnt;
	    }
	    if (count > 0 && avail <= 0) {
		if (PerlIO_fill(f) != 0)
		    break;
	    }
	  }
	}
	return (buf - (STDCHAR *) vbuf);
    }
    return 0;
}

IV
PerlIOBase_noop_ok(pTHX_ PerlIO *f)
{
    PERL_UNUSED_CONTEXT;
    PERL_UNUSED_ARG(f);
    return 0;
}

IV
PerlIOBase_noop_fail(pTHX_ PerlIO *f)
{
    PERL_UNUSED_CONTEXT;
    PERL_UNUSED_ARG(f);
    return -1;
}

IV
PerlIOBase_close(pTHX_ PerlIO *f)
{
    IV code = -1;
    if (PerlIOValid(f)) {
	PerlIO *n = PerlIONext(f);
	code = PerlIO_flush(f);
	PerlIOBase(f)->flags &=
	   ~(PERLIO_F_CANREAD | PERLIO_F_CANWRITE | PERLIO_F_OPEN);
	while (PerlIOValid(n)) {
	    const PerlIO_funcs * const tab = PerlIOBase(n)->tab;
	    if (tab && tab->Close) {
		if ((*tab->Close)(aTHX_ n) != 0)
		    code = -1;
		break;
	    }
	    else {
		PerlIOBase(n)->flags &=
		    ~(PERLIO_F_CANREAD | PERLIO_F_CANWRITE | PERLIO_F_OPEN);
	    }
	    n = PerlIONext(n);
	}
    }
    else {
	SETERRNO(EBADF, SS_IVCHAN);
    }
    return code;
}

IV
PerlIOBase_eof(pTHX_ PerlIO *f)
{
    PERL_UNUSED_CONTEXT;
    if (PerlIOValid(f)) {
	return (PerlIOBase(f)->flags & PERLIO_F_EOF) != 0;
    }
    return 1;
}

IV
PerlIOBase_error(pTHX_ PerlIO *f)
{
    PERL_UNUSED_CONTEXT;
    if (PerlIOValid(f)) {
	return (PerlIOBase(f)->flags & PERLIO_F_ERROR) != 0;
    }
    return 1;
}

void
PerlIOBase_clearerr(pTHX_ PerlIO *f)
{
    if (PerlIOValid(f)) {
	PerlIO * const n = PerlIONext(f);
	PerlIOBase(f)->flags &= ~(PERLIO_F_ERROR | PERLIO_F_EOF);
	if (PerlIOValid(n))
	    PerlIO_clearerr(n);
    }
}

void
PerlIOBase_setlinebuf(pTHX_ PerlIO *f)
{
    PERL_UNUSED_CONTEXT;
    if (PerlIOValid(f)) {
	PerlIOBase(f)->flags |= PERLIO_F_LINEBUF;
    }
}

SV *
PerlIO_sv_dup(pTHX_ SV *arg, CLONE_PARAMS *param)
{
    if (!arg)
	return NULL;
#ifdef USE_ITHREADS
    if (param) {
	arg = sv_dup(arg, param);
	SvREFCNT_inc_simple_void_NN(arg);
	return arg;
    }
    else {
	return newSVsv(arg);
    }
#else
    PERL_UNUSED_ARG(param);
    return newSVsv(arg);
#endif
}

PerlIO *
PerlIOBase_dup(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags)
{
    PerlIO * const nexto = PerlIONext(o);
    if (PerlIOValid(nexto)) {
	const PerlIO_funcs * const tab = PerlIOBase(nexto)->tab;
	if (tab && tab->Dup)
	    f = (*tab->Dup)(aTHX_ f, nexto, param, flags);
	else
	    f = PerlIOBase_dup(aTHX_ f, nexto, param, flags);
    }
    if (f) {
	PerlIO_funcs * const self = PerlIOBase(o)->tab;
	SV *arg = NULL;
	char buf[8];
	assert(self);
	DEBUG_i(PerlIO_debug("PerlIOBase_dup %s f=%p o=%p param=%p\n",
                             self->name,
                             (void*)f, (void*)o, (void*)param) );
	if (self->Getarg)
	  arg = (*self->Getarg)(aTHX_ o, param, flags);
	f = PerlIO_push(aTHX_ f, self, PerlIO_modestr(o,buf), arg);
	if (f && PerlIOBase(o)->flags & PERLIO_F_UTF8)
	    PerlIOBase(f)->flags |= PERLIO_F_UTF8;
	SvREFCNT_dec(arg);
    }
    return f;
}

/* PL_perlio_fd_refcnt[] is in intrpvar.h */

/* Must be called with PL_perlio_mutex locked. */
static void
S_more_refcounted_fds(pTHX_ const int new_fd)
  PERL_TSA_REQUIRES(PL_perlio_mutex)
{
    dVAR;
    const int old_max = PL_perlio_fd_refcnt_size;
    const int new_max = 16 + (new_fd & ~15);
    int *new_array;

#ifndef PERL_IMPLICIT_SYS
    PERL_UNUSED_CONTEXT;
#endif

    DEBUG_i( PerlIO_debug("More fds - old=%d, need %d, new=%d\n",
                          old_max, new_fd, new_max) );

    if (new_fd < old_max) {
	return;
    }

    assert (new_max > new_fd);

    /* Use plain realloc() since we need this memory to be really
     * global and visible to all the interpreters and/or threads. */
    new_array = (int*) realloc(PL_perlio_fd_refcnt, new_max * sizeof(int));

    if (!new_array) {
	MUTEX_UNLOCK(&PL_perlio_mutex);
	croak_no_mem();
    }

    PL_perlio_fd_refcnt_size = new_max;
    PL_perlio_fd_refcnt = new_array;

    DEBUG_i( PerlIO_debug("Zeroing %p, %d\n",
                          (void*)(new_array + old_max),
                          new_max - old_max) );

    Zero(new_array + old_max, new_max - old_max, int);
}


void
PerlIO_init(pTHX)
{
    /* MUTEX_INIT(&PL_perlio_mutex) is done in PERL_SYS_INIT3(). */
    PERL_UNUSED_CONTEXT;
}

void
PerlIOUnix_refcnt_inc(int fd)
{
    dTHX;
    if (fd >= 0) {
	dVAR;

	MUTEX_LOCK(&PL_perlio_mutex);
	if (fd >= PL_perlio_fd_refcnt_size)
	    S_more_refcounted_fds(aTHX_ fd);

	PL_perlio_fd_refcnt[fd]++;
	if (PL_perlio_fd_refcnt[fd] <= 0) {
	    /* diag_listed_as: refcnt_inc: fd %d%s */
	    Perl_croak(aTHX_ "refcnt_inc: fd %d: %d <= 0\n",
		       fd, PL_perlio_fd_refcnt[fd]);
	}
	DEBUG_i( PerlIO_debug("refcnt_inc: fd %d refcnt=%d\n",
                              fd, PL_perlio_fd_refcnt[fd]) );

	MUTEX_UNLOCK(&PL_perlio_mutex);
    } else {
	/* diag_listed_as: refcnt_inc: fd %d%s */
	Perl_croak(aTHX_ "refcnt_inc: fd %d < 0\n", fd);
    }
}

int
PerlIOUnix_refcnt_dec(int fd)
{
    int cnt = 0;
    if (fd >= 0) {
#ifdef DEBUGGING
        dTHX;
#else
	dVAR;
#endif
	MUTEX_LOCK(&PL_perlio_mutex);
	if (fd >= PL_perlio_fd_refcnt_size) {
	    /* diag_listed_as: refcnt_dec: fd %d%s */
	    Perl_croak_nocontext("refcnt_dec: fd %d >= refcnt_size %d\n",
		       fd, PL_perlio_fd_refcnt_size);
	}
	if (PL_perlio_fd_refcnt[fd] <= 0) {
	    /* diag_listed_as: refcnt_dec: fd %d%s */
	    Perl_croak_nocontext("refcnt_dec: fd %d: %d <= 0\n",
		       fd, PL_perlio_fd_refcnt[fd]);
	}
	cnt = --PL_perlio_fd_refcnt[fd];
	DEBUG_i( PerlIO_debug("refcnt_dec: fd %d refcnt=%d\n", fd, cnt) );
	MUTEX_UNLOCK(&PL_perlio_mutex);
    } else {
	/* diag_listed_as: refcnt_dec: fd %d%s */
	Perl_croak_nocontext("refcnt_dec: fd %d < 0\n", fd);
    }
    return cnt;
}

int
PerlIOUnix_refcnt(int fd)
{
    dTHX;
    int cnt = 0;
    if (fd >= 0) {
	dVAR;
	MUTEX_LOCK(&PL_perlio_mutex);
	if (fd >= PL_perlio_fd_refcnt_size) {
	    /* diag_listed_as: refcnt: fd %d%s */
	    Perl_croak(aTHX_ "refcnt: fd %d >= refcnt_size %d\n",
		       fd, PL_perlio_fd_refcnt_size);
	}
	if (PL_perlio_fd_refcnt[fd] <= 0) {
	    /* diag_listed_as: refcnt: fd %d%s */
	    Perl_croak(aTHX_ "refcnt: fd %d: %d <= 0\n",
		       fd, PL_perlio_fd_refcnt[fd]);
	}
	cnt = PL_perlio_fd_refcnt[fd];
	MUTEX_UNLOCK(&PL_perlio_mutex);
    } else {
	/* diag_listed_as: refcnt: fd %d%s */
	Perl_croak(aTHX_ "refcnt: fd %d < 0\n", fd);
    }
    return cnt;
}

void
PerlIO_cleanup(pTHX)
{
    int i;
#ifdef USE_ITHREADS
    DEBUG_i( PerlIO_debug("Cleanup layers for %p\n",(void*)aTHX) );
#else
    DEBUG_i( PerlIO_debug("Cleanup layers\n") );
#endif

    /* Raise STDIN..STDERR refcount so we don't close them */
    for (i=0; i < 3; i++)
	PerlIOUnix_refcnt_inc(i);
    PerlIO_cleantable(aTHX_ &PL_perlio);
    /* Restore STDIN..STDERR refcount */
    for (i=0; i < 3; i++)
	PerlIOUnix_refcnt_dec(i);

    if (PL_known_layers) {
	PerlIO_list_free(aTHX_ PL_known_layers);
	PL_known_layers = NULL;
    }
    if (PL_def_layerlist) {
	PerlIO_list_free(aTHX_ PL_def_layerlist);
	PL_def_layerlist = NULL;
    }
}

void PerlIO_teardown(void) /* Call only from PERL_SYS_TERM(). */
{
    dVAR;
#if 0
/* XXX we can't rely on an interpreter being present at this late stage,
   XXX so we can't use a function like PerlLIO_write that relies on one
   being present (at least in win32) :-(.
   Disable for now.
*/
#ifdef DEBUGGING
    {
	/* By now all filehandles should have been closed, so any
	 * stray (non-STD-)filehandles indicate *possible* (PerlIO)
	 * errors. */
#define PERLIO_TEARDOWN_MESSAGE_BUF_SIZE 64
#define PERLIO_TEARDOWN_MESSAGE_FD 2
	char buf[PERLIO_TEARDOWN_MESSAGE_BUF_SIZE];
	int i;
	for (i = 3; i < PL_perlio_fd_refcnt_size; i++) {
	    if (PL_perlio_fd_refcnt[i]) {
		const STRLEN len =
		    my_snprintf(buf, sizeof(buf),
				"PerlIO_teardown: fd %d refcnt=%d\n",
				i, PL_perlio_fd_refcnt[i]);
		PerlLIO_write(PERLIO_TEARDOWN_MESSAGE_FD, buf, len);
	    }
	}
    }
#endif
#endif
    /* Not bothering with PL_perlio_mutex since by now
     * all the interpreters are gone. */
    if (PL_perlio_fd_refcnt_size /* Assuming initial size of zero. */
        && PL_perlio_fd_refcnt) {
	free(PL_perlio_fd_refcnt); /* To match realloc() in S_more_refcounted_fds(). */
	PL_perlio_fd_refcnt = NULL;
	PL_perlio_fd_refcnt_size = 0;
    }
}

/*--------------------------------------------------------------------------------------*/
/*
 * Bottom-most level for UNIX-like case
 */

typedef struct {
    struct _PerlIO base;        /* The generic part */
    int fd;                     /* UNIX like file descriptor */
    int oflags;                 /* open/fcntl flags */
} PerlIOUnix;

static void
S_lockcnt_dec(pTHX_ const void* f)
{
#ifndef PERL_IMPLICIT_SYS
    PERL_UNUSED_CONTEXT;
#endif
    PerlIO_lockcnt((PerlIO*)f)--;
}


/* call the signal handler, and if that handler happens to clear
 * this handle, free what we can and return true */

static bool
S_perlio_async_run(pTHX_ PerlIO* f) {
    ENTER;
    SAVEDESTRUCTOR_X(S_lockcnt_dec, (void*)f);
    PerlIO_lockcnt(f)++;
    PERL_ASYNC_CHECK();
    if ( !(PerlIOBase(f)->flags & PERLIO_F_CLEARED) ) {
	LEAVE;
	return 0;
    }
    /* we've just run some perl-level code that could have done
     * anything, including closing the file or clearing this layer.
     * If so, free any lower layers that have already been
     * cleared, then return an error. */
    while (PerlIOValid(f) &&
	    (PerlIOBase(f)->flags & PERLIO_F_CLEARED))
    {
	const PerlIOl *l = *f;
	*f = l->next;
	Safefree(l);
    }
    LEAVE;
    return 1;
}

int
PerlIOUnix_oflags(const char *mode)
{
    int oflags = -1;
    if (*mode == IoTYPE_IMPLICIT || *mode == IoTYPE_NUMERIC)
	mode++;
    switch (*mode) {
    case 'r':
	oflags = O_RDONLY;
	if (*++mode == '+') {
	    oflags = O_RDWR;
	    mode++;
	}
	break;

    case 'w':
	oflags = O_CREAT | O_TRUNC;
	if (*++mode == '+') {
	    oflags |= O_RDWR;
	    mode++;
	}
	else
	    oflags |= O_WRONLY;
	break;

    case 'a':
	oflags = O_CREAT | O_APPEND;
	if (*++mode == '+') {
	    oflags |= O_RDWR;
	    mode++;
	}
	else
	    oflags |= O_WRONLY;
	break;
    }

    /* XXX TODO: PerlIO_open() test that exercises 'rb' and 'rt'. */

    /* Unless O_BINARY is different from O_TEXT, first bit-or:ing one
     * of them in, and then bit-and-masking the other them away, won't
     * have much of an effect. */
    switch (*mode) {
    case 'b':
#if O_TEXT != O_BINARY
        oflags |= O_BINARY;
	oflags &= ~O_TEXT;
#endif
        mode++;
        break;
    case 't':
#if O_TEXT != O_BINARY
	oflags |= O_TEXT;
	oflags &= ~O_BINARY;
#endif
        mode++;
        break;
    default:
#  if O_BINARY != 0
        /* bit-or:ing with zero O_BINARY would be useless. */
	/*
	 * If neither "t" nor "b" was specified, open the file
	 * in O_BINARY mode.
         *
         * Note that if something else than the zero byte was seen
         * here (e.g. bogus mode "rx"), just few lines later we will
         * set the errno and invalidate the flags.
	 */
	oflags |= O_BINARY;
#  endif
        break;
    }
    if (*mode || oflags == -1) {
	SETERRNO(EINVAL, LIB_INVARG);
	oflags = -1;
    }
    return oflags;
}

IV
PerlIOUnix_fileno(pTHX_ PerlIO *f)
{
    PERL_UNUSED_CONTEXT;
    return PerlIOSelf(f, PerlIOUnix)->fd;
}

static void
PerlIOUnix_setfd(pTHX_ PerlIO *f, int fd, int imode)
{
    PerlIOUnix * const s = PerlIOSelf(f, PerlIOUnix);
#if defined(WIN32)
    Stat_t st;
    if (PerlLIO_fstat(fd, &st) == 0) {
	if (!S_ISREG(st.st_mode)) {
	    DEBUG_i( PerlIO_debug("%d is not regular file\n",fd) );
    	    PerlIOBase(f)->flags |= PERLIO_F_NOTREG;
	}
	else {
	    DEBUG_i( PerlIO_debug("%d _is_ a regular file\n",fd) );
	}
    }
#endif
    s->fd = fd;
    s->oflags = imode;
    PerlIOUnix_refcnt_inc(fd);
    PERL_UNUSED_CONTEXT;
}

IV
PerlIOUnix_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
{
    IV code = PerlIOBase_pushed(aTHX_ f, mode, arg, tab);
    if (*PerlIONext(f)) {
	/* We never call down so do any pending stuff now */
	PerlIO_flush(PerlIONext(f));
	/*
	 * XXX could (or should) we retrieve the oflags from the open file
	 * handle rather than believing the "mode" we are passed in? XXX
	 * Should the value on NULL mode be 0 or -1?
	 */
        PerlIOUnix_setfd(aTHX_ f, PerlIO_fileno(PerlIONext(f)),
                         mode ? PerlIOUnix_oflags(mode) : -1);
    }
    PerlIOBase(f)->flags |= PERLIO_F_OPEN;

    return code;
}

IV
PerlIOUnix_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
{
    const int fd = PerlIOSelf(f, PerlIOUnix)->fd;
    Off_t new_loc;
    PERL_UNUSED_CONTEXT;
    if (PerlIOBase(f)->flags & PERLIO_F_NOTREG) {
#ifdef  ESPIPE
	SETERRNO(ESPIPE, LIB_INVARG);
#else
	SETERRNO(EINVAL, LIB_INVARG);
#endif
	return -1;
    }
    new_loc = PerlLIO_lseek(fd, offset, whence);
    if (new_loc == (Off_t) - 1)
	return -1;
    PerlIOBase(f)->flags &= ~PERLIO_F_EOF;
    return  0;
}

PerlIO *
PerlIOUnix_open(pTHX_ PerlIO_funcs *self, PerlIO_list_t *layers,
		IV n, const char *mode, int fd, int imode,
		int perm, PerlIO *f, int narg, SV **args)
{
    if (PerlIOValid(f)) {
	if (PerlIOBase(f)->tab && PerlIOBase(f)->flags & PERLIO_F_OPEN)
	    (*PerlIOBase(f)->tab->Close)(aTHX_ f);
    }
    if (narg > 0) {
	if (*mode == IoTYPE_NUMERIC)
	    mode++;
	else {
	    imode = PerlIOUnix_oflags(mode);
#ifdef VMS
	    perm = 0777; /* preserve RMS defaults, ACL inheritance, etc. */
#else
	    perm = 0666;
#endif
	}
	if (imode != -1) {
            STRLEN len;
	    const char *path = SvPV_const(*args, len);
	    if (!IS_SAFE_PATHNAME(path, len, "open"))
                return NULL;
	    fd = PerlLIO_open3(path, imode, perm);
	}
    }
    if (fd >= 0) {
	if (*mode == IoTYPE_IMPLICIT)
	    mode++;
	if (!f) {
	    f = PerlIO_allocate(aTHX);
	}
	if (!PerlIOValid(f)) {
	    if (!(f = PerlIO_push(aTHX_ f, self, mode, PerlIOArg))) {
		PerlLIO_close(fd);
		return NULL;
	    }
	}
        PerlIOUnix_setfd(aTHX_ f, fd, imode);
	PerlIOBase(f)->flags |= PERLIO_F_OPEN;
	if (*mode == IoTYPE_APPEND)
	    PerlIOUnix_seek(aTHX_ f, 0, SEEK_END);
	return f;
    }
    else {
	if (f) {
	    NOOP;
	    /*
	     * FIXME: pop layers ???
	     */
	}
	return NULL;
    }
}

PerlIO *
PerlIOUnix_dup(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags)
{
    const PerlIOUnix * const os = PerlIOSelf(o, PerlIOUnix);
    int fd = os->fd;
    if (flags & PERLIO_DUP_FD) {
	fd = PerlLIO_dup(fd);
    }
    if (fd >= 0) {
	f = PerlIOBase_dup(aTHX_ f, o, param, flags);
	if (f) {
	    /* If all went well overwrite fd in dup'ed lay with the dup()'ed fd */
	    PerlIOUnix_setfd(aTHX_ f, fd, os->oflags);
	    return f;
	}
        PerlLIO_close(fd);
    }
    return NULL;
}


SSize_t
PerlIOUnix_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
{
    int fd;
    if (PerlIO_lockcnt(f)) /* in use: abort ungracefully */
	return -1;
    fd = PerlIOSelf(f, PerlIOUnix)->fd;
#ifdef PERLIO_STD_SPECIAL
    if (fd == 0)
        return PERLIO_STD_IN(fd, vbuf, count);
#endif
    if (!(PerlIOBase(f)->flags & PERLIO_F_CANREAD) ||
         PerlIOBase(f)->flags & (PERLIO_F_EOF|PERLIO_F_ERROR)) {
	return 0;
    }
    while (1) {
	const SSize_t len = PerlLIO_read(fd, vbuf, count);
	if (len >= 0 || errno != EINTR) {
	    if (len < 0) {
		if (errno != EAGAIN) {
		    PerlIOBase(f)->flags |= PERLIO_F_ERROR;
		    PerlIO_save_errno(f);
		}
	    }
	    else if (len == 0 && count != 0) {
		PerlIOBase(f)->flags |= PERLIO_F_EOF;
		SETERRNO(0,0);
	    }
	    return len;
	}
	/* EINTR */
	if (PL_sig_pending && S_perlio_async_run(aTHX_ f))
	    return -1;
    }
    NOT_REACHED; /*NOTREACHED*/
}

SSize_t
PerlIOUnix_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
{
    int fd;
    if (PerlIO_lockcnt(f)) /* in use: abort ungracefully */
	return -1;
    fd = PerlIOSelf(f, PerlIOUnix)->fd;
#ifdef PERLIO_STD_SPECIAL
    if (fd == 1 || fd == 2)
        return PERLIO_STD_OUT(fd, vbuf, count);
#endif
    while (1) {
	const SSize_t len = PerlLIO_write(fd, vbuf, count);
	if (len >= 0 || errno != EINTR) {
	    if (len < 0) {
		if (errno != EAGAIN) {
		    PerlIOBase(f)->flags |= PERLIO_F_ERROR;
		    PerlIO_save_errno(f);
		}
	    }
	    return len;
	}
	/* EINTR */
	if (PL_sig_pending && S_perlio_async_run(aTHX_ f))
	    return -1;
    }
    NOT_REACHED; /*NOTREACHED*/
}

Off_t
PerlIOUnix_tell(pTHX_ PerlIO *f)
{
    PERL_UNUSED_CONTEXT;

    return PerlLIO_lseek(PerlIOSelf(f, PerlIOUnix)->fd, 0, SEEK_CUR);
}


IV
PerlIOUnix_close(pTHX_ PerlIO *f)
{
    const int fd = PerlIOSelf(f, PerlIOUnix)->fd;
    int code = 0;
    if (PerlIOBase(f)->flags & PERLIO_F_OPEN) {
	if (PerlIOUnix_refcnt_dec(fd) > 0) {
	    PerlIOBase(f)->flags &= ~PERLIO_F_OPEN;
	    return 0;
	}
    }
    else {
	SETERRNO(EBADF,SS_IVCHAN);
	return -1;
    }
    while (PerlLIO_close(fd) != 0) {
	if (errno != EINTR) {
	    code = -1;
	    break;
	}
	/* EINTR */
	if (PL_sig_pending && S_perlio_async_run(aTHX_ f))
	    return -1;
    }
    if (code == 0) {
	PerlIOBase(f)->flags &= ~PERLIO_F_OPEN;
    }
    return code;
}

PERLIO_FUNCS_DECL(PerlIO_unix) = {
    sizeof(PerlIO_funcs),
    "unix",
    sizeof(PerlIOUnix),
    PERLIO_K_RAW,
    PerlIOUnix_pushed,
    PerlIOBase_popped,
    PerlIOUnix_open,
    PerlIOBase_binmode,         /* binmode */
    NULL,
    PerlIOUnix_fileno,
    PerlIOUnix_dup,
    PerlIOUnix_read,
    PerlIOBase_unread,
    PerlIOUnix_write,
    PerlIOUnix_seek,
    PerlIOUnix_tell,
    PerlIOUnix_close,
    PerlIOBase_noop_ok,         /* flush */
    PerlIOBase_noop_fail,       /* fill */
    PerlIOBase_eof,
    PerlIOBase_error,
    PerlIOBase_clearerr,
    PerlIOBase_setlinebuf,
    NULL,                       /* get_base */
    NULL,                       /* get_bufsiz */
    NULL,                       /* get_ptr */
    NULL,                       /* get_cnt */
    NULL,                       /* set_ptrcnt */
};

/*--------------------------------------------------------------------------------------*/
/*
 * stdio as a layer
 */

#if defined(VMS) && !defined(STDIO_BUFFER_WRITABLE)
/* perl5.8 - This ensures the last minute VMS ungetc fix is not
   broken by the last second glibc 2.3 fix
 */
#define STDIO_BUFFER_WRITABLE
#endif


typedef struct {
    struct _PerlIO base;
    FILE *stdio;                /* The stream */
} PerlIOStdio;

IV
PerlIOStdio_fileno(pTHX_ PerlIO *f)
{
    PERL_UNUSED_CONTEXT;

    if (PerlIOValid(f)) {
	FILE * const s = PerlIOSelf(f, PerlIOStdio)->stdio;
	if (s)
	    return PerlSIO_fileno(s);
    }
    errno = EBADF;
    return -1;
}

char *
PerlIOStdio_mode(const char *mode, char *tmode)
{
    char * const ret = tmode;
    if (mode) {
	while (*mode) {
	    *tmode++ = *mode++;
	}
    }
#if defined(PERLIO_USING_CRLF) || defined(__CYGWIN__)
    *tmode++ = 'b';
#endif
    *tmode = '\0';
    return ret;
}

IV
PerlIOStdio_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
{
    PerlIO *n;
    if (PerlIOValid(f) && PerlIOValid(n = PerlIONext(f))) {
	PerlIO_funcs * const toptab = PerlIOBase(n)->tab;
        if (toptab == tab) {
	    /* Top is already stdio - pop self (duplicate) and use original */
	    PerlIO_pop(aTHX_ f);
	    return 0;
	} else {
	    const int fd = PerlIO_fileno(n);
	    char tmode[8];
	    FILE *stdio;
	    if (fd >= 0 && (stdio  = PerlSIO_fdopen(fd,
			    mode = PerlIOStdio_mode(mode, tmode)))) {
		PerlIOSelf(f, PerlIOStdio)->stdio = stdio;
	    	/* We never call down so do any pending stuff now */
	    	PerlIO_flush(PerlIONext(f));
                return PerlIOBase_pushed(aTHX_ f, mode, arg, tab);
	    }
	    else {
		return -1;
	    }
        }
    }
    return PerlIOBase_pushed(aTHX_ f, mode, arg, tab);
}


PerlIO *
PerlIO_importFILE(FILE *stdio, const char *mode)
{
    dTHX;
    PerlIO *f = NULL;
#ifdef EBCDIC
	 int rc;
	 char filename[FILENAME_MAX];
	 fldata_t fileinfo;
#endif
    if (stdio) {
	PerlIOStdio *s;
        int fd0 = fileno(stdio);
        if (fd0 < 0) {
#ifdef EBCDIC
			  rc = fldata(stdio,filename,&fileinfo);
			  if(rc != 0){
				  return NULL;
			  }
			  if(fileinfo.__dsorgHFS){
            return NULL;
        }
			  /*This MVS dataset , OK!*/
#else
            return NULL;
#endif
        }
	if (!mode || !*mode) {
	    /* We need to probe to see how we can open the stream
	       so start with read/write and then try write and read
	       we dup() so that we can fclose without loosing the fd.

	       Note that the errno value set by a failing fdopen
	       varies between stdio implementations.
	     */
            const int fd = PerlLIO_dup(fd0);
	    FILE *f2;
            if (fd < 0) {
                return f;
            }
	    f2 = PerlSIO_fdopen(fd, (mode = "r+"));
	    if (!f2) {
		f2 = PerlSIO_fdopen(fd, (mode = "w"));
	    }
	    if (!f2) {
		f2 = PerlSIO_fdopen(fd, (mode = "r"));
	    }
	    if (!f2) {
		/* Don't seem to be able to open */
		PerlLIO_close(fd);
		return f;
	    }
	    fclose(f2);
	}
	if ((f = PerlIO_push(aTHX_(PerlIO_allocate(aTHX)), PERLIO_FUNCS_CAST(&PerlIO_stdio), mode, NULL))) {
	    s = PerlIOSelf(f, PerlIOStdio);
	    s->stdio = stdio;
#ifdef EBCDIC
		fd0 = fileno(stdio);
		if(fd0 != -1){
			PerlIOUnix_refcnt_inc(fd0);
		}
		else{
			rc = fldata(stdio,filename,&fileinfo);
			if(rc != 0){
				PerlIOUnix_refcnt_inc(fd0);
			}
			if(fileinfo.__dsorgHFS){
				PerlIOUnix_refcnt_inc(fd0);
			}
			  /*This MVS dataset , OK!*/
		}
#else
	    PerlIOUnix_refcnt_inc(fileno(stdio));
#endif
	}
    }
    return f;
}

PerlIO *
PerlIOStdio_open(pTHX_ PerlIO_funcs *self, PerlIO_list_t *layers,
		 IV n, const char *mode, int fd, int imode,
		 int perm, PerlIO *f, int narg, SV **args)
{
    char tmode[8];
    if (PerlIOValid(f)) {
        STRLEN len;
	const char * const path = SvPV_const(*args, len);
	PerlIOStdio * const s = PerlIOSelf(f, PerlIOStdio);
	FILE *stdio;
	if (!IS_SAFE_PATHNAME(path, len, "open"))
            return NULL;
	PerlIOUnix_refcnt_dec(fileno(s->stdio));
	stdio = PerlSIO_freopen(path, PerlIOStdio_mode(mode, tmode),
                                s->stdio);
	if (!s->stdio)
	    return NULL;
	s->stdio = stdio;
	PerlIOUnix_refcnt_inc(fileno(s->stdio));
	return f;
    }
    else {
	if (narg > 0) {
            STRLEN len;
	    const char * const path = SvPV_const(*args, len);
            if (!IS_SAFE_PATHNAME(path, len, "open"))
                return NULL;
	    if (*mode == IoTYPE_NUMERIC) {
		mode++;
		fd = PerlLIO_open3(path, imode, perm);
	    }
	    else {
	        FILE *stdio;
	        bool appended = FALSE;
#ifdef __CYGWIN__
		/* Cygwin wants its 'b' early. */
		appended = TRUE;
		mode = PerlIOStdio_mode(mode, tmode);
#endif
		stdio = PerlSIO_fopen(path, mode);
		if (stdio) {
		    if (!f) {
			f = PerlIO_allocate(aTHX);
		    }
		    if (!appended)
		        mode = PerlIOStdio_mode(mode, tmode);
		    f = PerlIO_push(aTHX_ f, self, mode, PerlIOArg);
		    if (f) {
			PerlIOSelf(f, PerlIOStdio)->stdio = stdio;
			PerlIOUnix_refcnt_inc(fileno(stdio));
		    } else {
			PerlSIO_fclose(stdio);
		    }
		    return f;
		}
		else {
		    return NULL;
		}
	    }
	}
	if (fd >= 0) {
	    FILE *stdio = NULL;
	    int init = 0;
	    if (*mode == IoTYPE_IMPLICIT) {
		init = 1;
		mode++;
	    }
	    if (init) {
		switch (fd) {
		case 0:
		    stdio = PerlSIO_stdin;
		    break;
		case 1:
		    stdio = PerlSIO_stdout;
		    break;
		case 2:
		    stdio = PerlSIO_stderr;
		    break;
		}
	    }
	    else {
		stdio = PerlSIO_fdopen(fd, mode =
				       PerlIOStdio_mode(mode, tmode));
	    }
	    if (stdio) {
		if (!f) {
		    f = PerlIO_allocate(aTHX);
		}
		if ((f = PerlIO_push(aTHX_ f, self, mode, PerlIOArg))) {
		    PerlIOSelf(f, PerlIOStdio)->stdio = stdio;
		    PerlIOUnix_refcnt_inc(fileno(stdio));
		}
		return f;
	    }
            PerlLIO_close(fd);
	}
    }
    return NULL;
}

PerlIO *
PerlIOStdio_dup(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags)
{
    /* This assumes no layers underneath - which is what
       happens, but is not how I remember it. NI-S 2001/10/16
     */
    if ((f = PerlIOBase_dup(aTHX_ f, o, param, flags))) {
	FILE *stdio = PerlIOSelf(o, PerlIOStdio)->stdio;
	const int fd = fileno(stdio);
	char mode[8];
	if (flags & PERLIO_DUP_FD) {
	    const int dfd = PerlLIO_dup(fileno(stdio));
	    if (dfd >= 0) {
		stdio = PerlSIO_fdopen(dfd, PerlIO_modestr(o,mode));
		goto set_this;
	    }
	    else {
		NOOP;
		/* FIXME: To avoid messy error recovery if dup fails
		   re-use the existing stdio as though flag was not set
		 */
	    }
	}
    	stdio = PerlSIO_fdopen(fd, PerlIO_modestr(o,mode));
    set_this:
	PerlIOSelf(f, PerlIOStdio)->stdio = stdio;
        if(stdio) {
	    PerlIOUnix_refcnt_inc(fileno(stdio));
        }
    }
    return f;
}

static int
PerlIOStdio_invalidate_fileno(pTHX_ FILE *f)
{
    PERL_UNUSED_CONTEXT;

    /* XXX this could use PerlIO_canset_fileno() and
     * PerlIO_set_fileno() support from Configure
     */
#  if defined(HAS_FDCLOSE)
    return fdclose(f, NULL) == 0 ? 1 : 0;
#  elif defined(__UCLIBC__)
    /* uClibc must come before glibc because it defines __GLIBC__ as well. */
    f->__filedes = -1;
    return 1;
#  elif defined(__GLIBC__)
    /* There may be a better way for GLIBC:
    	- libio.h defines a flag to not close() on cleanup
     */	
    f->_fileno = -1;
    return 1;
#  elif defined(__sun)
    PERL_UNUSED_ARG(f);
    return 0;
#  elif defined(__hpux)
    f->__fileH = 0xff;
    f->__fileL = 0xff;
    return 1;
   /* Next one ->_file seems to be a reasonable fallback, i.e. if
      your platform does not have special entry try this one.
      [For OSF only have confirmation for Tru64 (alpha)
      but assume other OSFs will be similar.]
    */
#  elif defined(_AIX) || defined(__osf__) || defined(__irix__)
    f->_file = -1;
    return 1;
#  elif defined(__FreeBSD__)
    /* There may be a better way on FreeBSD:
        - we could insert a dummy func in the _close function entry
	f->_close = (int (*)(void *)) dummy_close;
     */
    f->_file = -1;
    return 1;
#  elif defined(__OpenBSD__)
    /* There may be a better way on OpenBSD:
        - we could insert a dummy func in the _close function entry
	f->_close = (int (*)(void *)) dummy_close;
     */
    f->_file = -1;
    return 1;
#  elif defined(__EMX__)
    /* f->_flags &= ~_IOOPEN; */	/* Will leak stream->_buffer */
    f->_handle = -1;
    return 1;
#  elif defined(__CYGWIN__)
    /* There may be a better way on CYGWIN:
        - we could insert a dummy func in the _close function entry
	f->_close = (int (*)(void *)) dummy_close;
     */
    f->_file = -1;
    return 1;
#  elif defined(WIN32)
#    if defined(UNDER_CE)
    /* WIN_CE does not have access to FILE internals, it hardly has FILE
       structure at all
     */
#    else
    PERLIO_FILE_file(f) = -1;
#    endif
    return 1;
#  else
#if 0
    /* Sarathy's code did this - we fall back to a dup/dup2 hack
       (which isn't thread safe) instead
     */
#    error "Don't know how to set FILE.fileno on your platform"
#endif
    PERL_UNUSED_ARG(f);
    return 0;
#  endif
}

IV
PerlIOStdio_close(pTHX_ PerlIO *f)
{
    FILE * const stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
    if (!stdio) {
	errno = EBADF;
	return -1;
    }
    else {
        const int fd = fileno(stdio);
	int invalidate = 0;
	IV result = 0;
	int dupfd = -1;
	dSAVEDERRNO;
#ifdef USE_ITHREADS
	dVAR;
#endif
#ifdef SOCKS5_VERSION_NAME
    	/* Socks lib overrides close() but stdio isn't linked to
	   that library (though we are) - so we must call close()
	   on sockets on stdio's behalf.
	 */
    	int optval;
    	Sock_size_t optlen = sizeof(int);
	if (getsockopt(fd, SOL_SOCKET, SO_TYPE, (void *) &optval, &optlen) == 0)
	    invalidate = 1;
#endif
	/* Test for -1, as *BSD stdio (at least) on fclose sets the FILE* such
	   that a subsequent fileno() on it returns -1. Don't want to croak()
	   from within PerlIOUnix_refcnt_dec() if some buggy caller code is
	   trying to close an already closed handle which somehow it still has
	   a reference to. (via.xs, I'm looking at you).  */
	if (fd != -1 && PerlIOUnix_refcnt_dec(fd) > 0) {
	    /* File descriptor still in use */
	    invalidate = 1;
	}
	if (invalidate) {
	    /* For STD* handles, don't close stdio, since we shared the FILE *, too. */
	    if (stdio == stdin) /* Some stdios are buggy fflush-ing inputs */
		return 0;
	    if (stdio == stdout || stdio == stderr)
		return PerlIO_flush(f);
        }
        MUTEX_LOCK(&PL_perlio_mutex);
        /* Right. We need a mutex here because for a brief while we
           will have the situation that fd is actually closed. Hence if
           a second thread were to get into this block, its dup() would
           likely return our fd as its dupfd. (after all, it is closed)
           Then if we get to the dup2() first, we blat the fd back
           (messing up its temporary as a side effect) only for it to
           then close its dupfd (== our fd) in its close(dupfd) */

        /* There is, of course, a race condition, that any other thread
           trying to input/output/whatever on this fd will be stuffed
           for the duration of this little manoeuvrer. Perhaps we
           should hold an IO mutex for the duration of every IO
           operation if we know that invalidate doesn't work on this
           platform, but that would suck, and could kill performance.

           Except that correctness trumps speed.
           Advice from klortho #11912. */
	if (invalidate) {
            /* Tricky - must fclose(stdio) to free memory but not close(fd)
	       Use Sarathy's trick from maint-5.6 to invalidate the
	       fileno slot of the FILE *
	    */
	    result = PerlIO_flush(f);
	    SAVE_ERRNO;
	    invalidate = PerlIOStdio_invalidate_fileno(aTHX_ stdio);
	    if (!invalidate) {
		dupfd = PerlLIO_dup(fd);
#ifdef USE_ITHREADS
		if (dupfd < 0) {
		    /* Oh cXap. This isn't going to go well. Not sure if we can
		       recover from here, or if closing this particular FILE *
		       is a good idea now.  */
		}
#endif
	    }
	} else {
	    SAVE_ERRNO;   /* This is here only to silence compiler warnings */
	}
        result = PerlSIO_fclose(stdio);
	/* We treat error from stdio as success if we invalidated
	   errno may NOT be expected EBADF
	 */
	if (invalidate && result != 0) {
	    RESTORE_ERRNO;
	    result = 0;
	}
#ifdef SOCKS5_VERSION_NAME
	/* in SOCKS' case, let close() determine return value */
	result = close(fd);
#endif
	if (dupfd >= 0) {
	    PerlLIO_dup2(dupfd,fd);
	    PerlLIO_close(dupfd);
	}
        MUTEX_UNLOCK(&PL_perlio_mutex);
	return result;
    }
}

SSize_t
PerlIOStdio_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
{
    FILE * s;
    SSize_t got = 0;
    if (PerlIO_lockcnt(f)) /* in use: abort ungracefully */
	return -1;
    s = PerlIOSelf(f, PerlIOStdio)->stdio;
    for (;;) {
	if (count == 1) {
	    STDCHAR *buf = (STDCHAR *) vbuf;
	    /*
	     * Perl is expecting PerlIO_getc() to fill the buffer Linux's
	     * stdio does not do that for fread()
	     */
	    const int ch = PerlSIO_fgetc(s);
	    if (ch != EOF) {
		*buf = ch;
		got = 1;
	    }
	}
	else
	    got = PerlSIO_fread(vbuf, 1, count, s);
	if (got == 0 && PerlSIO_ferror(s))
	    got = -1;
	if (got >= 0 || errno != EINTR)
	    break;
	if (PL_sig_pending && S_perlio_async_run(aTHX_ f))
	    return -1;
	SETERRNO(0,0);	/* just in case */
    }
#ifdef __sgi
    /* Under some circumstances IRIX stdio fgetc() and fread()
     * set the errno to ENOENT, which makes no sense according
     * to either IRIX or POSIX.  [rt.perl.org #123977] */
    if (errno == ENOENT) SETERRNO(0,0);
#endif
    return got;
}

SSize_t
PerlIOStdio_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
{
    SSize_t unread = 0;
    FILE * const s = PerlIOSelf(f, PerlIOStdio)->stdio;

#ifdef STDIO_BUFFER_WRITABLE
    if (PerlIO_fast_gets(f) && PerlIO_has_base(f)) {
	STDCHAR *buf = ((STDCHAR *) vbuf) + count;
	STDCHAR *base = PerlIO_get_base(f);
	SSize_t cnt   = PerlIO_get_cnt(f);
	STDCHAR *ptr  = PerlIO_get_ptr(f);
	SSize_t avail = ptr - base;
	if (avail > 0) {
	    if (avail > count) {
		avail = count;
	    }
	    ptr -= avail;
	    Move(buf-avail,ptr,avail,STDCHAR);
	    count -= avail;
	    unread += avail;
	    PerlIO_set_ptrcnt(f,ptr,cnt+avail);
	    if (PerlSIO_feof(s) && unread >= 0)
		PerlSIO_clearerr(s);
	}
    }
    else
#endif
    if (PerlIO_has_cntptr(f)) {
	/* We can get pointer to buffer but not its base
	   Do ungetc() but check chars are ending up in the
	   buffer
	 */
	STDCHAR *eptr = (STDCHAR*)PerlSIO_get_ptr(s);
	STDCHAR *buf = ((STDCHAR *) vbuf) + count;
	while (count > 0) {
	    const int ch = *--buf & 0xFF;
	    if (ungetc(ch,s) != ch) {
		/* ungetc did not work */
		break;
	    }
	    if ((STDCHAR*)PerlSIO_get_ptr(s) != --eptr || ((*eptr & 0xFF) != ch)) {
		/* Did not change pointer as expected */
		if (fgetc(s) != EOF)  /* get char back again */
                    break;
	    }
	    /* It worked ! */
	    count--;
	    unread++;
	}
    }

    if (count > 0) {
	unread += PerlIOBase_unread(aTHX_ f, vbuf, count);
    }
    return unread;
}

SSize_t
PerlIOStdio_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
{
    SSize_t got;
    if (PerlIO_lockcnt(f)) /* in use: abort ungracefully */
	return -1;
    for (;;) {
	got = PerlSIO_fwrite(vbuf, 1, count,
			      PerlIOSelf(f, PerlIOStdio)->stdio);
	if (got >= 0 || errno != EINTR)
	    break;
	if (PL_sig_pending && S_perlio_async_run(aTHX_ f))
	    return -1;
	SETERRNO(0,0);	/* just in case */
    }
    return got;
}

IV
PerlIOStdio_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
{
    FILE * const stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
    PERL_UNUSED_CONTEXT;

    return PerlSIO_fseek(stdio, offset, whence);
}

Off_t
PerlIOStdio_tell(pTHX_ PerlIO *f)
{
    FILE * const stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
    PERL_UNUSED_CONTEXT;

    return PerlSIO_ftell(stdio);
}

IV
PerlIOStdio_flush(pTHX_ PerlIO *f)
{
    FILE * const stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
    PERL_UNUSED_CONTEXT;

    if (PerlIOBase(f)->flags & PERLIO_F_CANWRITE) {
	return PerlSIO_fflush(stdio);
    }
    else {
	NOOP;
#if 0
	/*
	 * FIXME: This discards ungetc() and pre-read stuff which is not
	 * right if this is just a "sync" from a layer above Suspect right
	 * design is to do _this_ but not have layer above flush this
	 * layer read-to-read
	 */
	/*
	 * Not writeable - sync by attempting a seek
	 */
	dSAVE_ERRNO;
	if (PerlSIO_fseek(stdio, (Off_t) 0, SEEK_CUR) != 0)
	    RESTORE_ERRNO;
#endif
    }
    return 0;
}

IV
PerlIOStdio_eof(pTHX_ PerlIO *f)
{
    PERL_UNUSED_CONTEXT;

    return PerlSIO_feof(PerlIOSelf(f, PerlIOStdio)->stdio);
}

IV
PerlIOStdio_error(pTHX_ PerlIO *f)
{
    PERL_UNUSED_CONTEXT;

    return PerlSIO_ferror(PerlIOSelf(f, PerlIOStdio)->stdio);
}

void
PerlIOStdio_clearerr(pTHX_ PerlIO *f)
{
    PERL_UNUSED_CONTEXT;

    PerlSIO_clearerr(PerlIOSelf(f, PerlIOStdio)->stdio);
}

void
PerlIOStdio_setlinebuf(pTHX_ PerlIO *f)
{
    PERL_UNUSED_CONTEXT;

#ifdef HAS_SETLINEBUF
    PerlSIO_setlinebuf(PerlIOSelf(f, PerlIOStdio)->stdio);
#else
    PerlSIO_setvbuf(PerlIOSelf(f, PerlIOStdio)->stdio, NULL, _IOLBF, 0);
#endif
}

#ifdef FILE_base
STDCHAR *
PerlIOStdio_get_base(pTHX_ PerlIO *f)
{
    FILE * const stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
    PERL_UNUSED_CONTEXT;
    return (STDCHAR*)PerlSIO_get_base(stdio);
}

Size_t
PerlIOStdio_get_bufsiz(pTHX_ PerlIO *f)
{
    FILE * const stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
    PERL_UNUSED_CONTEXT;
    return PerlSIO_get_bufsiz(stdio);
}
#endif

#ifdef USE_STDIO_PTR
STDCHAR *
PerlIOStdio_get_ptr(pTHX_ PerlIO *f)
{
    FILE * const stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
    PERL_UNUSED_CONTEXT;
    return (STDCHAR*)PerlSIO_get_ptr(stdio);
}

SSize_t
PerlIOStdio_get_cnt(pTHX_ PerlIO *f)
{
    FILE * const stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
    PERL_UNUSED_CONTEXT;
    return PerlSIO_get_cnt(stdio);
}

void
PerlIOStdio_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, SSize_t cnt)
{
    FILE * const stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
    PERL_UNUSED_CONTEXT;
    if (ptr != NULL) {
#ifdef STDIO_PTR_LVALUE
        /* This is a long-standing infamous mess.  The root of the
         * problem is that one cannot know the signedness of char, and
         * more precisely the signedness of FILE._ptr.  The following
         * things have been tried, and they have all failed (across
         * different compilers (remember that core needs to to build
         * also with c++) and compiler options:
         *
         * - casting the RHS to (void*) -- works in *some* places
         * - casting the LHS to (void*) -- totally unportable
         *
         * So let's try silencing the warning at least for gcc. */
        GCC_DIAG_IGNORE(-Wpointer-sign);
	PerlSIO_set_ptr(stdio, ptr); /* LHS STDCHAR* cast non-portable */
        GCC_DIAG_RESTORE;
#ifdef STDIO_PTR_LVAL_SETS_CNT
	assert(PerlSIO_get_cnt(stdio) == (cnt));
#endif
#if (!defined(STDIO_PTR_LVAL_NOCHANGE_CNT))
	/*
	 * Setting ptr _does_ change cnt - we are done
	 */
	return;
#endif
#else                           /* STDIO_PTR_LVALUE */
	PerlProc_abort();
#endif                          /* STDIO_PTR_LVALUE */
    }
    /*
     * Now (or only) set cnt
     */
#ifdef STDIO_CNT_LVALUE
    PerlSIO_set_cnt(stdio, cnt);
#else                           /* STDIO_CNT_LVALUE */
#if (defined(STDIO_PTR_LVALUE) && defined(STDIO_PTR_LVAL_SETS_CNT))
    PerlSIO_set_ptr(stdio,
		    PerlSIO_get_ptr(stdio) + (PerlSIO_get_cnt(stdio) -
					      cnt));
#else                           /* STDIO_PTR_LVAL_SETS_CNT */
    PerlProc_abort();
#endif                          /* STDIO_PTR_LVAL_SETS_CNT */
#endif                          /* STDIO_CNT_LVALUE */
}


#endif

IV
PerlIOStdio_fill(pTHX_ PerlIO *f)
{
    FILE * stdio;
    int c;
    PERL_UNUSED_CONTEXT;
    if (PerlIO_lockcnt(f)) /* in use: abort ungracefully */
	return -1;
    stdio = PerlIOSelf(f, PerlIOStdio)->stdio;

    /*
     * fflush()ing read-only streams can cause trouble on some stdio-s
     */
    if ((PerlIOBase(f)->flags & PERLIO_F_CANWRITE)) {
	if (PerlSIO_fflush(stdio) != 0)
	    return EOF;
    }
    for (;;) {
	c = PerlSIO_fgetc(stdio);
	if (c != EOF)
	    break;
	if (! PerlSIO_ferror(stdio) || errno != EINTR)
	    return EOF;
	if (PL_sig_pending && S_perlio_async_run(aTHX_ f))
	    return -1;
	SETERRNO(0,0);
    }

#if (defined(STDIO_PTR_LVALUE) && (defined(STDIO_CNT_LVALUE) || defined(STDIO_PTR_LVAL_SETS_CNT)))

#ifdef STDIO_BUFFER_WRITABLE
    if (PerlIO_fast_gets(f) && PerlIO_has_base(f)) {
	/* Fake ungetc() to the real buffer in case system's ungetc
	   goes elsewhere
	 */
	STDCHAR *base = (STDCHAR*)PerlSIO_get_base(stdio);
	SSize_t cnt   = PerlSIO_get_cnt(stdio);
	STDCHAR *ptr  = (STDCHAR*)PerlSIO_get_ptr(stdio);
	if (ptr == base+1) {
	    *--ptr = (STDCHAR) c;
	    PerlIOStdio_set_ptrcnt(aTHX_ f,ptr,cnt+1);
	    if (PerlSIO_feof(stdio))
		PerlSIO_clearerr(stdio);
	    return 0;
	}
    }
    else
#endif
    if (PerlIO_has_cntptr(f)) {
	STDCHAR ch = c;
	if (PerlIOStdio_unread(aTHX_ f,&ch,1) == 1) {
	    return 0;
	}
    }
#endif

    /* If buffer snoop scheme above fails fall back to
       using ungetc().
     */
    if (PerlSIO_ungetc(c, stdio) != c)
	return EOF;

    return 0;
}



PERLIO_FUNCS_DECL(PerlIO_stdio) = {
    sizeof(PerlIO_funcs),
    "stdio",
    sizeof(PerlIOStdio),
    PERLIO_K_BUFFERED|PERLIO_K_RAW,
    PerlIOStdio_pushed,
    PerlIOBase_popped,
    PerlIOStdio_open,
    PerlIOBase_binmode,         /* binmode */
    NULL,
    PerlIOStdio_fileno,
    PerlIOStdio_dup,
    PerlIOStdio_read,
    PerlIOStdio_unread,
    PerlIOStdio_write,
    PerlIOStdio_seek,
    PerlIOStdio_tell,
    PerlIOStdio_close,
    PerlIOStdio_flush,
    PerlIOStdio_fill,
    PerlIOStdio_eof,
    PerlIOStdio_error,
    PerlIOStdio_clearerr,
    PerlIOStdio_setlinebuf,
#ifdef FILE_base
    PerlIOStdio_get_base,
    PerlIOStdio_get_bufsiz,
#else
    NULL,
    NULL,
#endif
#ifdef USE_STDIO_PTR
    PerlIOStdio_get_ptr,
    PerlIOStdio_get_cnt,
#   if defined(HAS_FAST_STDIO) && defined(USE_FAST_STDIO)
    PerlIOStdio_set_ptrcnt,
#   else
    NULL,
#   endif /* HAS_FAST_STDIO && USE_FAST_STDIO */
#else
    NULL,
    NULL,
    NULL,
#endif /* USE_STDIO_PTR */
};

/* Note that calls to PerlIO_exportFILE() are reversed using
 * PerlIO_releaseFILE(), not importFILE. */
FILE *
PerlIO_exportFILE(PerlIO * f, const char *mode)
{
    dTHX;
    FILE *stdio = NULL;
    if (PerlIOValid(f)) {
	char buf[8];
        int fd = PerlIO_fileno(f);
        if (fd < 0) {
            return NULL;
        }
	PerlIO_flush(f);
	if (!mode || !*mode) {
	    mode = PerlIO_modestr(f, buf);
	}
	stdio = PerlSIO_fdopen(PerlIO_fileno(f), mode);
	if (stdio) {
	    PerlIOl *l = *f;
	    PerlIO *f2;
	    /* De-link any lower layers so new :stdio sticks */
	    *f = NULL;
	    if ((f2 = PerlIO_push(aTHX_ f, PERLIO_FUNCS_CAST(&PerlIO_stdio), buf, NULL))) {
		PerlIOStdio *s = PerlIOSelf((f = f2), PerlIOStdio);
		s->stdio = stdio;
		PerlIOUnix_refcnt_inc(fileno(stdio));
		/* Link previous lower layers under new one */
		*PerlIONext(f) = l;
	    }
	    else {
		/* restore layers list */
		*f = l;
	    }
	}
    }
    return stdio;
}


FILE *
PerlIO_findFILE(PerlIO *f)
{
    PerlIOl *l = *f;
    FILE *stdio;
    while (l) {
	if (l->tab == &PerlIO_stdio) {
	    PerlIOStdio *s = PerlIOSelf(&l, PerlIOStdio);
	    return s->stdio;
	}
	l = *PerlIONext(&l);
    }
    /* Uses fallback "mode" via PerlIO_modestr() in PerlIO_exportFILE */
    /* However, we're not really exporting a FILE * to someone else (who
       becomes responsible for closing it, or calling PerlIO_releaseFILE())
       So we need to undo its reference count increase on the underlying file
       descriptor. We have to do this, because if the loop above returns you
       the FILE *, then *it* didn't increase any reference count. So there's
       only one way to be consistent. */
    stdio = PerlIO_exportFILE(f, NULL);
    if (stdio) {
	const int fd = fileno(stdio);
	if (fd >= 0)
	    PerlIOUnix_refcnt_dec(fd);
    }
    return stdio;
}

/* Use this to reverse PerlIO_exportFILE calls. */
void
PerlIO_releaseFILE(PerlIO *p, FILE *f)
{
    PerlIOl *l;
    while ((l = *p)) {
	if (l->tab == &PerlIO_stdio) {
	    PerlIOStdio *s = PerlIOSelf(&l, PerlIOStdio);
	    if (s->stdio == f) { /* not in a loop */
		const int fd = fileno(f);
		if (fd >= 0)
		    PerlIOUnix_refcnt_dec(fd);
		{
		    dTHX;
		    PerlIO_pop(aTHX_ p);
		}
		return;
	    }
	}
	p = PerlIONext(p);
    }
    return;
}

/*--------------------------------------------------------------------------------------*/
/*
 * perlio buffer layer
 */

IV
PerlIOBuf_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
{
    PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
    const int fd = PerlIO_fileno(f);
    if (fd >= 0 && PerlLIO_isatty(fd)) {
	PerlIOBase(f)->flags |= PERLIO_F_LINEBUF | PERLIO_F_TTY;
    }
    if (*PerlIONext(f)) {
	const Off_t posn = PerlIO_tell(PerlIONext(f));
	if (posn != (Off_t) - 1) {
	    b->posn = posn;
	}
    }
    return PerlIOBase_pushed(aTHX_ f, mode, arg, tab);
}

PerlIO *
PerlIOBuf_open(pTHX_ PerlIO_funcs *self, PerlIO_list_t *layers,
	       IV n, const char *mode, int fd, int imode, int perm,
	       PerlIO *f, int narg, SV **args)
{
    if (PerlIOValid(f)) {
	PerlIO *next = PerlIONext(f);
	PerlIO_funcs *tab =
	     PerlIO_layer_fetch(aTHX_ layers, n - 1, PerlIOBase(next)->tab);
	if (tab && tab->Open)
	     next =
		  (*tab->Open)(aTHX_ tab, layers, n - 1, mode, fd, imode, perm,
			       next, narg, args);
	if (!next || (*PerlIOBase(f)->tab->Pushed) (aTHX_ f, mode, PerlIOArg, self) != 0) {
	    return NULL;
	}
    }
    else {
	PerlIO_funcs *tab = PerlIO_layer_fetch(aTHX_ layers, n - 1, PerlIO_default_btm());
	int init = 0;
	if (*mode == IoTYPE_IMPLICIT) {
	    init = 1;
	    /*
	     * mode++;
	     */
	}
	if (tab && tab->Open)
	     f = (*tab->Open)(aTHX_ tab, layers, n - 1, mode, fd, imode, perm,
			      f, narg, args);
	else
	     SETERRNO(EINVAL, LIB_INVARG);
	if (f) {
	    if (PerlIO_push(aTHX_ f, self, mode, PerlIOArg) == 0) {
		/*
		 * if push fails during open, open fails. close will pop us.
		 */
		PerlIO_close (f);
		return NULL;
	    } else {
		fd = PerlIO_fileno(f);
		if (init && fd == 2) {
		    /*
		     * Initial stderr is unbuffered
		     */
		    PerlIOBase(f)->flags |= PERLIO_F_UNBUF;
		}
#ifdef PERLIO_USING_CRLF
#  ifdef PERLIO_IS_BINMODE_FD
		if (PERLIO_IS_BINMODE_FD(fd))
		    PerlIO_binmode(aTHX_ f,  '<'/*not used*/, O_BINARY, NULL);
		else
#  endif
		/*
		 * do something about failing setmode()? --jhi
		 */
		PerlLIO_setmode(fd, O_BINARY);
#endif
#ifdef VMS
		/* Enable line buffering with record-oriented regular files
		 * so we don't introduce an extraneous record boundary when
		 * the buffer fills up.
		 */
		if (PerlIOBase(f)->flags & PERLIO_F_CANWRITE) {
		    Stat_t st;
		    if (PerlLIO_fstat(fd, &st) == 0
		        && S_ISREG(st.st_mode)
		        && (st.st_fab_rfm == FAB$C_VAR 
			    || st.st_fab_rfm == FAB$C_VFC)) {
			PerlIOBase(f)->flags |= PERLIO_F_LINEBUF;
		    }
		}
#endif
	    }
	}
    }
    return f;
}

/*
 * This "flush" is akin to sfio's sync in that it handles files in either
 * read or write state.  For write state, we put the postponed data through
 * the next layers.  For read state, we seek() the next layers to the
 * offset given by current position in the buffer, and discard the buffer
 * state (XXXX supposed to be for seek()able buffers only, but now it is done
 * in any case?).  Then the pass the stick further in chain.
 */
IV
PerlIOBuf_flush(pTHX_ PerlIO *f)
{
    PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
    int code = 0;
    PerlIO *n = PerlIONext(f);
    if (PerlIOBase(f)->flags & PERLIO_F_WRBUF) {
	/*
	 * write() the buffer
	 */
	const STDCHAR *buf = b->buf;
	const STDCHAR *p = buf;
	while (p < b->ptr) {
	    SSize_t count = PerlIO_write(n, p, b->ptr - p);
	    if (count > 0) {
		p += count;
	    }
	    else if (count < 0 || PerlIO_error(n)) {
		PerlIOBase(f)->flags |= PERLIO_F_ERROR;
		PerlIO_save_errno(f);
		code = -1;
		break;
	    }
	}
	b->posn += (p - buf);
    }
    else if (PerlIOBase(f)->flags & PERLIO_F_RDBUF) {
	STDCHAR *buf = PerlIO_get_base(f);
	/*
	 * Note position change
	 */
	b->posn += (b->ptr - buf);
	if (b->ptr < b->end) {
	    /* We did not consume all of it - try and seek downstream to
	       our logical position
	     */
	    if (PerlIOValid(n) && PerlIO_seek(n, b->posn, SEEK_SET) == 0) {
		/* Reload n as some layers may pop themselves on seek */
		b->posn = PerlIO_tell(n = PerlIONext(f));
	    }
	    else {
		/* Seek failed (e.g. pipe or tty). Do NOT clear buffer or pre-read
		   data is lost for good - so return saying "ok" having undone
		   the position adjust
		 */
		b->posn -= (b->ptr - buf);
		return code;
	    }
	}
    }
    b->ptr = b->end = b->buf;
    PerlIOBase(f)->flags &= ~(PERLIO_F_RDBUF | PERLIO_F_WRBUF);
    /* We check for Valid because of dubious decision to make PerlIO_flush(NULL) flush all */
    if (PerlIOValid(n) && PerlIO_flush(n) != 0)
	code = -1;
    return code;
}

/* This discards the content of the buffer after b->ptr, and rereads
 * the buffer from the position off in the layer downstream; here off
 * is at offset corresponding to b->ptr - b->buf.
 */
IV
PerlIOBuf_fill(pTHX_ PerlIO *f)
{
    PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
    PerlIO *n = PerlIONext(f);
    SSize_t avail;
    /*
     * Down-stream flush is defined not to loose read data so is harmless.
     * we would not normally be fill'ing if there was data left in anycase.
     */
    if (PerlIO_flush(f) != 0)	/* XXXX Check that its seek() succeeded?! */
	return -1;
    if (PerlIOBase(f)->flags & PERLIO_F_TTY)
	PerlIOBase_flush_linebuf(aTHX);

    if (!b->buf)
	PerlIO_get_base(f);     /* allocate via vtable */

    assert(b->buf); /* The b->buf does get allocated via the vtable system. */

    b->ptr = b->end = b->buf;

    if (!PerlIOValid(n)) {
	PerlIOBase(f)->flags |= PERLIO_F_EOF;
	return -1;
    }

    if (PerlIO_fast_gets(n)) {
	/*
	 * Layer below is also buffered. We do _NOT_ want to call its
	 * ->Read() because that will loop till it gets what we asked for
	 * which may hang on a pipe etc. Instead take anything it has to
	 * hand, or ask it to fill _once_.
	 */
	avail = PerlIO_get_cnt(n);
	if (avail <= 0) {
	    avail = PerlIO_fill(n);
	    if (avail == 0)
		avail = PerlIO_get_cnt(n);
	    else {
		if (!PerlIO_error(n) && PerlIO_eof(n))
		    avail = 0;
	    }
	}
	if (avail > 0) {
	    STDCHAR *ptr = PerlIO_get_ptr(n);
	    const SSize_t cnt = avail;
	    if (avail > (SSize_t)b->bufsiz)
		avail = b->bufsiz;
	    Copy(ptr, b->buf, avail, STDCHAR);
	    PerlIO_set_ptrcnt(n, ptr + avail, cnt - avail);
	}
    }
    else {
	avail = PerlIO_read(n, b->ptr, b->bufsiz);
    }
    if (avail <= 0) {
	if (avail == 0)
	    PerlIOBase(f)->flags |= PERLIO_F_EOF;
	else
	{
	    PerlIOBase(f)->flags |= PERLIO_F_ERROR;
	    PerlIO_save_errno(f);
	}
	return -1;
    }
    b->end = b->buf + avail;
    PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
    return 0;
}

SSize_t
PerlIOBuf_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
{
    if (PerlIOValid(f)) {
        const PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
	if (!b->ptr)
	    PerlIO_get_base(f);
	return PerlIOBase_read(aTHX_ f, vbuf, count);
    }
    return 0;
}

SSize_t
PerlIOBuf_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
{
    const STDCHAR *buf = (const STDCHAR *) vbuf + count;
    PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
    SSize_t unread = 0;
    SSize_t avail;
    if (PerlIOBase(f)->flags & PERLIO_F_WRBUF)
	PerlIO_flush(f);
    if (!b->buf)
	PerlIO_get_base(f);
    if (b->buf) {
	if (PerlIOBase(f)->flags & PERLIO_F_RDBUF) {
	    /*
	     * Buffer is already a read buffer, we can overwrite any chars
	     * which have been read back to buffer start
	     */
	    avail = (b->ptr - b->buf);
	}
	else {
	    /*
	     * Buffer is idle, set it up so whole buffer is available for
	     * unread
	     */
	    avail = b->bufsiz;
	    b->end = b->buf + avail;
	    b->ptr = b->end;
	    PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
	    /*
	     * Buffer extends _back_ from where we are now
	     */
	    b->posn -= b->bufsiz;
	}
	if ((SSize_t) count >= 0 && avail > (SSize_t) count) {
	    /*
	     * If we have space for more than count, just move count
	     */
	    avail = count;
	}
	if (avail > 0) {
	    b->ptr -= avail;
	    buf -= avail;
	    /*
	     * In simple stdio-like ungetc() case chars will be already
	     * there
	     */
	    if (buf != b->ptr) {
		Copy(buf, b->ptr, avail, STDCHAR);
	    }
	    count -= avail;
	    unread += avail;
	    PerlIOBase(f)->flags &= ~PERLIO_F_EOF;
	}
    }
    if (count > 0) {
	unread += PerlIOBase_unread(aTHX_ f, vbuf, count);
    }
    return unread;
}

SSize_t
PerlIOBuf_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
{
    PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
    const STDCHAR *buf = (const STDCHAR *) vbuf;
    const STDCHAR *flushptr = buf;
    Size_t written = 0;
    if (!b->buf)
	PerlIO_get_base(f);
    if (!(PerlIOBase(f)->flags & PERLIO_F_CANWRITE))
	return 0;
    if (PerlIOBase(f)->flags & PERLIO_F_RDBUF) {
    	if (PerlIO_flush(f) != 0) {
	    return 0;
	}
    }	
    if (PerlIOBase(f)->flags & PERLIO_F_LINEBUF) {
	flushptr = buf + count;
	while (flushptr > buf && *(flushptr - 1) != '\n')
	    --flushptr;
    }
    while (count > 0) {
	SSize_t avail = b->bufsiz - (b->ptr - b->buf);
	if ((SSize_t) count >= 0 && (SSize_t) count < avail)
	    avail = count;
	if (flushptr > buf && flushptr <= buf + avail)
	    avail = flushptr - buf;
	PerlIOBase(f)->flags |= PERLIO_F_WRBUF;
	if (avail) {
	    Copy(buf, b->ptr, avail, STDCHAR);
	    count -= avail;
	    buf += avail;
	    written += avail;
	    b->ptr += avail;
	    if (buf == flushptr)
		PerlIO_flush(f);
	}
	if (b->ptr >= (b->buf + b->bufsiz))
	    if (PerlIO_flush(f) == -1)
		return -1;
    }
    if (PerlIOBase(f)->flags & PERLIO_F_UNBUF)
	PerlIO_flush(f);
    return written;
}

IV
PerlIOBuf_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
{
    IV code;
    if ((code = PerlIO_flush(f)) == 0) {
	PerlIOBase(f)->flags &= ~PERLIO_F_EOF;
	code = PerlIO_seek(PerlIONext(f), offset, whence);
	if (code == 0) {
	    PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
	    b->posn = PerlIO_tell(PerlIONext(f));
	}
    }
    return code;
}

Off_t
PerlIOBuf_tell(pTHX_ PerlIO *f)
{
    PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
    /*
     * b->posn is file position where b->buf was read, or will be written
     */
    Off_t posn = b->posn;
    if ((PerlIOBase(f)->flags & PERLIO_F_APPEND) &&
        (PerlIOBase(f)->flags & PERLIO_F_WRBUF)) {
#if 1
    	/* As O_APPEND files are normally shared in some sense it is better
	   to flush :
	 */  	
	PerlIO_flush(f);
#else	
        /* when file is NOT shared then this is sufficient */
	PerlIO_seek(PerlIONext(f),0, SEEK_END);
#endif
	posn = b->posn = PerlIO_tell(PerlIONext(f));
    }
    if (b->buf) {
	/*
	 * If buffer is valid adjust position by amount in buffer
	 */
	posn += (b->ptr - b->buf);
    }
    return posn;
}

IV
PerlIOBuf_popped(pTHX_ PerlIO *f)
{
    const IV code = PerlIOBase_popped(aTHX_ f);
    PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
    if (b->buf && b->buf != (STDCHAR *) & b->oneword) {
	Safefree(b->buf);
    }
    b->ptr = b->end = b->buf = NULL;
    PerlIOBase(f)->flags &= ~(PERLIO_F_RDBUF | PERLIO_F_WRBUF);
    return code;
}

IV
PerlIOBuf_close(pTHX_ PerlIO *f)
{
    const IV code = PerlIOBase_close(aTHX_ f);
    PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
    if (b->buf && b->buf != (STDCHAR *) & b->oneword) {
	Safefree(b->buf);
    }
    b->ptr = b->end = b->buf = NULL;
    PerlIOBase(f)->flags &= ~(PERLIO_F_RDBUF | PERLIO_F_WRBUF);
    return code;
}

STDCHAR *
PerlIOBuf_get_ptr(pTHX_ PerlIO *f)
{
    const PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
    if (!b->buf)
	PerlIO_get_base(f);
    return b->ptr;
}

SSize_t
PerlIOBuf_get_cnt(pTHX_ PerlIO *f)
{
    const PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
    if (!b->buf)
	PerlIO_get_base(f);
    if (PerlIOBase(f)->flags & PERLIO_F_RDBUF)
	return (b->end - b->ptr);
    return 0;
}

STDCHAR *
PerlIOBuf_get_base(pTHX_ PerlIO *f)
{
    PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
    PERL_UNUSED_CONTEXT;

    if (!b->buf) {
	if (!b->bufsiz)
	    b->bufsiz = PERLIOBUF_DEFAULT_BUFSIZ;
	Newxz(b->buf,b->bufsiz, STDCHAR);
	if (!b->buf) {
	    b->buf = (STDCHAR *) & b->oneword;
	    b->bufsiz = sizeof(b->oneword);
	}
	b->end = b->ptr = b->buf;
    }
    return b->buf;
}

Size_t
PerlIOBuf_bufsiz(pTHX_ PerlIO *f)
{
    const PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
    if (!b->buf)
	PerlIO_get_base(f);
    return (b->end - b->buf);
}

void
PerlIOBuf_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, SSize_t cnt)
{
    PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
#ifndef DEBUGGING
    PERL_UNUSED_ARG(cnt);
#endif
    if (!b->buf)
	PerlIO_get_base(f);
    b->ptr = ptr;
    assert(PerlIO_get_cnt(f) == cnt);
    assert(b->ptr >= b->buf);
    PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
}

PerlIO *
PerlIOBuf_dup(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags)
{
 return PerlIOBase_dup(aTHX_ f, o, param, flags);
}



PERLIO_FUNCS_DECL(PerlIO_perlio) = {
    sizeof(PerlIO_funcs),
    "perlio",
    sizeof(PerlIOBuf),
    PERLIO_K_BUFFERED|PERLIO_K_RAW,
    PerlIOBuf_pushed,
    PerlIOBuf_popped,
    PerlIOBuf_open,
    PerlIOBase_binmode,         /* binmode */
    NULL,
    PerlIOBase_fileno,
    PerlIOBuf_dup,
    PerlIOBuf_read,
    PerlIOBuf_unread,
    PerlIOBuf_write,
    PerlIOBuf_seek,
    PerlIOBuf_tell,
    PerlIOBuf_close,
    PerlIOBuf_flush,
    PerlIOBuf_fill,
    PerlIOBase_eof,
    PerlIOBase_error,
    PerlIOBase_clearerr,
    PerlIOBase_setlinebuf,
    PerlIOBuf_get_base,
    PerlIOBuf_bufsiz,
    PerlIOBuf_get_ptr,
    PerlIOBuf_get_cnt,
    PerlIOBuf_set_ptrcnt,
};

/*--------------------------------------------------------------------------------------*/
/*
 * Temp layer to hold unread chars when cannot do it any other way
 */

IV
PerlIOPending_fill(pTHX_ PerlIO *f)
{
    /*
     * Should never happen
     */
    PerlIO_flush(f);
    return 0;
}

IV
PerlIOPending_close(pTHX_ PerlIO *f)
{
    /*
     * A tad tricky - flush pops us, then we close new top
     */
    PerlIO_flush(f);
    return PerlIO_close(f);
}

IV
PerlIOPending_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
{
    /*
     * A tad tricky - flush pops us, then we seek new top
     */
    PerlIO_flush(f);
    return PerlIO_seek(f, offset, whence);
}


IV
PerlIOPending_flush(pTHX_ PerlIO *f)
{
    PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
    if (b->buf && b->buf != (STDCHAR *) & b->oneword) {
	Safefree(b->buf);
	b->buf = NULL;
    }
    PerlIO_pop(aTHX_ f);
    return 0;
}

void
PerlIOPending_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, SSize_t cnt)
{
    if (cnt <= 0) {
	PerlIO_flush(f);
    }
    else {
	PerlIOBuf_set_ptrcnt(aTHX_ f, ptr, cnt);
    }
}

IV
PerlIOPending_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
{
    const IV code = PerlIOBase_pushed(aTHX_ f, mode, arg, tab);
    PerlIOl * const l = PerlIOBase(f);
    /*
     * Our PerlIO_fast_gets must match what we are pushed on, or sv_gets()
     * etc. get muddled when it changes mid-string when we auto-pop.
     */
    l->flags = (l->flags & ~(PERLIO_F_FASTGETS | PERLIO_F_UTF8)) |
	(PerlIOBase(PerlIONext(f))->
	 flags & (PERLIO_F_FASTGETS | PERLIO_F_UTF8));
    return code;
}

SSize_t
PerlIOPending_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
{
    SSize_t avail = PerlIO_get_cnt(f);
    SSize_t got = 0;
    if ((SSize_t) count >= 0 && (SSize_t)count < avail)
	avail = count;
    if (avail > 0)
	got = PerlIOBuf_read(aTHX_ f, vbuf, avail);
    if (got >= 0 && got < (SSize_t)count) {
	const SSize_t more =
	    PerlIO_read(f, ((STDCHAR *) vbuf) + got, count - got);
	if (more >= 0 || got == 0)
	    got += more;
    }
    return got;
}

PERLIO_FUNCS_DECL(PerlIO_pending) = {
    sizeof(PerlIO_funcs),
    "pending",
    sizeof(PerlIOBuf),
    PERLIO_K_BUFFERED|PERLIO_K_RAW,  /* not sure about RAW here */
    PerlIOPending_pushed,
    PerlIOBuf_popped,
    NULL,
    PerlIOBase_binmode,         /* binmode */
    NULL,
    PerlIOBase_fileno,
    PerlIOBuf_dup,
    PerlIOPending_read,
    PerlIOBuf_unread,
    PerlIOBuf_write,
    PerlIOPending_seek,
    PerlIOBuf_tell,
    PerlIOPending_close,
    PerlIOPending_flush,
    PerlIOPending_fill,
    PerlIOBase_eof,
    PerlIOBase_error,
    PerlIOBase_clearerr,
    PerlIOBase_setlinebuf,
    PerlIOBuf_get_base,
    PerlIOBuf_bufsiz,
    PerlIOBuf_get_ptr,
    PerlIOBuf_get_cnt,
    PerlIOPending_set_ptrcnt,
};



/*--------------------------------------------------------------------------------------*/
/*
 * crlf - translation On read translate CR,LF to "\n" we do this by
 * overriding ptr/cnt entries to hand back a line at a time and keeping a
 * record of which nl we "lied" about. On write translate "\n" to CR,LF
 *
 * c->nl points on the first byte of CR LF pair when it is temporarily
 * replaced by LF, or to the last CR of the buffer.  In the former case
 * the caller thinks that the buffer ends at c->nl + 1, in the latter
 * that it ends at c->nl; these two cases can be distinguished by
 * *c->nl.  c->nl is set during _getcnt() call, and unset during
 * _unread() and _flush() calls.
 * It only matters for read operations.
 */

typedef struct {
    PerlIOBuf base;             /* PerlIOBuf stuff */
    STDCHAR *nl;                /* Position of crlf we "lied" about in the
				 * buffer */
} PerlIOCrlf;

/* Inherit the PERLIO_F_UTF8 flag from previous layer.
 * Otherwise the :crlf layer would always revert back to
 * raw mode.
 */
static void
S_inherit_utf8_flag(PerlIO *f)
{
    PerlIO *g = PerlIONext(f);
    if (PerlIOValid(g)) {
	if (PerlIOBase(g)->flags & PERLIO_F_UTF8) {
	    PerlIOBase(f)->flags |= PERLIO_F_UTF8;
	}
    }
}

IV
PerlIOCrlf_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
{
    IV code;
    PerlIOBase(f)->flags |= PERLIO_F_CRLF;
    code = PerlIOBuf_pushed(aTHX_ f, mode, arg, tab);
#if 0
    DEBUG_i(
    PerlIO_debug("PerlIOCrlf_pushed f=%p %s %s fl=%08" UVxf "\n",
		 (void*)f, PerlIOBase(f)->tab->name, (mode) ? mode : "(Null)",
		 PerlIOBase(f)->flags);
    );
#endif
    {
      /* If the old top layer is a CRLF layer, reactivate it (if
       * necessary) and remove this new layer from the stack */
	 PerlIO *g = PerlIONext(f);
	 if (PerlIOValid(g)) {
	      PerlIOl *b = PerlIOBase(g);
	      if (b && b->tab == &PerlIO_crlf) {
		   if (!(b->flags & PERLIO_F_CRLF))
			b->flags |= PERLIO_F_CRLF;
		   S_inherit_utf8_flag(g);
		   PerlIO_pop(aTHX_ f);
		   return code;
	      }
	 }
    }
    S_inherit_utf8_flag(f);
    return code;
}


SSize_t
PerlIOCrlf_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
{
    PerlIOCrlf * const c = PerlIOSelf(f, PerlIOCrlf);
    if (c->nl) {	/* XXXX Shouldn't it be done only if b->ptr > c->nl? */
	*(c->nl) = NATIVE_0xd;
	c->nl = NULL;
    }
    if (!(PerlIOBase(f)->flags & PERLIO_F_CRLF))
	return PerlIOBuf_unread(aTHX_ f, vbuf, count);
    else {
	const STDCHAR *buf = (const STDCHAR *) vbuf + count;
	PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
	SSize_t unread = 0;
	if (PerlIOBase(f)->flags & PERLIO_F_WRBUF)
	    PerlIO_flush(f);
	if (!b->buf)
	    PerlIO_get_base(f);
	if (b->buf) {
	    if (!(PerlIOBase(f)->flags & PERLIO_F_RDBUF)) {
		b->end = b->ptr = b->buf + b->bufsiz;
		PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
		b->posn -= b->bufsiz;
	    }
	    while (count > 0 && b->ptr > b->buf) {
		const int ch = *--buf;
		if (ch == '\n') {
		    if (b->ptr - 2 >= b->buf) {
			*--(b->ptr) = NATIVE_0xa;
			*--(b->ptr) = NATIVE_0xd;
			unread++;
			count--;
		    }
		    else {
		    /* If b->ptr - 1 == b->buf, we are undoing reading 0xa */
                        *--(b->ptr) = NATIVE_0xa;   /* Works even if 0xa ==
                                                       '\r' */
			unread++;
			count--;
		    }
		}
		else {
		    *--(b->ptr) = ch;
		    unread++;
		    count--;
		}
	    }
	}
        if (count > 0)
            unread += PerlIOBase_unread(aTHX_ f, (const STDCHAR *) vbuf + unread, count);
	return unread;
    }
}

/* XXXX This code assumes that buffer size >=2, but does not check it... */
SSize_t
PerlIOCrlf_get_cnt(pTHX_ PerlIO *f)
{
    PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
    if (!b->buf)
	PerlIO_get_base(f);
    if (PerlIOBase(f)->flags & PERLIO_F_RDBUF) {
	PerlIOCrlf * const c = PerlIOSelf(f, PerlIOCrlf);
	if ((PerlIOBase(f)->flags & PERLIO_F_CRLF) && (!c->nl || *c->nl == NATIVE_0xd)) {
	    STDCHAR *nl = (c->nl) ? c->nl : b->ptr;
	  scan:
	    while (nl < b->end && *nl != NATIVE_0xd)
		nl++;
	    if (nl < b->end && *nl == NATIVE_0xd) {
	      test:
		if (nl + 1 < b->end) {
		    if (nl[1] == NATIVE_0xa) {
			*nl = '\n';
			c->nl = nl;
		    }
		    else {
			/*
			 * Not CR,LF but just CR
			 */
			nl++;
			goto scan;
		    }
		}
		else {
		    /*
		     * Blast - found CR as last char in buffer
		     */

		    if (b->ptr < nl) {
			/*
			 * They may not care, defer work as long as
			 * possible
			 */
			c->nl = nl;
			return (nl - b->ptr);
		    }
		    else {
			int code;
			b->ptr++;       /* say we have read it as far as
					 * flush() is concerned */
			b->buf++;       /* Leave space in front of buffer */
			/* Note as we have moved buf up flush's
			   posn += ptr-buf
			   will naturally make posn point at CR
			 */
			b->bufsiz--;    /* Buffer is thus smaller */
			code = PerlIO_fill(f);  /* Fetch some more */
			b->bufsiz++;    /* Restore size for next time */
			b->buf--;       /* Point at space */
			b->ptr = nl = b->buf;   /* Which is what we hand
						 * off */
			*nl = NATIVE_0xd;      /* Fill in the CR */
			if (code == 0)
			    goto test;  /* fill() call worked */
			/*
			 * CR at EOF - just fall through
			 */
			/* Should we clear EOF though ??? */
		    }
		}
	    }
	}
	return (((c->nl) ? (c->nl + 1) : b->end) - b->ptr);
    }
    return 0;
}

void
PerlIOCrlf_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, SSize_t cnt)
{
    PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
    PerlIOCrlf * const c = PerlIOSelf(f, PerlIOCrlf);
    if (!b->buf)
	PerlIO_get_base(f);
    if (!ptr) {
	if (c->nl) {
	    ptr = c->nl + 1;
	    if (ptr == b->end && *c->nl == NATIVE_0xd) {
		/* Deferred CR at end of buffer case - we lied about count */
		ptr--;
	    }
	}
	else {
	    ptr = b->end;
	}
	ptr -= cnt;
    }
    else {
	NOOP;
#if 0
	/*
	 * Test code - delete when it works ...
	 */
	IV flags = PerlIOBase(f)->flags;
	STDCHAR *chk = (c->nl) ? (c->nl+1) : b->end;
	if (ptr+cnt == c->nl && c->nl+1 == b->end && *c->nl == NATIVE_0xd) {
	  /* Deferred CR at end of buffer case - we lied about count */
	  chk--;
	}
	chk -= cnt;

	if (ptr != chk ) {
	    Perl_croak(aTHX_ "ptr wrong %p != %p fl=%08" UVxf
		       " nl=%p e=%p for %d", (void*)ptr, (void*)chk,
		       flags, c->nl, b->end, cnt);
	}
#endif
    }
    if (c->nl) {
	if (ptr > c->nl) {
	    /*
	     * They have taken what we lied about
	     */
	    *(c->nl) = NATIVE_0xd;
	    c->nl = NULL;
	    ptr++;
	}
    }
    b->ptr = ptr;
    PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
}

SSize_t
PerlIOCrlf_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
{
    if (!(PerlIOBase(f)->flags & PERLIO_F_CRLF))
	return PerlIOBuf_write(aTHX_ f, vbuf, count);
    else {
	PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
	const STDCHAR *buf = (const STDCHAR *) vbuf;
	const STDCHAR * const ebuf = buf + count;
	if (!b->buf)
	    PerlIO_get_base(f);
	if (!(PerlIOBase(f)->flags & PERLIO_F_CANWRITE))
	    return 0;
	while (buf < ebuf) {
	    const STDCHAR * const eptr = b->buf + b->bufsiz;
	    PerlIOBase(f)->flags |= PERLIO_F_WRBUF;
	    while (buf < ebuf && b->ptr < eptr) {
		if (*buf == '\n') {
		    if ((b->ptr + 2) > eptr) {
			/*
			 * Not room for both
			 */
			PerlIO_flush(f);
			break;
		    }
		    else {
			*(b->ptr)++ = NATIVE_0xd;      /* CR */
			*(b->ptr)++ = NATIVE_0xa;      /* LF */
			buf++;
			if (PerlIOBase(f)->flags & PERLIO_F_LINEBUF) {
			    PerlIO_flush(f);
			    break;
			}
		    }
		}
		else {
		    *(b->ptr)++ = *buf++;
		}
		if (b->ptr >= eptr) {
		    PerlIO_flush(f);
		    break;
		}
	    }
	}
	if (PerlIOBase(f)->flags & PERLIO_F_UNBUF)
	    PerlIO_flush(f);
	return (buf - (STDCHAR *) vbuf);
    }
}

IV
PerlIOCrlf_flush(pTHX_ PerlIO *f)
{
    PerlIOCrlf * const c = PerlIOSelf(f, PerlIOCrlf);
    if (c->nl) {
	*(c->nl) = NATIVE_0xd;
	c->nl = NULL;
    }
    return PerlIOBuf_flush(aTHX_ f);
}

IV
PerlIOCrlf_binmode(pTHX_ PerlIO *f)
{
    if ((PerlIOBase(f)->flags & PERLIO_F_CRLF)) {
	/* In text mode - flush any pending stuff and flip it */
	PerlIOBase(f)->flags &= ~PERLIO_F_CRLF;
#ifndef PERLIO_USING_CRLF
	/* CRLF is unusual case - if this is just the :crlf layer pop it */
	PerlIO_pop(aTHX_ f);
#endif
    }
    return 0;
}

PERLIO_FUNCS_DECL(PerlIO_crlf) = {
    sizeof(PerlIO_funcs),
    "crlf",
    sizeof(PerlIOCrlf),
    PERLIO_K_BUFFERED | PERLIO_K_CANCRLF | PERLIO_K_RAW,
    PerlIOCrlf_pushed,
    PerlIOBuf_popped,         /* popped */
    PerlIOBuf_open,
    PerlIOCrlf_binmode,       /* binmode */
    NULL,
    PerlIOBase_fileno,
    PerlIOBuf_dup,
    PerlIOBuf_read,             /* generic read works with ptr/cnt lies */
    PerlIOCrlf_unread,          /* Put CR,LF in buffer for each '\n' */
    PerlIOCrlf_write,           /* Put CR,LF in buffer for each '\n' */
    PerlIOBuf_seek,
    PerlIOBuf_tell,
    PerlIOBuf_close,
    PerlIOCrlf_flush,
    PerlIOBuf_fill,
    PerlIOBase_eof,
    PerlIOBase_error,
    PerlIOBase_clearerr,
    PerlIOBase_setlinebuf,
    PerlIOBuf_get_base,
    PerlIOBuf_bufsiz,
    PerlIOBuf_get_ptr,
    PerlIOCrlf_get_cnt,
    PerlIOCrlf_set_ptrcnt,
};

PerlIO *
Perl_PerlIO_stdin(pTHX)
{
    if (!PL_perlio) {
	PerlIO_stdstreams(aTHX);
    }
    return (PerlIO*)&PL_perlio[1];
}

PerlIO *
Perl_PerlIO_stdout(pTHX)
{
    if (!PL_perlio) {
	PerlIO_stdstreams(aTHX);
    }
    return (PerlIO*)&PL_perlio[2];
}

PerlIO *
Perl_PerlIO_stderr(pTHX)
{
    if (!PL_perlio) {
	PerlIO_stdstreams(aTHX);
    }
    return (PerlIO*)&PL_perlio[3];
}

/*--------------------------------------------------------------------------------------*/

char *
PerlIO_getname(PerlIO *f, char *buf)
{
#ifdef VMS
    dTHX;
    char *name = NULL;
    bool exported = FALSE;
    FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
    if (!stdio) {
	stdio = PerlIO_exportFILE(f,0);
	exported = TRUE;
    }
    if (stdio) {
	name = fgetname(stdio, buf);
	if (exported) PerlIO_releaseFILE(f,stdio);
    }
    return name;
#else
    PERL_UNUSED_ARG(f);
    PERL_UNUSED_ARG(buf);
    Perl_croak_nocontext("Don't know how to get file name");
    return NULL;
#endif
}


/*--------------------------------------------------------------------------------------*/
/*
 * Functions which can be called on any kind of PerlIO implemented in
 * terms of above
 */

#undef PerlIO_fdopen
PerlIO *
PerlIO_fdopen(int fd, const char *mode)
{
    dTHX;
    return PerlIO_openn(aTHX_ NULL, mode, fd, 0, 0, NULL, 0, NULL);
}

#undef PerlIO_open
PerlIO *
PerlIO_open(const char *path, const char *mode)
{
    dTHX;
    SV *name = sv_2mortal(newSVpv(path, 0));
    return PerlIO_openn(aTHX_ NULL, mode, -1, 0, 0, NULL, 1, &name);
}

#undef Perlio_reopen
PerlIO *
PerlIO_reopen(const char *path, const char *mode, PerlIO *f)
{
    dTHX;
    SV *name = sv_2mortal(newSVpv(path,0));
    return PerlIO_openn(aTHX_ NULL, mode, -1, 0, 0, f, 1, &name);
}

#undef PerlIO_getc
int
PerlIO_getc(PerlIO *f)
{
    dTHX;
    STDCHAR buf[1];
    if ( 1 == PerlIO_read(f, buf, 1) ) {
	return (unsigned char) buf[0];
    }
    return EOF;
}

#undef PerlIO_ungetc
int
PerlIO_ungetc(PerlIO *f, int ch)
{
    dTHX;
    if (ch != EOF) {
	STDCHAR buf = ch;
	if (PerlIO_unread(f, &buf, 1) == 1)
	    return ch;
    }
    return EOF;
}

#undef PerlIO_putc
int
PerlIO_putc(PerlIO *f, int ch)
{
    dTHX;
    STDCHAR buf = ch;
    return PerlIO_write(f, &buf, 1);
}

#undef PerlIO_puts
int
PerlIO_puts(PerlIO *f, const char *s)
{
    dTHX;
    return PerlIO_write(f, s, strlen(s));
}

#undef PerlIO_rewind
void
PerlIO_rewind(PerlIO *f)
{
    dTHX;
    PerlIO_seek(f, (Off_t) 0, SEEK_SET);
    PerlIO_clearerr(f);
}

#undef PerlIO_vprintf
int
PerlIO_vprintf(PerlIO *f, const char *fmt, va_list ap)
{
    dTHX;
    SV * sv;
    const char *s;
    STRLEN len;
    SSize_t wrote;
#ifdef NEED_VA_COPY
    va_list apc;
    Perl_va_copy(ap, apc);
    sv = vnewSVpvf(fmt, &apc);
    va_end(apc);
#else
    sv = vnewSVpvf(fmt, &ap);
#endif
    s = SvPV_const(sv, len);
    wrote = PerlIO_write(f, s, len);
    SvREFCNT_dec(sv);
    return wrote;
}

#undef PerlIO_printf
int
PerlIO_printf(PerlIO *f, const char *fmt, ...)
{
    va_list ap;
    int result;
    va_start(ap, fmt);
    result = PerlIO_vprintf(f, fmt, ap);
    va_end(ap);
    return result;
}

#undef PerlIO_stdoutf
int
PerlIO_stdoutf(const char *fmt, ...)
{
    dTHX;
    va_list ap;
    int result;
    va_start(ap, fmt);
    result = PerlIO_vprintf(PerlIO_stdout(), fmt, ap);
    va_end(ap);
    return result;
}

#undef PerlIO_tmpfile
PerlIO *
PerlIO_tmpfile(void)
{
#ifndef WIN32
     dTHX;
#endif
     PerlIO *f = NULL;
#ifdef WIN32
     const int fd = win32_tmpfd();
     if (fd >= 0)
	  f = PerlIO_fdopen(fd, "w+b");
#else /* WIN32 */
#    if defined(HAS_MKSTEMP) && ! defined(VMS) && ! defined(OS2)
     int fd = -1;
     char tempname[] = "/tmp/PerlIO_XXXXXX";
     const char * const tmpdir = TAINTING_get ? NULL : PerlEnv_getenv("TMPDIR");
     SV * sv = NULL;
     int old_umask = umask(0177);
     /*
      * I have no idea how portable mkstemp() is ... NI-S
      */
     if (tmpdir && *tmpdir) {
	 /* if TMPDIR is set and not empty, we try that first */
	 sv = newSVpv(tmpdir, 0);
	 sv_catpv(sv, tempname + 4);
	 fd = mkstemp(SvPVX(sv));
     }
     if (fd < 0) {
	 SvREFCNT_dec(sv);
	 sv = NULL;
	 /* else we try /tmp */
	 fd = mkstemp(tempname);
     }
     if (fd < 0) {
         /* Try cwd */
         sv = newSVpvs(".");
         sv_catpv(sv, tempname + 4);
         fd = mkstemp(SvPVX(sv));
     }
     umask(old_umask);
     if (fd >= 0) {
	  f = PerlIO_fdopen(fd, "w+");
	  if (f)
	       PerlIOBase(f)->flags |= PERLIO_F_TEMP;
	  PerlLIO_unlink(sv ? SvPVX_const(sv) : tempname);
     }
     SvREFCNT_dec(sv);
#    else	/* !HAS_MKSTEMP, fallback to stdio tmpfile(). */
     FILE * const stdio = PerlSIO_tmpfile();

     if (stdio)
	  f = PerlIO_fdopen(fileno(stdio), "w+");

#    endif /* else HAS_MKSTEMP */
#endif /* else WIN32 */
     return f;
}

void
Perl_PerlIO_save_errno(pTHX_ PerlIO *f)
{
    PERL_UNUSED_CONTEXT;
    if (!PerlIOValid(f))
	return;
    PerlIOBase(f)->err = errno;
#ifdef VMS
    PerlIOBase(f)->os_err = vaxc$errno;
#elif defined(OS2)
    PerlIOBase(f)->os_err = Perl_rc;
#elif defined(WIN32)
    PerlIOBase(f)->os_err = GetLastError();
#endif
}

void
Perl_PerlIO_restore_errno(pTHX_ PerlIO *f)
{
    PERL_UNUSED_CONTEXT;
    if (!PerlIOValid(f))
	return;
    SETERRNO(PerlIOBase(f)->err, PerlIOBase(f)->os_err);
#ifdef OS2
    Perl_rc = PerlIOBase(f)->os_err);
#elif defined(WIN32)
    SetLastError(PerlIOBase(f)->os_err);
#endif
}

#undef HAS_FSETPOS
#undef HAS_FGETPOS


/*======================================================================================*/
/*
 * Now some functions in terms of above which may be needed even if we are
 * not in true PerlIO mode
 */
const char *
Perl_PerlIO_context_layers(pTHX_ const char *mode)
{
    const char *direction = NULL;
    SV *layers;
    /*
     * Need to supply default layer info from open.pm
     */

    if (!PL_curcop)
	return NULL;

    if (mode && mode[0] != 'r') {
	if (PL_curcop->cop_hints & HINT_LEXICAL_IO_OUT)
	    direction = "open>";
    } else {
	if (PL_curcop->cop_hints & HINT_LEXICAL_IO_IN)
	    direction = "open<";
    }
    if (!direction)
	return NULL;

    layers = cop_hints_fetch_pvn(PL_curcop, direction, 5, 0, 0);

    assert(layers);
    return SvOK(layers) ? SvPV_nolen_const(layers) : NULL;
}


#ifndef HAS_FSETPOS
#undef PerlIO_setpos
int
PerlIO_setpos(PerlIO *f, SV *pos)
{
    if (SvOK(pos)) {
	if (f) {
	    dTHX;
	    STRLEN len;
	    const Off_t * const posn = (Off_t *) SvPV(pos, len);
	    if(len == sizeof(Off_t))
		return PerlIO_seek(f, *posn, SEEK_SET);
	}
    }
    SETERRNO(EINVAL, SS_IVCHAN);
    return -1;
}
#else
#undef PerlIO_setpos
int
PerlIO_setpos(PerlIO *f, SV *pos)
{
    if (SvOK(pos)) {
	if (f) {
	    dTHX;
	    STRLEN len;
	    Fpos_t * const fpos = (Fpos_t *) SvPV(pos, len);
	    if(len == sizeof(Fpos_t))
#if defined(USE_64_BIT_STDIO) && defined(USE_FSETPOS64)
		return fsetpos64(f, fpos);
#else
		return fsetpos(f, fpos);
#endif
	}
    }
    SETERRNO(EINVAL, SS_IVCHAN);
    return -1;
}
#endif

#ifndef HAS_FGETPOS
#undef PerlIO_getpos
int
PerlIO_getpos(PerlIO *f, SV *pos)
{
    dTHX;
    Off_t posn = PerlIO_tell(f);
    sv_setpvn(pos, (char *) &posn, sizeof(posn));
    return (posn == (Off_t) - 1) ? -1 : 0;
}
#else
#undef PerlIO_getpos
int
PerlIO_getpos(PerlIO *f, SV *pos)
{
    dTHX;
    Fpos_t fpos;
    int code;
#if defined(USE_64_BIT_STDIO) && defined(USE_FSETPOS64)
    code = fgetpos64(f, &fpos);
#else
    code = fgetpos(f, &fpos);
#endif
    sv_setpvn(pos, (char *) &fpos, sizeof(fpos));
    return code;
}
#endif

#if !defined(HAS_VPRINTF)

int
vprintf(char *pat, char *args)
{
    _doprnt(pat, args, stdout);
    return 0;                   /* wrong, but perl doesn't use the return
				 * value */
}

int
vfprintf(FILE *fd, char *pat, char *args)
{
    _doprnt(pat, args, fd);
    return 0;                   /* wrong, but perl doesn't use the return
				 * value */
}

#endif

/* print a failure format string message to stderr and fail exit the process
   using only libc without depending on any perl data structures being
   initialized.
*/

void
Perl_noperl_die(const char* pat, ...)
{
    va_list(arglist);
    PERL_ARGS_ASSERT_NOPERL_DIE;
    va_start(arglist, pat);
    vfprintf(stderr, pat, arglist);
    va_end(arglist);
    exit(1);
}

/*
 * ex: set ts=8 sts=4 sw=4 et:
 */