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