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