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