9fa5deac68a0d83c14148f3df721f4c78a181b5e
[p5sagit/p5-mst-13.2.git] / perlio.c
1 /*
2  * perlio.c Copyright (c) 1996-2006, Nick Ing-Simmons You may distribute
3  * under the terms of either the GNU General Public License or the
4  * Artistic License, as specified in the README file.
5  */
6
7 /*
8  * Hour after hour for nearly three weary days he had jogged up and down,
9  * over passes, and through long dales, and across many streams.
10  */
11
12 /* This file contains the functions needed to implement PerlIO, which
13  * is Perl's private replacement for the C stdio library. This is used
14  * by default unless you compile with -Uuseperlio or run with
15  * PERLIO=:stdio (but don't do this unless you know what you're doing)
16  */
17
18 /*
19  * If we have ActivePerl-like PERL_IMPLICIT_SYS then we need a dTHX to get
20  * at the dispatch tables, even when we do not need it for other reasons.
21  * Invent a dSYS macro to abstract this out
22  */
23 #ifdef PERL_IMPLICIT_SYS
24 #define dSYS dTHX
25 #else
26 #define dSYS dNOOP
27 #endif
28
29 #define VOIDUSED 1
30 #ifdef PERL_MICRO
31 #   include "uconfig.h"
32 #else
33 #   include "config.h"
34 #endif
35
36 #define PERLIO_NOT_STDIO 0
37 #if !defined(PERLIO_IS_STDIO) && !defined(USE_SFIO)
38 /*
39  * #define PerlIO FILE
40  */
41 #endif
42 /*
43  * This file provides those parts of PerlIO abstraction
44  * which are not #defined in perlio.h.
45  * Which these are depends on various Configure #ifdef's
46  */
47
48 #include "EXTERN.h"
49 #define PERL_IN_PERLIO_C
50 #include "perl.h"
51
52 #ifdef PERL_IMPLICIT_CONTEXT
53 #undef dSYS
54 #define dSYS dTHX
55 #endif
56
57 #include "XSUB.h"
58
59 #ifdef __Lynx__
60 /* Missing proto on LynxOS */
61 int mkstemp(char*);
62 #endif
63
64 /* Call the callback or PerlIOBase, and return failure. */
65 #define Perl_PerlIO_or_Base(f, callback, base, failure, args)   \
66         if (PerlIOValid(f)) {                                   \
67                 const PerlIO_funcs * const tab = PerlIOBase(f)->tab;\
68                 if (tab && tab->callback)                       \
69                         return (*tab->callback) args;           \
70                 else                                            \
71                         return PerlIOBase_ ## base args;        \
72         }                                                       \
73         else                                                    \
74                 SETERRNO(EBADF, SS_IVCHAN);                     \
75         return failure
76
77 /* Call the callback or fail, and return failure. */
78 #define Perl_PerlIO_or_fail(f, callback, failure, args)         \
79         if (PerlIOValid(f)) {                                   \
80                 const PerlIO_funcs * const tab = PerlIOBase(f)->tab;\
81                 if (tab && tab->callback)                       \
82                         return (*tab->callback) args;           \
83                 SETERRNO(EINVAL, LIB_INVARG);                   \
84         }                                                       \
85         else                                                    \
86                 SETERRNO(EBADF, SS_IVCHAN);                     \
87         return failure
88
89 /* Call the callback or PerlIOBase, and be void. */
90 #define Perl_PerlIO_or_Base_void(f, callback, base, args)       \
91         if (PerlIOValid(f)) {                                   \
92                 const PerlIO_funcs * const tab = PerlIOBase(f)->tab;\
93                 if (tab && tab->callback)                       \
94                         (*tab->callback) args;                  \
95                 else                                            \
96                         PerlIOBase_ ## base args;               \
97         }                                                       \
98         else                                                    \
99                 SETERRNO(EBADF, SS_IVCHAN)
100
101 /* Call the callback or fail, and be void. */
102 #define Perl_PerlIO_or_fail_void(f, callback, args)             \
103         if (PerlIOValid(f)) {                                   \
104                 const PerlIO_funcs * const tab = PerlIOBase(f)->tab;\
105                 if (tab && tab->callback)                       \
106                         (*tab->callback) args;                  \
107                 else                                            \
108                         SETERRNO(EINVAL, LIB_INVARG);           \
109         }                                                       \
110         else                                                    \
111                 SETERRNO(EBADF, SS_IVCHAN)
112
113 #ifndef USE_SFIO
114 int
115 perlsio_binmode(FILE *fp, int iotype, int mode)
116 {
117     /*
118      * This used to be contents of do_binmode in doio.c
119      */
120 #ifdef DOSISH
121 #  if defined(atarist) || defined(__MINT__)
122     if (!fflush(fp)) {
123         if (mode & O_BINARY)
124             ((FILE *) fp)->_flag |= _IOBIN;
125         else
126             ((FILE *) fp)->_flag &= ~_IOBIN;
127         return 1;
128     }
129     return 0;
130 #  else
131     dTHX;
132 #ifdef NETWARE
133     if (PerlLIO_setmode(fp, mode) != -1) {
134 #else
135     if (PerlLIO_setmode(fileno(fp), mode) != -1) {
136 #endif
137 #    if defined(WIN32) && defined(__BORLANDC__)
138         /*
139          * The translation mode of the stream is maintained independent 
140 of
141          * the translation mode of the fd in the Borland RTL (heavy
142          * digging through their runtime sources reveal).  User has to 
143 set
144          * the mode explicitly for the stream (though they don't 
145 document
146          * this anywhere). GSAR 97-5-24
147          */
148         fseek(fp, 0L, 0);
149         if (mode & O_BINARY)
150             fp->flags |= _F_BIN;
151         else
152             fp->flags &= ~_F_BIN;
153 #    endif
154         return 1;
155     }
156     else
157         return 0;
158 #  endif
159 #else
160 #  if defined(USEMYBINMODE)
161     dTHX;
162     if (my_binmode(fp, iotype, mode) != FALSE)
163         return 1;
164     else
165         return 0;
166 #  else
167     PERL_UNUSED_ARG(fp);
168     PERL_UNUSED_ARG(iotype);
169     PERL_UNUSED_ARG(mode);
170     return 1;
171 #  endif
172 #endif
173 }
174 #endif /* sfio */
175
176 #ifndef O_ACCMODE
177 #define O_ACCMODE 3             /* Assume traditional implementation */
178 #endif
179
180 int
181 PerlIO_intmode2str(int rawmode, char *mode, int *writing)
182 {
183     const int result = rawmode & O_ACCMODE;
184     int ix = 0;
185     int ptype;
186     switch (result) {
187     case O_RDONLY:
188         ptype = IoTYPE_RDONLY;
189         break;
190     case O_WRONLY:
191         ptype = IoTYPE_WRONLY;
192         break;
193     case O_RDWR:
194     default:
195         ptype = IoTYPE_RDWR;
196         break;
197     }
198     if (writing)
199         *writing = (result != O_RDONLY);
200
201     if (result == O_RDONLY) {
202         mode[ix++] = 'r';
203     }
204 #ifdef O_APPEND
205     else if (rawmode & O_APPEND) {
206         mode[ix++] = 'a';
207         if (result != O_WRONLY)
208             mode[ix++] = '+';
209     }
210 #endif
211     else {
212         if (result == O_WRONLY)
213             mode[ix++] = 'w';
214         else {
215             mode[ix++] = 'r';
216             mode[ix++] = '+';
217         }
218     }
219     if (rawmode & O_BINARY)
220         mode[ix++] = 'b';
221     mode[ix] = '\0';
222     return ptype;
223 }
224
225 #ifndef PERLIO_LAYERS
226 int
227 PerlIO_apply_layers(pTHX_ PerlIO *f, const char *mode, const char *names)
228 {
229     if (!names || !*names
230         || strEQ(names, ":crlf")
231         || strEQ(names, ":raw")
232         || strEQ(names, ":bytes")
233        ) {
234         return 0;
235     }
236     Perl_croak(aTHX_ "Cannot apply \"%s\" in non-PerlIO perl", names);
237     /*
238      * NOTREACHED
239      */
240     return -1;
241 }
242
243 void
244 PerlIO_destruct(pTHX)
245 {
246 }
247
248 int
249 PerlIO_binmode(pTHX_ PerlIO *fp, int iotype, int mode, const char *names)
250 {
251 #ifdef USE_SFIO
252     PERL_UNUSED_ARG(iotype);
253     PERL_UNUSED_ARG(mode);
254     PERL_UNUSED_ARG(names);
255     return 1;
256 #else
257     return perlsio_binmode(fp, iotype, mode);
258 #endif
259 }
260
261 PerlIO *
262 PerlIO_fdupopen(pTHX_ PerlIO *f, CLONE_PARAMS *param, int flags)
263 {
264 #if defined(PERL_MICRO) || defined(__SYMBIAN32__)
265     return NULL;
266 #else
267 #ifdef PERL_IMPLICIT_SYS
268     return PerlSIO_fdupopen(f);
269 #else
270 #ifdef WIN32
271     return win32_fdupopen(f);
272 #else
273     if (f) {
274         const int fd = PerlLIO_dup(PerlIO_fileno(f));
275         if (fd >= 0) {
276             char mode[8];
277 #ifdef DJGPP
278             const int omode = djgpp_get_stream_mode(f);
279 #else
280             const int omode = fcntl(fd, F_GETFL);
281 #endif
282             PerlIO_intmode2str(omode,mode,NULL);
283             /* the r+ is a hack */
284             return PerlIO_fdopen(fd, mode);
285         }
286         return NULL;
287     }
288     else {
289         SETERRNO(EBADF, SS_IVCHAN);
290     }
291 #endif
292     return NULL;
293 #endif
294 #endif
295 }
296
297
298 /*
299  * De-mux PerlIO_openn() into fdopen, freopen and fopen type entries
300  */
301
302 PerlIO *
303 PerlIO_openn(pTHX_ const char *layers, const char *mode, int fd,
304              int imode, int perm, PerlIO *old, int narg, SV **args)
305 {
306     if (narg) {
307         if (narg > 1) {
308             Perl_croak(aTHX_ "More than one argument to open");
309         }
310         if (*args == &PL_sv_undef)
311             return PerlIO_tmpfile();
312         else {
313             const char *name = SvPV_nolen_const(*args);
314             if (*mode == IoTYPE_NUMERIC) {
315                 fd = PerlLIO_open3(name, imode, perm);
316                 if (fd >= 0)
317                     return PerlIO_fdopen(fd, mode + 1);
318             }
319             else if (old) {
320                 return PerlIO_reopen(name, mode, old);
321             }
322             else {
323                 return PerlIO_open(name, mode);
324             }
325         }
326     }
327     else {
328         return PerlIO_fdopen(fd, (char *) mode);
329     }
330     return NULL;
331 }
332
333 XS(XS_PerlIO__Layer__find)
334 {
335     dXSARGS;
336     if (items < 2)
337         Perl_croak(aTHX_ "Usage class->find(name[,load])");
338     else {
339         const char * const name = SvPV_nolen_const(ST(1));
340         ST(0) = (strEQ(name, "crlf")
341                  || strEQ(name, "raw")) ? &PL_sv_yes : &PL_sv_undef;
342         XSRETURN(1);
343     }
344 }
345
346
347 void
348 Perl_boot_core_PerlIO(pTHX)
349 {
350     newXS("PerlIO::Layer::find", XS_PerlIO__Layer__find, __FILE__);
351 }
352
353 #endif
354
355
356 #ifdef PERLIO_IS_STDIO
357
358 void
359 PerlIO_init(pTHX)
360 {
361     /*
362      * Does nothing (yet) except force this file to be included in perl
363      * binary. That allows this file to force inclusion of other functions
364      * that may be required by loadable extensions e.g. for
365      * FileHandle::tmpfile
366      */
367 }
368
369 #undef PerlIO_tmpfile
370 PerlIO *
371 PerlIO_tmpfile(void)
372 {
373     return tmpfile();
374 }
375
376 #else                           /* PERLIO_IS_STDIO */
377
378 #ifdef USE_SFIO
379
380 #undef HAS_FSETPOS
381 #undef HAS_FGETPOS
382
383 /*
384  * This section is just to make sure these functions get pulled in from
385  * libsfio.a
386  */
387
388 #undef PerlIO_tmpfile
389 PerlIO *
390 PerlIO_tmpfile(void)
391 {
392     return sftmp(0);
393 }
394
395 void
396 PerlIO_init(pTHX)
397 {
398     /*
399      * Force this file to be included in perl binary. Which allows this
400      * file to force inclusion of other functions that may be required by
401      * loadable extensions e.g. for FileHandle::tmpfile
402      */
403
404     /*
405      * Hack sfio does its own 'autoflush' on stdout in common cases. Flush
406      * results in a lot of lseek()s to regular files and lot of small
407      * writes to pipes.
408      */
409     sfset(sfstdout, SF_SHARE, 0);
410 }
411
412 /* This is not the reverse of PerlIO_exportFILE(), PerlIO_releaseFILE() is. */
413 PerlIO *
414 PerlIO_importFILE(FILE *stdio, const char *mode)
415 {
416     const int fd = fileno(stdio);
417     if (!mode || !*mode) {
418         mode = "r+";
419     }
420     return PerlIO_fdopen(fd, mode);
421 }
422
423 FILE *
424 PerlIO_findFILE(PerlIO *pio)
425 {
426     const int fd = PerlIO_fileno(pio);
427     FILE * const f = fdopen(fd, "r+");
428     PerlIO_flush(pio);
429     if (!f && errno == EINVAL)
430         f = fdopen(fd, "w");
431     if (!f && errno == EINVAL)
432         f = fdopen(fd, "r");
433     return f;
434 }
435
436
437 #else                           /* USE_SFIO */
438 /*======================================================================================*/
439 /*
440  * Implement all the PerlIO interface ourselves.
441  */
442
443 #include "perliol.h"
444
445 /*
446  * We _MUST_ have <unistd.h> if we are using lseek() and may have large
447  * files
448  */
449 #ifdef I_UNISTD
450 #include <unistd.h>
451 #endif
452 #ifdef HAS_MMAP
453 #include <sys/mman.h>
454 #endif
455
456 void
457 PerlIO_debug(const char *fmt, ...)
458 {
459     va_list ap;
460     dSYS;
461     va_start(ap, fmt);
462     if (!PL_perlio_debug_fd && !PL_tainting && PL_uid == PL_euid && PL_gid == PL_egid) {
463         const char * const s = PerlEnv_getenv("PERLIO_DEBUG");
464         if (s && *s)
465             PL_perlio_debug_fd = PerlLIO_open3(s, O_WRONLY | O_CREAT | O_APPEND, 0666);
466         else
467             PL_perlio_debug_fd = -1;
468     }
469     if (PL_perlio_debug_fd > 0) {
470         dTHX;
471 #ifdef USE_ITHREADS
472         const char * const s = CopFILE(PL_curcop);
473         /* Use fixed buffer as sv_catpvf etc. needs SVs */
474         char buffer[1024];
475         const STRLEN len = my_sprintf(buffer, "%.40s:%" IVdf " ", s ? s : "(none)", (IV) CopLINE(PL_curcop));
476         const STRLEN len2 = vsprintf(buffer+len, fmt, ap);
477         PerlLIO_write(PL_perlio_debug_fd, buffer, len + len2);
478 #else
479         const char *s = CopFILE(PL_curcop);
480         STRLEN len;
481         SV * const sv = newSVpvs("");
482         Perl_sv_catpvf(aTHX_ sv, "%s:%" IVdf " ", s ? s : "(none)",
483                        (IV) CopLINE(PL_curcop));
484         Perl_sv_vcatpvf(aTHX_ sv, fmt, &ap);
485
486         s = SvPV_const(sv, len);
487         PerlLIO_write(PL_perlio_debug_fd, s, len);
488         SvREFCNT_dec(sv);
489 #endif
490     }
491     va_end(ap);
492 }
493
494 /*--------------------------------------------------------------------------------------*/
495
496 /*
497  * Inner level routines
498  */
499
500 /*
501  * Table of pointers to the PerlIO structs (malloc'ed)
502  */
503 #define PERLIO_TABLE_SIZE 64
504
505 PerlIO *
506 PerlIO_allocate(pTHX)
507 {
508     dVAR;
509     /*
510      * Find a free slot in the table, allocating new table as necessary
511      */
512     PerlIO **last;
513     PerlIO *f;
514     last = &PL_perlio;
515     while ((f = *last)) {
516         int i;
517         last = (PerlIO **) (f);
518         for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
519             if (!*++f) {
520                 return f;
521             }
522         }
523     }
524     Newxz(f,PERLIO_TABLE_SIZE,PerlIO);
525     if (!f) {
526         return NULL;
527     }
528     *last = f;
529     return f + 1;
530 }
531
532 #undef PerlIO_fdupopen
533 PerlIO *
534 PerlIO_fdupopen(pTHX_ PerlIO *f, CLONE_PARAMS *param, int flags)
535 {
536     if (PerlIOValid(f)) {
537         const PerlIO_funcs * const tab = PerlIOBase(f)->tab;
538         PerlIO_debug("fdupopen f=%p param=%p\n",(void*)f,(void*)param);
539         if (tab && tab->Dup)
540              return (*tab->Dup)(aTHX_ PerlIO_allocate(aTHX), f, param, flags);
541         else {
542              return PerlIOBase_dup(aTHX_ PerlIO_allocate(aTHX), f, param, flags);
543         }
544     }
545     else
546          SETERRNO(EBADF, SS_IVCHAN);
547
548     return NULL;
549 }
550
551 void
552 PerlIO_cleantable(pTHX_ PerlIO **tablep)
553 {
554     PerlIO * const table = *tablep;
555     if (table) {
556         int i;
557         PerlIO_cleantable(aTHX_(PerlIO **) & (table[0]));
558         for (i = PERLIO_TABLE_SIZE - 1; i > 0; i--) {
559             PerlIO * const f = table + i;
560             if (*f) {
561                 PerlIO_close(f);
562             }
563         }
564         Safefree(table);
565         *tablep = NULL;
566     }
567 }
568
569
570 PerlIO_list_t *
571 PerlIO_list_alloc(pTHX)
572 {
573     PerlIO_list_t *list;
574     Newxz(list, 1, PerlIO_list_t);
575     list->refcnt = 1;
576     return list;
577 }
578
579 void
580 PerlIO_list_free(pTHX_ PerlIO_list_t *list)
581 {
582     if (list) {
583         if (--list->refcnt == 0) {
584             if (list->array) {
585                 IV i;
586                 for (i = 0; i < list->cur; i++) {
587                     if (list->array[i].arg)
588                         SvREFCNT_dec(list->array[i].arg);
589                 }
590                 Safefree(list->array);
591             }
592             Safefree(list);
593         }
594     }
595 }
596
597 void
598 PerlIO_list_push(pTHX_ PerlIO_list_t *list, PerlIO_funcs *funcs, SV *arg)
599 {
600     dVAR;
601     PerlIO_pair_t *p;
602     if (list->cur >= list->len) {
603         list->len += 8;
604         if (list->array)
605             Renew(list->array, list->len, PerlIO_pair_t);
606         else
607             Newx(list->array, list->len, PerlIO_pair_t);
608     }
609     p = &(list->array[list->cur++]);
610     p->funcs = funcs;
611     if ((p->arg = arg)) {
612         (void)SvREFCNT_inc(arg);
613     }
614 }
615
616 PerlIO_list_t *
617 PerlIO_clone_list(pTHX_ PerlIO_list_t *proto, CLONE_PARAMS *param)
618 {
619     PerlIO_list_t *list = (PerlIO_list_t *) NULL;
620     if (proto) {
621         int i;
622         list = PerlIO_list_alloc(aTHX);
623         for (i=0; i < proto->cur; i++) {
624             SV *arg = NULL;
625             if (proto->array[i].arg)
626                 arg = PerlIO_sv_dup(aTHX_ proto->array[i].arg,param);
627             PerlIO_list_push(aTHX_ list, proto->array[i].funcs, arg);
628         }
629     }
630     return list;
631 }
632
633 void
634 PerlIO_clone(pTHX_ PerlInterpreter *proto, CLONE_PARAMS *param)
635 {
636 #ifdef USE_ITHREADS
637     PerlIO **table = &proto->Iperlio;
638     PerlIO *f;
639     PL_perlio = NULL;
640     PL_known_layers = PerlIO_clone_list(aTHX_ proto->Iknown_layers, param);
641     PL_def_layerlist = PerlIO_clone_list(aTHX_ proto->Idef_layerlist, param);
642     PerlIO_allocate(aTHX); /* root slot is never used */
643     PerlIO_debug("Clone %p from %p\n",aTHX,proto);
644     while ((f = *table)) {
645             int i;
646             table = (PerlIO **) (f++);
647             for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
648                 if (*f) {
649                     (void) fp_dup(f, 0, param);
650                 }
651                 f++;
652             }
653         }
654 #else
655     PERL_UNUSED_ARG(proto);
656     PERL_UNUSED_ARG(param);
657 #endif
658 }
659
660 void
661 PerlIO_destruct(pTHX)
662 {
663     dVAR;
664     PerlIO **table = &PL_perlio;
665     PerlIO *f;
666 #ifdef USE_ITHREADS
667     PerlIO_debug("Destruct %p\n",aTHX);
668 #endif
669     while ((f = *table)) {
670         int i;
671         table = (PerlIO **) (f++);
672         for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
673             PerlIO *x = f;
674             const PerlIOl *l;
675             while ((l = *x)) {
676                 if (l->tab->kind & PERLIO_K_DESTRUCT) {
677                     PerlIO_debug("Destruct popping %s\n", l->tab->name);
678                     PerlIO_flush(x);
679                     PerlIO_pop(aTHX_ x);
680                 }
681                 else {
682                     x = PerlIONext(x);
683                 }
684             }
685             f++;
686         }
687     }
688 }
689
690 void
691 PerlIO_pop(pTHX_ PerlIO *f)
692 {
693     const PerlIOl *l = *f;
694     if (l) {
695         PerlIO_debug("PerlIO_pop f=%p %s\n", (void*)f, l->tab->name);
696         if (l->tab->Popped) {
697             /*
698              * If popped returns non-zero do not free its layer structure
699              * it has either done so itself, or it is shared and still in
700              * use
701              */
702             if ((*l->tab->Popped) (aTHX_ f) != 0)
703                 return;
704         }
705         *f = l->next;
706         Safefree(l);
707     }
708 }
709
710 /* Return as an array the stack of layers on a filehandle.  Note that
711  * the stack is returned top-first in the array, and there are three
712  * times as many array elements as there are layers in the stack: the
713  * first element of a layer triplet is the name, the second one is the
714  * arguments, and the third one is the flags. */
715
716 AV *
717 PerlIO_get_layers(pTHX_ PerlIO *f)
718 {
719     dVAR;
720     AV * const av = newAV();
721
722     if (PerlIOValid(f)) {
723         PerlIOl *l = PerlIOBase(f);
724
725         while (l) {
726             SV * const name = l->tab && l->tab->name ?
727             newSVpv(l->tab->name, 0) : &PL_sv_undef;
728             SV * const arg = l->tab && l->tab->Getarg ?
729             (*l->tab->Getarg)(aTHX_ &l, 0, 0) : &PL_sv_undef;
730             av_push(av, name);
731             av_push(av, arg);
732             av_push(av, newSViv((IV)l->flags));
733             l = l->next;
734         }
735     }
736
737     return av;
738 }
739
740 /*--------------------------------------------------------------------------------------*/
741 /*
742  * XS Interface for perl code
743  */
744
745 PerlIO_funcs *
746 PerlIO_find_layer(pTHX_ const char *name, STRLEN len, int load)
747 {
748     dVAR;
749     IV i;
750     if ((SSize_t) len <= 0)
751         len = strlen(name);
752     for (i = 0; i < PL_known_layers->cur; i++) {
753         PerlIO_funcs * const f = PL_known_layers->array[i].funcs;
754         if (memEQ(f->name, name, len) && f->name[len] == 0) {
755             PerlIO_debug("%.*s => %p\n", (int) len, name, (void*)f);
756             return f;
757         }
758     }
759     if (load && PL_subname && PL_def_layerlist
760         && PL_def_layerlist->cur >= 2) {
761         if (PL_in_load_module) {
762             Perl_croak(aTHX_ "Recursive call to Perl_load_module in PerlIO_find_layer");
763             return NULL;
764         } else {
765             SV * const pkgsv = newSVpvs("PerlIO");
766             SV * const layer = newSVpvn(name, len);
767             CV * const cv    = get_cv("PerlIO::Layer::NoWarnings", FALSE);
768             ENTER;
769             SAVEINT(PL_in_load_module);
770             if (cv) {
771                 SAVEGENERICSV(PL_warnhook);
772                 (void)SvREFCNT_inc(cv);
773                 PL_warnhook = (SV *) cv;
774             }
775             PL_in_load_module++;
776             /*
777              * The two SVs are magically freed by load_module
778              */
779             Perl_load_module(aTHX_ 0, pkgsv, NULL, layer, NULL);
780             PL_in_load_module--;
781             LEAVE;
782             return PerlIO_find_layer(aTHX_ name, len, 0);
783         }
784     }
785     PerlIO_debug("Cannot find %.*s\n", (int) len, name);
786     return NULL;
787 }
788
789 #ifdef USE_ATTRIBUTES_FOR_PERLIO
790
791 static int
792 perlio_mg_set(pTHX_ SV *sv, MAGIC *mg)
793 {
794     if (SvROK(sv)) {
795         IO * const io = GvIOn((GV *) SvRV(sv));
796         PerlIO * const ifp = IoIFP(io);
797         PerlIO * const ofp = IoOFP(io);
798         Perl_warn(aTHX_ "set %" SVf " %p %p %p", sv, io, ifp, ofp);
799     }
800     return 0;
801 }
802
803 static int
804 perlio_mg_get(pTHX_ SV *sv, MAGIC *mg)
805 {
806     if (SvROK(sv)) {
807         IO * const io = GvIOn((GV *) SvRV(sv));
808         PerlIO * const ifp = IoIFP(io);
809         PerlIO * const ofp = IoOFP(io);
810         Perl_warn(aTHX_ "get %" SVf " %p %p %p", sv, io, ifp, ofp);
811     }
812     return 0;
813 }
814
815 static int
816 perlio_mg_clear(pTHX_ SV *sv, MAGIC *mg)
817 {
818     Perl_warn(aTHX_ "clear %" SVf, sv);
819     return 0;
820 }
821
822 static int
823 perlio_mg_free(pTHX_ SV *sv, MAGIC *mg)
824 {
825     Perl_warn(aTHX_ "free %" SVf, sv);
826     return 0;
827 }
828
829 MGVTBL perlio_vtab = {
830     perlio_mg_get,
831     perlio_mg_set,
832     NULL,                       /* len */
833     perlio_mg_clear,
834     perlio_mg_free
835 };
836
837 XS(XS_io_MODIFY_SCALAR_ATTRIBUTES)
838 {
839     dXSARGS;
840     SV * const sv = SvRV(ST(1));
841     AV * const av = newAV();
842     MAGIC *mg;
843     int count = 0;
844     int i;
845     sv_magic(sv, (SV *) av, PERL_MAGIC_ext, NULL, 0);
846     SvRMAGICAL_off(sv);
847     mg = mg_find(sv, PERL_MAGIC_ext);
848     mg->mg_virtual = &perlio_vtab;
849     mg_magical(sv);
850     Perl_warn(aTHX_ "attrib %" SVf, sv);
851     for (i = 2; i < items; i++) {
852         STRLEN len;
853         const char * const name = SvPV_const(ST(i), len);
854         SV * const layer = PerlIO_find_layer(aTHX_ name, len, 1);
855         if (layer) {
856             av_push(av, SvREFCNT_inc(layer));
857         }
858         else {
859             ST(count) = ST(i);
860             count++;
861         }
862     }
863     SvREFCNT_dec(av);
864     XSRETURN(count);
865 }
866
867 #endif                          /* USE_ATTIBUTES_FOR_PERLIO */
868
869 SV *
870 PerlIO_tab_sv(pTHX_ PerlIO_funcs *tab)
871 {
872     HV * const stash = gv_stashpvs("PerlIO::Layer", TRUE);
873     SV * const sv = sv_bless(newRV_noinc(newSViv(PTR2IV(tab))), stash);
874     return sv;
875 }
876
877 XS(XS_PerlIO__Layer__NoWarnings)
878 {
879     /* This is used as a %SIG{__WARN__} handler to supress warnings
880        during loading of layers.
881      */
882     dVAR;
883     dXSARGS;
884     if (items)
885         PerlIO_debug("warning:%s\n",SvPV_nolen_const(ST(0)));
886     XSRETURN(0);
887 }
888
889 XS(XS_PerlIO__Layer__find)
890 {
891     dVAR;
892     dXSARGS;
893     if (items < 2)
894         Perl_croak(aTHX_ "Usage class->find(name[,load])");
895     else {
896         STRLEN len;
897         const char * const name = SvPV_const(ST(1), len);
898         const bool load = (items > 2) ? SvTRUE(ST(2)) : 0;
899         PerlIO_funcs * const layer = PerlIO_find_layer(aTHX_ name, len, load);
900         ST(0) =
901             (layer) ? sv_2mortal(PerlIO_tab_sv(aTHX_ layer)) :
902             &PL_sv_undef;
903         XSRETURN(1);
904     }
905 }
906
907 void
908 PerlIO_define_layer(pTHX_ PerlIO_funcs *tab)
909 {
910     dVAR;
911     if (!PL_known_layers)
912         PL_known_layers = PerlIO_list_alloc(aTHX);
913     PerlIO_list_push(aTHX_ PL_known_layers, tab, NULL);
914     PerlIO_debug("define %s %p\n", tab->name, (void*)tab);
915 }
916
917 int
918 PerlIO_parse_layers(pTHX_ PerlIO_list_t *av, const char *names)
919 {
920     dVAR;
921     if (names) {
922         const char *s = names;
923         while (*s) {
924             while (isSPACE(*s) || *s == ':')
925                 s++;
926             if (*s) {
927                 STRLEN llen = 0;
928                 const char *e = s;
929                 const char *as = NULL;
930                 STRLEN alen = 0;
931                 if (!isIDFIRST(*s)) {
932                     /*
933                      * Message is consistent with how attribute lists are
934                      * passed. Even though this means "foo : : bar" is
935                      * seen as an invalid separator character.
936                      */
937                     const char q = ((*s == '\'') ? '"' : '\'');
938                     if (ckWARN(WARN_LAYER))
939                         Perl_warner(aTHX_ packWARN(WARN_LAYER),
940                               "Invalid separator character %c%c%c in PerlIO layer specification %s",
941                               q, *s, q, s);
942                     SETERRNO(EINVAL, LIB_INVARG);
943                     return -1;
944                 }
945                 do {
946                     e++;
947                 } while (isALNUM(*e));
948                 llen = e - s;
949                 if (*e == '(') {
950                     int nesting = 1;
951                     as = ++e;
952                     while (nesting) {
953                         switch (*e++) {
954                         case ')':
955                             if (--nesting == 0)
956                                 alen = (e - 1) - as;
957                             break;
958                         case '(':
959                             ++nesting;
960                             break;
961                         case '\\':
962                             /*
963                              * It's a nul terminated string, not allowed
964                              * to \ the terminating null. Anything other
965                              * character is passed over.
966                              */
967                             if (*e++) {
968                                 break;
969                             }
970                             /*
971                              * Drop through
972                              */
973                         case '\0':
974                             e--;
975                             if (ckWARN(WARN_LAYER))
976                                 Perl_warner(aTHX_ packWARN(WARN_LAYER),
977                                       "Argument list not closed for PerlIO layer \"%.*s\"",
978                                       (int) (e - s), s);
979                             return -1;
980                         default:
981                             /*
982                              * boring.
983                              */
984                             break;
985                         }
986                     }
987                 }
988                 if (e > s) {
989                     PerlIO_funcs * const layer =
990                         PerlIO_find_layer(aTHX_ s, llen, 1);
991                     if (layer) {
992                         PerlIO_list_push(aTHX_ av, layer,
993                                          (as) ? newSVpvn(as,
994                                                          alen) :
995                                          &PL_sv_undef);
996                     }
997                     else {
998                         if (ckWARN(WARN_LAYER))
999                             Perl_warner(aTHX_ packWARN(WARN_LAYER), "Unknown PerlIO layer \"%.*s\"",
1000                                   (int) llen, s);
1001                         return -1;
1002                     }
1003                 }
1004                 s = e;
1005             }
1006         }
1007     }
1008     return 0;
1009 }
1010
1011 void
1012 PerlIO_default_buffer(pTHX_ PerlIO_list_t *av)
1013 {
1014     dVAR;
1015     PERLIO_FUNCS_DECL(*tab) = &PerlIO_perlio;
1016 #ifdef PERLIO_USING_CRLF
1017     tab = &PerlIO_crlf;
1018 #else
1019     if (PerlIO_stdio.Set_ptrcnt)
1020         tab = &PerlIO_stdio;
1021 #endif
1022     PerlIO_debug("Pushing %s\n", tab->name);
1023     PerlIO_list_push(aTHX_ av, PerlIO_find_layer(aTHX_ tab->name, 0, 0),
1024                      &PL_sv_undef);
1025 }
1026
1027 SV *
1028 PerlIO_arg_fetch(PerlIO_list_t *av, IV n)
1029 {
1030     return av->array[n].arg;
1031 }
1032
1033 PerlIO_funcs *
1034 PerlIO_layer_fetch(pTHX_ PerlIO_list_t *av, IV n, PerlIO_funcs *def)
1035 {
1036     if (n >= 0 && n < av->cur) {
1037         PerlIO_debug("Layer %" IVdf " is %s\n", n,
1038                      av->array[n].funcs->name);
1039         return av->array[n].funcs;
1040     }
1041     if (!def)
1042         Perl_croak(aTHX_ "panic: PerlIO layer array corrupt");
1043     return def;
1044 }
1045
1046 IV
1047 PerlIOPop_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
1048 {
1049     PERL_UNUSED_ARG(mode);
1050     PERL_UNUSED_ARG(arg);
1051     PERL_UNUSED_ARG(tab);
1052     if (PerlIOValid(f)) {
1053         PerlIO_flush(f);
1054         PerlIO_pop(aTHX_ f);
1055         return 0;
1056     }
1057     return -1;
1058 }
1059
1060 PERLIO_FUNCS_DECL(PerlIO_remove) = {
1061     sizeof(PerlIO_funcs),
1062     "pop",
1063     0,
1064     PERLIO_K_DUMMY | PERLIO_K_UTF8,
1065     PerlIOPop_pushed,
1066     NULL,
1067     NULL,
1068     NULL,
1069     NULL,
1070     NULL,
1071     NULL,
1072     NULL,
1073     NULL,
1074     NULL,
1075     NULL,
1076     NULL,
1077     NULL,
1078     NULL,                       /* flush */
1079     NULL,                       /* fill */
1080     NULL,
1081     NULL,
1082     NULL,
1083     NULL,
1084     NULL,                       /* get_base */
1085     NULL,                       /* get_bufsiz */
1086     NULL,                       /* get_ptr */
1087     NULL,                       /* get_cnt */
1088     NULL,                       /* set_ptrcnt */
1089 };
1090
1091 PerlIO_list_t *
1092 PerlIO_default_layers(pTHX)
1093 {
1094     dVAR;
1095     if (!PL_def_layerlist) {
1096         const char * const s = (PL_tainting) ? NULL : PerlEnv_getenv("PERLIO");
1097         PERLIO_FUNCS_DECL(*osLayer) = &PerlIO_unix;
1098         PL_def_layerlist = PerlIO_list_alloc(aTHX);
1099         PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_unix));
1100 #if defined(WIN32)
1101         PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_win32));
1102 #if 0
1103         osLayer = &PerlIO_win32;
1104 #endif
1105 #endif
1106         PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_raw));
1107         PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_perlio));
1108         PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_stdio));
1109         PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_crlf));
1110 #ifdef HAS_MMAP
1111         PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_mmap));
1112 #endif
1113         PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_utf8));
1114         PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_remove));
1115         PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_byte));
1116         PerlIO_list_push(aTHX_ PL_def_layerlist,
1117                          PerlIO_find_layer(aTHX_ osLayer->name, 0, 0),
1118                          &PL_sv_undef);
1119         if (s) {
1120             PerlIO_parse_layers(aTHX_ PL_def_layerlist, s);
1121         }
1122         else {
1123             PerlIO_default_buffer(aTHX_ PL_def_layerlist);
1124         }
1125     }
1126     if (PL_def_layerlist->cur < 2) {
1127         PerlIO_default_buffer(aTHX_ PL_def_layerlist);
1128     }
1129     return PL_def_layerlist;
1130 }
1131
1132 void
1133 Perl_boot_core_PerlIO(pTHX)
1134 {
1135 #ifdef USE_ATTRIBUTES_FOR_PERLIO
1136     newXS("io::MODIFY_SCALAR_ATTRIBUTES", XS_io_MODIFY_SCALAR_ATTRIBUTES,
1137           __FILE__);
1138 #endif
1139     newXS("PerlIO::Layer::find", XS_PerlIO__Layer__find, __FILE__);
1140     newXS("PerlIO::Layer::NoWarnings", XS_PerlIO__Layer__NoWarnings, __FILE__);
1141 }
1142
1143 PerlIO_funcs *
1144 PerlIO_default_layer(pTHX_ I32 n)
1145 {
1146     dVAR;
1147     PerlIO_list_t * const av = PerlIO_default_layers(aTHX);
1148     if (n < 0)
1149         n += av->cur;
1150     return PerlIO_layer_fetch(aTHX_ av, n, PERLIO_FUNCS_CAST(&PerlIO_stdio));
1151 }
1152
1153 #define PerlIO_default_top() PerlIO_default_layer(aTHX_ -1)
1154 #define PerlIO_default_btm() PerlIO_default_layer(aTHX_ 0)
1155
1156 void
1157 PerlIO_stdstreams(pTHX)
1158 {
1159     dVAR;
1160     if (!PL_perlio) {
1161         PerlIO_allocate(aTHX);
1162         PerlIO_fdopen(0, "Ir" PERLIO_STDTEXT);
1163         PerlIO_fdopen(1, "Iw" PERLIO_STDTEXT);
1164         PerlIO_fdopen(2, "Iw" PERLIO_STDTEXT);
1165     }
1166 }
1167
1168 PerlIO *
1169 PerlIO_push(pTHX_ PerlIO *f, PERLIO_FUNCS_DECL(*tab), const char *mode, SV *arg)
1170 {
1171     if (tab->fsize != sizeof(PerlIO_funcs)) {
1172       mismatch:
1173         Perl_croak(aTHX_ "Layer does not match this perl");
1174     }
1175     if (tab->size) {
1176         PerlIOl *l;
1177         if (tab->size < sizeof(PerlIOl)) {
1178             goto mismatch;
1179         }
1180         /* Real layer with a data area */
1181         Newxc(l,tab->size,char,PerlIOl);
1182         if (l && f) {
1183             Zero(l, tab->size, char);
1184             l->next = *f;
1185             l->tab = (PerlIO_funcs*) tab;
1186             *f = l;
1187             PerlIO_debug("PerlIO_push f=%p %s %s %p\n", (void*)f, tab->name,
1188                         (mode) ? mode : "(Null)", (void*)arg);
1189             if (*l->tab->Pushed &&
1190                 (*l->tab->Pushed) (aTHX_ f, mode, arg, (PerlIO_funcs*) tab) != 0) {
1191                 PerlIO_pop(aTHX_ f);
1192                 return NULL;
1193             }
1194         }
1195     }
1196     else if (f) {
1197         /* Pseudo-layer where push does its own stack adjust */
1198         PerlIO_debug("PerlIO_push f=%p %s %s %p\n", (void*)f, tab->name,
1199                      (mode) ? mode : "(Null)", (void*)arg);
1200         if (tab->Pushed &&
1201             (*tab->Pushed) (aTHX_ f, mode, arg, (PerlIO_funcs*) tab) != 0) {
1202              return NULL;
1203         }
1204     }
1205     return f;
1206 }
1207
1208 IV
1209 PerlIOBase_binmode(pTHX_ PerlIO *f)
1210 {
1211    if (PerlIOValid(f)) {
1212         /* Is layer suitable for raw stream ? */
1213         if (PerlIOBase(f)->tab->kind & PERLIO_K_RAW) {
1214             /* Yes - turn off UTF-8-ness, to undo UTF-8 locale effects */
1215             PerlIOBase(f)->flags &= ~PERLIO_F_UTF8;
1216         }
1217         else {
1218             /* Not suitable - pop it */
1219             PerlIO_pop(aTHX_ f);
1220         }
1221         return 0;
1222    }
1223    return -1;
1224 }
1225
1226 IV
1227 PerlIORaw_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
1228 {
1229     PERL_UNUSED_ARG(mode);
1230     PERL_UNUSED_ARG(arg);
1231     PERL_UNUSED_ARG(tab);
1232
1233     if (PerlIOValid(f)) {
1234         PerlIO *t;
1235         const PerlIOl *l;
1236         PerlIO_flush(f);
1237         /*
1238          * Strip all layers that are not suitable for a raw stream
1239          */
1240         t = f;
1241         while (t && (l = *t)) {
1242             if (l->tab->Binmode) {
1243                 /* Has a handler - normal case */
1244                 if ((*l->tab->Binmode)(aTHX_ f) == 0) {
1245                     if (*t == l) {
1246                         /* Layer still there - move down a layer */
1247                         t = PerlIONext(t);
1248                     }
1249                 }
1250                 else {
1251                     return -1;
1252                 }
1253             }
1254             else {
1255                 /* No handler - pop it */
1256                 PerlIO_pop(aTHX_ t);
1257             }
1258         }
1259         if (PerlIOValid(f)) {
1260             PerlIO_debug(":raw f=%p :%s\n", (void*)f, PerlIOBase(f)->tab->name);
1261             return 0;
1262         }
1263     }
1264     return -1;
1265 }
1266
1267 int
1268 PerlIO_apply_layera(pTHX_ PerlIO *f, const char *mode,
1269                     PerlIO_list_t *layers, IV n, IV max)
1270 {
1271     int code = 0;
1272     while (n < max) {
1273         PerlIO_funcs * const tab = PerlIO_layer_fetch(aTHX_ layers, n, NULL);
1274         if (tab) {
1275             if (!PerlIO_push(aTHX_ f, tab, mode, PerlIOArg)) {
1276                 code = -1;
1277                 break;
1278             }
1279         }
1280         n++;
1281     }
1282     return code;
1283 }
1284
1285 int
1286 PerlIO_apply_layers(pTHX_ PerlIO *f, const char *mode, const char *names)
1287 {
1288     int code = 0;
1289     if (f && names) {
1290         PerlIO_list_t * const layers = PerlIO_list_alloc(aTHX);
1291         code = PerlIO_parse_layers(aTHX_ layers, names);
1292         if (code == 0) {
1293             code = PerlIO_apply_layera(aTHX_ f, mode, layers, 0, layers->cur);
1294         }
1295         PerlIO_list_free(aTHX_ layers);
1296     }
1297     return code;
1298 }
1299
1300
1301 /*--------------------------------------------------------------------------------------*/
1302 /*
1303  * Given the abstraction above the public API functions
1304  */
1305
1306 int
1307 PerlIO_binmode(pTHX_ PerlIO *f, int iotype, int mode, const char *names)
1308 {
1309     PerlIO_debug("PerlIO_binmode f=%p %s %c %x %s\n", (void*)f,
1310                  (PerlIOBase(f)) ? PerlIOBase(f)->tab->name : "(Null)",
1311                  iotype, mode, (names) ? names : "(Null)");
1312
1313     if (names) {
1314         /* Do not flush etc. if (e.g.) switching encodings.
1315            if a pushed layer knows it needs to flush lower layers
1316            (for example :unix which is never going to call them)
1317            it can do the flush when it is pushed.
1318          */
1319         return PerlIO_apply_layers(aTHX_ f, NULL, names) == 0 ? TRUE : FALSE;
1320     }
1321     else {
1322         /* Fake 5.6 legacy of using this call to turn ON O_TEXT */
1323 #ifdef PERLIO_USING_CRLF
1324         /* Legacy binmode only has meaning if O_TEXT has a value distinct from
1325            O_BINARY so we can look for it in mode.
1326          */
1327         if (!(mode & O_BINARY)) {
1328             /* Text mode */
1329             /* FIXME?: Looking down the layer stack seems wrong,
1330                but is a way of reaching past (say) an encoding layer
1331                to flip CRLF-ness of the layer(s) below
1332              */
1333             while (*f) {
1334                 /* Perhaps we should turn on bottom-most aware layer
1335                    e.g. Ilya's idea that UNIX TTY could serve
1336                  */
1337                 if (PerlIOBase(f)->tab->kind & PERLIO_K_CANCRLF) {
1338                     if (!(PerlIOBase(f)->flags & PERLIO_F_CRLF)) {
1339                         /* Not in text mode - flush any pending stuff and flip it */
1340                         PerlIO_flush(f);
1341                         PerlIOBase(f)->flags |= PERLIO_F_CRLF;
1342                     }
1343                     /* Only need to turn it on in one layer so we are done */
1344                     return TRUE;
1345                 }
1346                 f = PerlIONext(f);
1347             }
1348             /* Not finding a CRLF aware layer presumably means we are binary
1349                which is not what was requested - so we failed
1350                We _could_ push :crlf layer but so could caller
1351              */
1352             return FALSE;
1353         }
1354 #endif
1355         /* Legacy binmode is now _defined_ as being equivalent to pushing :raw
1356            So code that used to be here is now in PerlIORaw_pushed().
1357          */
1358         return PerlIO_push(aTHX_ f, PERLIO_FUNCS_CAST(&PerlIO_raw), NULL, NULL) ? TRUE : FALSE;
1359     }
1360 }
1361
1362 int
1363 PerlIO__close(pTHX_ PerlIO *f)
1364 {
1365     if (PerlIOValid(f)) {
1366         PerlIO_funcs * const tab = PerlIOBase(f)->tab;
1367         if (tab && tab->Close)
1368             return (*tab->Close)(aTHX_ f);
1369         else
1370             return PerlIOBase_close(aTHX_ f);
1371     }
1372     else {
1373         SETERRNO(EBADF, SS_IVCHAN);
1374         return -1;
1375     }
1376 }
1377
1378 int
1379 Perl_PerlIO_close(pTHX_ PerlIO *f)
1380 {
1381     const int code = PerlIO__close(aTHX_ f);
1382     while (PerlIOValid(f)) {
1383         PerlIO_pop(aTHX_ f);
1384     }
1385     return code;
1386 }
1387
1388 int
1389 Perl_PerlIO_fileno(pTHX_ PerlIO *f)
1390 {
1391     dVAR;
1392      Perl_PerlIO_or_Base(f, Fileno, fileno, -1, (aTHX_ f));
1393 }
1394
1395 static const char *
1396 PerlIO_context_layers(pTHX_ const char *mode)
1397 {
1398     dVAR;
1399     const char *type = NULL;
1400     /*
1401      * Need to supply default layer info from open.pm
1402      */
1403     if (PL_curcop) {
1404         SV * const layers = PL_curcop->cop_io;
1405         if (layers) {
1406             STRLEN len;
1407             type = SvPV_const(layers, len);
1408             if (type && mode[0] != 'r') {
1409                 /*
1410                  * Skip to write part
1411                  */
1412                 const char * const s = strchr(type, 0);
1413                 if (s && (STRLEN)(s - type) < len) {
1414                     type = s + 1;
1415                 }
1416             }
1417         }
1418     }
1419     return type;
1420 }
1421
1422 static PerlIO_funcs *
1423 PerlIO_layer_from_ref(pTHX_ SV *sv)
1424 {
1425     dVAR;
1426     /*
1427      * For any scalar type load the handler which is bundled with perl
1428      */
1429     if (SvTYPE(sv) < SVt_PVAV)
1430         return PerlIO_find_layer(aTHX_ STR_WITH_LEN("scalar"), 1);
1431
1432     /*
1433      * For other types allow if layer is known but don't try and load it
1434      */
1435     switch (SvTYPE(sv)) {
1436     case SVt_PVAV:
1437         return PerlIO_find_layer(aTHX_ STR_WITH_LEN("Array"), 0);
1438     case SVt_PVHV:
1439         return PerlIO_find_layer(aTHX_ STR_WITH_LEN("Hash"), 0);
1440     case SVt_PVCV:
1441         return PerlIO_find_layer(aTHX_ STR_WITH_LEN("Code"), 0);
1442     case SVt_PVGV:
1443         return PerlIO_find_layer(aTHX_ STR_WITH_LEN("Glob"), 0);
1444     }
1445     return NULL;
1446 }
1447
1448 PerlIO_list_t *
1449 PerlIO_resolve_layers(pTHX_ const char *layers,
1450                       const char *mode, int narg, SV **args)
1451 {
1452     dVAR;
1453     PerlIO_list_t *def = PerlIO_default_layers(aTHX);
1454     int incdef = 1;
1455     if (!PL_perlio)
1456         PerlIO_stdstreams(aTHX);
1457     if (narg) {
1458         SV * const arg = *args;
1459         /*
1460          * If it is a reference but not an object see if we have a handler
1461          * for it
1462          */
1463         if (SvROK(arg) && !sv_isobject(arg)) {
1464             PerlIO_funcs * const handler = PerlIO_layer_from_ref(aTHX_ SvRV(arg));
1465             if (handler) {
1466                 def = PerlIO_list_alloc(aTHX);
1467                 PerlIO_list_push(aTHX_ def, handler, &PL_sv_undef);
1468                 incdef = 0;
1469             }
1470             /*
1471              * Don't fail if handler cannot be found :via(...) etc. may do
1472              * something sensible else we will just stringfy and open
1473              * resulting string.
1474              */
1475         }
1476     }
1477     if (!layers || !*layers)
1478         layers = PerlIO_context_layers(aTHX_ mode);
1479     if (layers && *layers) {
1480         PerlIO_list_t *av;
1481         if (incdef) {
1482             IV i;
1483             av = PerlIO_list_alloc(aTHX);
1484             for (i = 0; i < def->cur; i++) {
1485                 PerlIO_list_push(aTHX_ av, def->array[i].funcs,
1486                                  def->array[i].arg);
1487             }
1488         }
1489         else {
1490             av = def;
1491         }
1492         if (PerlIO_parse_layers(aTHX_ av, layers) == 0) {
1493              return av;
1494         }
1495         else {
1496             PerlIO_list_free(aTHX_ av);
1497             return (PerlIO_list_t *) NULL;
1498         }
1499     }
1500     else {
1501         if (incdef)
1502             def->refcnt++;
1503         return def;
1504     }
1505 }
1506
1507 PerlIO *
1508 PerlIO_openn(pTHX_ const char *layers, const char *mode, int fd,
1509              int imode, int perm, PerlIO *f, int narg, SV **args)
1510 {
1511     dVAR;
1512     if (!f && narg == 1 && *args == &PL_sv_undef) {
1513         if ((f = PerlIO_tmpfile())) {
1514             if (!layers || !*layers)
1515                 layers = PerlIO_context_layers(aTHX_ mode);
1516             if (layers && *layers)
1517                 PerlIO_apply_layers(aTHX_ f, mode, layers);
1518         }
1519     }
1520     else {
1521         PerlIO_list_t *layera;
1522         IV n;
1523         PerlIO_funcs *tab = NULL;
1524         if (PerlIOValid(f)) {
1525             /*
1526              * This is "reopen" - it is not tested as perl does not use it
1527              * yet
1528              */
1529             PerlIOl *l = *f;
1530             layera = PerlIO_list_alloc(aTHX);
1531             while (l) {
1532                 SV * const arg = (l->tab->Getarg)
1533                         ? (*l->tab->Getarg) (aTHX_ &l, NULL, 0)
1534                         : &PL_sv_undef;
1535                 PerlIO_list_push(aTHX_ layera, l->tab, arg);
1536                 l = *PerlIONext(&l);
1537             }
1538         }
1539         else {
1540             layera = PerlIO_resolve_layers(aTHX_ layers, mode, narg, args);
1541             if (!layera) {
1542                 return NULL;
1543             }
1544         }
1545         /*
1546          * Start at "top" of layer stack
1547          */
1548         n = layera->cur - 1;
1549         while (n >= 0) {
1550             PerlIO_funcs * const t = PerlIO_layer_fetch(aTHX_ layera, n, NULL);
1551             if (t && t->Open) {
1552                 tab = t;
1553                 break;
1554             }
1555             n--;
1556         }
1557         if (tab) {
1558             /*
1559              * Found that layer 'n' can do opens - call it
1560              */
1561             if (narg > 1 && !(tab->kind & PERLIO_K_MULTIARG)) {
1562                 Perl_croak(aTHX_ "More than one argument to open(,':%s')",tab->name);
1563             }
1564             PerlIO_debug("openn(%s,'%s','%s',%d,%x,%o,%p,%d,%p)\n",
1565                          tab->name, layers ? layers : "(Null)", mode, fd,
1566                          imode, perm, (void*)f, narg, (void*)args);
1567             if (tab->Open)
1568                  f = (*tab->Open) (aTHX_ tab, layera, n, mode, fd, imode, perm,
1569                                    f, narg, args);
1570             else {
1571                  SETERRNO(EINVAL, LIB_INVARG);
1572                  f = NULL;
1573             }
1574             if (f) {
1575                 if (n + 1 < layera->cur) {
1576                     /*
1577                      * More layers above the one that we used to open -
1578                      * apply them now
1579                      */
1580                     if (PerlIO_apply_layera(aTHX_ f, mode, layera, n + 1, layera->cur) != 0) {
1581                         /* If pushing layers fails close the file */
1582                         PerlIO_close(f);
1583                         f = NULL;
1584                     }
1585                 }
1586             }
1587         }
1588         PerlIO_list_free(aTHX_ layera);
1589     }
1590     return f;
1591 }
1592
1593
1594 SSize_t
1595 Perl_PerlIO_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
1596 {
1597      Perl_PerlIO_or_Base(f, Read, read, -1, (aTHX_ f, vbuf, count));
1598 }
1599
1600 SSize_t
1601 Perl_PerlIO_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
1602 {
1603      Perl_PerlIO_or_Base(f, Unread, unread, -1, (aTHX_ f, vbuf, count));
1604 }
1605
1606 SSize_t
1607 Perl_PerlIO_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
1608 {
1609      Perl_PerlIO_or_fail(f, Write, -1, (aTHX_ f, vbuf, count));
1610 }
1611
1612 int
1613 Perl_PerlIO_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
1614 {
1615      Perl_PerlIO_or_fail(f, Seek, -1, (aTHX_ f, offset, whence));
1616 }
1617
1618 Off_t
1619 Perl_PerlIO_tell(pTHX_ PerlIO *f)
1620 {
1621      Perl_PerlIO_or_fail(f, Tell, -1, (aTHX_ f));
1622 }
1623
1624 int
1625 Perl_PerlIO_flush(pTHX_ PerlIO *f)
1626 {
1627     dVAR;
1628     if (f) {
1629         if (*f) {
1630             const PerlIO_funcs *tab = PerlIOBase(f)->tab;
1631
1632             if (tab && tab->Flush)
1633                 return (*tab->Flush) (aTHX_ f);
1634             else
1635                  return 0; /* If no Flush defined, silently succeed. */
1636         }
1637         else {
1638             PerlIO_debug("Cannot flush f=%p\n", (void*)f);
1639             SETERRNO(EBADF, SS_IVCHAN);
1640             return -1;
1641         }
1642     }
1643     else {
1644         /*
1645          * Is it good API design to do flush-all on NULL, a potentially
1646          * errorneous input? Maybe some magical value (PerlIO*
1647          * PERLIO_FLUSH_ALL = (PerlIO*)-1;)? Yes, stdio does similar
1648          * things on fflush(NULL), but should we be bound by their design
1649          * decisions? --jhi
1650          */
1651         PerlIO **table = &PL_perlio;
1652         int code = 0;
1653         while ((f = *table)) {
1654             int i;
1655             table = (PerlIO **) (f++);
1656             for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
1657                 if (*f && PerlIO_flush(f) != 0)
1658                     code = -1;
1659                 f++;
1660             }
1661         }
1662         return code;
1663     }
1664 }
1665
1666 void
1667 PerlIOBase_flush_linebuf(pTHX)
1668 {
1669     dVAR;
1670     PerlIO **table = &PL_perlio;
1671     PerlIO *f;
1672     while ((f = *table)) {
1673         int i;
1674         table = (PerlIO **) (f++);
1675         for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
1676             if (*f
1677                 && (PerlIOBase(f)->
1678                     flags & (PERLIO_F_LINEBUF | PERLIO_F_CANWRITE))
1679                 == (PERLIO_F_LINEBUF | PERLIO_F_CANWRITE))
1680                 PerlIO_flush(f);
1681             f++;
1682         }
1683     }
1684 }
1685
1686 int
1687 Perl_PerlIO_fill(pTHX_ PerlIO *f)
1688 {
1689      Perl_PerlIO_or_fail(f, Fill, -1, (aTHX_ f));
1690 }
1691
1692 int
1693 PerlIO_isutf8(PerlIO *f)
1694 {
1695      if (PerlIOValid(f))
1696           return (PerlIOBase(f)->flags & PERLIO_F_UTF8) != 0;
1697      else
1698           SETERRNO(EBADF, SS_IVCHAN);
1699
1700      return -1;
1701 }
1702
1703 int
1704 Perl_PerlIO_eof(pTHX_ PerlIO *f)
1705 {
1706      Perl_PerlIO_or_Base(f, Eof, eof, -1, (aTHX_ f));
1707 }
1708
1709 int
1710 Perl_PerlIO_error(pTHX_ PerlIO *f)
1711 {
1712      Perl_PerlIO_or_Base(f, Error, error, -1, (aTHX_ f));
1713 }
1714
1715 void
1716 Perl_PerlIO_clearerr(pTHX_ PerlIO *f)
1717 {
1718      Perl_PerlIO_or_Base_void(f, Clearerr, clearerr, (aTHX_ f));
1719 }
1720
1721 void
1722 Perl_PerlIO_setlinebuf(pTHX_ PerlIO *f)
1723 {
1724      Perl_PerlIO_or_Base_void(f, Setlinebuf, setlinebuf, (aTHX_ f));
1725 }
1726
1727 int
1728 PerlIO_has_base(PerlIO *f)
1729 {
1730      if (PerlIOValid(f)) {
1731           const PerlIO_funcs * const tab = PerlIOBase(f)->tab;
1732
1733           if (tab)
1734                return (tab->Get_base != NULL);
1735           SETERRNO(EINVAL, LIB_INVARG);
1736      }
1737      else
1738           SETERRNO(EBADF, SS_IVCHAN);
1739
1740      return 0;
1741 }
1742
1743 int
1744 PerlIO_fast_gets(PerlIO *f)
1745 {
1746     if (PerlIOValid(f) && (PerlIOBase(f)->flags & PERLIO_F_FASTGETS)) {
1747          const PerlIO_funcs * const tab = PerlIOBase(f)->tab;
1748
1749          if (tab)
1750               return (tab->Set_ptrcnt != NULL);
1751          SETERRNO(EINVAL, LIB_INVARG);
1752     }
1753     else
1754          SETERRNO(EBADF, SS_IVCHAN);
1755
1756     return 0;
1757 }
1758
1759 int
1760 PerlIO_has_cntptr(PerlIO *f)
1761 {
1762     if (PerlIOValid(f)) {
1763         const PerlIO_funcs * const tab = PerlIOBase(f)->tab;
1764
1765         if (tab)
1766              return (tab->Get_ptr != NULL && tab->Get_cnt != NULL);
1767           SETERRNO(EINVAL, LIB_INVARG);
1768     }
1769     else
1770          SETERRNO(EBADF, SS_IVCHAN);
1771
1772     return 0;
1773 }
1774
1775 int
1776 PerlIO_canset_cnt(PerlIO *f)
1777 {
1778     if (PerlIOValid(f)) {
1779           const PerlIO_funcs * const tab = PerlIOBase(f)->tab;
1780
1781           if (tab)
1782                return (tab->Set_ptrcnt != NULL);
1783           SETERRNO(EINVAL, LIB_INVARG);
1784     }
1785     else
1786          SETERRNO(EBADF, SS_IVCHAN);
1787
1788     return 0;
1789 }
1790
1791 STDCHAR *
1792 Perl_PerlIO_get_base(pTHX_ PerlIO *f)
1793 {
1794      Perl_PerlIO_or_fail(f, Get_base, NULL, (aTHX_ f));
1795 }
1796
1797 int
1798 Perl_PerlIO_get_bufsiz(pTHX_ PerlIO *f)
1799 {
1800      Perl_PerlIO_or_fail(f, Get_bufsiz, -1, (aTHX_ f));
1801 }
1802
1803 STDCHAR *
1804 Perl_PerlIO_get_ptr(pTHX_ PerlIO *f)
1805 {
1806      Perl_PerlIO_or_fail(f, Get_ptr, NULL, (aTHX_ f));
1807 }
1808
1809 int
1810 Perl_PerlIO_get_cnt(pTHX_ PerlIO *f)
1811 {
1812      Perl_PerlIO_or_fail(f, Get_cnt, -1, (aTHX_ f));
1813 }
1814
1815 void
1816 Perl_PerlIO_set_cnt(pTHX_ PerlIO *f, int cnt)
1817 {
1818      Perl_PerlIO_or_fail_void(f, Set_ptrcnt, (aTHX_ f, NULL, cnt));
1819 }
1820
1821 void
1822 Perl_PerlIO_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, int cnt)
1823 {
1824      Perl_PerlIO_or_fail_void(f, Set_ptrcnt, (aTHX_ f, ptr, cnt));
1825 }
1826
1827
1828 /*--------------------------------------------------------------------------------------*/
1829 /*
1830  * utf8 and raw dummy layers
1831  */
1832
1833 IV
1834 PerlIOUtf8_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
1835 {
1836     PERL_UNUSED_ARG(mode);
1837     PERL_UNUSED_ARG(arg);
1838     if (PerlIOValid(f)) {
1839         if (tab->kind & PERLIO_K_UTF8)
1840             PerlIOBase(f)->flags |= PERLIO_F_UTF8;
1841         else
1842             PerlIOBase(f)->flags &= ~PERLIO_F_UTF8;
1843         return 0;
1844     }
1845     return -1;
1846 }
1847
1848 PERLIO_FUNCS_DECL(PerlIO_utf8) = {
1849     sizeof(PerlIO_funcs),
1850     "utf8",
1851     0,
1852     PERLIO_K_DUMMY | PERLIO_K_UTF8,
1853     PerlIOUtf8_pushed,
1854     NULL,
1855     NULL,
1856     NULL,
1857     NULL,
1858     NULL,
1859     NULL,
1860     NULL,
1861     NULL,
1862     NULL,
1863     NULL,
1864     NULL,
1865     NULL,
1866     NULL,                       /* flush */
1867     NULL,                       /* fill */
1868     NULL,
1869     NULL,
1870     NULL,
1871     NULL,
1872     NULL,                       /* get_base */
1873     NULL,                       /* get_bufsiz */
1874     NULL,                       /* get_ptr */
1875     NULL,                       /* get_cnt */
1876     NULL,                       /* set_ptrcnt */
1877 };
1878
1879 PERLIO_FUNCS_DECL(PerlIO_byte) = {
1880     sizeof(PerlIO_funcs),
1881     "bytes",
1882     0,
1883     PERLIO_K_DUMMY,
1884     PerlIOUtf8_pushed,
1885     NULL,
1886     NULL,
1887     NULL,
1888     NULL,
1889     NULL,
1890     NULL,
1891     NULL,
1892     NULL,
1893     NULL,
1894     NULL,
1895     NULL,
1896     NULL,
1897     NULL,                       /* flush */
1898     NULL,                       /* fill */
1899     NULL,
1900     NULL,
1901     NULL,
1902     NULL,
1903     NULL,                       /* get_base */
1904     NULL,                       /* get_bufsiz */
1905     NULL,                       /* get_ptr */
1906     NULL,                       /* get_cnt */
1907     NULL,                       /* set_ptrcnt */
1908 };
1909
1910 PerlIO *
1911 PerlIORaw_open(pTHX_ PerlIO_funcs *self, PerlIO_list_t *layers,
1912                IV n, const char *mode, int fd, int imode, int perm,
1913                PerlIO *old, int narg, SV **args)
1914 {
1915     PerlIO_funcs * const tab = PerlIO_default_btm();
1916     PERL_UNUSED_ARG(self);
1917     if (tab && tab->Open)
1918          return (*tab->Open) (aTHX_ tab, layers, n - 1, mode, fd, imode, perm,
1919                               old, narg, args);
1920     SETERRNO(EINVAL, LIB_INVARG);
1921     return NULL;
1922 }
1923
1924 PERLIO_FUNCS_DECL(PerlIO_raw) = {
1925     sizeof(PerlIO_funcs),
1926     "raw",
1927     0,
1928     PERLIO_K_DUMMY,
1929     PerlIORaw_pushed,
1930     PerlIOBase_popped,
1931     PerlIORaw_open,
1932     NULL,
1933     NULL,
1934     NULL,
1935     NULL,
1936     NULL,
1937     NULL,
1938     NULL,
1939     NULL,
1940     NULL,
1941     NULL,
1942     NULL,                       /* flush */
1943     NULL,                       /* fill */
1944     NULL,
1945     NULL,
1946     NULL,
1947     NULL,
1948     NULL,                       /* get_base */
1949     NULL,                       /* get_bufsiz */
1950     NULL,                       /* get_ptr */
1951     NULL,                       /* get_cnt */
1952     NULL,                       /* set_ptrcnt */
1953 };
1954 /*--------------------------------------------------------------------------------------*/
1955 /*--------------------------------------------------------------------------------------*/
1956 /*
1957  * "Methods" of the "base class"
1958  */
1959
1960 IV
1961 PerlIOBase_fileno(pTHX_ PerlIO *f)
1962 {
1963     return PerlIOValid(f) ? PerlIO_fileno(PerlIONext(f)) : -1;
1964 }
1965
1966 char *
1967 PerlIO_modestr(PerlIO * f, char *buf)
1968 {
1969     char *s = buf;
1970     if (PerlIOValid(f)) {
1971         const IV flags = PerlIOBase(f)->flags;
1972         if (flags & PERLIO_F_APPEND) {
1973             *s++ = 'a';
1974             if (flags & PERLIO_F_CANREAD) {
1975                 *s++ = '+';
1976             }
1977         }
1978         else if (flags & PERLIO_F_CANREAD) {
1979             *s++ = 'r';
1980             if (flags & PERLIO_F_CANWRITE)
1981                 *s++ = '+';
1982         }
1983         else if (flags & PERLIO_F_CANWRITE) {
1984             *s++ = 'w';
1985             if (flags & PERLIO_F_CANREAD) {
1986                 *s++ = '+';
1987             }
1988         }
1989 #ifdef PERLIO_USING_CRLF
1990         if (!(flags & PERLIO_F_CRLF))
1991             *s++ = 'b';
1992 #endif
1993     }
1994     *s = '\0';
1995     return buf;
1996 }
1997
1998
1999 IV
2000 PerlIOBase_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
2001 {
2002     PerlIOl * const l = PerlIOBase(f);
2003     PERL_UNUSED_ARG(arg);
2004
2005     l->flags &= ~(PERLIO_F_CANREAD | PERLIO_F_CANWRITE |
2006                   PERLIO_F_TRUNCATE | PERLIO_F_APPEND);
2007     if (tab->Set_ptrcnt != NULL)
2008         l->flags |= PERLIO_F_FASTGETS;
2009     if (mode) {
2010         if (*mode == IoTYPE_NUMERIC || *mode == IoTYPE_IMPLICIT)
2011             mode++;
2012         switch (*mode++) {
2013         case 'r':
2014             l->flags |= PERLIO_F_CANREAD;
2015             break;
2016         case 'a':
2017             l->flags |= PERLIO_F_APPEND | PERLIO_F_CANWRITE;
2018             break;
2019         case 'w':
2020             l->flags |= PERLIO_F_TRUNCATE | PERLIO_F_CANWRITE;
2021             break;
2022         default:
2023             SETERRNO(EINVAL, LIB_INVARG);
2024             return -1;
2025         }
2026         while (*mode) {
2027             switch (*mode++) {
2028             case '+':
2029                 l->flags |= PERLIO_F_CANREAD | PERLIO_F_CANWRITE;
2030                 break;
2031             case 'b':
2032                 l->flags &= ~PERLIO_F_CRLF;
2033                 break;
2034             case 't':
2035                 l->flags |= PERLIO_F_CRLF;
2036                 break;
2037             default:
2038                 SETERRNO(EINVAL, LIB_INVARG);
2039                 return -1;
2040             }
2041         }
2042     }
2043     else {
2044         if (l->next) {
2045             l->flags |= l->next->flags &
2046                 (PERLIO_F_CANREAD | PERLIO_F_CANWRITE | PERLIO_F_TRUNCATE |
2047                  PERLIO_F_APPEND);
2048         }
2049     }
2050 #if 0
2051     PerlIO_debug("PerlIOBase_pushed f=%p %s %s fl=%08" UVxf " (%s)\n",
2052                  f, PerlIOBase(f)->tab->name, (omode) ? omode : "(Null)",
2053                  l->flags, PerlIO_modestr(f, temp));
2054 #endif
2055     return 0;
2056 }
2057
2058 IV
2059 PerlIOBase_popped(pTHX_ PerlIO *f)
2060 {
2061     PERL_UNUSED_ARG(f);
2062     return 0;
2063 }
2064
2065 SSize_t
2066 PerlIOBase_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
2067 {
2068     /*
2069      * Save the position as current head considers it
2070      */
2071     const Off_t old = PerlIO_tell(f);
2072     PerlIO_push(aTHX_ f, PERLIO_FUNCS_CAST(&PerlIO_pending), "r", NULL);
2073     PerlIOSelf(f, PerlIOBuf)->posn = old;
2074     return PerlIOBuf_unread(aTHX_ f, vbuf, count);
2075 }
2076
2077 SSize_t
2078 PerlIOBase_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
2079 {
2080     STDCHAR *buf = (STDCHAR *) vbuf;
2081     if (f) {
2082         if (!(PerlIOBase(f)->flags & PERLIO_F_CANREAD)) {
2083             PerlIOBase(f)->flags |= PERLIO_F_ERROR;
2084             SETERRNO(EBADF, SS_IVCHAN);
2085             return 0;
2086         }
2087         while (count > 0) {
2088          get_cnt:
2089           {
2090             SSize_t avail = PerlIO_get_cnt(f);
2091             SSize_t take = 0;
2092             if (avail > 0)
2093                 take = ((SSize_t)count < avail) ? count : avail;
2094             if (take > 0) {
2095                 STDCHAR *ptr = PerlIO_get_ptr(f);
2096                 Copy(ptr, buf, take, STDCHAR);
2097                 PerlIO_set_ptrcnt(f, ptr + take, (avail -= take));
2098                 count -= take;
2099                 buf += take;
2100                 if (avail == 0)         /* set_ptrcnt could have reset avail */
2101                     goto get_cnt;
2102             }
2103             if (count > 0 && avail <= 0) {
2104                 if (PerlIO_fill(f) != 0)
2105                     break;
2106             }
2107           }
2108         }
2109         return (buf - (STDCHAR *) vbuf);
2110     }
2111     return 0;
2112 }
2113
2114 IV
2115 PerlIOBase_noop_ok(pTHX_ PerlIO *f)
2116 {
2117     PERL_UNUSED_ARG(f);
2118     return 0;
2119 }
2120
2121 IV
2122 PerlIOBase_noop_fail(pTHX_ PerlIO *f)
2123 {
2124     PERL_UNUSED_ARG(f);
2125     return -1;
2126 }
2127
2128 IV
2129 PerlIOBase_close(pTHX_ PerlIO *f)
2130 {
2131     IV code = -1;
2132     if (PerlIOValid(f)) {
2133         PerlIO *n = PerlIONext(f);
2134         code = PerlIO_flush(f);
2135         PerlIOBase(f)->flags &=
2136            ~(PERLIO_F_CANREAD | PERLIO_F_CANWRITE | PERLIO_F_OPEN);
2137         while (PerlIOValid(n)) {
2138             const PerlIO_funcs * const tab = PerlIOBase(n)->tab;
2139             if (tab && tab->Close) {
2140                 if ((*tab->Close)(aTHX_ n) != 0)
2141                     code = -1;
2142                 break;
2143             }
2144             else {
2145                 PerlIOBase(n)->flags &=
2146                     ~(PERLIO_F_CANREAD | PERLIO_F_CANWRITE | PERLIO_F_OPEN);
2147             }
2148             n = PerlIONext(n);
2149         }
2150     }
2151     else {
2152         SETERRNO(EBADF, SS_IVCHAN);
2153     }
2154     return code;
2155 }
2156
2157 IV
2158 PerlIOBase_eof(pTHX_ PerlIO *f)
2159 {
2160     if (PerlIOValid(f)) {
2161         return (PerlIOBase(f)->flags & PERLIO_F_EOF) != 0;
2162     }
2163     return 1;
2164 }
2165
2166 IV
2167 PerlIOBase_error(pTHX_ PerlIO *f)
2168 {
2169     if (PerlIOValid(f)) {
2170         return (PerlIOBase(f)->flags & PERLIO_F_ERROR) != 0;
2171     }
2172     return 1;
2173 }
2174
2175 void
2176 PerlIOBase_clearerr(pTHX_ PerlIO *f)
2177 {
2178     if (PerlIOValid(f)) {
2179         PerlIO * const n = PerlIONext(f);
2180         PerlIOBase(f)->flags &= ~(PERLIO_F_ERROR | PERLIO_F_EOF);
2181         if (PerlIOValid(n))
2182             PerlIO_clearerr(n);
2183     }
2184 }
2185
2186 void
2187 PerlIOBase_setlinebuf(pTHX_ PerlIO *f)
2188 {
2189     if (PerlIOValid(f)) {
2190         PerlIOBase(f)->flags |= PERLIO_F_LINEBUF;
2191     }
2192 }
2193
2194 SV *
2195 PerlIO_sv_dup(pTHX_ SV *arg, CLONE_PARAMS *param)
2196 {
2197     if (!arg)
2198         return NULL;
2199 #ifdef sv_dup
2200     if (param) {
2201         return sv_dup(arg, param);
2202     }
2203     else {
2204         return newSVsv(arg);
2205     }
2206 #else
2207     PERL_UNUSED_ARG(param);
2208     return newSVsv(arg);
2209 #endif
2210 }
2211
2212 PerlIO *
2213 PerlIOBase_dup(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags)
2214 {
2215     PerlIO * const nexto = PerlIONext(o);
2216     if (PerlIOValid(nexto)) {
2217         const PerlIO_funcs * const tab = PerlIOBase(nexto)->tab;
2218         if (tab && tab->Dup)
2219             f = (*tab->Dup)(aTHX_ f, nexto, param, flags);
2220         else
2221             f = PerlIOBase_dup(aTHX_ f, nexto, param, flags);
2222     }
2223     if (f) {
2224         PerlIO_funcs * const self = PerlIOBase(o)->tab;
2225         SV *arg;
2226         char buf[8];
2227         PerlIO_debug("PerlIOBase_dup %s f=%p o=%p param=%p\n",
2228                      self->name, (void*)f, (void*)o, (void*)param);
2229         if (self->Getarg)
2230             arg = (*self->Getarg)(aTHX_ o, param, flags);
2231         else {
2232             arg = NULL;
2233         }
2234         f = PerlIO_push(aTHX_ f, self, PerlIO_modestr(o,buf), arg);
2235         if (arg) {
2236             SvREFCNT_dec(arg);
2237         }
2238     }
2239     return f;
2240 }
2241
2242 #ifdef USE_THREADS
2243 perl_mutex PerlIO_mutex;
2244 #endif
2245
2246 /* PL_perlio_fd_refcnt[] is in intrpvar.h */
2247
2248 /* Must be called with PerlIO_mutex locked.  */
2249 static void
2250 S_more_refcounted_fds(pTHX_ const int new_fd) {
2251     const int old_max = PL_perlio_fd_refcnt_size;
2252     const int new_max = 16 + (new_fd & ~15);
2253     int *new_array;
2254
2255     PerlIO_debug("More fds - old=%d, need %d, new=%d\n",
2256                  old_max, new_fd, new_max);
2257
2258     if (new_fd < old_max) {
2259         return;
2260     }
2261
2262     assert (new_max > new_fd);
2263
2264     new_array
2265         = PerlMemShared_realloc(PL_perlio_fd_refcnt, new_max * sizeof(int));
2266
2267     if (!new_array) {
2268 #ifdef USE_THREADS
2269         MUTEX_UNLOCK(&PerlIO_mutex);
2270 #endif
2271         /* Can't use PerlIO to write as it allocates memory */
2272         PerlLIO_write(PerlIO_fileno(Perl_error_log),
2273                       PL_no_mem, strlen(PL_no_mem));
2274         my_exit(1);
2275     }
2276
2277     PL_perlio_fd_refcnt_size = new_max;
2278     PL_perlio_fd_refcnt = new_array;
2279
2280     PerlIO_debug("Zeroing %p, %d\n", new_array + old_max, new_max - old_max);
2281
2282     Zero(new_array + old_max, new_max - old_max, int);
2283 }
2284
2285
2286 void
2287 PerlIO_init(pTHX)
2288 {
2289  /* Place holder for stdstreams call ??? */
2290 #ifdef USE_THREADS
2291     MUTEX_INIT(&PerlIO_mutex);
2292 #else
2293     PERL_UNUSED_ARG(my_perl);
2294 #endif
2295 }
2296
2297 void
2298 PerlIOUnix_refcnt_inc(int fd)
2299 {
2300     dTHX;
2301     if (fd >= 0) {
2302         dVAR;
2303
2304 #ifdef USE_THREADS
2305         MUTEX_LOCK(&PerlIO_mutex);
2306 #endif
2307         if (fd >= PL_perlio_fd_refcnt_size)
2308             S_more_refcounted_fds(aTHX_ fd);
2309
2310         PL_perlio_fd_refcnt[fd]++;
2311         PerlIO_debug("fd %d refcnt=%d\n",fd,PL_perlio_fd_refcnt[fd]);
2312
2313 #ifdef USE_THREADS
2314         MUTEX_UNLOCK(&PerlIO_mutex);
2315 #endif
2316     }
2317 }
2318
2319 int
2320 PerlIOUnix_refcnt_dec(int fd)
2321 {
2322     dTHX;
2323     int cnt = 0;
2324     if (fd >= 0) {
2325         dVAR;
2326 #ifdef USE_THREADS
2327         MUTEX_LOCK(&PerlIO_mutex);
2328 #endif
2329         /* XXX should this be a panic?  */
2330         if (fd >= PL_perlio_fd_refcnt_size)
2331             S_more_refcounted_fds(aTHX_ fd);
2332
2333         /* XXX should this be a panic if it drops below 0?  */
2334         cnt = --PL_perlio_fd_refcnt[fd];
2335         PerlIO_debug("fd %d refcnt=%d\n",fd,cnt);
2336 #ifdef USE_THREADS
2337         MUTEX_UNLOCK(&PerlIO_mutex);
2338 #endif
2339     }
2340     return cnt;
2341 }
2342
2343 void
2344 PerlIO_cleanup(pTHX)
2345 {
2346     dVAR;
2347     int i;
2348 #ifdef USE_ITHREADS
2349     PerlIO_debug("Cleanup layers for %p\n",aTHX);
2350 #else
2351     PerlIO_debug("Cleanup layers\n");
2352 #endif
2353     /* Raise STDIN..STDERR refcount so we don't close them */
2354     for (i=0; i < 3; i++)
2355         PerlIOUnix_refcnt_inc(i);
2356     PerlIO_cleantable(aTHX_ &PL_perlio);
2357     /* Restore STDIN..STDERR refcount */
2358     for (i=0; i < 3; i++)
2359         PerlIOUnix_refcnt_dec(i);
2360
2361     if (PL_known_layers) {
2362         PerlIO_list_free(aTHX_ PL_known_layers);
2363         PL_known_layers = NULL;
2364     }
2365     if (PL_def_layerlist) {
2366         PerlIO_list_free(aTHX_ PL_def_layerlist);
2367         PL_def_layerlist = NULL;
2368     }
2369 }
2370
2371
2372
2373 /*--------------------------------------------------------------------------------------*/
2374 /*
2375  * Bottom-most level for UNIX-like case
2376  */
2377
2378 typedef struct {
2379     struct _PerlIO base;        /* The generic part */
2380     int fd;                     /* UNIX like file descriptor */
2381     int oflags;                 /* open/fcntl flags */
2382 } PerlIOUnix;
2383
2384 int
2385 PerlIOUnix_oflags(const char *mode)
2386 {
2387     int oflags = -1;
2388     if (*mode == IoTYPE_IMPLICIT || *mode == IoTYPE_NUMERIC)
2389         mode++;
2390     switch (*mode) {
2391     case 'r':
2392         oflags = O_RDONLY;
2393         if (*++mode == '+') {
2394             oflags = O_RDWR;
2395             mode++;
2396         }
2397         break;
2398
2399     case 'w':
2400         oflags = O_CREAT | O_TRUNC;
2401         if (*++mode == '+') {
2402             oflags |= O_RDWR;
2403             mode++;
2404         }
2405         else
2406             oflags |= O_WRONLY;
2407         break;
2408
2409     case 'a':
2410         oflags = O_CREAT | O_APPEND;
2411         if (*++mode == '+') {
2412             oflags |= O_RDWR;
2413             mode++;
2414         }
2415         else
2416             oflags |= O_WRONLY;
2417         break;
2418     }
2419     if (*mode == 'b') {
2420         oflags |= O_BINARY;
2421         oflags &= ~O_TEXT;
2422         mode++;
2423     }
2424     else if (*mode == 't') {
2425         oflags |= O_TEXT;
2426         oflags &= ~O_BINARY;
2427         mode++;
2428     }
2429     /*
2430      * Always open in binary mode
2431      */
2432     oflags |= O_BINARY;
2433     if (*mode || oflags == -1) {
2434         SETERRNO(EINVAL, LIB_INVARG);
2435         oflags = -1;
2436     }
2437     return oflags;
2438 }
2439
2440 IV
2441 PerlIOUnix_fileno(pTHX_ PerlIO *f)
2442 {
2443     return PerlIOSelf(f, PerlIOUnix)->fd;
2444 }
2445
2446 static void
2447 PerlIOUnix_setfd(pTHX_ PerlIO *f, int fd, int imode)
2448 {
2449     PerlIOUnix * const s = PerlIOSelf(f, PerlIOUnix);
2450 #if defined(WIN32)
2451     Stat_t st;
2452     if (PerlLIO_fstat(fd, &st) == 0) {
2453         if (!S_ISREG(st.st_mode)) {
2454             PerlIO_debug("%d is not regular file\n",fd);
2455             PerlIOBase(f)->flags |= PERLIO_F_NOTREG;
2456         }
2457         else {
2458             PerlIO_debug("%d _is_ a regular file\n",fd);
2459         }
2460     }
2461 #endif
2462     s->fd = fd;
2463     s->oflags = imode;
2464     PerlIOUnix_refcnt_inc(fd);
2465 }
2466
2467 IV
2468 PerlIOUnix_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
2469 {
2470     IV code = PerlIOBase_pushed(aTHX_ f, mode, arg, tab);
2471     if (*PerlIONext(f)) {
2472         /* We never call down so do any pending stuff now */
2473         PerlIO_flush(PerlIONext(f));
2474         /*
2475          * XXX could (or should) we retrieve the oflags from the open file
2476          * handle rather than believing the "mode" we are passed in? XXX
2477          * Should the value on NULL mode be 0 or -1?
2478          */
2479         PerlIOUnix_setfd(aTHX_ f, PerlIO_fileno(PerlIONext(f)),
2480                          mode ? PerlIOUnix_oflags(mode) : -1);
2481     }
2482     PerlIOBase(f)->flags |= PERLIO_F_OPEN;
2483
2484     return code;
2485 }
2486
2487 IV
2488 PerlIOUnix_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
2489 {
2490     const int fd = PerlIOSelf(f, PerlIOUnix)->fd;
2491     Off_t new_loc;
2492     if (PerlIOBase(f)->flags & PERLIO_F_NOTREG) {
2493 #ifdef  ESPIPE
2494         SETERRNO(ESPIPE, LIB_INVARG);
2495 #else
2496         SETERRNO(EINVAL, LIB_INVARG);
2497 #endif
2498         return -1;
2499     }
2500     new_loc = PerlLIO_lseek(fd, offset, whence);
2501     if (new_loc == (Off_t) - 1)
2502         return -1;
2503     PerlIOBase(f)->flags &= ~PERLIO_F_EOF;
2504     return  0;
2505 }
2506
2507 PerlIO *
2508 PerlIOUnix_open(pTHX_ PerlIO_funcs *self, PerlIO_list_t *layers,
2509                 IV n, const char *mode, int fd, int imode,
2510                 int perm, PerlIO *f, int narg, SV **args)
2511 {
2512     if (PerlIOValid(f)) {
2513         if (PerlIOBase(f)->flags & PERLIO_F_OPEN)
2514             (*PerlIOBase(f)->tab->Close)(aTHX_ f);
2515     }
2516     if (narg > 0) {
2517         if (*mode == IoTYPE_NUMERIC)
2518             mode++;
2519         else {
2520             imode = PerlIOUnix_oflags(mode);
2521             perm = 0666;
2522         }
2523         if (imode != -1) {
2524             const char *path = SvPV_nolen_const(*args);
2525             fd = PerlLIO_open3(path, imode, perm);
2526         }
2527     }
2528     if (fd >= 0) {
2529         if (*mode == IoTYPE_IMPLICIT)
2530             mode++;
2531         if (!f) {
2532             f = PerlIO_allocate(aTHX);
2533         }
2534         if (!PerlIOValid(f)) {
2535             if (!(f = PerlIO_push(aTHX_ f, self, mode, PerlIOArg))) {
2536                 return NULL;
2537             }
2538         }
2539         PerlIOUnix_setfd(aTHX_ f, fd, imode);
2540         PerlIOBase(f)->flags |= PERLIO_F_OPEN;
2541         if (*mode == IoTYPE_APPEND)
2542             PerlIOUnix_seek(aTHX_ f, 0, SEEK_END);
2543         return f;
2544     }
2545     else {
2546         if (f) {
2547             /*EMPTY*/;
2548             /*
2549              * FIXME: pop layers ???
2550              */
2551         }
2552         return NULL;
2553     }
2554 }
2555
2556 PerlIO *
2557 PerlIOUnix_dup(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags)
2558 {
2559     const PerlIOUnix * const os = PerlIOSelf(o, PerlIOUnix);
2560     int fd = os->fd;
2561     if (flags & PERLIO_DUP_FD) {
2562         fd = PerlLIO_dup(fd);
2563     }
2564     if (fd >= 0) {
2565         f = PerlIOBase_dup(aTHX_ f, o, param, flags);
2566         if (f) {
2567             /* If all went well overwrite fd in dup'ed lay with the dup()'ed fd */
2568             PerlIOUnix_setfd(aTHX_ f, fd, os->oflags);
2569             return f;
2570         }
2571     }
2572     return NULL;
2573 }
2574
2575
2576 SSize_t
2577 PerlIOUnix_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
2578 {
2579     dVAR;
2580     const int fd = PerlIOSelf(f, PerlIOUnix)->fd;
2581 #ifdef PERLIO_STD_SPECIAL
2582     if (fd == 0)
2583         return PERLIO_STD_IN(fd, vbuf, count);
2584 #endif
2585     if (!(PerlIOBase(f)->flags & PERLIO_F_CANREAD) ||
2586          PerlIOBase(f)->flags & (PERLIO_F_EOF|PERLIO_F_ERROR)) {
2587         return 0;
2588     }
2589     while (1) {
2590         const SSize_t len = PerlLIO_read(fd, vbuf, count);
2591         if (len >= 0 || errno != EINTR) {
2592             if (len < 0) {
2593                 if (errno != EAGAIN) {
2594                     PerlIOBase(f)->flags |= PERLIO_F_ERROR;
2595                 }
2596             }
2597             else if (len == 0 && count != 0) {
2598                 PerlIOBase(f)->flags |= PERLIO_F_EOF;
2599                 SETERRNO(0,0);
2600             }
2601             return len;
2602         }
2603         PERL_ASYNC_CHECK();
2604     }
2605     /*NOTREACHED*/
2606 }
2607
2608 SSize_t
2609 PerlIOUnix_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
2610 {
2611     dVAR;
2612     const int fd = PerlIOSelf(f, PerlIOUnix)->fd;
2613 #ifdef PERLIO_STD_SPECIAL
2614     if (fd == 1 || fd == 2)
2615         return PERLIO_STD_OUT(fd, vbuf, count);
2616 #endif
2617     while (1) {
2618         const SSize_t len = PerlLIO_write(fd, vbuf, count);
2619         if (len >= 0 || errno != EINTR) {
2620             if (len < 0) {
2621                 if (errno != EAGAIN) {
2622                     PerlIOBase(f)->flags |= PERLIO_F_ERROR;
2623                 }
2624             }
2625             return len;
2626         }
2627         PERL_ASYNC_CHECK();
2628     }
2629     /*NOTREACHED*/
2630 }
2631
2632 Off_t
2633 PerlIOUnix_tell(pTHX_ PerlIO *f)
2634 {
2635     return PerlLIO_lseek(PerlIOSelf(f, PerlIOUnix)->fd, 0, SEEK_CUR);
2636 }
2637
2638
2639 IV
2640 PerlIOUnix_close(pTHX_ PerlIO *f)
2641 {
2642     dVAR;
2643     const int fd = PerlIOSelf(f, PerlIOUnix)->fd;
2644     int code = 0;
2645     if (PerlIOBase(f)->flags & PERLIO_F_OPEN) {
2646         if (PerlIOUnix_refcnt_dec(fd) > 0) {
2647             PerlIOBase(f)->flags &= ~PERLIO_F_OPEN;
2648             return 0;
2649         }
2650     }
2651     else {
2652         SETERRNO(EBADF,SS_IVCHAN);
2653         return -1;
2654     }
2655     while (PerlLIO_close(fd) != 0) {
2656         if (errno != EINTR) {
2657             code = -1;
2658             break;
2659         }
2660         PERL_ASYNC_CHECK();
2661     }
2662     if (code == 0) {
2663         PerlIOBase(f)->flags &= ~PERLIO_F_OPEN;
2664     }
2665     return code;
2666 }
2667
2668 PERLIO_FUNCS_DECL(PerlIO_unix) = {
2669     sizeof(PerlIO_funcs),
2670     "unix",
2671     sizeof(PerlIOUnix),
2672     PERLIO_K_RAW,
2673     PerlIOUnix_pushed,
2674     PerlIOBase_popped,
2675     PerlIOUnix_open,
2676     PerlIOBase_binmode,         /* binmode */
2677     NULL,
2678     PerlIOUnix_fileno,
2679     PerlIOUnix_dup,
2680     PerlIOUnix_read,
2681     PerlIOBase_unread,
2682     PerlIOUnix_write,
2683     PerlIOUnix_seek,
2684     PerlIOUnix_tell,
2685     PerlIOUnix_close,
2686     PerlIOBase_noop_ok,         /* flush */
2687     PerlIOBase_noop_fail,       /* fill */
2688     PerlIOBase_eof,
2689     PerlIOBase_error,
2690     PerlIOBase_clearerr,
2691     PerlIOBase_setlinebuf,
2692     NULL,                       /* get_base */
2693     NULL,                       /* get_bufsiz */
2694     NULL,                       /* get_ptr */
2695     NULL,                       /* get_cnt */
2696     NULL,                       /* set_ptrcnt */
2697 };
2698
2699 /*--------------------------------------------------------------------------------------*/
2700 /*
2701  * stdio as a layer
2702  */
2703
2704 #if defined(VMS) && !defined(STDIO_BUFFER_WRITABLE)
2705 /* perl5.8 - This ensures the last minute VMS ungetc fix is not
2706    broken by the last second glibc 2.3 fix
2707  */
2708 #define STDIO_BUFFER_WRITABLE
2709 #endif
2710
2711
2712 typedef struct {
2713     struct _PerlIO base;
2714     FILE *stdio;                /* The stream */
2715 } PerlIOStdio;
2716
2717 IV
2718 PerlIOStdio_fileno(pTHX_ PerlIO *f)
2719 {
2720     if (PerlIOValid(f)) {
2721         FILE * const s = PerlIOSelf(f, PerlIOStdio)->stdio;
2722         if (s)
2723             return PerlSIO_fileno(s);
2724     }
2725     errno = EBADF;
2726     return -1;
2727 }
2728
2729 char *
2730 PerlIOStdio_mode(const char *mode, char *tmode)
2731 {
2732     char * const ret = tmode;
2733     if (mode) {
2734         while (*mode) {
2735             *tmode++ = *mode++;
2736         }
2737     }
2738 #if defined(PERLIO_USING_CRLF) || defined(__CYGWIN__)
2739     *tmode++ = 'b';
2740 #endif
2741     *tmode = '\0';
2742     return ret;
2743 }
2744
2745 IV
2746 PerlIOStdio_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
2747 {
2748     PerlIO *n;
2749     if (PerlIOValid(f) && PerlIOValid(n = PerlIONext(f))) {
2750         PerlIO_funcs * const toptab = PerlIOBase(n)->tab;
2751         if (toptab == tab) {
2752             /* Top is already stdio - pop self (duplicate) and use original */
2753             PerlIO_pop(aTHX_ f);
2754             return 0;
2755         } else {
2756             const int fd = PerlIO_fileno(n);
2757             char tmode[8];
2758             FILE *stdio;
2759             if (fd >= 0 && (stdio  = PerlSIO_fdopen(fd,
2760                             mode = PerlIOStdio_mode(mode, tmode)))) {
2761                 PerlIOSelf(f, PerlIOStdio)->stdio = stdio;
2762                 /* We never call down so do any pending stuff now */
2763                 PerlIO_flush(PerlIONext(f));
2764             }
2765             else {
2766                 return -1;
2767             }
2768         }
2769     }
2770     return PerlIOBase_pushed(aTHX_ f, mode, arg, tab);
2771 }
2772
2773
2774 PerlIO *
2775 PerlIO_importFILE(FILE *stdio, const char *mode)
2776 {
2777     dTHX;
2778     PerlIO *f = NULL;
2779     if (stdio) {
2780         PerlIOStdio *s;
2781         if (!mode || !*mode) {
2782             /* We need to probe to see how we can open the stream
2783                so start with read/write and then try write and read
2784                we dup() so that we can fclose without loosing the fd.
2785
2786                Note that the errno value set by a failing fdopen
2787                varies between stdio implementations.
2788              */
2789             const int fd = PerlLIO_dup(fileno(stdio));
2790             FILE *f2 = PerlSIO_fdopen(fd, (mode = "r+"));
2791             if (!f2) {
2792                 f2 = PerlSIO_fdopen(fd, (mode = "w"));
2793             }
2794             if (!f2) {
2795                 f2 = PerlSIO_fdopen(fd, (mode = "r"));
2796             }
2797             if (!f2) {
2798                 /* Don't seem to be able to open */
2799                 PerlLIO_close(fd);
2800                 return f;
2801             }
2802             fclose(f2);
2803         }
2804         if ((f = PerlIO_push(aTHX_(f = PerlIO_allocate(aTHX)), PERLIO_FUNCS_CAST(&PerlIO_stdio), mode, NULL))) {
2805             s = PerlIOSelf(f, PerlIOStdio);
2806             s->stdio = stdio;
2807         }
2808     }
2809     return f;
2810 }
2811
2812 PerlIO *
2813 PerlIOStdio_open(pTHX_ PerlIO_funcs *self, PerlIO_list_t *layers,
2814                  IV n, const char *mode, int fd, int imode,
2815                  int perm, PerlIO *f, int narg, SV **args)
2816 {
2817     char tmode[8];
2818     if (PerlIOValid(f)) {
2819         const char * const path = SvPV_nolen_const(*args);
2820         PerlIOStdio * const s = PerlIOSelf(f, PerlIOStdio);
2821         FILE *stdio;
2822         PerlIOUnix_refcnt_dec(fileno(s->stdio));
2823         stdio = PerlSIO_freopen(path, (mode = PerlIOStdio_mode(mode, tmode)),
2824                             s->stdio);
2825         if (!s->stdio)
2826             return NULL;
2827         s->stdio = stdio;
2828         PerlIOUnix_refcnt_inc(fileno(s->stdio));
2829         return f;
2830     }
2831     else {
2832         if (narg > 0) {
2833             const char * const path = SvPV_nolen_const(*args);
2834             if (*mode == IoTYPE_NUMERIC) {
2835                 mode++;
2836                 fd = PerlLIO_open3(path, imode, perm);
2837             }
2838             else {
2839                 FILE *stdio;
2840                 bool appended = FALSE;
2841 #ifdef __CYGWIN__
2842                 /* Cygwin wants its 'b' early. */
2843                 appended = TRUE;
2844                 mode = PerlIOStdio_mode(mode, tmode);
2845 #endif
2846                 stdio = PerlSIO_fopen(path, mode);
2847                 if (stdio) {
2848                     PerlIOStdio *s;
2849                     if (!f) {
2850                         f = PerlIO_allocate(aTHX);
2851                     }
2852                     if (!appended)
2853                         mode = PerlIOStdio_mode(mode, tmode);
2854                     f = PerlIO_push(aTHX_ f, self, mode, PerlIOArg);
2855                     if (f) {
2856                         s = PerlIOSelf(f, PerlIOStdio);
2857                         s->stdio = stdio;
2858                         PerlIOUnix_refcnt_inc(fileno(s->stdio));
2859                     }
2860                     return f;
2861                 }
2862                 else {
2863                     return NULL;
2864                 }
2865             }
2866         }
2867         if (fd >= 0) {
2868             FILE *stdio = NULL;
2869             int init = 0;
2870             if (*mode == IoTYPE_IMPLICIT) {
2871                 init = 1;
2872                 mode++;
2873             }
2874             if (init) {
2875                 switch (fd) {
2876                 case 0:
2877                     stdio = PerlSIO_stdin;
2878                     break;
2879                 case 1:
2880                     stdio = PerlSIO_stdout;
2881                     break;
2882                 case 2:
2883                     stdio = PerlSIO_stderr;
2884                     break;
2885                 }
2886             }
2887             else {
2888                 stdio = PerlSIO_fdopen(fd, mode =
2889                                        PerlIOStdio_mode(mode, tmode));
2890             }
2891             if (stdio) {
2892                 if (!f) {
2893                     f = PerlIO_allocate(aTHX);
2894                 }
2895                 if ((f = PerlIO_push(aTHX_ f, self, mode, PerlIOArg))) {
2896                     PerlIOStdio * const s = PerlIOSelf(f, PerlIOStdio);
2897                     s->stdio = stdio;
2898                     PerlIOUnix_refcnt_inc(fileno(s->stdio));
2899                 }
2900                 return f;
2901             }
2902         }
2903     }
2904     return NULL;
2905 }
2906
2907 PerlIO *
2908 PerlIOStdio_dup(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags)
2909 {
2910     /* This assumes no layers underneath - which is what
2911        happens, but is not how I remember it. NI-S 2001/10/16
2912      */
2913     if ((f = PerlIOBase_dup(aTHX_ f, o, param, flags))) {
2914         FILE *stdio = PerlIOSelf(o, PerlIOStdio)->stdio;
2915         const int fd = fileno(stdio);
2916         char mode[8];
2917         if (flags & PERLIO_DUP_FD) {
2918             const int dfd = PerlLIO_dup(fileno(stdio));
2919             if (dfd >= 0) {
2920                 stdio = PerlSIO_fdopen(dfd, PerlIO_modestr(o,mode));
2921                 goto set_this;
2922             }
2923             else {
2924                 /*EMPTY*/;
2925                 /* FIXME: To avoid messy error recovery if dup fails
2926                    re-use the existing stdio as though flag was not set
2927                  */
2928             }
2929         }
2930         stdio = PerlSIO_fdopen(fd, PerlIO_modestr(o,mode));
2931     set_this:
2932         PerlIOSelf(f, PerlIOStdio)->stdio = stdio;
2933         PerlIOUnix_refcnt_inc(fileno(stdio));
2934     }
2935     return f;
2936 }
2937
2938 static int
2939 PerlIOStdio_invalidate_fileno(pTHX_ FILE *f)
2940 {
2941     /* XXX this could use PerlIO_canset_fileno() and
2942      * PerlIO_set_fileno() support from Configure
2943      */
2944 #  if defined(__UCLIBC__)
2945     /* uClibc must come before glibc because it defines __GLIBC__ as well. */
2946     f->__filedes = -1;
2947     return 1;
2948 #  elif defined(__GLIBC__)
2949     /* There may be a better way for GLIBC:
2950         - libio.h defines a flag to not close() on cleanup
2951      */ 
2952     f->_fileno = -1;
2953     return 1;
2954 #  elif defined(__sun__)
2955 #    if defined(_LP64)
2956     /* On solaris, if _LP64 is defined, the FILE structure is this:
2957      *
2958      *  struct FILE {
2959      *      long __pad[16];
2960      *  };
2961      *
2962      * It turns out that the fd is stored in the top 32 bits of
2963      * file->__pad[4]. The lower 32 bits contain flags. file->pad[5] appears
2964      * to contain a pointer or offset into another structure. All the
2965      * remaining fields are zero.
2966      *
2967      * We set the top bits to -1 (0xFFFFFFFF).
2968      */
2969     f->__pad[4] |= 0xffffffff00000000L;
2970     assert(fileno(f) == 0xffffffff);
2971 #    else /* !defined(_LP64) */
2972     /* _file is just a unsigned char :-(
2973        Not clear why we dup() rather than using -1
2974        even if that would be treated as 0xFF - so will
2975        a dup fail ...
2976      */
2977     f->_file = PerlLIO_dup(fileno(f));
2978 #    endif /* defined(_LP64) */
2979     return 1;
2980 #  elif defined(__hpux)
2981     f->__fileH = 0xff;
2982     f->__fileL = 0xff;
2983     return 1;
2984    /* Next one ->_file seems to be a reasonable fallback, i.e. if
2985       your platform does not have special entry try this one.
2986       [For OSF only have confirmation for Tru64 (alpha)
2987       but assume other OSFs will be similar.]
2988     */
2989 #  elif defined(_AIX) || defined(__osf__) || defined(__irix__)
2990     f->_file = -1;
2991     return 1;
2992 #  elif defined(__FreeBSD__)
2993     /* There may be a better way on FreeBSD:
2994         - we could insert a dummy func in the _close function entry
2995         f->_close = (int (*)(void *)) dummy_close;
2996      */
2997     f->_file = -1;
2998     return 1;
2999 #  elif defined(__OpenBSD__)
3000     /* There may be a better way on OpenBSD:
3001         - we could insert a dummy func in the _close function entry
3002         f->_close = (int (*)(void *)) dummy_close;
3003      */
3004     f->_file = -1;
3005     return 1;
3006 #  elif defined(__EMX__)
3007     /* f->_flags &= ~_IOOPEN; */        /* Will leak stream->_buffer */
3008     f->_handle = -1;
3009     return 1;
3010 #  elif defined(__CYGWIN__)
3011     /* There may be a better way on CYGWIN:
3012         - we could insert a dummy func in the _close function entry
3013         f->_close = (int (*)(void *)) dummy_close;
3014      */
3015     f->_file = -1;
3016     return 1;
3017 #  elif defined(WIN32)
3018 #    if defined(__BORLANDC__)
3019     f->fd = PerlLIO_dup(fileno(f));
3020 #    elif defined(UNDER_CE)
3021     /* WIN_CE does not have access to FILE internals, it hardly has FILE
3022        structure at all
3023      */
3024 #    else
3025     f->_file = -1;
3026 #    endif
3027     return 1;
3028 #  else
3029 #if 0
3030     /* Sarathy's code did this - we fall back to a dup/dup2 hack
3031        (which isn't thread safe) instead
3032      */
3033 #    error "Don't know how to set FILE.fileno on your platform"
3034 #endif
3035     PERL_UNUSED_ARG(f);
3036     return 0;
3037 #  endif
3038 }
3039
3040 IV
3041 PerlIOStdio_close(pTHX_ PerlIO *f)
3042 {
3043     FILE * const stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3044     if (!stdio) {
3045         errno = EBADF;
3046         return -1;
3047     }
3048     else {
3049         const int fd = fileno(stdio);
3050         int socksfd = 0;
3051         int invalidate = 0;
3052         IV result = 0;
3053         int saveerr = 0;
3054         int dupfd = 0;
3055 #ifdef SOCKS5_VERSION_NAME
3056         /* Socks lib overrides close() but stdio isn't linked to
3057            that library (though we are) - so we must call close()
3058            on sockets on stdio's behalf.
3059          */
3060         int optval;
3061         Sock_size_t optlen = sizeof(int);
3062         if (getsockopt(fd, SOL_SOCKET, SO_TYPE, (void *) &optval, &optlen) == 0) {
3063             socksfd = 1;
3064             invalidate = 1;
3065         }
3066 #endif
3067         if (PerlIOUnix_refcnt_dec(fd) > 0) {
3068             /* File descriptor still in use */
3069             invalidate = 1;
3070             socksfd = 0;
3071         }
3072         if (invalidate) {
3073             /* For STD* handles don't close the stdio at all
3074                this is because we have shared the FILE * too
3075              */
3076             if (stdio == stdin) {
3077                 /* Some stdios are buggy fflush-ing inputs */
3078                 return 0;
3079             }
3080             else if (stdio == stdout || stdio == stderr) {
3081                 return PerlIO_flush(f);
3082             }
3083             /* Tricky - must fclose(stdio) to free memory but not close(fd)
3084                Use Sarathy's trick from maint-5.6 to invalidate the
3085                fileno slot of the FILE *
3086             */
3087             result = PerlIO_flush(f);
3088             saveerr = errno;
3089             if (!(invalidate = PerlIOStdio_invalidate_fileno(aTHX_ stdio))) {
3090                 dupfd = PerlLIO_dup(fd);
3091             }
3092         }
3093         result = PerlSIO_fclose(stdio);
3094         /* We treat error from stdio as success if we invalidated
3095            errno may NOT be expected EBADF
3096          */
3097         if (invalidate && result != 0) {
3098             errno = saveerr;
3099             result = 0;
3100         }
3101         if (socksfd) {
3102             /* in SOCKS case let close() determine return value */
3103             result = close(fd);
3104         }
3105         if (dupfd) {
3106             PerlLIO_dup2(dupfd,fd);
3107             PerlLIO_close(dupfd);
3108         }
3109         return result;
3110     }
3111 }
3112
3113 SSize_t
3114 PerlIOStdio_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
3115 {
3116     dVAR;
3117     FILE * const s = PerlIOSelf(f, PerlIOStdio)->stdio;
3118     SSize_t got = 0;
3119     for (;;) {
3120         if (count == 1) {
3121             STDCHAR *buf = (STDCHAR *) vbuf;
3122             /*
3123              * Perl is expecting PerlIO_getc() to fill the buffer Linux's
3124              * stdio does not do that for fread()
3125              */
3126             const int ch = PerlSIO_fgetc(s);
3127             if (ch != EOF) {
3128                 *buf = ch;
3129                 got = 1;
3130             }
3131         }
3132         else
3133             got = PerlSIO_fread(vbuf, 1, count, s);
3134         if (got == 0 && PerlSIO_ferror(s))
3135             got = -1;
3136         if (got >= 0 || errno != EINTR)
3137             break;
3138         PERL_ASYNC_CHECK();
3139         SETERRNO(0,0);  /* just in case */
3140     }
3141     return got;
3142 }
3143
3144 SSize_t
3145 PerlIOStdio_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
3146 {
3147     SSize_t unread = 0;
3148     FILE * const s = PerlIOSelf(f, PerlIOStdio)->stdio;
3149
3150 #ifdef STDIO_BUFFER_WRITABLE
3151     if (PerlIO_fast_gets(f) && PerlIO_has_base(f)) {
3152         STDCHAR *buf = ((STDCHAR *) vbuf) + count;
3153         STDCHAR *base = PerlIO_get_base(f);
3154         SSize_t cnt   = PerlIO_get_cnt(f);
3155         STDCHAR *ptr  = PerlIO_get_ptr(f);
3156         SSize_t avail = ptr - base;
3157         if (avail > 0) {
3158             if (avail > count) {
3159                 avail = count;
3160             }
3161             ptr -= avail;
3162             Move(buf-avail,ptr,avail,STDCHAR);
3163             count -= avail;
3164             unread += avail;
3165             PerlIO_set_ptrcnt(f,ptr,cnt+avail);
3166             if (PerlSIO_feof(s) && unread >= 0)
3167                 PerlSIO_clearerr(s);
3168         }
3169     }
3170     else
3171 #endif
3172     if (PerlIO_has_cntptr(f)) {
3173         /* We can get pointer to buffer but not its base
3174            Do ungetc() but check chars are ending up in the
3175            buffer
3176          */
3177         STDCHAR *eptr = (STDCHAR*)PerlSIO_get_ptr(s);
3178         STDCHAR *buf = ((STDCHAR *) vbuf) + count;
3179         while (count > 0) {
3180             const int ch = *--buf & 0xFF;
3181             if (ungetc(ch,s) != ch) {
3182                 /* ungetc did not work */
3183                 break;
3184             }
3185             if ((STDCHAR*)PerlSIO_get_ptr(s) != --eptr || ((*eptr & 0xFF) != ch)) {
3186                 /* Did not change pointer as expected */
3187                 fgetc(s);  /* get char back again */
3188                 break;
3189             }
3190             /* It worked ! */
3191             count--;
3192             unread++;
3193         }
3194     }
3195
3196     if (count > 0) {
3197         unread += PerlIOBase_unread(aTHX_ f, vbuf, count);
3198     }
3199     return unread;
3200 }
3201
3202 SSize_t
3203 PerlIOStdio_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
3204 {
3205     dVAR;
3206     SSize_t got;
3207     for (;;) {
3208         got = PerlSIO_fwrite(vbuf, 1, count,
3209                               PerlIOSelf(f, PerlIOStdio)->stdio);
3210         if (got >= 0 || errno != EINTR)
3211             break;
3212         PERL_ASYNC_CHECK();
3213         SETERRNO(0,0);  /* just in case */
3214     }
3215     return got;
3216 }
3217
3218 IV
3219 PerlIOStdio_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
3220 {
3221     FILE * const stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3222     return PerlSIO_fseek(stdio, offset, whence);
3223 }
3224
3225 Off_t
3226 PerlIOStdio_tell(pTHX_ PerlIO *f)
3227 {
3228     FILE * const stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3229     return PerlSIO_ftell(stdio);
3230 }
3231
3232 IV
3233 PerlIOStdio_flush(pTHX_ PerlIO *f)
3234 {
3235     FILE * const stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3236     if (PerlIOBase(f)->flags & PERLIO_F_CANWRITE) {
3237         return PerlSIO_fflush(stdio);
3238     }
3239     else {
3240         /*EMPTY*/;
3241 #if 0
3242         /*
3243          * FIXME: This discards ungetc() and pre-read stuff which is not
3244          * right if this is just a "sync" from a layer above Suspect right
3245          * design is to do _this_ but not have layer above flush this
3246          * layer read-to-read
3247          */
3248         /*
3249          * Not writeable - sync by attempting a seek
3250          */
3251         const int err = errno;
3252         if (PerlSIO_fseek(stdio, (Off_t) 0, SEEK_CUR) != 0)
3253             errno = err;
3254 #endif
3255     }
3256     return 0;
3257 }
3258
3259 IV
3260 PerlIOStdio_eof(pTHX_ PerlIO *f)
3261 {
3262     return PerlSIO_feof(PerlIOSelf(f, PerlIOStdio)->stdio);
3263 }
3264
3265 IV
3266 PerlIOStdio_error(pTHX_ PerlIO *f)
3267 {
3268     return PerlSIO_ferror(PerlIOSelf(f, PerlIOStdio)->stdio);
3269 }
3270
3271 void
3272 PerlIOStdio_clearerr(pTHX_ PerlIO *f)
3273 {
3274     PerlSIO_clearerr(PerlIOSelf(f, PerlIOStdio)->stdio);
3275 }
3276
3277 void
3278 PerlIOStdio_setlinebuf(pTHX_ PerlIO *f)
3279 {
3280 #ifdef HAS_SETLINEBUF
3281     PerlSIO_setlinebuf(PerlIOSelf(f, PerlIOStdio)->stdio);
3282 #else
3283     PerlSIO_setvbuf(PerlIOSelf(f, PerlIOStdio)->stdio, NULL, _IOLBF, 0);
3284 #endif
3285 }
3286
3287 #ifdef FILE_base
3288 STDCHAR *
3289 PerlIOStdio_get_base(pTHX_ PerlIO *f)
3290 {
3291     FILE * const stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3292     return (STDCHAR*)PerlSIO_get_base(stdio);
3293 }
3294
3295 Size_t
3296 PerlIOStdio_get_bufsiz(pTHX_ PerlIO *f)
3297 {
3298     FILE * const stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3299     return PerlSIO_get_bufsiz(stdio);
3300 }
3301 #endif
3302
3303 #ifdef USE_STDIO_PTR
3304 STDCHAR *
3305 PerlIOStdio_get_ptr(pTHX_ PerlIO *f)
3306 {
3307     FILE * const stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3308     return (STDCHAR*)PerlSIO_get_ptr(stdio);
3309 }
3310
3311 SSize_t
3312 PerlIOStdio_get_cnt(pTHX_ PerlIO *f)
3313 {
3314     FILE * const stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3315     return PerlSIO_get_cnt(stdio);
3316 }
3317
3318 void
3319 PerlIOStdio_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, SSize_t cnt)
3320 {
3321     FILE * const stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3322     if (ptr != NULL) {
3323 #ifdef STDIO_PTR_LVALUE
3324         PerlSIO_set_ptr(stdio, (void*)ptr); /* LHS STDCHAR* cast non-portable */
3325 #ifdef STDIO_PTR_LVAL_SETS_CNT
3326         if (PerlSIO_get_cnt(stdio) != (cnt)) {
3327             assert(PerlSIO_get_cnt(stdio) == (cnt));
3328         }
3329 #endif
3330 #if (!defined(STDIO_PTR_LVAL_NOCHANGE_CNT))
3331         /*
3332          * Setting ptr _does_ change cnt - we are done
3333          */
3334         return;
3335 #endif
3336 #else                           /* STDIO_PTR_LVALUE */
3337         PerlProc_abort();
3338 #endif                          /* STDIO_PTR_LVALUE */
3339     }
3340     /*
3341      * Now (or only) set cnt
3342      */
3343 #ifdef STDIO_CNT_LVALUE
3344     PerlSIO_set_cnt(stdio, cnt);
3345 #else                           /* STDIO_CNT_LVALUE */
3346 #if (defined(STDIO_PTR_LVALUE) && defined(STDIO_PTR_LVAL_SETS_CNT))
3347     PerlSIO_set_ptr(stdio,
3348                     PerlSIO_get_ptr(stdio) + (PerlSIO_get_cnt(stdio) -
3349                                               cnt));
3350 #else                           /* STDIO_PTR_LVAL_SETS_CNT */
3351     PerlProc_abort();
3352 #endif                          /* STDIO_PTR_LVAL_SETS_CNT */
3353 #endif                          /* STDIO_CNT_LVALUE */
3354 }
3355
3356
3357 #endif
3358
3359 IV
3360 PerlIOStdio_fill(pTHX_ PerlIO *f)
3361 {
3362     FILE * const stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3363     int c;
3364     /*
3365      * fflush()ing read-only streams can cause trouble on some stdio-s
3366      */
3367     if ((PerlIOBase(f)->flags & PERLIO_F_CANWRITE)) {
3368         if (PerlSIO_fflush(stdio) != 0)
3369             return EOF;
3370     }
3371     c = PerlSIO_fgetc(stdio);
3372     if (c == EOF)
3373         return EOF;
3374
3375 #if (defined(STDIO_PTR_LVALUE) && (defined(STDIO_CNT_LVALUE) || defined(STDIO_PTR_LVAL_SETS_CNT)))
3376
3377 #ifdef STDIO_BUFFER_WRITABLE
3378     if (PerlIO_fast_gets(f) && PerlIO_has_base(f)) {
3379         /* Fake ungetc() to the real buffer in case system's ungetc
3380            goes elsewhere
3381          */
3382         STDCHAR *base = (STDCHAR*)PerlSIO_get_base(stdio);
3383         SSize_t cnt   = PerlSIO_get_cnt(stdio);
3384         STDCHAR *ptr  = (STDCHAR*)PerlSIO_get_ptr(stdio);
3385         if (ptr == base+1) {
3386             *--ptr = (STDCHAR) c;
3387             PerlIOStdio_set_ptrcnt(aTHX_ f,ptr,cnt+1);
3388             if (PerlSIO_feof(stdio))
3389                 PerlSIO_clearerr(stdio);
3390             return 0;
3391         }
3392     }
3393     else
3394 #endif
3395     if (PerlIO_has_cntptr(f)) {
3396         STDCHAR ch = c;
3397         if (PerlIOStdio_unread(aTHX_ f,&ch,1) == 1) {
3398             return 0;
3399         }
3400     }
3401 #endif
3402
3403 #if defined(VMS)
3404     /* An ungetc()d char is handled separately from the regular
3405      * buffer, so we stuff it in the buffer ourselves.
3406      * Should never get called as should hit code above
3407      */
3408     *(--((*stdio)->_ptr)) = (unsigned char) c;
3409     (*stdio)->_cnt++;
3410 #else
3411     /* If buffer snoop scheme above fails fall back to
3412        using ungetc().
3413      */
3414     if (PerlSIO_ungetc(c, stdio) != c)
3415         return EOF;
3416 #endif
3417     return 0;
3418 }
3419
3420
3421
3422 PERLIO_FUNCS_DECL(PerlIO_stdio) = {
3423     sizeof(PerlIO_funcs),
3424     "stdio",
3425     sizeof(PerlIOStdio),
3426     PERLIO_K_BUFFERED|PERLIO_K_RAW,
3427     PerlIOStdio_pushed,
3428     PerlIOBase_popped,
3429     PerlIOStdio_open,
3430     PerlIOBase_binmode,         /* binmode */
3431     NULL,
3432     PerlIOStdio_fileno,
3433     PerlIOStdio_dup,
3434     PerlIOStdio_read,
3435     PerlIOStdio_unread,
3436     PerlIOStdio_write,
3437     PerlIOStdio_seek,
3438     PerlIOStdio_tell,
3439     PerlIOStdio_close,
3440     PerlIOStdio_flush,
3441     PerlIOStdio_fill,
3442     PerlIOStdio_eof,
3443     PerlIOStdio_error,
3444     PerlIOStdio_clearerr,
3445     PerlIOStdio_setlinebuf,
3446 #ifdef FILE_base
3447     PerlIOStdio_get_base,
3448     PerlIOStdio_get_bufsiz,
3449 #else
3450     NULL,
3451     NULL,
3452 #endif
3453 #ifdef USE_STDIO_PTR
3454     PerlIOStdio_get_ptr,
3455     PerlIOStdio_get_cnt,
3456 #   if defined(HAS_FAST_STDIO) && defined(USE_FAST_STDIO)
3457     PerlIOStdio_set_ptrcnt,
3458 #   else
3459     NULL,
3460 #   endif /* HAS_FAST_STDIO && USE_FAST_STDIO */
3461 #else
3462     NULL,
3463     NULL,
3464     NULL,
3465 #endif /* USE_STDIO_PTR */
3466 };
3467
3468 /* Note that calls to PerlIO_exportFILE() are reversed using
3469  * PerlIO_releaseFILE(), not importFILE. */
3470 FILE *
3471 PerlIO_exportFILE(PerlIO * f, const char *mode)
3472 {
3473     dTHX;
3474     FILE *stdio = NULL;
3475     if (PerlIOValid(f)) {
3476         char buf[8];
3477         PerlIO_flush(f);
3478         if (!mode || !*mode) {
3479             mode = PerlIO_modestr(f, buf);
3480         }
3481         stdio = PerlSIO_fdopen(PerlIO_fileno(f), mode);
3482         if (stdio) {
3483             PerlIOl *l = *f;
3484             PerlIO *f2;
3485             /* De-link any lower layers so new :stdio sticks */
3486             *f = NULL;
3487             if ((f2 = PerlIO_push(aTHX_ f, PERLIO_FUNCS_CAST(&PerlIO_stdio), buf, NULL))) {
3488                 PerlIOStdio *s = PerlIOSelf((f = f2), PerlIOStdio);
3489                 s->stdio = stdio;
3490                 /* Link previous lower layers under new one */
3491                 *PerlIONext(f) = l;
3492             }
3493             else {
3494                 /* restore layers list */
3495                 *f = l;
3496             }
3497         }
3498     }
3499     return stdio;
3500 }
3501
3502
3503 FILE *
3504 PerlIO_findFILE(PerlIO *f)
3505 {
3506     PerlIOl *l = *f;
3507     while (l) {
3508         if (l->tab == &PerlIO_stdio) {
3509             PerlIOStdio *s = PerlIOSelf(&l, PerlIOStdio);
3510             return s->stdio;
3511         }
3512         l = *PerlIONext(&l);
3513     }
3514     /* Uses fallback "mode" via PerlIO_modestr() in PerlIO_exportFILE */
3515     return PerlIO_exportFILE(f, NULL);
3516 }
3517
3518 /* Use this to reverse PerlIO_exportFILE calls. */
3519 void
3520 PerlIO_releaseFILE(PerlIO *p, FILE *f)
3521 {
3522     dVAR;
3523     PerlIOl *l;
3524     while ((l = *p)) {
3525         if (l->tab == &PerlIO_stdio) {
3526             PerlIOStdio *s = PerlIOSelf(&l, PerlIOStdio);
3527             if (s->stdio == f) {
3528                 dTHX;
3529                 PerlIO_pop(aTHX_ p);
3530                 return;
3531             }
3532         }
3533         p = PerlIONext(p);
3534     }
3535     return;
3536 }
3537
3538 /*--------------------------------------------------------------------------------------*/
3539 /*
3540  * perlio buffer layer
3541  */
3542
3543 IV
3544 PerlIOBuf_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
3545 {
3546     PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3547     const int fd = PerlIO_fileno(f);
3548     if (fd >= 0 && PerlLIO_isatty(fd)) {
3549         PerlIOBase(f)->flags |= PERLIO_F_LINEBUF | PERLIO_F_TTY;
3550     }
3551     if (*PerlIONext(f)) {
3552         const Off_t posn = PerlIO_tell(PerlIONext(f));
3553         if (posn != (Off_t) - 1) {
3554             b->posn = posn;
3555         }
3556     }
3557     return PerlIOBase_pushed(aTHX_ f, mode, arg, tab);
3558 }
3559
3560 PerlIO *
3561 PerlIOBuf_open(pTHX_ PerlIO_funcs *self, PerlIO_list_t *layers,
3562                IV n, const char *mode, int fd, int imode, int perm,
3563                PerlIO *f, int narg, SV **args)
3564 {
3565     if (PerlIOValid(f)) {
3566         PerlIO *next = PerlIONext(f);
3567         PerlIO_funcs *tab =
3568              PerlIO_layer_fetch(aTHX_ layers, n - 1, PerlIOBase(next)->tab);
3569         if (tab && tab->Open)
3570              next =
3571                   (*tab->Open)(aTHX_ tab, layers, n - 1, mode, fd, imode, perm,
3572                                next, narg, args);
3573         if (!next || (*PerlIOBase(f)->tab->Pushed) (aTHX_ f, mode, PerlIOArg, self) != 0) {
3574             return NULL;
3575         }
3576     }
3577     else {
3578         PerlIO_funcs *tab = PerlIO_layer_fetch(aTHX_ layers, n - 1, PerlIO_default_btm());
3579         int init = 0;
3580         if (*mode == IoTYPE_IMPLICIT) {
3581             init = 1;
3582             /*
3583              * mode++;
3584              */
3585         }
3586         if (tab && tab->Open)
3587              f = (*tab->Open)(aTHX_ tab, layers, n - 1, mode, fd, imode, perm,
3588                               f, narg, args);
3589         else
3590              SETERRNO(EINVAL, LIB_INVARG);
3591         if (f) {
3592             if (PerlIO_push(aTHX_ f, self, mode, PerlIOArg) == 0) {
3593                 /*
3594                  * if push fails during open, open fails. close will pop us.
3595                  */
3596                 PerlIO_close (f);
3597                 return NULL;
3598             } else {
3599                 fd = PerlIO_fileno(f);
3600                 if (init && fd == 2) {
3601                     /*
3602                      * Initial stderr is unbuffered
3603                      */
3604                     PerlIOBase(f)->flags |= PERLIO_F_UNBUF;
3605                 }
3606 #ifdef PERLIO_USING_CRLF
3607 #  ifdef PERLIO_IS_BINMODE_FD
3608                 if (PERLIO_IS_BINMODE_FD(fd))
3609                     PerlIO_binmode(aTHX_ f,  '<'/*not used*/, O_BINARY, NULL);
3610                 else
3611 #  endif
3612                 /*
3613                  * do something about failing setmode()? --jhi
3614                  */
3615                 PerlLIO_setmode(fd, O_BINARY);
3616 #endif
3617             }
3618         }
3619     }
3620     return f;
3621 }
3622
3623 /*
3624  * This "flush" is akin to sfio's sync in that it handles files in either
3625  * read or write state.  For write state, we put the postponed data through
3626  * the next layers.  For read state, we seek() the next layers to the
3627  * offset given by current position in the buffer, and discard the buffer
3628  * state (XXXX supposed to be for seek()able buffers only, but now it is done
3629  * in any case?).  Then the pass the stick further in chain.
3630  */
3631 IV
3632 PerlIOBuf_flush(pTHX_ PerlIO *f)
3633 {
3634     PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
3635     int code = 0;
3636     PerlIO *n = PerlIONext(f);
3637     if (PerlIOBase(f)->flags & PERLIO_F_WRBUF) {
3638         /*
3639          * write() the buffer
3640          */
3641         const STDCHAR *buf = b->buf;
3642         const STDCHAR *p = buf;
3643         while (p < b->ptr) {
3644             SSize_t count = PerlIO_write(n, p, b->ptr - p);
3645             if (count > 0) {
3646                 p += count;
3647             }
3648             else if (count < 0 || PerlIO_error(n)) {
3649                 PerlIOBase(f)->flags |= PERLIO_F_ERROR;
3650                 code = -1;
3651                 break;
3652             }
3653         }
3654         b->posn += (p - buf);
3655     }
3656     else if (PerlIOBase(f)->flags & PERLIO_F_RDBUF) {
3657         STDCHAR *buf = PerlIO_get_base(f);
3658         /*
3659          * Note position change
3660          */
3661         b->posn += (b->ptr - buf);
3662         if (b->ptr < b->end) {
3663             /* We did not consume all of it - try and seek downstream to
3664                our logical position
3665              */
3666             if (PerlIOValid(n) && PerlIO_seek(n, b->posn, SEEK_SET) == 0) {
3667                 /* Reload n as some layers may pop themselves on seek */
3668                 b->posn = PerlIO_tell(n = PerlIONext(f));
3669             }
3670             else {
3671                 /* Seek failed (e.g. pipe or tty). Do NOT clear buffer or pre-read
3672                    data is lost for good - so return saying "ok" having undone
3673                    the position adjust
3674                  */
3675                 b->posn -= (b->ptr - buf);
3676                 return code;
3677             }
3678         }
3679     }
3680     b->ptr = b->end = b->buf;
3681     PerlIOBase(f)->flags &= ~(PERLIO_F_RDBUF | PERLIO_F_WRBUF);
3682     /* We check for Valid because of dubious decision to make PerlIO_flush(NULL) flush all */
3683     if (PerlIOValid(n) && PerlIO_flush(n) != 0)
3684         code = -1;
3685     return code;
3686 }
3687
3688 /* This discards the content of the buffer after b->ptr, and rereads
3689  * the buffer from the position off in the layer downstream; here off
3690  * is at offset corresponding to b->ptr - b->buf.
3691  */
3692 IV
3693 PerlIOBuf_fill(pTHX_ PerlIO *f)
3694 {
3695     PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
3696     PerlIO *n = PerlIONext(f);
3697     SSize_t avail;
3698     /*
3699      * Down-stream flush is defined not to loose read data so is harmless.
3700      * we would not normally be fill'ing if there was data left in anycase.
3701      */
3702     if (PerlIO_flush(f) != 0)   /* XXXX Check that its seek() succeeded?! */
3703         return -1;
3704     if (PerlIOBase(f)->flags & PERLIO_F_TTY)
3705         PerlIOBase_flush_linebuf(aTHX);
3706
3707     if (!b->buf)
3708         PerlIO_get_base(f);     /* allocate via vtable */
3709
3710     b->ptr = b->end = b->buf;
3711
3712     if (!PerlIOValid(n)) {
3713         PerlIOBase(f)->flags |= PERLIO_F_EOF;
3714         return -1;
3715     }
3716
3717     if (PerlIO_fast_gets(n)) {
3718         /*
3719          * Layer below is also buffered. We do _NOT_ want to call its
3720          * ->Read() because that will loop till it gets what we asked for
3721          * which may hang on a pipe etc. Instead take anything it has to
3722          * hand, or ask it to fill _once_.
3723          */
3724         avail = PerlIO_get_cnt(n);
3725         if (avail <= 0) {
3726             avail = PerlIO_fill(n);
3727             if (avail == 0)
3728                 avail = PerlIO_get_cnt(n);
3729             else {
3730                 if (!PerlIO_error(n) && PerlIO_eof(n))
3731                     avail = 0;
3732             }
3733         }
3734         if (avail > 0) {
3735             STDCHAR *ptr = PerlIO_get_ptr(n);
3736             const SSize_t cnt = avail;
3737             if (avail > (SSize_t)b->bufsiz)
3738                 avail = b->bufsiz;
3739             Copy(ptr, b->buf, avail, STDCHAR);
3740             PerlIO_set_ptrcnt(n, ptr + avail, cnt - avail);
3741         }
3742     }
3743     else {
3744         avail = PerlIO_read(n, b->ptr, b->bufsiz);
3745     }
3746     if (avail <= 0) {
3747         if (avail == 0)
3748             PerlIOBase(f)->flags |= PERLIO_F_EOF;
3749         else
3750             PerlIOBase(f)->flags |= PERLIO_F_ERROR;
3751         return -1;
3752     }
3753     b->end = b->buf + avail;
3754     PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
3755     return 0;
3756 }
3757
3758 SSize_t
3759 PerlIOBuf_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
3760 {
3761     if (PerlIOValid(f)) {
3762         const PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
3763         if (!b->ptr)
3764             PerlIO_get_base(f);
3765         return PerlIOBase_read(aTHX_ f, vbuf, count);
3766     }
3767     return 0;
3768 }
3769
3770 SSize_t
3771 PerlIOBuf_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
3772 {
3773     const STDCHAR *buf = (const STDCHAR *) vbuf + count;
3774     PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
3775     SSize_t unread = 0;
3776     SSize_t avail;
3777     if (PerlIOBase(f)->flags & PERLIO_F_WRBUF)
3778         PerlIO_flush(f);
3779     if (!b->buf)
3780         PerlIO_get_base(f);
3781     if (b->buf) {
3782         if (PerlIOBase(f)->flags & PERLIO_F_RDBUF) {
3783             /*
3784              * Buffer is already a read buffer, we can overwrite any chars
3785              * which have been read back to buffer start
3786              */
3787             avail = (b->ptr - b->buf);
3788         }
3789         else {
3790             /*
3791              * Buffer is idle, set it up so whole buffer is available for
3792              * unread
3793              */
3794             avail = b->bufsiz;
3795             b->end = b->buf + avail;
3796             b->ptr = b->end;
3797             PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
3798             /*
3799              * Buffer extends _back_ from where we are now
3800              */
3801             b->posn -= b->bufsiz;
3802         }
3803         if (avail > (SSize_t) count) {
3804             /*
3805              * If we have space for more than count, just move count
3806              */
3807             avail = count;
3808         }
3809         if (avail > 0) {
3810             b->ptr -= avail;
3811             buf -= avail;
3812             /*
3813              * In simple stdio-like ungetc() case chars will be already
3814              * there
3815              */
3816             if (buf != b->ptr) {
3817                 Copy(buf, b->ptr, avail, STDCHAR);
3818             }
3819             count -= avail;
3820             unread += avail;
3821             PerlIOBase(f)->flags &= ~PERLIO_F_EOF;
3822         }
3823     }
3824     if (count > 0) {
3825         unread += PerlIOBase_unread(aTHX_ f, vbuf, count);
3826     }
3827     return unread;
3828 }
3829
3830 SSize_t
3831 PerlIOBuf_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
3832 {
3833     PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
3834     const STDCHAR *buf = (const STDCHAR *) vbuf;
3835     const STDCHAR *flushptr = buf;
3836     Size_t written = 0;
3837     if (!b->buf)
3838         PerlIO_get_base(f);
3839     if (!(PerlIOBase(f)->flags & PERLIO_F_CANWRITE))
3840         return 0;
3841     if (PerlIOBase(f)->flags & PERLIO_F_RDBUF) {
3842         if (PerlIO_flush(f) != 0) {
3843             return 0;
3844         }
3845     }   
3846     if (PerlIOBase(f)->flags & PERLIO_F_LINEBUF) {
3847         flushptr = buf + count;
3848         while (flushptr > buf && *(flushptr - 1) != '\n')
3849             --flushptr;
3850     }
3851     while (count > 0) {
3852         SSize_t avail = b->bufsiz - (b->ptr - b->buf);
3853         if ((SSize_t) count < avail)
3854             avail = count;
3855         if (flushptr > buf && flushptr <= buf + avail)
3856             avail = flushptr - buf;
3857         PerlIOBase(f)->flags |= PERLIO_F_WRBUF;
3858         if (avail) {
3859             Copy(buf, b->ptr, avail, STDCHAR);
3860             count -= avail;
3861             buf += avail;
3862             written += avail;
3863             b->ptr += avail;
3864             if (buf == flushptr)
3865                 PerlIO_flush(f);
3866         }
3867         if (b->ptr >= (b->buf + b->bufsiz))
3868             PerlIO_flush(f);
3869     }
3870     if (PerlIOBase(f)->flags & PERLIO_F_UNBUF)
3871         PerlIO_flush(f);
3872     return written;
3873 }
3874
3875 IV
3876 PerlIOBuf_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
3877 {
3878     IV code;
3879     if ((code = PerlIO_flush(f)) == 0) {
3880         PerlIOBase(f)->flags &= ~PERLIO_F_EOF;
3881         code = PerlIO_seek(PerlIONext(f), offset, whence);
3882         if (code == 0) {
3883             PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3884             b->posn = PerlIO_tell(PerlIONext(f));
3885         }
3886     }
3887     return code;
3888 }
3889
3890 Off_t
3891 PerlIOBuf_tell(pTHX_ PerlIO *f)
3892 {
3893     PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
3894     /*
3895      * b->posn is file position where b->buf was read, or will be written
3896      */
3897     Off_t posn = b->posn;
3898     if ((PerlIOBase(f)->flags & PERLIO_F_APPEND) &&
3899         (PerlIOBase(f)->flags & PERLIO_F_WRBUF)) {
3900 #if 1
3901         /* As O_APPEND files are normally shared in some sense it is better
3902            to flush :
3903          */     
3904         PerlIO_flush(f);
3905 #else   
3906         /* when file is NOT shared then this is sufficient */
3907         PerlIO_seek(PerlIONext(f),0, SEEK_END);
3908 #endif
3909         posn = b->posn = PerlIO_tell(PerlIONext(f));
3910     }
3911     if (b->buf) {
3912         /*
3913          * If buffer is valid adjust position by amount in buffer
3914          */
3915         posn += (b->ptr - b->buf);
3916     }
3917     return posn;
3918 }
3919
3920 IV
3921 PerlIOBuf_popped(pTHX_ PerlIO *f)
3922 {
3923     const IV code = PerlIOBase_popped(aTHX_ f);
3924     PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
3925     if (b->buf && b->buf != (STDCHAR *) & b->oneword) {
3926         Safefree(b->buf);
3927     }
3928     b->ptr = b->end = b->buf = NULL;
3929     PerlIOBase(f)->flags &= ~(PERLIO_F_RDBUF | PERLIO_F_WRBUF);
3930     return code;
3931 }
3932
3933 IV
3934 PerlIOBuf_close(pTHX_ PerlIO *f)
3935 {
3936     const IV code = PerlIOBase_close(aTHX_ f);
3937     PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
3938     if (b->buf && b->buf != (STDCHAR *) & b->oneword) {
3939         Safefree(b->buf);
3940     }
3941     b->ptr = b->end = b->buf = NULL;
3942     PerlIOBase(f)->flags &= ~(PERLIO_F_RDBUF | PERLIO_F_WRBUF);
3943     return code;
3944 }
3945
3946 STDCHAR *
3947 PerlIOBuf_get_ptr(pTHX_ PerlIO *f)
3948 {
3949     const PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
3950     if (!b->buf)
3951         PerlIO_get_base(f);
3952     return b->ptr;
3953 }
3954
3955 SSize_t
3956 PerlIOBuf_get_cnt(pTHX_ PerlIO *f)
3957 {
3958     const PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
3959     if (!b->buf)
3960         PerlIO_get_base(f);
3961     if (PerlIOBase(f)->flags & PERLIO_F_RDBUF)
3962         return (b->end - b->ptr);
3963     return 0;
3964 }
3965
3966 STDCHAR *
3967 PerlIOBuf_get_base(pTHX_ PerlIO *f)
3968 {
3969     PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
3970     if (!b->buf) {
3971         if (!b->bufsiz)
3972             b->bufsiz = 4096;
3973         b->buf = Newxz(b->buf,b->bufsiz, STDCHAR);
3974         if (!b->buf) {
3975             b->buf = (STDCHAR *) & b->oneword;
3976             b->bufsiz = sizeof(b->oneword);
3977         }
3978         b->end = b->ptr = b->buf;
3979     }
3980     return b->buf;
3981 }
3982
3983 Size_t
3984 PerlIOBuf_bufsiz(pTHX_ PerlIO *f)
3985 {
3986     const PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
3987     if (!b->buf)
3988         PerlIO_get_base(f);
3989     return (b->end - b->buf);
3990 }
3991
3992 void
3993 PerlIOBuf_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, SSize_t cnt)
3994 {
3995     PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
3996     if (!b->buf)
3997         PerlIO_get_base(f);
3998     b->ptr = ptr;
3999     if (PerlIO_get_cnt(f) != cnt || b->ptr < b->buf) {
4000         assert(PerlIO_get_cnt(f) == cnt);
4001         assert(b->ptr >= b->buf);
4002     }
4003     PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
4004 }
4005
4006 PerlIO *
4007 PerlIOBuf_dup(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags)
4008 {
4009  return PerlIOBase_dup(aTHX_ f, o, param, flags);
4010 }
4011
4012
4013
4014 PERLIO_FUNCS_DECL(PerlIO_perlio) = {
4015     sizeof(PerlIO_funcs),
4016     "perlio",
4017     sizeof(PerlIOBuf),
4018     PERLIO_K_BUFFERED|PERLIO_K_RAW,
4019     PerlIOBuf_pushed,
4020     PerlIOBuf_popped,
4021     PerlIOBuf_open,
4022     PerlIOBase_binmode,         /* binmode */
4023     NULL,
4024     PerlIOBase_fileno,
4025     PerlIOBuf_dup,
4026     PerlIOBuf_read,
4027     PerlIOBuf_unread,
4028     PerlIOBuf_write,
4029     PerlIOBuf_seek,
4030     PerlIOBuf_tell,
4031     PerlIOBuf_close,
4032     PerlIOBuf_flush,
4033     PerlIOBuf_fill,
4034     PerlIOBase_eof,
4035     PerlIOBase_error,
4036     PerlIOBase_clearerr,
4037     PerlIOBase_setlinebuf,
4038     PerlIOBuf_get_base,
4039     PerlIOBuf_bufsiz,
4040     PerlIOBuf_get_ptr,
4041     PerlIOBuf_get_cnt,
4042     PerlIOBuf_set_ptrcnt,
4043 };
4044
4045 /*--------------------------------------------------------------------------------------*/
4046 /*
4047  * Temp layer to hold unread chars when cannot do it any other way
4048  */
4049
4050 IV
4051 PerlIOPending_fill(pTHX_ PerlIO *f)
4052 {
4053     /*
4054      * Should never happen
4055      */
4056     PerlIO_flush(f);
4057     return 0;
4058 }
4059
4060 IV
4061 PerlIOPending_close(pTHX_ PerlIO *f)
4062 {
4063     /*
4064      * A tad tricky - flush pops us, then we close new top
4065      */
4066     PerlIO_flush(f);
4067     return PerlIO_close(f);
4068 }
4069
4070 IV
4071 PerlIOPending_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
4072 {
4073     /*
4074      * A tad tricky - flush pops us, then we seek new top
4075      */
4076     PerlIO_flush(f);
4077     return PerlIO_seek(f, offset, whence);
4078 }
4079
4080
4081 IV
4082 PerlIOPending_flush(pTHX_ PerlIO *f)
4083 {
4084     PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
4085     if (b->buf && b->buf != (STDCHAR *) & b->oneword) {
4086         Safefree(b->buf);
4087         b->buf = NULL;
4088     }
4089     PerlIO_pop(aTHX_ f);
4090     return 0;
4091 }
4092
4093 void
4094 PerlIOPending_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, SSize_t cnt)
4095 {
4096     if (cnt <= 0) {
4097         PerlIO_flush(f);
4098     }
4099     else {
4100         PerlIOBuf_set_ptrcnt(aTHX_ f, ptr, cnt);
4101     }
4102 }
4103
4104 IV
4105 PerlIOPending_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
4106 {
4107     const IV code = PerlIOBase_pushed(aTHX_ f, mode, arg, tab);
4108     PerlIOl * const l = PerlIOBase(f);
4109     /*
4110      * Our PerlIO_fast_gets must match what we are pushed on, or sv_gets()
4111      * etc. get muddled when it changes mid-string when we auto-pop.
4112      */
4113     l->flags = (l->flags & ~(PERLIO_F_FASTGETS | PERLIO_F_UTF8)) |
4114         (PerlIOBase(PerlIONext(f))->
4115          flags & (PERLIO_F_FASTGETS | PERLIO_F_UTF8));
4116     return code;
4117 }
4118
4119 SSize_t
4120 PerlIOPending_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
4121 {
4122     SSize_t avail = PerlIO_get_cnt(f);
4123     SSize_t got = 0;
4124     if ((SSize_t)count < avail)
4125         avail = count;
4126     if (avail > 0)
4127         got = PerlIOBuf_read(aTHX_ f, vbuf, avail);
4128     if (got >= 0 && got < (SSize_t)count) {
4129         const SSize_t more =
4130             PerlIO_read(f, ((STDCHAR *) vbuf) + got, count - got);
4131         if (more >= 0 || got == 0)
4132             got += more;
4133     }
4134     return got;
4135 }
4136
4137 PERLIO_FUNCS_DECL(PerlIO_pending) = {
4138     sizeof(PerlIO_funcs),
4139     "pending",
4140     sizeof(PerlIOBuf),
4141     PERLIO_K_BUFFERED|PERLIO_K_RAW,  /* not sure about RAW here */
4142     PerlIOPending_pushed,
4143     PerlIOBuf_popped,
4144     NULL,
4145     PerlIOBase_binmode,         /* binmode */
4146     NULL,
4147     PerlIOBase_fileno,
4148     PerlIOBuf_dup,
4149     PerlIOPending_read,
4150     PerlIOBuf_unread,
4151     PerlIOBuf_write,
4152     PerlIOPending_seek,
4153     PerlIOBuf_tell,
4154     PerlIOPending_close,
4155     PerlIOPending_flush,
4156     PerlIOPending_fill,
4157     PerlIOBase_eof,
4158     PerlIOBase_error,
4159     PerlIOBase_clearerr,
4160     PerlIOBase_setlinebuf,
4161     PerlIOBuf_get_base,
4162     PerlIOBuf_bufsiz,
4163     PerlIOBuf_get_ptr,
4164     PerlIOBuf_get_cnt,
4165     PerlIOPending_set_ptrcnt,
4166 };
4167
4168
4169
4170 /*--------------------------------------------------------------------------------------*/
4171 /*
4172  * crlf - translation On read translate CR,LF to "\n" we do this by
4173  * overriding ptr/cnt entries to hand back a line at a time and keeping a
4174  * record of which nl we "lied" about. On write translate "\n" to CR,LF
4175  *
4176  * c->nl points on the first byte of CR LF pair when it is temporarily
4177  * replaced by LF, or to the last CR of the buffer.  In the former case
4178  * the caller thinks that the buffer ends at c->nl + 1, in the latter
4179  * that it ends at c->nl; these two cases can be distinguished by
4180  * *c->nl.  c->nl is set during _getcnt() call, and unset during
4181  * _unread() and _flush() calls.
4182  * It only matters for read operations.
4183  */
4184
4185 typedef struct {
4186     PerlIOBuf base;             /* PerlIOBuf stuff */
4187     STDCHAR *nl;                /* Position of crlf we "lied" about in the
4188                                  * buffer */
4189 } PerlIOCrlf;
4190
4191 IV
4192 PerlIOCrlf_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
4193 {
4194     IV code;
4195     PerlIOBase(f)->flags |= PERLIO_F_CRLF;
4196     code = PerlIOBuf_pushed(aTHX_ f, mode, arg, tab);
4197 #if 0
4198     PerlIO_debug("PerlIOCrlf_pushed f=%p %s %s fl=%08" UVxf "\n",
4199                  f, PerlIOBase(f)->tab->name, (mode) ? mode : "(Null)",
4200                  PerlIOBase(f)->flags);
4201 #endif
4202     {
4203       /* Enable the first CRLF capable layer you can find, but if none
4204        * found, the one we just pushed is fine.  This results in at
4205        * any given moment at most one CRLF-capable layer being enabled
4206        * in the whole layer stack. */
4207          PerlIO *g = PerlIONext(f);
4208          while (g && *g) {
4209               PerlIOl *b = PerlIOBase(g);
4210               if (b && b->tab == &PerlIO_crlf) {
4211                    if (!(b->flags & PERLIO_F_CRLF))
4212                         b->flags |= PERLIO_F_CRLF;
4213                    PerlIO_pop(aTHX_ f);
4214                    return code;
4215               }           
4216               g = PerlIONext(g);
4217          }
4218     }
4219     return code;
4220 }
4221
4222
4223 SSize_t
4224 PerlIOCrlf_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
4225 {
4226     PerlIOCrlf * const c = PerlIOSelf(f, PerlIOCrlf);
4227     if (c->nl) {        /* XXXX Shouldn't it be done only if b->ptr > c->nl? */
4228         *(c->nl) = 0xd;
4229         c->nl = NULL;
4230     }
4231     if (!(PerlIOBase(f)->flags & PERLIO_F_CRLF))
4232         return PerlIOBuf_unread(aTHX_ f, vbuf, count);
4233     else {
4234         const STDCHAR *buf = (const STDCHAR *) vbuf + count;
4235         PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
4236         SSize_t unread = 0;
4237         if (PerlIOBase(f)->flags & PERLIO_F_WRBUF)
4238             PerlIO_flush(f);
4239         if (!b->buf)
4240             PerlIO_get_base(f);
4241         if (b->buf) {
4242             if (!(PerlIOBase(f)->flags & PERLIO_F_RDBUF)) {
4243                 b->end = b->ptr = b->buf + b->bufsiz;
4244                 PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
4245                 b->posn -= b->bufsiz;
4246             }
4247             while (count > 0 && b->ptr > b->buf) {
4248                 const int ch = *--buf;
4249                 if (ch == '\n') {
4250                     if (b->ptr - 2 >= b->buf) {
4251                         *--(b->ptr) = 0xa;
4252                         *--(b->ptr) = 0xd;
4253                         unread++;
4254                         count--;
4255                     }
4256                     else {
4257                     /* If b->ptr - 1 == b->buf, we are undoing reading 0xa */
4258                         *--(b->ptr) = 0xa;      /* Works even if 0xa == '\r' */
4259                         unread++;
4260                         count--;
4261                     }
4262                 }
4263                 else {
4264                     *--(b->ptr) = ch;
4265                     unread++;
4266                     count--;
4267                 }
4268             }
4269         }
4270         return unread;
4271     }
4272 }
4273
4274 /* XXXX This code assumes that buffer size >=2, but does not check it... */
4275 SSize_t
4276 PerlIOCrlf_get_cnt(pTHX_ PerlIO *f)
4277 {
4278     PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
4279     if (!b->buf)
4280         PerlIO_get_base(f);
4281     if (PerlIOBase(f)->flags & PERLIO_F_RDBUF) {
4282         PerlIOCrlf * const c = PerlIOSelf(f, PerlIOCrlf);
4283         if ((PerlIOBase(f)->flags & PERLIO_F_CRLF) && (!c->nl || *c->nl == 0xd)) {
4284             STDCHAR *nl = (c->nl) ? c->nl : b->ptr;
4285           scan:
4286             while (nl < b->end && *nl != 0xd)
4287                 nl++;
4288             if (nl < b->end && *nl == 0xd) {
4289               test:
4290                 if (nl + 1 < b->end) {
4291                     if (nl[1] == 0xa) {
4292                         *nl = '\n';
4293                         c->nl = nl;
4294                     }
4295                     else {
4296                         /*
4297                          * Not CR,LF but just CR
4298                          */
4299                         nl++;
4300                         goto scan;
4301                     }
4302                 }
4303                 else {
4304                     /*
4305                      * Blast - found CR as last char in buffer
4306                      */
4307
4308                     if (b->ptr < nl) {
4309                         /*
4310                          * They may not care, defer work as long as
4311                          * possible
4312                          */
4313                         c->nl = nl;
4314                         return (nl - b->ptr);
4315                     }
4316                     else {
4317                         int code;
4318                         b->ptr++;       /* say we have read it as far as
4319                                          * flush() is concerned */
4320                         b->buf++;       /* Leave space in front of buffer */
4321                         /* Note as we have moved buf up flush's
4322                            posn += ptr-buf
4323                            will naturally make posn point at CR
4324                          */
4325                         b->bufsiz--;    /* Buffer is thus smaller */
4326                         code = PerlIO_fill(f);  /* Fetch some more */
4327                         b->bufsiz++;    /* Restore size for next time */
4328                         b->buf--;       /* Point at space */
4329                         b->ptr = nl = b->buf;   /* Which is what we hand
4330                                                  * off */
4331                         *nl = 0xd;      /* Fill in the CR */
4332                         if (code == 0)
4333                             goto test;  /* fill() call worked */
4334                         /*
4335                          * CR at EOF - just fall through
4336                          */
4337                         /* Should we clear EOF though ??? */
4338                     }
4339                 }
4340             }
4341         }
4342         return (((c->nl) ? (c->nl + 1) : b->end) - b->ptr);
4343     }
4344     return 0;
4345 }
4346
4347 void
4348 PerlIOCrlf_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, SSize_t cnt)
4349 {
4350     PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
4351     PerlIOCrlf * const c = PerlIOSelf(f, PerlIOCrlf);
4352     if (!b->buf)
4353         PerlIO_get_base(f);
4354     if (!ptr) {
4355         if (c->nl) {
4356             ptr = c->nl + 1;
4357             if (ptr == b->end && *c->nl == 0xd) {
4358                 /* Defered CR at end of buffer case - we lied about count */
4359                 ptr--;
4360             }
4361         }
4362         else {
4363             ptr = b->end;
4364         }
4365         ptr -= cnt;
4366     }
4367     else {
4368         /*EMPTY*/;
4369 #if 0
4370         /*
4371          * Test code - delete when it works ...
4372          */
4373         IV flags = PerlIOBase(f)->flags;
4374         STDCHAR *chk = (c->nl) ? (c->nl+1) : b->end;
4375         if (ptr+cnt == c->nl && c->nl+1 == b->end && *c->nl == 0xd) {
4376           /* Defered CR at end of buffer case - we lied about count */
4377           chk--;
4378         }
4379         chk -= cnt;
4380
4381         if (ptr != chk ) {
4382             Perl_croak(aTHX_ "ptr wrong %p != %p fl=%08" UVxf
4383                        " nl=%p e=%p for %d", ptr, chk, flags, c->nl,
4384                        b->end, cnt);
4385         }
4386 #endif
4387     }
4388     if (c->nl) {
4389         if (ptr > c->nl) {
4390             /*
4391              * They have taken what we lied about
4392              */
4393             *(c->nl) = 0xd;
4394             c->nl = NULL;
4395             ptr++;
4396         }
4397     }
4398     b->ptr = ptr;
4399     PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
4400 }
4401
4402 SSize_t
4403 PerlIOCrlf_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
4404 {
4405     if (!(PerlIOBase(f)->flags & PERLIO_F_CRLF))
4406         return PerlIOBuf_write(aTHX_ f, vbuf, count);
4407     else {
4408         PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
4409         const STDCHAR *buf = (const STDCHAR *) vbuf;
4410         const STDCHAR * const ebuf = buf + count;
4411         if (!b->buf)
4412             PerlIO_get_base(f);
4413         if (!(PerlIOBase(f)->flags & PERLIO_F_CANWRITE))
4414             return 0;
4415         while (buf < ebuf) {
4416             const STDCHAR * const eptr = b->buf + b->bufsiz;
4417             PerlIOBase(f)->flags |= PERLIO_F_WRBUF;
4418             while (buf < ebuf && b->ptr < eptr) {
4419                 if (*buf == '\n') {
4420                     if ((b->ptr + 2) > eptr) {
4421                         /*
4422                          * Not room for both
4423                          */
4424                         PerlIO_flush(f);
4425                         break;
4426                     }
4427                     else {
4428                         *(b->ptr)++ = 0xd;      /* CR */
4429                         *(b->ptr)++ = 0xa;      /* LF */
4430                         buf++;
4431                         if (PerlIOBase(f)->flags & PERLIO_F_LINEBUF) {
4432                             PerlIO_flush(f);
4433                             break;
4434                         }
4435                     }
4436                 }
4437                 else {
4438                     *(b->ptr)++ = *buf++;
4439                 }
4440                 if (b->ptr >= eptr) {
4441                     PerlIO_flush(f);
4442                     break;
4443                 }
4444             }
4445         }
4446         if (PerlIOBase(f)->flags & PERLIO_F_UNBUF)
4447             PerlIO_flush(f);
4448         return (buf - (STDCHAR *) vbuf);
4449     }
4450 }
4451
4452 IV
4453 PerlIOCrlf_flush(pTHX_ PerlIO *f)
4454 {
4455     PerlIOCrlf * const c = PerlIOSelf(f, PerlIOCrlf);
4456     if (c->nl) {
4457         *(c->nl) = 0xd;
4458         c->nl = NULL;
4459     }
4460     return PerlIOBuf_flush(aTHX_ f);
4461 }
4462
4463 IV
4464 PerlIOCrlf_binmode(pTHX_ PerlIO *f)
4465 {
4466     if ((PerlIOBase(f)->flags & PERLIO_F_CRLF)) {
4467         /* In text mode - flush any pending stuff and flip it */
4468         PerlIOBase(f)->flags &= ~PERLIO_F_CRLF;
4469 #ifndef PERLIO_USING_CRLF
4470         /* CRLF is unusual case - if this is just the :crlf layer pop it */
4471         if (PerlIOBase(f)->tab == &PerlIO_crlf) {
4472                 PerlIO_pop(aTHX_ f);
4473         }
4474 #endif
4475     }
4476     return 0;
4477 }
4478
4479 PERLIO_FUNCS_DECL(PerlIO_crlf) = {
4480     sizeof(PerlIO_funcs),
4481     "crlf",
4482     sizeof(PerlIOCrlf),
4483     PERLIO_K_BUFFERED | PERLIO_K_CANCRLF | PERLIO_K_RAW,
4484     PerlIOCrlf_pushed,
4485     PerlIOBuf_popped,         /* popped */
4486     PerlIOBuf_open,
4487     PerlIOCrlf_binmode,       /* binmode */
4488     NULL,
4489     PerlIOBase_fileno,
4490     PerlIOBuf_dup,
4491     PerlIOBuf_read,             /* generic read works with ptr/cnt lies */
4492     PerlIOCrlf_unread,          /* Put CR,LF in buffer for each '\n' */
4493     PerlIOCrlf_write,           /* Put CR,LF in buffer for each '\n' */
4494     PerlIOBuf_seek,
4495     PerlIOBuf_tell,
4496     PerlIOBuf_close,
4497     PerlIOCrlf_flush,
4498     PerlIOBuf_fill,
4499     PerlIOBase_eof,
4500     PerlIOBase_error,
4501     PerlIOBase_clearerr,
4502     PerlIOBase_setlinebuf,
4503     PerlIOBuf_get_base,
4504     PerlIOBuf_bufsiz,
4505     PerlIOBuf_get_ptr,
4506     PerlIOCrlf_get_cnt,
4507     PerlIOCrlf_set_ptrcnt,
4508 };
4509
4510 #ifdef HAS_MMAP
4511 /*--------------------------------------------------------------------------------------*/
4512 /*
4513  * mmap as "buffer" layer
4514  */
4515
4516 typedef struct {
4517     PerlIOBuf base;             /* PerlIOBuf stuff */
4518     Mmap_t mptr;                /* Mapped address */
4519     Size_t len;                 /* mapped length */
4520     STDCHAR *bbuf;              /* malloced buffer if map fails */
4521 } PerlIOMmap;
4522
4523 IV
4524 PerlIOMmap_map(pTHX_ PerlIO *f)
4525 {
4526     dVAR;
4527     PerlIOMmap * const m = PerlIOSelf(f, PerlIOMmap);
4528     const IV flags = PerlIOBase(f)->flags;
4529     IV code = 0;
4530     if (m->len)
4531         abort();
4532     if (flags & PERLIO_F_CANREAD) {
4533         PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
4534         const int fd = PerlIO_fileno(f);
4535         Stat_t st;
4536         code = Fstat(fd, &st);
4537         if (code == 0 && S_ISREG(st.st_mode)) {
4538             SSize_t len = st.st_size - b->posn;
4539             if (len > 0) {
4540                 Off_t posn;
4541                 if (PL_mmap_page_size <= 0)
4542                   Perl_croak(aTHX_ "panic: bad pagesize %" IVdf,
4543                              PL_mmap_page_size);
4544                 if (b->posn < 0) {
4545                     /*
4546                      * This is a hack - should never happen - open should
4547                      * have set it !
4548                      */
4549                     b->posn = PerlIO_tell(PerlIONext(f));
4550                 }
4551                 posn = (b->posn / PL_mmap_page_size) * PL_mmap_page_size;
4552                 len = st.st_size - posn;
4553                 m->mptr = mmap(NULL, len, PROT_READ, MAP_SHARED, fd, posn);
4554                 if (m->mptr && m->mptr != (Mmap_t) - 1) {
4555 #if 0 && defined(HAS_MADVISE) && defined(MADV_SEQUENTIAL)
4556                     madvise(m->mptr, len, MADV_SEQUENTIAL);
4557 #endif
4558 #if 0 && defined(HAS_MADVISE) && defined(MADV_WILLNEED)
4559                     madvise(m->mptr, len, MADV_WILLNEED);
4560 #endif
4561                     PerlIOBase(f)->flags =
4562                         (flags & ~PERLIO_F_EOF) | PERLIO_F_RDBUF;
4563                     b->end = ((STDCHAR *) m->mptr) + len;
4564                     b->buf = ((STDCHAR *) m->mptr) + (b->posn - posn);
4565                     b->ptr = b->buf;
4566                     m->len = len;
4567                 }
4568                 else {
4569                     b->buf = NULL;
4570                 }
4571             }
4572             else {
4573                 PerlIOBase(f)->flags =
4574                     flags | PERLIO_F_EOF | PERLIO_F_RDBUF;
4575                 b->buf = NULL;
4576                 b->ptr = b->end = b->ptr;
4577                 code = -1;
4578             }
4579         }
4580     }
4581     return code;
4582 }
4583
4584 IV
4585 PerlIOMmap_unmap(pTHX_ PerlIO *f)
4586 {
4587     PerlIOMmap * const m = PerlIOSelf(f, PerlIOMmap);
4588     IV code = 0;
4589     if (m->len) {
4590         PerlIOBuf * const b = &m->base;
4591         if (b->buf) {
4592             code = munmap(m->mptr, m->len);
4593             b->buf = NULL;
4594             m->len = 0;
4595             m->mptr = NULL;
4596             if (PerlIO_seek(PerlIONext(f), b->posn, SEEK_SET) != 0)
4597                 code = -1;
4598         }
4599         b->ptr = b->end = b->buf;
4600         PerlIOBase(f)->flags &= ~(PERLIO_F_RDBUF | PERLIO_F_WRBUF);
4601     }
4602     return code;
4603 }
4604
4605 STDCHAR *
4606 PerlIOMmap_get_base(pTHX_ PerlIO *f)
4607 {
4608     PerlIOMmap * const m = PerlIOSelf(f, PerlIOMmap);
4609     PerlIOBuf * const b = &m->base;
4610     if (b->buf && (PerlIOBase(f)->flags & PERLIO_F_RDBUF)) {
4611         /*
4612          * Already have a readbuffer in progress
4613          */
4614         return b->buf;
4615     }
4616     if (b->buf) {
4617         /*
4618          * We have a write buffer or flushed PerlIOBuf read buffer
4619          */
4620         m->bbuf = b->buf;       /* save it in case we need it again */
4621         b->buf = NULL;          /* Clear to trigger below */
4622     }
4623     if (!b->buf) {
4624         PerlIOMmap_map(aTHX_ f);        /* Try and map it */
4625         if (!b->buf) {
4626             /*
4627              * Map did not work - recover PerlIOBuf buffer if we have one
4628              */
4629             b->buf = m->bbuf;
4630         }
4631     }
4632     b->ptr = b->end = b->buf;
4633     if (b->buf)
4634         return b->buf;
4635     return PerlIOBuf_get_base(aTHX_ f);
4636 }
4637
4638 SSize_t
4639 PerlIOMmap_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
4640 {
4641     PerlIOMmap * const m = PerlIOSelf(f, PerlIOMmap);
4642     PerlIOBuf * const b = &m->base;
4643     if (PerlIOBase(f)->flags & PERLIO_F_WRBUF)
4644         PerlIO_flush(f);
4645     if (b->ptr && (b->ptr - count) >= b->buf
4646         && memEQ(b->ptr - count, vbuf, count)) {
4647         b->ptr -= count;
4648         PerlIOBase(f)->flags &= ~PERLIO_F_EOF;
4649         return count;
4650     }
4651     if (m->len) {
4652         /*
4653          * Loose the unwritable mapped buffer
4654          */
4655         PerlIO_flush(f);
4656         /*
4657          * If flush took the "buffer" see if we have one from before
4658          */
4659         if (!b->buf && m->bbuf)
4660             b->buf = m->bbuf;
4661         if (!b->buf) {
4662             PerlIOBuf_get_base(aTHX_ f);
4663             m->bbuf = b->buf;
4664         }
4665     }
4666     return PerlIOBuf_unread(aTHX_ f, vbuf, count);
4667 }
4668
4669 SSize_t
4670 PerlIOMmap_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
4671 {
4672     PerlIOMmap * const m = PerlIOSelf(f, PerlIOMmap);
4673     PerlIOBuf * const b = &m->base;
4674
4675     if (!b->buf || !(PerlIOBase(f)->flags & PERLIO_F_WRBUF)) {
4676         /*
4677          * No, or wrong sort of, buffer
4678          */
4679         if (m->len) {
4680             if (PerlIOMmap_unmap(aTHX_ f) != 0)
4681                 return 0;
4682         }
4683         /*
4684          * If unmap took the "buffer" see if we have one from before
4685          */
4686         if (!b->buf && m->bbuf)
4687             b->buf = m->bbuf;
4688         if (!b->buf) {
4689             PerlIOBuf_get_base(aTHX_ f);
4690             m->bbuf = b->buf;
4691         }
4692     }
4693     return PerlIOBuf_write(aTHX_ f, vbuf, count);
4694 }
4695
4696 IV
4697 PerlIOMmap_flush(pTHX_ PerlIO *f)
4698 {
4699     PerlIOMmap * const m = PerlIOSelf(f, PerlIOMmap);
4700     PerlIOBuf * const b = &m->base;
4701     IV code = PerlIOBuf_flush(aTHX_ f);
4702     /*
4703      * Now we are "synced" at PerlIOBuf level
4704      */
4705     if (b->buf) {
4706         if (m->len) {
4707             /*
4708              * Unmap the buffer
4709              */
4710             if (PerlIOMmap_unmap(aTHX_ f) != 0)
4711                 code = -1;
4712         }
4713         else {
4714             /*
4715              * We seem to have a PerlIOBuf buffer which was not mapped
4716              * remember it in case we need one later
4717              */
4718             m->bbuf = b->buf;
4719         }
4720     }
4721     return code;
4722 }
4723
4724 IV
4725 PerlIOMmap_fill(pTHX_ PerlIO *f)
4726 {
4727     PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
4728     IV code = PerlIO_flush(f);
4729     if (code == 0 && !b->buf) {
4730         code = PerlIOMmap_map(aTHX_ f);
4731     }
4732     if (code == 0 && !(PerlIOBase(f)->flags & PERLIO_F_RDBUF)) {
4733         code = PerlIOBuf_fill(aTHX_ f);
4734     }
4735     return code;
4736 }
4737
4738 IV
4739 PerlIOMmap_close(pTHX_ PerlIO *f)
4740 {
4741     PerlIOMmap * const m = PerlIOSelf(f, PerlIOMmap);
4742     PerlIOBuf * const b = &m->base;
4743     IV code = PerlIO_flush(f);
4744     if (m->bbuf) {
4745         b->buf = m->bbuf;
4746         m->bbuf = NULL;
4747         b->ptr = b->end = b->buf;
4748     }
4749     if (PerlIOBuf_close(aTHX_ f) != 0)
4750         code = -1;
4751     return code;
4752 }
4753
4754 PerlIO *
4755 PerlIOMmap_dup(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags)
4756 {
4757  return PerlIOBase_dup(aTHX_ f, o, param, flags);
4758 }
4759
4760
4761 PERLIO_FUNCS_DECL(PerlIO_mmap) = {
4762     sizeof(PerlIO_funcs),
4763     "mmap",
4764     sizeof(PerlIOMmap),
4765     PERLIO_K_BUFFERED|PERLIO_K_RAW,
4766     PerlIOBuf_pushed,
4767     PerlIOBuf_popped,
4768     PerlIOBuf_open,
4769     PerlIOBase_binmode,         /* binmode */
4770     NULL,
4771     PerlIOBase_fileno,
4772     PerlIOMmap_dup,
4773     PerlIOBuf_read,
4774     PerlIOMmap_unread,
4775     PerlIOMmap_write,
4776     PerlIOBuf_seek,
4777     PerlIOBuf_tell,
4778     PerlIOBuf_close,
4779     PerlIOMmap_flush,
4780     PerlIOMmap_fill,
4781     PerlIOBase_eof,
4782     PerlIOBase_error,
4783     PerlIOBase_clearerr,
4784     PerlIOBase_setlinebuf,
4785     PerlIOMmap_get_base,
4786     PerlIOBuf_bufsiz,
4787     PerlIOBuf_get_ptr,
4788     PerlIOBuf_get_cnt,
4789     PerlIOBuf_set_ptrcnt,
4790 };
4791
4792 #endif                          /* HAS_MMAP */
4793
4794 PerlIO *
4795 Perl_PerlIO_stdin(pTHX)
4796 {
4797     dVAR;
4798     if (!PL_perlio) {
4799         PerlIO_stdstreams(aTHX);
4800     }
4801     return &PL_perlio[1];
4802 }
4803
4804 PerlIO *
4805 Perl_PerlIO_stdout(pTHX)
4806 {
4807     dVAR;
4808     if (!PL_perlio) {
4809         PerlIO_stdstreams(aTHX);
4810     }
4811     return &PL_perlio[2];
4812 }
4813
4814 PerlIO *
4815 Perl_PerlIO_stderr(pTHX)
4816 {
4817     dVAR;
4818     if (!PL_perlio) {
4819         PerlIO_stdstreams(aTHX);
4820     }
4821     return &PL_perlio[3];
4822 }
4823
4824 /*--------------------------------------------------------------------------------------*/
4825
4826 char *
4827 PerlIO_getname(PerlIO *f, char *buf)
4828 {
4829     dTHX;
4830 #ifdef VMS
4831     char *name = NULL;
4832     bool exported = FALSE;
4833     FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
4834     if (!stdio) {
4835         stdio = PerlIO_exportFILE(f,0);
4836         exported = TRUE;
4837     }
4838     if (stdio) {
4839         name = fgetname(stdio, buf);
4840         if (exported) PerlIO_releaseFILE(f,stdio);
4841     }
4842     return name;
4843 #else
4844     PERL_UNUSED_ARG(f);
4845     PERL_UNUSED_ARG(buf);
4846     Perl_croak(aTHX_ "Don't know how to get file name");
4847     return NULL;
4848 #endif
4849 }
4850
4851
4852 /*--------------------------------------------------------------------------------------*/
4853 /*
4854  * Functions which can be called on any kind of PerlIO implemented in
4855  * terms of above
4856  */
4857
4858 #undef PerlIO_fdopen
4859 PerlIO *
4860 PerlIO_fdopen(int fd, const char *mode)
4861 {
4862     dTHX;
4863     return PerlIO_openn(aTHX_ NULL, mode, fd, 0, 0, NULL, 0, NULL);
4864 }
4865
4866 #undef PerlIO_open
4867 PerlIO *
4868 PerlIO_open(const char *path, const char *mode)
4869 {
4870     dTHX;
4871     SV *name = sv_2mortal(newSVpv(path, 0));
4872     return PerlIO_openn(aTHX_ NULL, mode, -1, 0, 0, NULL, 1, &name);
4873 }
4874
4875 #undef Perlio_reopen
4876 PerlIO *
4877 PerlIO_reopen(const char *path, const char *mode, PerlIO *f)
4878 {
4879     dTHX;
4880     SV *name = sv_2mortal(newSVpv(path,0));
4881     return PerlIO_openn(aTHX_ NULL, mode, -1, 0, 0, f, 1, &name);
4882 }
4883
4884 #undef PerlIO_getc
4885 int
4886 PerlIO_getc(PerlIO *f)
4887 {
4888     dTHX;
4889     STDCHAR buf[1];
4890     if ( 1 == PerlIO_read(f, buf, 1) ) {
4891         return (unsigned char) buf[0];
4892     }
4893     return EOF;
4894 }
4895
4896 #undef PerlIO_ungetc
4897 int
4898 PerlIO_ungetc(PerlIO *f, int ch)
4899 {
4900     dTHX;
4901     if (ch != EOF) {
4902         STDCHAR buf = ch;
4903         if (PerlIO_unread(f, &buf, 1) == 1)
4904             return ch;
4905     }
4906     return EOF;
4907 }
4908
4909 #undef PerlIO_putc
4910 int
4911 PerlIO_putc(PerlIO *f, int ch)
4912 {
4913     dTHX;
4914     STDCHAR buf = ch;
4915     return PerlIO_write(f, &buf, 1);
4916 }
4917
4918 #undef PerlIO_puts
4919 int
4920 PerlIO_puts(PerlIO *f, const char *s)
4921 {
4922     dTHX;
4923     return PerlIO_write(f, s, strlen(s));
4924 }
4925
4926 #undef PerlIO_rewind
4927 void
4928 PerlIO_rewind(PerlIO *f)
4929 {
4930     dTHX;
4931     PerlIO_seek(f, (Off_t) 0, SEEK_SET);
4932     PerlIO_clearerr(f);
4933 }
4934
4935 #undef PerlIO_vprintf
4936 int
4937 PerlIO_vprintf(PerlIO *f, const char *fmt, va_list ap)
4938 {
4939     dTHX;
4940     SV * const sv = newSVpvs("");
4941     const char *s;
4942     STRLEN len;
4943     SSize_t wrote;
4944 #ifdef NEED_VA_COPY
4945     va_list apc;
4946     Perl_va_copy(ap, apc);
4947     sv_vcatpvf(sv, fmt, &apc);
4948 #else
4949     sv_vcatpvf(sv, fmt, &ap);
4950 #endif
4951     s = SvPV_const(sv, len);
4952     wrote = PerlIO_write(f, s, len);
4953     SvREFCNT_dec(sv);
4954     return wrote;
4955 }
4956
4957 #undef PerlIO_printf
4958 int
4959 PerlIO_printf(PerlIO *f, const char *fmt, ...)
4960 {
4961     va_list ap;
4962     int result;
4963     va_start(ap, fmt);
4964     result = PerlIO_vprintf(f, fmt, ap);
4965     va_end(ap);
4966     return result;
4967 }
4968
4969 #undef PerlIO_stdoutf
4970 int
4971 PerlIO_stdoutf(const char *fmt, ...)
4972 {
4973     dTHX;
4974     va_list ap;
4975     int result;
4976     va_start(ap, fmt);
4977     result = PerlIO_vprintf(PerlIO_stdout(), fmt, ap);
4978     va_end(ap);
4979     return result;
4980 }
4981
4982 #undef PerlIO_tmpfile
4983 PerlIO *
4984 PerlIO_tmpfile(void)
4985 {
4986      dTHX;
4987      PerlIO *f = NULL;
4988 #ifdef WIN32
4989      const int fd = win32_tmpfd();
4990      if (fd >= 0)
4991           f = PerlIO_fdopen(fd, "w+b");
4992 #else /* WIN32 */
4993 #    if defined(HAS_MKSTEMP) && ! defined(VMS) && ! defined(OS2)
4994      SV * const sv = newSVpvs("/tmp/PerlIO_XXXXXX");
4995      /*
4996       * I have no idea how portable mkstemp() is ... NI-S
4997       */
4998      const int fd = mkstemp(SvPVX(sv));
4999      if (fd >= 0) {
5000           f = PerlIO_fdopen(fd, "w+");
5001           if (f)
5002                PerlIOBase(f)->flags |= PERLIO_F_TEMP;
5003           PerlLIO_unlink(SvPVX_const(sv));
5004           SvREFCNT_dec(sv);
5005      }
5006 #    else       /* !HAS_MKSTEMP, fallback to stdio tmpfile(). */
5007      FILE * const stdio = PerlSIO_tmpfile();
5008
5009      if (stdio) {
5010           if ((f = PerlIO_push(aTHX_(PerlIO_allocate(aTHX)),
5011                                PERLIO_FUNCS_CAST(&PerlIO_stdio),
5012                                "w+", NULL))) {
5013                PerlIOStdio * const s = PerlIOSelf(f, PerlIOStdio);
5014
5015                if (s)
5016                     s->stdio = stdio;
5017           }
5018      }
5019 #    endif /* else HAS_MKSTEMP */
5020 #endif /* else WIN32 */
5021      return f;
5022 }
5023
5024 #undef HAS_FSETPOS
5025 #undef HAS_FGETPOS
5026
5027 #endif                          /* USE_SFIO */
5028 #endif                          /* PERLIO_IS_STDIO */
5029
5030 /*======================================================================================*/
5031 /*
5032  * Now some functions in terms of above which may be needed even if we are
5033  * not in true PerlIO mode
5034  */
5035
5036 #ifndef HAS_FSETPOS
5037 #undef PerlIO_setpos
5038 int
5039 PerlIO_setpos(PerlIO *f, SV *pos)
5040 {
5041     dTHX;
5042     if (SvOK(pos)) {
5043         STRLEN len;
5044         const Off_t * const posn = (Off_t *) SvPV(pos, len);
5045         if (f && len == sizeof(Off_t))
5046             return PerlIO_seek(f, *posn, SEEK_SET);
5047     }
5048     SETERRNO(EINVAL, SS_IVCHAN);
5049     return -1;
5050 }
5051 #else
5052 #undef PerlIO_setpos
5053 int
5054 PerlIO_setpos(PerlIO *f, SV *pos)
5055 {
5056     dTHX;
5057     if (SvOK(pos)) {
5058         STRLEN len;
5059         Fpos_t * const fpos = (Fpos_t *) SvPV(pos, len);
5060         if (f && len == sizeof(Fpos_t)) {
5061 #if defined(USE_64_BIT_STDIO) && defined(USE_FSETPOS64)
5062             return fsetpos64(f, fpos);
5063 #else
5064             return fsetpos(f, fpos);
5065 #endif
5066         }
5067     }
5068     SETERRNO(EINVAL, SS_IVCHAN);
5069     return -1;
5070 }
5071 #endif
5072
5073 #ifndef HAS_FGETPOS
5074 #undef PerlIO_getpos
5075 int
5076 PerlIO_getpos(PerlIO *f, SV *pos)
5077 {
5078     dTHX;
5079     Off_t posn = PerlIO_tell(f);
5080     sv_setpvn(pos, (char *) &posn, sizeof(posn));
5081     return (posn == (Off_t) - 1) ? -1 : 0;
5082 }
5083 #else
5084 #undef PerlIO_getpos
5085 int
5086 PerlIO_getpos(PerlIO *f, SV *pos)
5087 {
5088     dTHX;
5089     Fpos_t fpos;
5090     int code;
5091 #if defined(USE_64_BIT_STDIO) && defined(USE_FSETPOS64)
5092     code = fgetpos64(f, &fpos);
5093 #else
5094     code = fgetpos(f, &fpos);
5095 #endif
5096     sv_setpvn(pos, (char *) &fpos, sizeof(fpos));
5097     return code;
5098 }
5099 #endif
5100
5101 #if (defined(PERLIO_IS_STDIO) || !defined(USE_SFIO)) && !defined(HAS_VPRINTF)
5102
5103 int
5104 vprintf(char *pat, char *args)
5105 {
5106     _doprnt(pat, args, stdout);
5107     return 0;                   /* wrong, but perl doesn't use the return
5108                                  * value */
5109 }
5110
5111 int
5112 vfprintf(FILE *fd, char *pat, char *args)
5113 {
5114     _doprnt(pat, args, fd);
5115     return 0;                   /* wrong, but perl doesn't use the return
5116                                  * value */
5117 }
5118
5119 #endif
5120
5121 #ifndef PerlIO_vsprintf
5122 int
5123 PerlIO_vsprintf(char *s, int n, const char *fmt, va_list ap)
5124 {
5125     dVAR;
5126     const int val = vsprintf(s, fmt, ap);
5127     if (n >= 0) {
5128         if (strlen(s) >= (STRLEN) n) {
5129             dTHX;
5130             (void) PerlIO_puts(Perl_error_log,
5131                                "panic: sprintf overflow - memory corrupted!\n");
5132             my_exit(1);
5133         }
5134     }
5135     return val;
5136 }
5137 #endif
5138
5139 #ifndef PerlIO_sprintf
5140 int
5141 PerlIO_sprintf(char *s, int n, const char *fmt, ...)
5142 {
5143     va_list ap;
5144     int result;
5145     va_start(ap, fmt);
5146     result = PerlIO_vsprintf(s, n, fmt, ap);
5147     va_end(ap);
5148     return result;
5149 }
5150 #endif
5151
5152 /*
5153  * Local variables:
5154  * c-indentation-style: bsd
5155  * c-basic-offset: 4
5156  * indent-tabs-mode: t
5157  * End:
5158  *
5159  * ex: set ts=8 sts=4 sw=4 noet:
5160  */