2 * perlio.c Copyright (c) 1996-2002, 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.
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.
13 * If we have ActivePerl-like PERL_IMPLICIT_SYS then we need a dTHX to get
14 * at the dispatch tables, even when we do not need it for other reasons.
15 * Invent a dSYS macro to abstract this out
17 #ifdef PERL_IMPLICIT_SYS
30 #define PERLIO_NOT_STDIO 0
31 #if !defined(PERLIO_IS_STDIO) && !defined(USE_SFIO)
37 * This file provides those parts of PerlIO abstraction
38 * which are not #defined in perlio.h.
39 * Which these are depends on various Configure #ifdef's
43 #define PERL_IN_PERLIO_C
46 #ifdef PERL_IMPLICIT_CONTEXT
54 /* Missing proto on LynxOS */
58 /* Call the callback or PerlIOBase, and return failure. */
59 #define Perl_PerlIO_or_Base(f, callback, base, failure, args) \
60 if (PerlIOValid(f)) { \
61 PerlIO_funcs *tab = PerlIOBase(f)->tab; \
62 if (tab && tab->callback) \
63 return (*tab->callback) args; \
65 return PerlIOBase_ ## base args; \
68 SETERRNO(EBADF, SS_IVCHAN); \
71 /* Call the callback or fail, and return failure. */
72 #define Perl_PerlIO_or_fail(f, callback, failure, args) \
73 if (PerlIOValid(f)) { \
74 PerlIO_funcs *tab = PerlIOBase(f)->tab; \
75 if (tab && tab->callback) \
76 return (*tab->callback) args; \
77 SETERRNO(EINVAL, LIB_INVARG); \
80 SETERRNO(EBADF, SS_IVCHAN); \
83 /* Call the callback or PerlIOBase, and be void. */
84 #define Perl_PerlIO_or_Base_void(f, callback, base, args) \
85 if (PerlIOValid(f)) { \
86 PerlIO_funcs *tab = PerlIOBase(f)->tab; \
87 if (tab && tab->callback) \
88 (*tab->callback) args; \
90 PerlIOBase_ ## base args; \
93 SETERRNO(EBADF, SS_IVCHAN)
95 /* Call the callback or fail, and be void. */
96 #define Perl_PerlIO_or_fail_void(f, callback, args) \
97 if (PerlIOValid(f)) { \
98 PerlIO_funcs *tab = PerlIOBase(f)->tab; \
99 if (tab && tab->callback) \
100 (*tab->callback) args; \
102 SETERRNO(EINVAL, LIB_INVARG); \
105 SETERRNO(EBADF, SS_IVCHAN)
108 perlsio_binmode(FILE *fp, int iotype, int mode)
111 * This used to be contents of do_binmode in doio.c
114 # if defined(atarist) || defined(__MINT__)
117 ((FILE *) fp)->_flag |= _IOBIN;
119 ((FILE *) fp)->_flag &= ~_IOBIN;
126 if (PerlLIO_setmode(fp, mode) != -1) {
128 if (PerlLIO_setmode(fileno(fp), mode) != -1) {
130 # if defined(WIN32) && defined(__BORLANDC__)
132 * The translation mode of the stream is maintained independent of
133 * the translation mode of the fd in the Borland RTL (heavy
134 * digging through their runtime sources reveal). User has to set
135 * the mode explicitly for the stream (though they don't document
136 * this anywhere). GSAR 97-5-24
142 fp->flags &= ~_F_BIN;
150 # if defined(USEMYBINMODE)
152 if (my_binmode(fp, iotype, mode) != FALSE)
163 #define O_ACCMODE 3 /* Assume traditional implementation */
167 PerlIO_intmode2str(int rawmode, char *mode, int *writing)
169 int result = rawmode & O_ACCMODE;
174 ptype = IoTYPE_RDONLY;
177 ptype = IoTYPE_WRONLY;
185 *writing = (result != O_RDONLY);
187 if (result == O_RDONLY) {
191 else if (rawmode & O_APPEND) {
193 if (result != O_WRONLY)
198 if (result == O_WRONLY)
205 if (rawmode & O_BINARY)
211 #ifndef PERLIO_LAYERS
213 PerlIO_apply_layers(pTHX_ PerlIO *f, const char *mode, const char *names)
215 if (!names || !*names
216 || strEQ(names, ":crlf")
217 || strEQ(names, ":raw")
218 || strEQ(names, ":bytes")
222 Perl_croak(aTHX_ "Cannot apply \"%s\" in non-PerlIO perl", names);
230 PerlIO_destruct(pTHX)
235 PerlIO_binmode(pTHX_ PerlIO *fp, int iotype, int mode, const char *names)
240 return perlsio_binmode(fp, iotype, mode);
245 PerlIO_fdupopen(pTHX_ PerlIO *f, CLONE_PARAMS *param, int flags)
250 #ifdef PERL_IMPLICIT_SYS
251 return PerlSIO_fdupopen(f);
254 return win32_fdupopen(f);
257 int fd = PerlLIO_dup(PerlIO_fileno(f));
260 int omode = fcntl(fd, F_GETFL);
262 omode = djgpp_get_stream_mode(f);
264 PerlIO_intmode2str(omode,mode,NULL);
265 /* the r+ is a hack */
266 return PerlIO_fdopen(fd, mode);
271 SETERRNO(EBADF, SS_IVCHAN);
281 * De-mux PerlIO_openn() into fdopen, freopen and fopen type entries
285 PerlIO_openn(pTHX_ const char *layers, const char *mode, int fd,
286 int imode, int perm, PerlIO *old, int narg, SV **args)
290 Perl_croak(aTHX_ "More than one argument to open");
292 if (*args == &PL_sv_undef)
293 return PerlIO_tmpfile();
295 char *name = SvPV_nolen(*args);
296 if (*mode == IoTYPE_NUMERIC) {
297 fd = PerlLIO_open3(name, imode, perm);
299 return PerlIO_fdopen(fd, (char *) mode + 1);
302 return PerlIO_reopen(name, mode, old);
305 return PerlIO_open(name, mode);
310 return PerlIO_fdopen(fd, (char *) mode);
315 XS(XS_PerlIO__Layer__find)
319 Perl_croak(aTHX_ "Usage class->find(name[,load])");
321 char *name = SvPV_nolen(ST(1));
322 ST(0) = (strEQ(name, "crlf")
323 || strEQ(name, "raw")) ? &PL_sv_yes : &PL_sv_undef;
330 Perl_boot_core_PerlIO(pTHX)
332 newXS("PerlIO::Layer::find", XS_PerlIO__Layer__find, __FILE__);
338 #ifdef PERLIO_IS_STDIO
344 * Does nothing (yet) except force this file to be included in perl
345 * binary. That allows this file to force inclusion of other functions
346 * that may be required by loadable extensions e.g. for
347 * FileHandle::tmpfile
351 #undef PerlIO_tmpfile
358 #else /* PERLIO_IS_STDIO */
366 * This section is just to make sure these functions get pulled in from
370 #undef PerlIO_tmpfile
381 * Force this file to be included in perl binary. Which allows this
382 * file to force inclusion of other functions that may be required by
383 * loadable extensions e.g. for FileHandle::tmpfile
387 * Hack sfio does its own 'autoflush' on stdout in common cases. Flush
388 * results in a lot of lseek()s to regular files and lot of small
391 sfset(sfstdout, SF_SHARE, 0);
394 /* This is not the reverse of PerlIO_exportFILE(), PerlIO_releaseFILE() is. */
396 PerlIO_importFILE(FILE *stdio, const char *mode)
398 int fd = fileno(stdio);
399 if (!mode || !*mode) {
402 return PerlIO_fdopen(fd, mode);
406 PerlIO_findFILE(PerlIO *pio)
408 int fd = PerlIO_fileno(pio);
409 FILE *f = fdopen(fd, "r+");
411 if (!f && errno == EINVAL)
413 if (!f && errno == EINVAL)
420 /*======================================================================================*/
422 * Implement all the PerlIO interface ourselves.
428 * We _MUST_ have <unistd.h> if we are using lseek() and may have large
435 #include <sys/mman.h>
439 * Why is this here - not in perlio.h? RMB
441 void PerlIO_debug(const char *fmt, ...)
442 __attribute__format__(__printf__, 1, 2);
445 PerlIO_debug(const char *fmt, ...)
452 char *s = PerlEnv_getenv("PERLIO_DEBUG");
454 dbg = PerlLIO_open3(s, O_WRONLY | O_CREAT | O_APPEND, 0666);
461 /* Use fixed buffer as sv_catpvf etc. needs SVs */
465 s = CopFILE(PL_curcop);
468 sprintf(buffer, "%s:%" IVdf " ", s, (IV) CopLINE(PL_curcop));
469 len = strlen(buffer);
470 vsprintf(buffer+len, fmt, ap);
471 PerlLIO_write(dbg, buffer, strlen(buffer));
473 SV *sv = newSVpvn("", 0);
476 s = CopFILE(PL_curcop);
479 Perl_sv_catpvf(aTHX_ sv, "%s:%" IVdf " ", s,
480 (IV) CopLINE(PL_curcop));
481 Perl_sv_vcatpvf(aTHX_ sv, fmt, &ap);
484 PerlLIO_write(dbg, s, len);
491 /*--------------------------------------------------------------------------------------*/
494 * Inner level routines
498 * Table of pointers to the PerlIO structs (malloc'ed)
500 #define PERLIO_TABLE_SIZE 64
503 PerlIO_allocate(pTHX)
506 * Find a free slot in the table, allocating new table as necessary
511 while ((f = *last)) {
513 last = (PerlIO **) (f);
514 for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
520 Newz('I',f,PERLIO_TABLE_SIZE,PerlIO);
528 #undef PerlIO_fdupopen
530 PerlIO_fdupopen(pTHX_ PerlIO *f, CLONE_PARAMS *param, int flags)
532 if (PerlIOValid(f)) {
533 PerlIO_funcs *tab = PerlIOBase(f)->tab;
534 PerlIO_debug("fdupopen f=%p param=%p\n",(void*)f,(void*)param);
536 return (*tab->Dup)(aTHX_ PerlIO_allocate(aTHX), f, param, flags);
538 return PerlIOBase_dup(aTHX_ PerlIO_allocate(aTHX), f, param, flags);
542 SETERRNO(EBADF, SS_IVCHAN);
548 PerlIO_cleantable(pTHX_ PerlIO **tablep)
550 PerlIO *table = *tablep;
553 PerlIO_cleantable(aTHX_(PerlIO **) & (table[0]));
554 for (i = PERLIO_TABLE_SIZE - 1; i > 0; i--) {
555 PerlIO *f = table + i;
567 PerlIO_list_alloc(pTHX)
570 Newz('L', list, 1, PerlIO_list_t);
576 PerlIO_list_free(pTHX_ PerlIO_list_t *list)
579 if (--list->refcnt == 0) {
582 for (i = 0; i < list->cur; i++) {
583 if (list->array[i].arg)
584 SvREFCNT_dec(list->array[i].arg);
586 Safefree(list->array);
594 PerlIO_list_push(pTHX_ PerlIO_list_t *list, PerlIO_funcs *funcs, SV *arg)
597 if (list->cur >= list->len) {
600 Renew(list->array, list->len, PerlIO_pair_t);
602 New('l', list->array, list->len, PerlIO_pair_t);
604 p = &(list->array[list->cur++]);
606 if ((p->arg = arg)) {
612 PerlIO_clone_list(pTHX_ PerlIO_list_t *proto, CLONE_PARAMS *param)
614 PerlIO_list_t *list = (PerlIO_list_t *) NULL;
617 list = PerlIO_list_alloc(aTHX);
618 for (i=0; i < proto->cur; i++) {
620 if (proto->array[i].arg)
621 arg = PerlIO_sv_dup(aTHX_ proto->array[i].arg,param);
622 PerlIO_list_push(aTHX_ list, proto->array[i].funcs, arg);
629 PerlIO_clone(pTHX_ PerlInterpreter *proto, CLONE_PARAMS *param)
632 PerlIO **table = &proto->Iperlio;
635 PL_known_layers = PerlIO_clone_list(aTHX_ proto->Iknown_layers, param);
636 PL_def_layerlist = PerlIO_clone_list(aTHX_ proto->Idef_layerlist, param);
637 PerlIO_allocate(aTHX); /* root slot is never used */
638 PerlIO_debug("Clone %p from %p\n",aTHX,proto);
639 while ((f = *table)) {
641 table = (PerlIO **) (f++);
642 for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
644 (void) fp_dup(f, 0, param);
653 PerlIO_destruct(pTHX)
655 PerlIO **table = &PL_perlio;
658 PerlIO_debug("Destruct %p\n",aTHX);
660 while ((f = *table)) {
662 table = (PerlIO **) (f++);
663 for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
667 if (l->tab->kind & PERLIO_K_DESTRUCT) {
668 PerlIO_debug("Destruct popping %s\n", l->tab->name);
682 PerlIO_pop(pTHX_ PerlIO *f)
686 PerlIO_debug("PerlIO_pop f=%p %s\n", (void*)f, l->tab->name);
687 if (l->tab->Popped) {
689 * If popped returns non-zero do not free its layer structure
690 * it has either done so itself, or it is shared and still in
693 if ((*l->tab->Popped) (aTHX_ f) != 0)
701 /* Return as an array the stack of layers on a filehandle. Note that
702 * the stack is returned top-first in the array, and there are three
703 * times as many array elements as there are layers in the stack: the
704 * first element of a layer triplet is the name, the second one is the
705 * arguments, and the third one is the flags. */
708 PerlIO_get_layers(pTHX_ PerlIO *f)
712 if (PerlIOValid(f)) {
713 PerlIOl *l = PerlIOBase(f);
716 SV *name = l->tab && l->tab->name ?
717 newSVpv(l->tab->name, 0) : &PL_sv_undef;
718 SV *arg = l->tab && l->tab->Getarg ?
719 (*l->tab->Getarg)(aTHX_ &l, 0, 0) : &PL_sv_undef;
722 av_push(av, newSViv((IV)l->flags));
730 /*--------------------------------------------------------------------------------------*/
732 * XS Interface for perl code
736 PerlIO_find_layer(pTHX_ const char *name, STRLEN len, int load)
739 if ((SSize_t) len <= 0)
741 for (i = 0; i < PL_known_layers->cur; i++) {
742 PerlIO_funcs *f = PL_known_layers->array[i].funcs;
743 if (memEQ(f->name, name, len) && f->name[len] == 0) {
744 PerlIO_debug("%.*s => %p\n", (int) len, name, (void*)f);
748 if (load && PL_subname && PL_def_layerlist
749 && PL_def_layerlist->cur >= 2) {
750 if (PL_in_load_module) {
751 Perl_croak(aTHX_ "Recursive call to Perl_load_module in PerlIO_find_layer");
754 SV *pkgsv = newSVpvn("PerlIO", 6);
755 SV *layer = newSVpvn(name, len);
756 CV *cv = get_cv("PerlIO::Layer::NoWarnings", FALSE);
758 SAVEINT(PL_in_load_module);
760 SAVESPTR(PL_warnhook);
761 PL_warnhook = (SV *) cv;
765 * The two SVs are magically freed by load_module
767 Perl_load_module(aTHX_ 0, pkgsv, Nullsv, layer, Nullsv);
770 return PerlIO_find_layer(aTHX_ name, len, 0);
773 PerlIO_debug("Cannot find %.*s\n", (int) len, name);
777 #ifdef USE_ATTRIBUTES_FOR_PERLIO
780 perlio_mg_set(pTHX_ SV *sv, MAGIC *mg)
783 IO *io = GvIOn((GV *) SvRV(sv));
784 PerlIO *ifp = IoIFP(io);
785 PerlIO *ofp = IoOFP(io);
786 Perl_warn(aTHX_ "set %" SVf " %p %p %p", sv, io, ifp, ofp);
792 perlio_mg_get(pTHX_ SV *sv, MAGIC *mg)
795 IO *io = GvIOn((GV *) SvRV(sv));
796 PerlIO *ifp = IoIFP(io);
797 PerlIO *ofp = IoOFP(io);
798 Perl_warn(aTHX_ "get %" SVf " %p %p %p", sv, io, ifp, ofp);
804 perlio_mg_clear(pTHX_ SV *sv, MAGIC *mg)
806 Perl_warn(aTHX_ "clear %" SVf, sv);
811 perlio_mg_free(pTHX_ SV *sv, MAGIC *mg)
813 Perl_warn(aTHX_ "free %" SVf, sv);
817 MGVTBL perlio_vtab = {
825 XS(XS_io_MODIFY_SCALAR_ATTRIBUTES)
828 SV *sv = SvRV(ST(1));
833 sv_magic(sv, (SV *) av, PERL_MAGIC_ext, NULL, 0);
835 mg = mg_find(sv, PERL_MAGIC_ext);
836 mg->mg_virtual = &perlio_vtab;
838 Perl_warn(aTHX_ "attrib %" SVf, sv);
839 for (i = 2; i < items; i++) {
841 const char *name = SvPV(ST(i), len);
842 SV *layer = PerlIO_find_layer(aTHX_ name, len, 1);
844 av_push(av, SvREFCNT_inc(layer));
855 #endif /* USE_ATTIBUTES_FOR_PERLIO */
858 PerlIO_tab_sv(pTHX_ PerlIO_funcs *tab)
860 HV *stash = gv_stashpv("PerlIO::Layer", TRUE);
861 SV *sv = sv_bless(newRV_noinc(newSViv(PTR2IV(tab))), stash);
865 XS(XS_PerlIO__Layer__NoWarnings)
867 /* This is used as a %SIG{__WARN__} handler to supress warnings
868 during loading of layers.
872 PerlIO_debug("warning:%s\n",SvPV_nolen(ST(0)));
876 XS(XS_PerlIO__Layer__find)
880 Perl_croak(aTHX_ "Usage class->find(name[,load])");
883 char *name = SvPV(ST(1), len);
884 bool load = (items > 2) ? SvTRUE(ST(2)) : 0;
885 PerlIO_funcs *layer = PerlIO_find_layer(aTHX_ name, len, load);
887 (layer) ? sv_2mortal(PerlIO_tab_sv(aTHX_ layer)) :
894 PerlIO_define_layer(pTHX_ PerlIO_funcs *tab)
896 if (!PL_known_layers)
897 PL_known_layers = PerlIO_list_alloc(aTHX);
898 PerlIO_list_push(aTHX_ PL_known_layers, tab, Nullsv);
899 PerlIO_debug("define %s %p\n", tab->name, (void*)tab);
903 PerlIO_parse_layers(pTHX_ PerlIO_list_t *av, const char *names)
906 const char *s = names;
908 while (isSPACE(*s) || *s == ':')
913 const char *as = Nullch;
915 if (!isIDFIRST(*s)) {
917 * Message is consistent with how attribute lists are
918 * passed. Even though this means "foo : : bar" is
919 * seen as an invalid separator character.
921 char q = ((*s == '\'') ? '"' : '\'');
922 if (ckWARN(WARN_LAYER))
923 Perl_warner(aTHX_ packWARN(WARN_LAYER),
924 "Invalid separator character %c%c%c in PerlIO layer specification %s",
926 SETERRNO(EINVAL, LIB_INVARG);
931 } while (isALNUM(*e));
947 * It's a nul terminated string, not allowed
948 * to \ the terminating null. Anything other
949 * character is passed over.
959 if (ckWARN(WARN_LAYER))
960 Perl_warner(aTHX_ packWARN(WARN_LAYER),
961 "Argument list not closed for PerlIO layer \"%.*s\"",
973 bool warn_layer = ckWARN(WARN_LAYER);
974 PerlIO_funcs *layer =
975 PerlIO_find_layer(aTHX_ s, llen, 1);
977 PerlIO_list_push(aTHX_ av, layer,
984 Perl_warner(aTHX_ packWARN(WARN_LAYER), "Unknown PerlIO layer \"%.*s\"",
997 PerlIO_default_buffer(pTHX_ PerlIO_list_t *av)
999 PerlIO_funcs *tab = &PerlIO_perlio;
1000 #ifdef PERLIO_USING_CRLF
1003 if (PerlIO_stdio.Set_ptrcnt)
1004 tab = &PerlIO_stdio;
1006 PerlIO_debug("Pushing %s\n", tab->name);
1007 PerlIO_list_push(aTHX_ av, PerlIO_find_layer(aTHX_ tab->name, 0, 0),
1012 PerlIO_arg_fetch(PerlIO_list_t *av, IV n)
1014 return av->array[n].arg;
1018 PerlIO_layer_fetch(pTHX_ PerlIO_list_t *av, IV n, PerlIO_funcs *def)
1020 if (n >= 0 && n < av->cur) {
1021 PerlIO_debug("Layer %" IVdf " is %s\n", n,
1022 av->array[n].funcs->name);
1023 return av->array[n].funcs;
1026 Perl_croak(aTHX_ "panic: PerlIO layer array corrupt");
1031 PerlIOPop_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
1033 if (PerlIOValid(f)) {
1035 PerlIO_pop(aTHX_ f);
1041 PerlIO_funcs PerlIO_remove = {
1042 sizeof(PerlIO_funcs),
1045 PERLIO_K_DUMMY | PERLIO_K_UTF8,
1063 NULL, /* get_base */
1064 NULL, /* get_bufsiz */
1067 NULL, /* set_ptrcnt */
1071 PerlIO_default_layers(pTHX)
1073 if (!PL_def_layerlist) {
1074 const char *s = (PL_tainting) ? Nullch : PerlEnv_getenv("PERLIO");
1075 PerlIO_funcs *osLayer = &PerlIO_unix;
1076 PL_def_layerlist = PerlIO_list_alloc(aTHX);
1077 PerlIO_define_layer(aTHX_ & PerlIO_unix);
1079 PerlIO_define_layer(aTHX_ & PerlIO_win32);
1081 osLayer = &PerlIO_win32;
1084 PerlIO_define_layer(aTHX_ & PerlIO_raw);
1085 PerlIO_define_layer(aTHX_ & PerlIO_perlio);
1086 PerlIO_define_layer(aTHX_ & PerlIO_stdio);
1087 PerlIO_define_layer(aTHX_ & PerlIO_crlf);
1089 PerlIO_define_layer(aTHX_ & PerlIO_mmap);
1091 PerlIO_define_layer(aTHX_ & PerlIO_utf8);
1092 PerlIO_define_layer(aTHX_ & PerlIO_remove);
1093 PerlIO_define_layer(aTHX_ & PerlIO_byte);
1094 PerlIO_list_push(aTHX_ PL_def_layerlist,
1095 PerlIO_find_layer(aTHX_ osLayer->name, 0, 0),
1098 PerlIO_parse_layers(aTHX_ PL_def_layerlist, s);
1101 PerlIO_default_buffer(aTHX_ PL_def_layerlist);
1104 if (PL_def_layerlist->cur < 2) {
1105 PerlIO_default_buffer(aTHX_ PL_def_layerlist);
1107 return PL_def_layerlist;
1111 Perl_boot_core_PerlIO(pTHX)
1113 #ifdef USE_ATTRIBUTES_FOR_PERLIO
1114 newXS("io::MODIFY_SCALAR_ATTRIBUTES", XS_io_MODIFY_SCALAR_ATTRIBUTES,
1117 newXS("PerlIO::Layer::find", XS_PerlIO__Layer__find, __FILE__);
1118 newXS("PerlIO::Layer::NoWarnings", XS_PerlIO__Layer__NoWarnings, __FILE__);
1122 PerlIO_default_layer(pTHX_ I32 n)
1124 PerlIO_list_t *av = PerlIO_default_layers(aTHX);
1127 return PerlIO_layer_fetch(aTHX_ av, n, &PerlIO_stdio);
1130 #define PerlIO_default_top() PerlIO_default_layer(aTHX_ -1)
1131 #define PerlIO_default_btm() PerlIO_default_layer(aTHX_ 0)
1134 PerlIO_stdstreams(pTHX)
1137 PerlIO_allocate(aTHX);
1138 PerlIO_fdopen(0, "Ir" PERLIO_STDTEXT);
1139 PerlIO_fdopen(1, "Iw" PERLIO_STDTEXT);
1140 PerlIO_fdopen(2, "Iw" PERLIO_STDTEXT);
1145 PerlIO_push(pTHX_ PerlIO *f, PerlIO_funcs *tab, const char *mode, SV *arg)
1147 if (tab->fsize != sizeof(PerlIO_funcs)) {
1149 Perl_croak(aTHX_ "Layer does not match this perl");
1153 if (tab->size < sizeof(PerlIOl)) {
1156 /* Real layer with a data area */
1157 Newc('L',l,tab->size,char,PerlIOl);
1159 Zero(l, tab->size, char);
1163 PerlIO_debug("PerlIO_push f=%p %s %s %p\n", (void*)f, tab->name,
1164 (mode) ? mode : "(Null)", (void*)arg);
1165 if (*l->tab->Pushed &&
1166 (*l->tab->Pushed) (aTHX_ f, mode, arg, tab) != 0) {
1167 PerlIO_pop(aTHX_ f);
1173 /* Pseudo-layer where push does its own stack adjust */
1174 PerlIO_debug("PerlIO_push f=%p %s %s %p\n", (void*)f, tab->name,
1175 (mode) ? mode : "(Null)", (void*)arg);
1177 (*tab->Pushed) (aTHX_ f, mode, arg, tab) != 0) {
1185 PerlIOBase_binmode(pTHX_ PerlIO *f)
1187 if (PerlIOValid(f)) {
1188 /* Is layer suitable for raw stream ? */
1189 if (PerlIOBase(f)->tab->kind & PERLIO_K_RAW) {
1190 /* Yes - turn off UTF-8-ness, to undo UTF-8 locale effects */
1191 PerlIOBase(f)->flags &= ~PERLIO_F_UTF8;
1194 /* Not suitable - pop it */
1195 PerlIO_pop(aTHX_ f);
1203 PerlIORaw_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
1206 if (PerlIOValid(f)) {
1211 * Strip all layers that are not suitable for a raw stream
1214 while (t && (l = *t)) {
1215 if (l->tab->Binmode) {
1216 /* Has a handler - normal case */
1217 if ((*l->tab->Binmode)(aTHX_ f) == 0) {
1219 /* Layer still there - move down a layer */
1228 /* No handler - pop it */
1229 PerlIO_pop(aTHX_ t);
1232 if (PerlIOValid(f)) {
1233 PerlIO_debug(":raw f=%p :%s\n", (void*)f, PerlIOBase(f)->tab->name);
1241 PerlIO_apply_layera(pTHX_ PerlIO *f, const char *mode,
1242 PerlIO_list_t *layers, IV n, IV max)
1246 PerlIO_funcs *tab = PerlIO_layer_fetch(aTHX_ layers, n, NULL);
1248 if (!PerlIO_push(aTHX_ f, tab, mode, PerlIOArg)) {
1259 PerlIO_apply_layers(pTHX_ PerlIO *f, const char *mode, const char *names)
1263 PerlIO_list_t *layers = PerlIO_list_alloc(aTHX);
1264 code = PerlIO_parse_layers(aTHX_ layers, names);
1266 code = PerlIO_apply_layera(aTHX_ f, mode, layers, 0, layers->cur);
1268 PerlIO_list_free(aTHX_ layers);
1274 /*--------------------------------------------------------------------------------------*/
1276 * Given the abstraction above the public API functions
1280 PerlIO_binmode(pTHX_ PerlIO *f, int iotype, int mode, const char *names)
1282 PerlIO_debug("PerlIO_binmode f=%p %s %c %x %s\n",
1283 (void*)f, PerlIOBase(f)->tab->name, iotype, mode,
1284 (names) ? names : "(Null)");
1286 /* Do not flush etc. if (e.g.) switching encodings.
1287 if a pushed layer knows it needs to flush lower layers
1288 (for example :unix which is never going to call them)
1289 it can do the flush when it is pushed.
1291 return PerlIO_apply_layers(aTHX_ f, NULL, names) == 0 ? TRUE : FALSE;
1294 /* Fake 5.6 legacy of using this call to turn ON O_TEXT */
1295 #ifdef PERLIO_USING_CRLF
1296 /* Legacy binmode only has meaning if O_TEXT has a value distinct from
1297 O_BINARY so we can look for it in mode.
1299 if (!(mode & O_BINARY)) {
1301 /* FIXME?: Looking down the layer stack seems wrong,
1302 but is a way of reaching past (say) an encoding layer
1303 to flip CRLF-ness of the layer(s) below
1306 /* Perhaps we should turn on bottom-most aware layer
1307 e.g. Ilya's idea that UNIX TTY could serve
1309 if (PerlIOBase(f)->tab->kind & PERLIO_K_CANCRLF) {
1310 if (!(PerlIOBase(f)->flags & PERLIO_F_CRLF)) {
1311 /* Not in text mode - flush any pending stuff and flip it */
1313 PerlIOBase(f)->flags |= PERLIO_F_CRLF;
1315 /* Only need to turn it on in one layer so we are done */
1320 /* Not finding a CRLF aware layer presumably means we are binary
1321 which is not what was requested - so we failed
1322 We _could_ push :crlf layer but so could caller
1327 /* Legacy binmode is now _defined_ as being equivalent to pushing :raw
1328 So code that used to be here is now in PerlIORaw_pushed().
1330 return PerlIO_push(aTHX_ f, &PerlIO_raw, Nullch, Nullsv) ? TRUE : FALSE;
1335 PerlIO__close(pTHX_ PerlIO *f)
1337 if (PerlIOValid(f)) {
1338 PerlIO_funcs *tab = PerlIOBase(f)->tab;
1339 if (tab && tab->Close)
1340 return (*tab->Close)(aTHX_ f);
1342 return PerlIOBase_close(aTHX_ f);
1345 SETERRNO(EBADF, SS_IVCHAN);
1351 Perl_PerlIO_close(pTHX_ PerlIO *f)
1353 int code = PerlIO__close(aTHX_ f);
1354 while (PerlIOValid(f)) {
1355 PerlIO_pop(aTHX_ f);
1361 Perl_PerlIO_fileno(pTHX_ PerlIO *f)
1363 Perl_PerlIO_or_Base(f, Fileno, fileno, -1, (aTHX_ f));
1367 PerlIO_context_layers(pTHX_ const char *mode)
1369 const char *type = NULL;
1371 * Need to supply default layer info from open.pm
1374 SV *layers = PL_curcop->cop_io;
1377 type = SvPV(layers, len);
1378 if (type && mode[0] != 'r') {
1380 * Skip to write part
1382 const char *s = strchr(type, 0);
1383 if (s && (STRLEN)(s - type) < len) {
1392 static PerlIO_funcs *
1393 PerlIO_layer_from_ref(pTHX_ SV *sv)
1396 * For any scalar type load the handler which is bundled with perl
1398 if (SvTYPE(sv) < SVt_PVAV)
1399 return PerlIO_find_layer(aTHX_ "scalar", 6, 1);
1402 * For other types allow if layer is known but don't try and load it
1404 switch (SvTYPE(sv)) {
1406 return PerlIO_find_layer(aTHX_ "Array", 5, 0);
1408 return PerlIO_find_layer(aTHX_ "Hash", 4, 0);
1410 return PerlIO_find_layer(aTHX_ "Code", 4, 0);
1412 return PerlIO_find_layer(aTHX_ "Glob", 4, 0);
1418 PerlIO_resolve_layers(pTHX_ const char *layers,
1419 const char *mode, int narg, SV **args)
1421 PerlIO_list_t *def = PerlIO_default_layers(aTHX);
1424 PerlIO_stdstreams(aTHX);
1428 * If it is a reference but not an object see if we have a handler
1431 if (SvROK(arg) && !sv_isobject(arg)) {
1432 PerlIO_funcs *handler = PerlIO_layer_from_ref(aTHX_ SvRV(arg));
1434 def = PerlIO_list_alloc(aTHX);
1435 PerlIO_list_push(aTHX_ def, handler, &PL_sv_undef);
1439 * Don't fail if handler cannot be found :via(...) etc. may do
1440 * something sensible else we will just stringfy and open
1446 layers = PerlIO_context_layers(aTHX_ mode);
1447 if (layers && *layers) {
1451 av = PerlIO_list_alloc(aTHX);
1452 for (i = 0; i < def->cur; i++) {
1453 PerlIO_list_push(aTHX_ av, def->array[i].funcs,
1460 if (PerlIO_parse_layers(aTHX_ av, layers) == 0) {
1464 PerlIO_list_free(aTHX_ av);
1465 return (PerlIO_list_t *) NULL;
1476 PerlIO_openn(pTHX_ const char *layers, const char *mode, int fd,
1477 int imode, int perm, PerlIO *f, int narg, SV **args)
1479 if (!f && narg == 1 && *args == &PL_sv_undef) {
1480 if ((f = PerlIO_tmpfile())) {
1482 layers = PerlIO_context_layers(aTHX_ mode);
1483 if (layers && *layers)
1484 PerlIO_apply_layers(aTHX_ f, mode, layers);
1488 PerlIO_list_t *layera = NULL;
1490 PerlIO_funcs *tab = NULL;
1491 if (PerlIOValid(f)) {
1493 * This is "reopen" - it is not tested as perl does not use it
1497 layera = PerlIO_list_alloc(aTHX);
1499 SV *arg = (l->tab->Getarg)
1500 ? (*l->tab->Getarg) (aTHX_ &l, NULL, 0)
1502 PerlIO_list_push(aTHX_ layera, l->tab, arg);
1503 l = *PerlIONext(&l);
1507 layera = PerlIO_resolve_layers(aTHX_ layers, mode, narg, args);
1513 * Start at "top" of layer stack
1515 n = layera->cur - 1;
1517 PerlIO_funcs *t = PerlIO_layer_fetch(aTHX_ layera, n, NULL);
1526 * Found that layer 'n' can do opens - call it
1528 if (narg > 1 && !(tab->kind & PERLIO_K_MULTIARG)) {
1529 Perl_croak(aTHX_ "More than one argument to open(,':%s')",tab->name);
1531 PerlIO_debug("openn(%s,'%s','%s',%d,%x,%o,%p,%d,%p)\n",
1532 tab->name, layers, mode, fd, imode, perm,
1533 (void*)f, narg, (void*)args);
1535 f = (*tab->Open) (aTHX_ tab, layera, n, mode, fd, imode, perm,
1538 SETERRNO(EINVAL, LIB_INVARG);
1542 if (n + 1 < layera->cur) {
1544 * More layers above the one that we used to open -
1547 if (PerlIO_apply_layera(aTHX_ f, mode, layera, n + 1, layera->cur) != 0) {
1548 /* If pushing layers fails close the file */
1555 PerlIO_list_free(aTHX_ layera);
1562 Perl_PerlIO_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
1564 Perl_PerlIO_or_Base(f, Read, read, -1, (aTHX_ f, vbuf, count));
1568 Perl_PerlIO_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
1570 Perl_PerlIO_or_Base(f, Unread, unread, -1, (aTHX_ f, vbuf, count));
1574 Perl_PerlIO_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
1576 Perl_PerlIO_or_fail(f, Write, -1, (aTHX_ f, vbuf, count));
1580 Perl_PerlIO_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
1582 Perl_PerlIO_or_fail(f, Seek, -1, (aTHX_ f, offset, whence));
1586 Perl_PerlIO_tell(pTHX_ PerlIO *f)
1588 Perl_PerlIO_or_fail(f, Tell, -1, (aTHX_ f));
1592 Perl_PerlIO_flush(pTHX_ PerlIO *f)
1596 PerlIO_funcs *tab = PerlIOBase(f)->tab;
1598 if (tab && tab->Flush)
1599 return (*tab->Flush) (aTHX_ f);
1601 return 0; /* If no Flush defined, silently succeed. */
1604 PerlIO_debug("Cannot flush f=%p\n", (void*)f);
1605 SETERRNO(EBADF, SS_IVCHAN);
1611 * Is it good API design to do flush-all on NULL, a potentially
1612 * errorneous input? Maybe some magical value (PerlIO*
1613 * PERLIO_FLUSH_ALL = (PerlIO*)-1;)? Yes, stdio does similar
1614 * things on fflush(NULL), but should we be bound by their design
1617 PerlIO **table = &PL_perlio;
1619 while ((f = *table)) {
1621 table = (PerlIO **) (f++);
1622 for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
1623 if (*f && PerlIO_flush(f) != 0)
1633 PerlIOBase_flush_linebuf(pTHX)
1635 PerlIO **table = &PL_perlio;
1637 while ((f = *table)) {
1639 table = (PerlIO **) (f++);
1640 for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
1643 flags & (PERLIO_F_LINEBUF | PERLIO_F_CANWRITE))
1644 == (PERLIO_F_LINEBUF | PERLIO_F_CANWRITE))
1652 Perl_PerlIO_fill(pTHX_ PerlIO *f)
1654 Perl_PerlIO_or_fail(f, Fill, -1, (aTHX_ f));
1658 PerlIO_isutf8(PerlIO *f)
1661 return (PerlIOBase(f)->flags & PERLIO_F_UTF8) != 0;
1663 SETERRNO(EBADF, SS_IVCHAN);
1669 Perl_PerlIO_eof(pTHX_ PerlIO *f)
1671 Perl_PerlIO_or_Base(f, Eof, eof, -1, (aTHX_ f));
1675 Perl_PerlIO_error(pTHX_ PerlIO *f)
1677 Perl_PerlIO_or_Base(f, Error, error, -1, (aTHX_ f));
1681 Perl_PerlIO_clearerr(pTHX_ PerlIO *f)
1683 Perl_PerlIO_or_Base_void(f, Clearerr, clearerr, (aTHX_ f));
1687 Perl_PerlIO_setlinebuf(pTHX_ PerlIO *f)
1689 Perl_PerlIO_or_Base_void(f, Setlinebuf, setlinebuf, (aTHX_ f));
1693 PerlIO_has_base(PerlIO *f)
1695 if (PerlIOValid(f)) {
1696 PerlIO_funcs *tab = PerlIOBase(f)->tab;
1699 return (tab->Get_base != NULL);
1700 SETERRNO(EINVAL, LIB_INVARG);
1703 SETERRNO(EBADF, SS_IVCHAN);
1709 PerlIO_fast_gets(PerlIO *f)
1711 if (PerlIOValid(f) && (PerlIOBase(f)->flags & PERLIO_F_FASTGETS)) {
1712 PerlIO_funcs *tab = PerlIOBase(f)->tab;
1715 return (tab->Set_ptrcnt != NULL);
1716 SETERRNO(EINVAL, LIB_INVARG);
1719 SETERRNO(EBADF, SS_IVCHAN);
1725 PerlIO_has_cntptr(PerlIO *f)
1727 if (PerlIOValid(f)) {
1728 PerlIO_funcs *tab = PerlIOBase(f)->tab;
1731 return (tab->Get_ptr != NULL && tab->Get_cnt != NULL);
1732 SETERRNO(EINVAL, LIB_INVARG);
1735 SETERRNO(EBADF, SS_IVCHAN);
1741 PerlIO_canset_cnt(PerlIO *f)
1743 if (PerlIOValid(f)) {
1744 PerlIO_funcs *tab = PerlIOBase(f)->tab;
1747 return (tab->Set_ptrcnt != NULL);
1748 SETERRNO(EINVAL, LIB_INVARG);
1751 SETERRNO(EBADF, SS_IVCHAN);
1757 Perl_PerlIO_get_base(pTHX_ PerlIO *f)
1759 Perl_PerlIO_or_fail(f, Get_base, NULL, (aTHX_ f));
1763 Perl_PerlIO_get_bufsiz(pTHX_ PerlIO *f)
1765 Perl_PerlIO_or_fail(f, Get_bufsiz, -1, (aTHX_ f));
1769 Perl_PerlIO_get_ptr(pTHX_ PerlIO *f)
1771 Perl_PerlIO_or_fail(f, Get_ptr, NULL, (aTHX_ f));
1775 Perl_PerlIO_get_cnt(pTHX_ PerlIO *f)
1777 Perl_PerlIO_or_fail(f, Get_cnt, -1, (aTHX_ f));
1781 Perl_PerlIO_set_cnt(pTHX_ PerlIO *f, int cnt)
1783 Perl_PerlIO_or_fail_void(f, Set_ptrcnt, (aTHX_ f, NULL, cnt));
1787 Perl_PerlIO_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, int cnt)
1789 Perl_PerlIO_or_fail_void(f, Set_ptrcnt, (aTHX_ f, ptr, cnt));
1793 /*--------------------------------------------------------------------------------------*/
1795 * utf8 and raw dummy layers
1799 PerlIOUtf8_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
1801 if (PerlIOValid(f)) {
1802 if (tab->kind & PERLIO_K_UTF8)
1803 PerlIOBase(f)->flags |= PERLIO_F_UTF8;
1805 PerlIOBase(f)->flags &= ~PERLIO_F_UTF8;
1811 PerlIO_funcs PerlIO_utf8 = {
1812 sizeof(PerlIO_funcs),
1815 PERLIO_K_DUMMY | PERLIO_K_UTF8,
1833 NULL, /* get_base */
1834 NULL, /* get_bufsiz */
1837 NULL, /* set_ptrcnt */
1840 PerlIO_funcs PerlIO_byte = {
1841 sizeof(PerlIO_funcs),
1862 NULL, /* get_base */
1863 NULL, /* get_bufsiz */
1866 NULL, /* set_ptrcnt */
1870 PerlIORaw_open(pTHX_ PerlIO_funcs *self, PerlIO_list_t *layers,
1871 IV n, const char *mode, int fd, int imode, int perm,
1872 PerlIO *old, int narg, SV **args)
1874 PerlIO_funcs *tab = PerlIO_default_btm();
1875 if (tab && tab->Open)
1876 return (*tab->Open) (aTHX_ tab, layers, n - 1, mode, fd, imode, perm,
1878 SETERRNO(EINVAL, LIB_INVARG);
1882 PerlIO_funcs PerlIO_raw = {
1883 sizeof(PerlIO_funcs),
1904 NULL, /* get_base */
1905 NULL, /* get_bufsiz */
1908 NULL, /* set_ptrcnt */
1910 /*--------------------------------------------------------------------------------------*/
1911 /*--------------------------------------------------------------------------------------*/
1913 * "Methods" of the "base class"
1917 PerlIOBase_fileno(pTHX_ PerlIO *f)
1919 return PerlIOValid(f) ? PerlIO_fileno(PerlIONext(f)) : -1;
1923 PerlIO_modestr(PerlIO * f, char *buf)
1926 if (PerlIOValid(f)) {
1927 IV flags = PerlIOBase(f)->flags;
1928 if (flags & PERLIO_F_APPEND) {
1930 if (flags & PERLIO_F_CANREAD) {
1934 else if (flags & PERLIO_F_CANREAD) {
1936 if (flags & PERLIO_F_CANWRITE)
1939 else if (flags & PERLIO_F_CANWRITE) {
1941 if (flags & PERLIO_F_CANREAD) {
1945 #ifdef PERLIO_USING_CRLF
1946 if (!(flags & PERLIO_F_CRLF))
1956 PerlIOBase_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
1958 PerlIOl *l = PerlIOBase(f);
1960 const char *omode = mode;
1963 l->flags &= ~(PERLIO_F_CANREAD | PERLIO_F_CANWRITE |
1964 PERLIO_F_TRUNCATE | PERLIO_F_APPEND);
1965 if (tab->Set_ptrcnt != NULL)
1966 l->flags |= PERLIO_F_FASTGETS;
1968 if (*mode == IoTYPE_NUMERIC || *mode == IoTYPE_IMPLICIT)
1972 l->flags |= PERLIO_F_CANREAD;
1975 l->flags |= PERLIO_F_APPEND | PERLIO_F_CANWRITE;
1978 l->flags |= PERLIO_F_TRUNCATE | PERLIO_F_CANWRITE;
1981 SETERRNO(EINVAL, LIB_INVARG);
1987 l->flags |= PERLIO_F_CANREAD | PERLIO_F_CANWRITE;
1990 l->flags &= ~PERLIO_F_CRLF;
1993 l->flags |= PERLIO_F_CRLF;
1996 SETERRNO(EINVAL, LIB_INVARG);
2003 l->flags |= l->next->flags &
2004 (PERLIO_F_CANREAD | PERLIO_F_CANWRITE | PERLIO_F_TRUNCATE |
2009 PerlIO_debug("PerlIOBase_pushed f=%p %s %s fl=%08" UVxf " (%s)\n",
2010 f, PerlIOBase(f)->tab->name, (omode) ? omode : "(Null)",
2011 l->flags, PerlIO_modestr(f, temp));
2017 PerlIOBase_popped(pTHX_ PerlIO *f)
2023 PerlIOBase_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
2026 * Save the position as current head considers it
2028 Off_t old = PerlIO_tell(f);
2030 PerlIO_push(aTHX_ f, &PerlIO_pending, "r", Nullsv);
2031 PerlIOSelf(f, PerlIOBuf)->posn = old;
2032 done = PerlIOBuf_unread(aTHX_ f, vbuf, count);
2037 PerlIOBase_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
2039 STDCHAR *buf = (STDCHAR *) vbuf;
2041 if (!(PerlIOBase(f)->flags & PERLIO_F_CANREAD)) {
2042 PerlIOBase(f)->flags |= PERLIO_F_ERROR;
2043 SETERRNO(EBADF, SS_IVCHAN);
2047 SSize_t avail = PerlIO_get_cnt(f);
2050 take = ((SSize_t)count < avail) ? count : avail;
2052 STDCHAR *ptr = PerlIO_get_ptr(f);
2053 Copy(ptr, buf, take, STDCHAR);
2054 PerlIO_set_ptrcnt(f, ptr + take, (avail -= take));
2058 if (count > 0 && avail <= 0) {
2059 if (PerlIO_fill(f) != 0)
2063 return (buf - (STDCHAR *) vbuf);
2069 PerlIOBase_noop_ok(pTHX_ PerlIO *f)
2075 PerlIOBase_noop_fail(pTHX_ PerlIO *f)
2081 PerlIOBase_close(pTHX_ PerlIO *f)
2084 if (PerlIOValid(f)) {
2085 PerlIO *n = PerlIONext(f);
2086 code = PerlIO_flush(f);
2087 PerlIOBase(f)->flags &=
2088 ~(PERLIO_F_CANREAD | PERLIO_F_CANWRITE | PERLIO_F_OPEN);
2089 while (PerlIOValid(n)) {
2090 PerlIO_funcs *tab = PerlIOBase(n)->tab;
2091 if (tab && tab->Close) {
2092 if ((*tab->Close)(aTHX_ n) != 0)
2097 PerlIOBase(n)->flags &=
2098 ~(PERLIO_F_CANREAD | PERLIO_F_CANWRITE | PERLIO_F_OPEN);
2104 SETERRNO(EBADF, SS_IVCHAN);
2110 PerlIOBase_eof(pTHX_ PerlIO *f)
2112 if (PerlIOValid(f)) {
2113 return (PerlIOBase(f)->flags & PERLIO_F_EOF) != 0;
2119 PerlIOBase_error(pTHX_ PerlIO *f)
2121 if (PerlIOValid(f)) {
2122 return (PerlIOBase(f)->flags & PERLIO_F_ERROR) != 0;
2128 PerlIOBase_clearerr(pTHX_ PerlIO *f)
2130 if (PerlIOValid(f)) {
2131 PerlIO *n = PerlIONext(f);
2132 PerlIOBase(f)->flags &= ~(PERLIO_F_ERROR | PERLIO_F_EOF);
2139 PerlIOBase_setlinebuf(pTHX_ PerlIO *f)
2141 if (PerlIOValid(f)) {
2142 PerlIOBase(f)->flags |= PERLIO_F_LINEBUF;
2147 PerlIO_sv_dup(pTHX_ SV *arg, CLONE_PARAMS *param)
2153 return sv_dup(arg, param);
2156 return newSVsv(arg);
2159 return newSVsv(arg);
2164 PerlIOBase_dup(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags)
2166 PerlIO *nexto = PerlIONext(o);
2167 if (PerlIOValid(nexto)) {
2168 PerlIO_funcs *tab = PerlIOBase(nexto)->tab;
2169 if (tab && tab->Dup)
2170 f = (*tab->Dup)(aTHX_ f, nexto, param, flags);
2172 f = PerlIOBase_dup(aTHX_ f, nexto, param, flags);
2175 PerlIO_funcs *self = PerlIOBase(o)->tab;
2178 PerlIO_debug("PerlIOBase_dup %s f=%p o=%p param=%p\n",
2179 self->name, (void*)f, (void*)o, (void*)param);
2181 arg = (*self->Getarg)(aTHX_ o, param, flags);
2185 f = PerlIO_push(aTHX_ f, self, PerlIO_modestr(o,buf), arg);
2193 #define PERLIO_MAX_REFCOUNTABLE_FD 2048
2195 perl_mutex PerlIO_mutex;
2197 int PerlIO_fd_refcnt[PERLIO_MAX_REFCOUNTABLE_FD];
2202 /* Place holder for stdstreams call ??? */
2204 MUTEX_INIT(&PerlIO_mutex);
2209 PerlIOUnix_refcnt_inc(int fd)
2211 if (fd >= 0 && fd < PERLIO_MAX_REFCOUNTABLE_FD) {
2213 MUTEX_LOCK(&PerlIO_mutex);
2215 PerlIO_fd_refcnt[fd]++;
2216 PerlIO_debug("fd %d refcnt=%d\n",fd,PerlIO_fd_refcnt[fd]);
2218 MUTEX_UNLOCK(&PerlIO_mutex);
2224 PerlIOUnix_refcnt_dec(int fd)
2227 if (fd >= 0 && fd < PERLIO_MAX_REFCOUNTABLE_FD) {
2229 MUTEX_LOCK(&PerlIO_mutex);
2231 cnt = --PerlIO_fd_refcnt[fd];
2232 PerlIO_debug("fd %d refcnt=%d\n",fd,cnt);
2234 MUTEX_UNLOCK(&PerlIO_mutex);
2241 PerlIO_cleanup(pTHX)
2245 PerlIO_debug("Cleanup layers for %p\n",aTHX);
2247 PerlIO_debug("Cleanup layers\n");
2249 /* Raise STDIN..STDERR refcount so we don't close them */
2250 for (i=0; i < 3; i++)
2251 PerlIOUnix_refcnt_inc(i);
2252 PerlIO_cleantable(aTHX_ &PL_perlio);
2253 /* Restore STDIN..STDERR refcount */
2254 for (i=0; i < 3; i++)
2255 PerlIOUnix_refcnt_dec(i);
2257 if (PL_known_layers) {
2258 PerlIO_list_free(aTHX_ PL_known_layers);
2259 PL_known_layers = NULL;
2261 if(PL_def_layerlist) {
2262 PerlIO_list_free(aTHX_ PL_def_layerlist);
2263 PL_def_layerlist = NULL;
2269 /*--------------------------------------------------------------------------------------*/
2271 * Bottom-most level for UNIX-like case
2275 struct _PerlIO base; /* The generic part */
2276 int fd; /* UNIX like file descriptor */
2277 int oflags; /* open/fcntl flags */
2281 PerlIOUnix_oflags(const char *mode)
2284 if (*mode == IoTYPE_IMPLICIT || *mode == IoTYPE_NUMERIC)
2289 if (*++mode == '+') {
2296 oflags = O_CREAT | O_TRUNC;
2297 if (*++mode == '+') {
2306 oflags = O_CREAT | O_APPEND;
2307 if (*++mode == '+') {
2320 else if (*mode == 't') {
2322 oflags &= ~O_BINARY;
2326 * Always open in binary mode
2329 if (*mode || oflags == -1) {
2330 SETERRNO(EINVAL, LIB_INVARG);
2337 PerlIOUnix_fileno(pTHX_ PerlIO *f)
2339 return PerlIOSelf(f, PerlIOUnix)->fd;
2343 PerlIOUnix_setfd(pTHX_ PerlIO *f, int fd, int imode)
2345 PerlIOUnix *s = PerlIOSelf(f, PerlIOUnix);
2348 if (PerlLIO_fstat(fd, &st) == 0) {
2349 if (!S_ISREG(st.st_mode)) {
2350 PerlIO_debug("%d is not regular file\n",fd);
2351 PerlIOBase(f)->flags |= PERLIO_F_NOTREG;
2354 PerlIO_debug("%d _is_ a regular file\n",fd);
2360 PerlIOUnix_refcnt_inc(fd);
2364 PerlIOUnix_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
2366 IV code = PerlIOBase_pushed(aTHX_ f, mode, arg, tab);
2367 if (*PerlIONext(f)) {
2368 /* We never call down so do any pending stuff now */
2369 PerlIO_flush(PerlIONext(f));
2371 * XXX could (or should) we retrieve the oflags from the open file
2372 * handle rather than believing the "mode" we are passed in? XXX
2373 * Should the value on NULL mode be 0 or -1?
2375 PerlIOUnix_setfd(aTHX_ f, PerlIO_fileno(PerlIONext(f)),
2376 mode ? PerlIOUnix_oflags(mode) : -1);
2378 PerlIOBase(f)->flags |= PERLIO_F_OPEN;
2384 PerlIOUnix_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
2386 int fd = PerlIOSelf(f, PerlIOUnix)->fd;
2388 if (PerlIOBase(f)->flags & PERLIO_F_NOTREG) {
2390 SETERRNO(ESPIPE, LIB_INVARG);
2392 SETERRNO(EINVAL, LIB_INVARG);
2396 new = PerlLIO_lseek(fd, offset, whence);
2397 if (new == (Off_t) - 1)
2401 PerlIOBase(f)->flags &= ~PERLIO_F_EOF;
2406 PerlIOUnix_open(pTHX_ PerlIO_funcs *self, PerlIO_list_t *layers,
2407 IV n, const char *mode, int fd, int imode,
2408 int perm, PerlIO *f, int narg, SV **args)
2410 if (PerlIOValid(f)) {
2411 if (PerlIOBase(f)->flags & PERLIO_F_OPEN)
2412 (*PerlIOBase(f)->tab->Close)(aTHX_ f);
2415 char *path = SvPV_nolen(*args);
2416 if (*mode == IoTYPE_NUMERIC)
2419 imode = PerlIOUnix_oflags(mode);
2423 fd = PerlLIO_open3(path, imode, perm);
2427 if (*mode == IoTYPE_IMPLICIT)
2430 f = PerlIO_allocate(aTHX);
2432 if (!PerlIOValid(f)) {
2433 if (!(f = PerlIO_push(aTHX_ f, self, mode, PerlIOArg))) {
2437 PerlIOUnix_setfd(aTHX_ f, fd, imode);
2438 PerlIOBase(f)->flags |= PERLIO_F_OPEN;
2439 if (*mode == IoTYPE_APPEND)
2440 PerlIOUnix_seek(aTHX_ f, 0, SEEK_END);
2446 * FIXME: pop layers ???
2454 PerlIOUnix_dup(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags)
2456 PerlIOUnix *os = PerlIOSelf(o, PerlIOUnix);
2458 if (flags & PERLIO_DUP_FD) {
2459 fd = PerlLIO_dup(fd);
2461 if (fd >= 0 && fd < PERLIO_MAX_REFCOUNTABLE_FD) {
2462 f = PerlIOBase_dup(aTHX_ f, o, param, flags);
2464 /* If all went well overwrite fd in dup'ed lay with the dup()'ed fd */
2465 PerlIOUnix_setfd(aTHX_ f, fd, os->oflags);
2474 PerlIOUnix_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
2476 int fd = PerlIOSelf(f, PerlIOUnix)->fd;
2477 if (!(PerlIOBase(f)->flags & PERLIO_F_CANREAD) ||
2478 PerlIOBase(f)->flags & (PERLIO_F_EOF|PERLIO_F_ERROR)) {
2482 SSize_t len = PerlLIO_read(fd, vbuf, count);
2483 if (len >= 0 || errno != EINTR) {
2485 if (errno != EAGAIN) {
2486 PerlIOBase(f)->flags |= PERLIO_F_ERROR;
2489 else if (len == 0 && count != 0) {
2490 PerlIOBase(f)->flags |= PERLIO_F_EOF;
2500 PerlIOUnix_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
2502 int fd = PerlIOSelf(f, PerlIOUnix)->fd;
2504 SSize_t len = PerlLIO_write(fd, vbuf, count);
2505 if (len >= 0 || errno != EINTR) {
2507 if (errno != EAGAIN) {
2508 PerlIOBase(f)->flags |= PERLIO_F_ERROR;
2518 PerlIOUnix_tell(pTHX_ PerlIO *f)
2520 return PerlLIO_lseek(PerlIOSelf(f, PerlIOUnix)->fd, 0, SEEK_CUR);
2525 PerlIOUnix_close(pTHX_ PerlIO *f)
2527 int fd = PerlIOSelf(f, PerlIOUnix)->fd;
2529 if (PerlIOBase(f)->flags & PERLIO_F_OPEN) {
2530 if (PerlIOUnix_refcnt_dec(fd) > 0) {
2531 PerlIOBase(f)->flags &= ~PERLIO_F_OPEN;
2536 SETERRNO(EBADF,SS_IVCHAN);
2539 while (PerlLIO_close(fd) != 0) {
2540 if (errno != EINTR) {
2547 PerlIOBase(f)->flags &= ~PERLIO_F_OPEN;
2552 PerlIO_funcs PerlIO_unix = {
2553 sizeof(PerlIO_funcs),
2560 PerlIOBase_binmode, /* binmode */
2570 PerlIOBase_noop_ok, /* flush */
2571 PerlIOBase_noop_fail, /* fill */
2574 PerlIOBase_clearerr,
2575 PerlIOBase_setlinebuf,
2576 NULL, /* get_base */
2577 NULL, /* get_bufsiz */
2580 NULL, /* set_ptrcnt */
2583 /*--------------------------------------------------------------------------------------*/
2588 #if defined(VMS) && !defined(STDIO_BUFFER_WRITABLE)
2589 /* perl5.8 - This ensures the last minute VMS ungetc fix is not
2590 broken by the last second glibc 2.3 fix
2592 #define STDIO_BUFFER_WRITABLE
2597 struct _PerlIO base;
2598 FILE *stdio; /* The stream */
2602 PerlIOStdio_fileno(pTHX_ PerlIO *f)
2605 if (PerlIOValid(f) && (s = PerlIOSelf(f, PerlIOStdio)->stdio)) {
2606 return PerlSIO_fileno(s);
2613 PerlIOStdio_mode(const char *mode, char *tmode)
2619 #if defined(PERLIO_USING_CRLF) || defined(__CYGWIN__)
2627 PerlIOStdio_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
2630 if (PerlIOValid(f) && PerlIOValid(n = PerlIONext(f))) {
2631 PerlIO_funcs *toptab = PerlIOBase(n)->tab;
2632 if (toptab == tab) {
2633 /* Top is already stdio - pop self (duplicate) and use original */
2634 PerlIO_pop(aTHX_ f);
2637 int fd = PerlIO_fileno(n);
2640 if (fd >= 0 && (stdio = PerlSIO_fdopen(fd,
2641 mode = PerlIOStdio_mode(mode, tmode)))) {
2642 PerlIOSelf(f, PerlIOStdio)->stdio = stdio;
2643 /* We never call down so do any pending stuff now */
2644 PerlIO_flush(PerlIONext(f));
2651 return PerlIOBase_pushed(aTHX_ f, mode, arg, tab);
2656 PerlIO_importFILE(FILE *stdio, const char *mode)
2662 if (!mode || !*mode) {
2663 /* We need to probe to see how we can open the stream
2664 so start with read/write and then try write and read
2665 we dup() so that we can fclose without loosing the fd.
2667 Note that the errno value set by a failing fdopen
2668 varies between stdio implementations.
2670 int fd = PerlLIO_dup(fileno(stdio));
2671 FILE *f2 = PerlSIO_fdopen(fd, (mode = "r+"));
2673 f2 = PerlSIO_fdopen(fd, (mode = "w"));
2676 f2 = PerlSIO_fdopen(fd, (mode = "r"));
2679 /* Don't seem to be able to open */
2685 if ((f = PerlIO_push(aTHX_(f = PerlIO_allocate(aTHX)), &PerlIO_stdio, mode, Nullsv))) {
2686 s = PerlIOSelf(f, PerlIOStdio);
2694 PerlIOStdio_open(pTHX_ PerlIO_funcs *self, PerlIO_list_t *layers,
2695 IV n, const char *mode, int fd, int imode,
2696 int perm, PerlIO *f, int narg, SV **args)
2699 if (PerlIOValid(f)) {
2700 char *path = SvPV_nolen(*args);
2701 PerlIOStdio *s = PerlIOSelf(f, PerlIOStdio);
2703 PerlIOUnix_refcnt_dec(fileno(s->stdio));
2704 stdio = PerlSIO_freopen(path, (mode = PerlIOStdio_mode(mode, tmode)),
2709 PerlIOUnix_refcnt_inc(fileno(s->stdio));
2714 char *path = SvPV_nolen(*args);
2715 if (*mode == IoTYPE_NUMERIC) {
2717 fd = PerlLIO_open3(path, imode, perm);
2721 bool appended = FALSE;
2723 /* Cygwin wants its 'b' early. */
2725 mode = PerlIOStdio_mode(mode, tmode);
2727 stdio = PerlSIO_fopen(path, mode);
2731 f = PerlIO_allocate(aTHX);
2734 mode = PerlIOStdio_mode(mode, tmode);
2735 f = PerlIO_push(aTHX_ f, self, mode, PerlIOArg);
2737 s = PerlIOSelf(f, PerlIOStdio);
2739 PerlIOUnix_refcnt_inc(fileno(s->stdio));
2751 if (*mode == IoTYPE_IMPLICIT) {
2758 stdio = PerlSIO_stdin;
2761 stdio = PerlSIO_stdout;
2764 stdio = PerlSIO_stderr;
2769 stdio = PerlSIO_fdopen(fd, mode =
2770 PerlIOStdio_mode(mode, tmode));
2775 f = PerlIO_allocate(aTHX);
2777 if ((f = PerlIO_push(aTHX_ f, self, mode, PerlIOArg))) {
2778 s = PerlIOSelf(f, PerlIOStdio);
2780 PerlIOUnix_refcnt_inc(fileno(s->stdio));
2790 PerlIOStdio_dup(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags)
2792 /* This assumes no layers underneath - which is what
2793 happens, but is not how I remember it. NI-S 2001/10/16
2795 if ((f = PerlIOBase_dup(aTHX_ f, o, param, flags))) {
2796 FILE *stdio = PerlIOSelf(o, PerlIOStdio)->stdio;
2797 int fd = fileno(stdio);
2799 if (flags & PERLIO_DUP_FD) {
2800 int dfd = PerlLIO_dup(fileno(stdio));
2802 stdio = PerlSIO_fdopen(dfd, PerlIO_modestr(o,mode));
2806 /* FIXME: To avoid messy error recovery if dup fails
2807 re-use the existing stdio as though flag was not set
2811 stdio = PerlSIO_fdopen(fd, PerlIO_modestr(o,mode));
2813 PerlIOSelf(f, PerlIOStdio)->stdio = stdio;
2814 PerlIOUnix_refcnt_inc(fileno(stdio));
2820 PerlIOStdio_invalidate_fileno(pTHX_ FILE *f)
2822 /* XXX this could use PerlIO_canset_fileno() and
2823 * PerlIO_set_fileno() support from Configure
2825 # if defined(__GLIBC__)
2826 /* There may be a better way for GLIBC:
2827 - libio.h defines a flag to not close() on cleanup
2831 # elif defined(__sun__)
2833 /* On solaris, if _LP64 is defined, the FILE structure is this:
2839 * It turns out that the fd is stored in the top 32 bits of
2840 * file->__pad[4]. The lower 32 bits contain flags. file->pad[5] appears
2841 * to contain a pointer or offset into another structure. All the
2842 * remaining fields are zero.
2844 * We set the top bits to -1 (0xFFFFFFFF).
2846 f->__pad[4] |= 0xffffffff00000000L;
2847 assert(fileno(f) == 0xffffffff);
2848 # else /* !defined(_LP64) */
2849 /* _file is just a unsigned char :-(
2850 Not clear why we dup() rather than using -1
2851 even if that would be treated as 0xFF - so will
2854 f->_file = PerlLIO_dup(fileno(f));
2855 # endif /* defined(_LP64) */
2857 # elif defined(__hpux)
2861 /* Next one ->_file seems to be a reasonable fallback, i.e. if
2862 your platform does not have special entry try this one.
2863 [For OSF only have confirmation for Tru64 (alpha)
2864 but assume other OSFs will be similar.]
2866 # elif defined(_AIX) || defined(__osf__) || defined(__irix__)
2869 # elif defined(__FreeBSD__)
2870 /* There may be a better way on FreeBSD:
2871 - we could insert a dummy func in the _close function entry
2872 f->_close = (int (*)(void *)) dummy_close;
2876 # elif defined(__CYGWIN__)
2877 /* There may be a better way on CYGWIN:
2878 - we could insert a dummy func in the _close function entry
2879 f->_close = (int (*)(void *)) dummy_close;
2883 # elif defined(WIN32)
2884 # if defined(__BORLANDC__)
2885 f->fd = PerlLIO_dup(fileno(f));
2886 # elif defined(UNDER_CE)
2887 /* WIN_CE does not have access to FILE internals, it hardly has FILE
2896 /* Sarathy's code did this - we fall back to a dup/dup2 hack
2897 (which isn't thread safe) instead
2899 # error "Don't know how to set FILE.fileno on your platform"
2906 PerlIOStdio_close(pTHX_ PerlIO *f)
2908 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
2914 int fd = fileno(stdio);
2920 #ifdef SOCKS5_VERSION_NAME
2921 /* Socks lib overrides close() but stdio isn't linked to
2922 that library (though we are) - so we must call close()
2923 on sockets on stdio's behalf.
2926 Sock_size_t optlen = sizeof(int);
2927 if (getsockopt(fd, SOL_SOCKET, SO_TYPE, (void *) &optval, &optlen) == 0) {
2932 if (PerlIOUnix_refcnt_dec(fd) > 0) {
2933 /* File descriptor still in use */
2938 /* For STD* handles don't close the stdio at all
2939 this is because we have shared the FILE * too
2941 if (stdio == stdin) {
2942 /* Some stdios are buggy fflush-ing inputs */
2945 else if (stdio == stdout || stdio == stderr) {
2946 return PerlIO_flush(f);
2948 /* Tricky - must fclose(stdio) to free memory but not close(fd)
2949 Use Sarathy's trick from maint-5.6 to invalidate the
2950 fileno slot of the FILE *
2952 result = PerlIO_flush(f);
2954 if (!(invalidate = PerlIOStdio_invalidate_fileno(aTHX_ stdio))) {
2955 dupfd = PerlLIO_dup(fd);
2958 result = PerlSIO_fclose(stdio);
2959 /* We treat error from stdio as success if we invalidated
2960 errno may NOT be expected EBADF
2962 if (invalidate && result != 0) {
2967 /* in SOCKS case let close() determine return value */
2971 PerlLIO_dup2(dupfd,fd);
2972 PerlLIO_close(dupfd);
2979 PerlIOStdio_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
2981 FILE *s = PerlIOSelf(f, PerlIOStdio)->stdio;
2985 STDCHAR *buf = (STDCHAR *) vbuf;
2987 * Perl is expecting PerlIO_getc() to fill the buffer Linux's
2988 * stdio does not do that for fread()
2990 int ch = PerlSIO_fgetc(s);
2997 got = PerlSIO_fread(vbuf, 1, count, s);
2998 if (got == 0 && PerlSIO_ferror(s))
3000 if (got >= 0 || errno != EINTR)
3003 SETERRNO(0,0); /* just in case */
3009 PerlIOStdio_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
3012 FILE *s = PerlIOSelf(f, PerlIOStdio)->stdio;
3014 #ifdef STDIO_BUFFER_WRITABLE
3015 if (PerlIO_fast_gets(f) && PerlIO_has_base(f)) {
3016 STDCHAR *buf = ((STDCHAR *) vbuf) + count;
3017 STDCHAR *base = PerlIO_get_base(f);
3018 SSize_t cnt = PerlIO_get_cnt(f);
3019 STDCHAR *ptr = PerlIO_get_ptr(f);
3020 SSize_t avail = ptr - base;
3022 if (avail > count) {
3026 Move(buf-avail,ptr,avail,STDCHAR);
3029 PerlIO_set_ptrcnt(f,ptr,cnt+avail);
3030 if (PerlSIO_feof(s) && unread >= 0)
3031 PerlSIO_clearerr(s);
3036 if (PerlIO_has_cntptr(f)) {
3037 /* We can get pointer to buffer but not its base
3038 Do ungetc() but check chars are ending up in the
3041 STDCHAR *eptr = (STDCHAR*)PerlSIO_get_ptr(s);
3042 STDCHAR *buf = ((STDCHAR *) vbuf) + count;
3044 int ch = *--buf & 0xFF;
3045 if (ungetc(ch,s) != ch) {
3046 /* ungetc did not work */
3049 if ((STDCHAR*)PerlSIO_get_ptr(s) != --eptr || ((*eptr & 0xFF) != ch)) {
3050 /* Did not change pointer as expected */
3051 fgetc(s); /* get char back again */
3061 unread += PerlIOBase_unread(aTHX_ f, vbuf, count);
3067 PerlIOStdio_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
3071 got = PerlSIO_fwrite(vbuf, 1, count,
3072 PerlIOSelf(f, PerlIOStdio)->stdio);
3073 if (got >= 0 || errno != EINTR)
3076 SETERRNO(0,0); /* just in case */
3082 PerlIOStdio_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
3084 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3085 return PerlSIO_fseek(stdio, offset, whence);
3089 PerlIOStdio_tell(pTHX_ PerlIO *f)
3091 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3092 return PerlSIO_ftell(stdio);
3096 PerlIOStdio_flush(pTHX_ PerlIO *f)
3098 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3099 if (PerlIOBase(f)->flags & PERLIO_F_CANWRITE) {
3100 return PerlSIO_fflush(stdio);
3105 * FIXME: This discards ungetc() and pre-read stuff which is not
3106 * right if this is just a "sync" from a layer above Suspect right
3107 * design is to do _this_ but not have layer above flush this
3108 * layer read-to-read
3111 * Not writeable - sync by attempting a seek
3114 if (PerlSIO_fseek(stdio, (Off_t) 0, SEEK_CUR) != 0)
3122 PerlIOStdio_eof(pTHX_ PerlIO *f)
3124 return PerlSIO_feof(PerlIOSelf(f, PerlIOStdio)->stdio);
3128 PerlIOStdio_error(pTHX_ PerlIO *f)
3130 return PerlSIO_ferror(PerlIOSelf(f, PerlIOStdio)->stdio);
3134 PerlIOStdio_clearerr(pTHX_ PerlIO *f)
3136 PerlSIO_clearerr(PerlIOSelf(f, PerlIOStdio)->stdio);
3140 PerlIOStdio_setlinebuf(pTHX_ PerlIO *f)
3142 #ifdef HAS_SETLINEBUF
3143 PerlSIO_setlinebuf(PerlIOSelf(f, PerlIOStdio)->stdio);
3145 PerlSIO_setvbuf(PerlIOSelf(f, PerlIOStdio)->stdio, Nullch, _IOLBF, 0);
3151 PerlIOStdio_get_base(pTHX_ PerlIO *f)
3153 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3154 return (STDCHAR*)PerlSIO_get_base(stdio);
3158 PerlIOStdio_get_bufsiz(pTHX_ PerlIO *f)
3160 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3161 return PerlSIO_get_bufsiz(stdio);
3165 #ifdef USE_STDIO_PTR
3167 PerlIOStdio_get_ptr(pTHX_ PerlIO *f)
3169 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3170 return (STDCHAR*)PerlSIO_get_ptr(stdio);
3174 PerlIOStdio_get_cnt(pTHX_ PerlIO *f)
3176 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3177 return PerlSIO_get_cnt(stdio);
3181 PerlIOStdio_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, SSize_t cnt)
3183 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3185 #ifdef STDIO_PTR_LVALUE
3186 PerlSIO_set_ptr(stdio, (void*)ptr); /* LHS STDCHAR* cast non-portable */
3187 #ifdef STDIO_PTR_LVAL_SETS_CNT
3188 if (PerlSIO_get_cnt(stdio) != (cnt)) {
3189 assert(PerlSIO_get_cnt(stdio) == (cnt));
3192 #if (!defined(STDIO_PTR_LVAL_NOCHANGE_CNT))
3194 * Setting ptr _does_ change cnt - we are done
3198 #else /* STDIO_PTR_LVALUE */
3200 #endif /* STDIO_PTR_LVALUE */
3203 * Now (or only) set cnt
3205 #ifdef STDIO_CNT_LVALUE
3206 PerlSIO_set_cnt(stdio, cnt);
3207 #else /* STDIO_CNT_LVALUE */
3208 #if (defined(STDIO_PTR_LVALUE) && defined(STDIO_PTR_LVAL_SETS_CNT))
3209 PerlSIO_set_ptr(stdio,
3210 PerlSIO_get_ptr(stdio) + (PerlSIO_get_cnt(stdio) -
3212 #else /* STDIO_PTR_LVAL_SETS_CNT */
3214 #endif /* STDIO_PTR_LVAL_SETS_CNT */
3215 #endif /* STDIO_CNT_LVALUE */
3222 PerlIOStdio_fill(pTHX_ PerlIO *f)
3224 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3227 * fflush()ing read-only streams can cause trouble on some stdio-s
3229 if ((PerlIOBase(f)->flags & PERLIO_F_CANWRITE)) {
3230 if (PerlSIO_fflush(stdio) != 0)
3233 c = PerlSIO_fgetc(stdio);
3237 #if (defined(STDIO_PTR_LVALUE) && (defined(STDIO_CNT_LVALUE) || defined(STDIO_PTR_LVAL_SETS_CNT)))
3239 #ifdef STDIO_BUFFER_WRITABLE
3240 if (PerlIO_fast_gets(f) && PerlIO_has_base(f)) {
3241 /* Fake ungetc() to the real buffer in case system's ungetc
3244 STDCHAR *base = (STDCHAR*)PerlSIO_get_base(stdio);
3245 SSize_t cnt = PerlSIO_get_cnt(stdio);
3246 STDCHAR *ptr = (STDCHAR*)PerlSIO_get_ptr(stdio);
3247 if (ptr == base+1) {
3248 *--ptr = (STDCHAR) c;
3249 PerlIOStdio_set_ptrcnt(aTHX_ f,ptr,cnt+1);
3250 if (PerlSIO_feof(stdio))
3251 PerlSIO_clearerr(stdio);
3257 if (PerlIO_has_cntptr(f)) {
3259 if (PerlIOStdio_unread(aTHX_ f,&ch,1) == 1) {
3266 /* An ungetc()d char is handled separately from the regular
3267 * buffer, so we stuff it in the buffer ourselves.
3268 * Should never get called as should hit code above
3270 *(--((*stdio)->_ptr)) = (unsigned char) c;
3273 /* If buffer snoop scheme above fails fall back to
3276 if (PerlSIO_ungetc(c, stdio) != c)
3284 PerlIO_funcs PerlIO_stdio = {
3285 sizeof(PerlIO_funcs),
3287 sizeof(PerlIOStdio),
3288 PERLIO_K_BUFFERED|PERLIO_K_RAW,
3292 PerlIOBase_binmode, /* binmode */
3306 PerlIOStdio_clearerr,
3307 PerlIOStdio_setlinebuf,
3309 PerlIOStdio_get_base,
3310 PerlIOStdio_get_bufsiz,
3315 #ifdef USE_STDIO_PTR
3316 PerlIOStdio_get_ptr,
3317 PerlIOStdio_get_cnt,
3318 # if defined(HAS_FAST_STDIO) && defined(USE_FAST_STDIO)
3319 PerlIOStdio_set_ptrcnt,
3322 # endif /* HAS_FAST_STDIO && USE_FAST_STDIO */
3327 #endif /* USE_STDIO_PTR */
3330 /* Note that calls to PerlIO_exportFILE() are reversed using
3331 * PerlIO_releaseFILE(), not importFILE. */
3333 PerlIO_exportFILE(PerlIO * f, const char *mode)
3337 if (PerlIOValid(f)) {
3340 if (!mode || !*mode) {
3341 mode = PerlIO_modestr(f, buf);
3343 stdio = PerlSIO_fdopen(PerlIO_fileno(f), mode);
3347 /* De-link any lower layers so new :stdio sticks */
3349 if ((f2 = PerlIO_push(aTHX_ f, &PerlIO_stdio, buf, Nullsv))) {
3350 PerlIOStdio *s = PerlIOSelf((f = f2), PerlIOStdio);
3352 /* Link previous lower layers under new one */
3356 /* restore layers list */
3366 PerlIO_findFILE(PerlIO *f)
3370 if (l->tab == &PerlIO_stdio) {
3371 PerlIOStdio *s = PerlIOSelf(&l, PerlIOStdio);
3374 l = *PerlIONext(&l);
3376 /* Uses fallback "mode" via PerlIO_modestr() in PerlIO_exportFILE */
3377 return PerlIO_exportFILE(f, Nullch);
3380 /* Use this to reverse PerlIO_exportFILE calls. */
3382 PerlIO_releaseFILE(PerlIO *p, FILE *f)
3386 if (l->tab == &PerlIO_stdio) {
3387 PerlIOStdio *s = PerlIOSelf(&l, PerlIOStdio);
3388 if (s->stdio == f) {
3390 PerlIO_pop(aTHX_ p);
3399 /*--------------------------------------------------------------------------------------*/
3401 * perlio buffer layer
3405 PerlIOBuf_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
3407 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3408 int fd = PerlIO_fileno(f);
3409 if (fd >= 0 && PerlLIO_isatty(fd)) {
3410 PerlIOBase(f)->flags |= PERLIO_F_LINEBUF | PERLIO_F_TTY;
3412 if (*PerlIONext(f)) {
3413 Off_t posn = PerlIO_tell(PerlIONext(f));
3414 if (posn != (Off_t) - 1) {
3418 return PerlIOBase_pushed(aTHX_ f, mode, arg, tab);
3422 PerlIOBuf_open(pTHX_ PerlIO_funcs *self, PerlIO_list_t *layers,
3423 IV n, const char *mode, int fd, int imode, int perm,
3424 PerlIO *f, int narg, SV **args)
3426 if (PerlIOValid(f)) {
3427 PerlIO *next = PerlIONext(f);
3429 PerlIO_layer_fetch(aTHX_ layers, n - 1, PerlIOBase(next)->tab);
3430 if (tab && tab->Open)
3432 (*tab->Open)(aTHX_ tab, layers, n - 1, mode, fd, imode, perm,
3434 if (!next || (*PerlIOBase(f)->tab->Pushed) (aTHX_ f, mode, PerlIOArg, self) != 0) {
3439 PerlIO_funcs *tab = PerlIO_layer_fetch(aTHX_ layers, n - 1, PerlIO_default_btm());
3441 if (*mode == IoTYPE_IMPLICIT) {
3447 if (tab && tab->Open)
3448 f = (*tab->Open)(aTHX_ tab, layers, n - 1, mode, fd, imode, perm,
3451 SETERRNO(EINVAL, LIB_INVARG);
3453 if (PerlIO_push(aTHX_ f, self, mode, PerlIOArg) == 0) {
3455 * if push fails during open, open fails. close will pop us.
3460 fd = PerlIO_fileno(f);
3461 if (init && fd == 2) {
3463 * Initial stderr is unbuffered
3465 PerlIOBase(f)->flags |= PERLIO_F_UNBUF;
3467 #ifdef PERLIO_USING_CRLF
3468 # ifdef PERLIO_IS_BINMODE_FD
3469 if (PERLIO_IS_BINMODE_FD(fd))
3470 PerlIO_binmode(aTHX_ f, '<'/*not used*/, O_BINARY, Nullch);
3474 * do something about failing setmode()? --jhi
3476 PerlLIO_setmode(fd, O_BINARY);
3485 * This "flush" is akin to sfio's sync in that it handles files in either
3486 * read or write state
3489 PerlIOBuf_flush(pTHX_ PerlIO *f)
3491 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3493 PerlIO *n = PerlIONext(f);
3494 if (PerlIOBase(f)->flags & PERLIO_F_WRBUF) {
3496 * write() the buffer
3498 STDCHAR *buf = b->buf;
3500 while (p < b->ptr) {
3501 SSize_t count = PerlIO_write(n, p, b->ptr - p);
3505 else if (count < 0 || PerlIO_error(n)) {
3506 PerlIOBase(f)->flags |= PERLIO_F_ERROR;
3511 b->posn += (p - buf);
3513 else if (PerlIOBase(f)->flags & PERLIO_F_RDBUF) {
3514 STDCHAR *buf = PerlIO_get_base(f);
3516 * Note position change
3518 b->posn += (b->ptr - buf);
3519 if (b->ptr < b->end) {
3520 /* We did not consume all of it - try and seek downstream to
3521 our logical position
3523 if (PerlIOValid(n) && PerlIO_seek(n, b->posn, SEEK_SET) == 0) {
3524 /* Reload n as some layers may pop themselves on seek */
3525 b->posn = PerlIO_tell(n = PerlIONext(f));
3528 /* Seek failed (e.g. pipe or tty). Do NOT clear buffer or pre-read
3529 data is lost for good - so return saying "ok" having undone
3532 b->posn -= (b->ptr - buf);
3537 b->ptr = b->end = b->buf;
3538 PerlIOBase(f)->flags &= ~(PERLIO_F_RDBUF | PERLIO_F_WRBUF);
3539 /* We check for Valid because of dubious decision to make PerlIO_flush(NULL) flush all */
3540 if (PerlIOValid(n) && PerlIO_flush(n) != 0)
3546 PerlIOBuf_fill(pTHX_ PerlIO *f)
3548 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3549 PerlIO *n = PerlIONext(f);
3552 * Down-stream flush is defined not to loose read data so is harmless.
3553 * we would not normally be fill'ing if there was data left in anycase.
3555 if (PerlIO_flush(f) != 0)
3557 if (PerlIOBase(f)->flags & PERLIO_F_TTY)
3558 PerlIOBase_flush_linebuf(aTHX);
3561 PerlIO_get_base(f); /* allocate via vtable */
3563 b->ptr = b->end = b->buf;
3565 if (!PerlIOValid(n)) {
3566 PerlIOBase(f)->flags |= PERLIO_F_EOF;
3570 if (PerlIO_fast_gets(n)) {
3572 * Layer below is also buffered. We do _NOT_ want to call its
3573 * ->Read() because that will loop till it gets what we asked for
3574 * which may hang on a pipe etc. Instead take anything it has to
3575 * hand, or ask it to fill _once_.
3577 avail = PerlIO_get_cnt(n);
3579 avail = PerlIO_fill(n);
3581 avail = PerlIO_get_cnt(n);
3583 if (!PerlIO_error(n) && PerlIO_eof(n))
3588 STDCHAR *ptr = PerlIO_get_ptr(n);
3589 SSize_t cnt = avail;
3590 if (avail > (SSize_t)b->bufsiz)
3592 Copy(ptr, b->buf, avail, STDCHAR);
3593 PerlIO_set_ptrcnt(n, ptr + avail, cnt - avail);
3597 avail = PerlIO_read(n, b->ptr, b->bufsiz);
3601 PerlIOBase(f)->flags |= PERLIO_F_EOF;
3603 PerlIOBase(f)->flags |= PERLIO_F_ERROR;
3606 b->end = b->buf + avail;
3607 PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
3612 PerlIOBuf_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
3614 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3615 if (PerlIOValid(f)) {
3618 return PerlIOBase_read(aTHX_ f, vbuf, count);
3624 PerlIOBuf_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
3626 const STDCHAR *buf = (const STDCHAR *) vbuf + count;
3627 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3630 if (PerlIOBase(f)->flags & PERLIO_F_WRBUF)
3635 if (PerlIOBase(f)->flags & PERLIO_F_RDBUF) {
3637 * Buffer is already a read buffer, we can overwrite any chars
3638 * which have been read back to buffer start
3640 avail = (b->ptr - b->buf);
3644 * Buffer is idle, set it up so whole buffer is available for
3648 b->end = b->buf + avail;
3650 PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
3652 * Buffer extends _back_ from where we are now
3654 b->posn -= b->bufsiz;
3656 if (avail > (SSize_t) count) {
3658 * If we have space for more than count, just move count
3666 * In simple stdio-like ungetc() case chars will be already
3669 if (buf != b->ptr) {
3670 Copy(buf, b->ptr, avail, STDCHAR);
3674 PerlIOBase(f)->flags &= ~PERLIO_F_EOF;
3678 unread += PerlIOBase_unread(aTHX_ f, vbuf, count);
3684 PerlIOBuf_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
3686 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3687 const STDCHAR *buf = (const STDCHAR *) vbuf;
3691 if (!(PerlIOBase(f)->flags & PERLIO_F_CANWRITE))
3693 if (PerlIOBase(f)->flags & PERLIO_F_RDBUF) {
3694 if (PerlIO_flush(f) != 0) {
3699 SSize_t avail = b->bufsiz - (b->ptr - b->buf);
3700 if ((SSize_t) count < avail)
3702 PerlIOBase(f)->flags |= PERLIO_F_WRBUF;
3703 if (PerlIOBase(f)->flags & PERLIO_F_LINEBUF) {
3718 Copy(buf, b->ptr, avail, STDCHAR);
3725 if (b->ptr >= (b->buf + b->bufsiz))
3728 if (PerlIOBase(f)->flags & PERLIO_F_UNBUF)
3734 PerlIOBuf_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
3737 if ((code = PerlIO_flush(f)) == 0) {
3738 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3739 PerlIOBase(f)->flags &= ~PERLIO_F_EOF;
3740 code = PerlIO_seek(PerlIONext(f), offset, whence);
3742 b->posn = PerlIO_tell(PerlIONext(f));
3749 PerlIOBuf_tell(pTHX_ PerlIO *f)
3751 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3753 * b->posn is file position where b->buf was read, or will be written
3755 Off_t posn = b->posn;
3756 if ((PerlIOBase(f)->flags & PERLIO_F_APPEND) &&
3757 (PerlIOBase(f)->flags & PERLIO_F_WRBUF)) {
3759 /* As O_APPEND files are normally shared in some sense it is better
3764 /* when file is NOT shared then this is sufficient */
3765 PerlIO_seek(PerlIONext(f),0, SEEK_END);
3767 posn = b->posn = PerlIO_tell(PerlIONext(f));
3771 * If buffer is valid adjust position by amount in buffer
3773 posn += (b->ptr - b->buf);
3779 PerlIOBuf_popped(pTHX_ PerlIO *f)
3781 IV code = PerlIOBase_popped(aTHX_ f);
3782 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3783 if (b->buf && b->buf != (STDCHAR *) & b->oneword) {
3787 b->ptr = b->end = b->buf;
3788 PerlIOBase(f)->flags &= ~(PERLIO_F_RDBUF | PERLIO_F_WRBUF);
3793 PerlIOBuf_close(pTHX_ PerlIO *f)
3795 IV code = PerlIOBase_close(aTHX_ f);
3796 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3797 if (b->buf && b->buf != (STDCHAR *) & b->oneword) {
3801 b->ptr = b->end = b->buf;
3802 PerlIOBase(f)->flags &= ~(PERLIO_F_RDBUF | PERLIO_F_WRBUF);
3807 PerlIOBuf_get_ptr(pTHX_ PerlIO *f)
3809 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3816 PerlIOBuf_get_cnt(pTHX_ PerlIO *f)
3818 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3821 if (PerlIOBase(f)->flags & PERLIO_F_RDBUF)
3822 return (b->end - b->ptr);
3827 PerlIOBuf_get_base(pTHX_ PerlIO *f)
3829 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3834 Newz('B',b->buf,b->bufsiz, STDCHAR);
3836 b->buf = (STDCHAR *) & b->oneword;
3837 b->bufsiz = sizeof(b->oneword);
3846 PerlIOBuf_bufsiz(pTHX_ PerlIO *f)
3848 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3851 return (b->end - b->buf);
3855 PerlIOBuf_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, SSize_t cnt)
3857 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3861 if (PerlIO_get_cnt(f) != cnt || b->ptr < b->buf) {
3862 assert(PerlIO_get_cnt(f) == cnt);
3863 assert(b->ptr >= b->buf);
3865 PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
3869 PerlIOBuf_dup(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags)
3871 return PerlIOBase_dup(aTHX_ f, o, param, flags);
3876 PerlIO_funcs PerlIO_perlio = {
3877 sizeof(PerlIO_funcs),
3880 PERLIO_K_BUFFERED|PERLIO_K_RAW,
3884 PerlIOBase_binmode, /* binmode */
3898 PerlIOBase_clearerr,
3899 PerlIOBase_setlinebuf,
3904 PerlIOBuf_set_ptrcnt,
3907 /*--------------------------------------------------------------------------------------*/
3909 * Temp layer to hold unread chars when cannot do it any other way
3913 PerlIOPending_fill(pTHX_ PerlIO *f)
3916 * Should never happen
3923 PerlIOPending_close(pTHX_ PerlIO *f)
3926 * A tad tricky - flush pops us, then we close new top
3929 return PerlIO_close(f);
3933 PerlIOPending_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
3936 * A tad tricky - flush pops us, then we seek new top
3939 return PerlIO_seek(f, offset, whence);
3944 PerlIOPending_flush(pTHX_ PerlIO *f)
3946 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3947 if (b->buf && b->buf != (STDCHAR *) & b->oneword) {
3951 PerlIO_pop(aTHX_ f);
3956 PerlIOPending_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, SSize_t cnt)
3962 PerlIOBuf_set_ptrcnt(aTHX_ f, ptr, cnt);
3967 PerlIOPending_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
3969 IV code = PerlIOBase_pushed(aTHX_ f, mode, arg, tab);
3970 PerlIOl *l = PerlIOBase(f);
3972 * Our PerlIO_fast_gets must match what we are pushed on, or sv_gets()
3973 * etc. get muddled when it changes mid-string when we auto-pop.
3975 l->flags = (l->flags & ~(PERLIO_F_FASTGETS | PERLIO_F_UTF8)) |
3976 (PerlIOBase(PerlIONext(f))->
3977 flags & (PERLIO_F_FASTGETS | PERLIO_F_UTF8));
3982 PerlIOPending_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
3984 SSize_t avail = PerlIO_get_cnt(f);
3986 if ((SSize_t)count < avail)
3989 got = PerlIOBuf_read(aTHX_ f, vbuf, avail);
3990 if (got >= 0 && got < (SSize_t)count) {
3992 PerlIO_read(f, ((STDCHAR *) vbuf) + got, count - got);
3993 if (more >= 0 || got == 0)
3999 PerlIO_funcs PerlIO_pending = {
4000 sizeof(PerlIO_funcs),
4003 PERLIO_K_BUFFERED|PERLIO_K_RAW, /* not sure about RAW here */
4004 PerlIOPending_pushed,
4007 PerlIOBase_binmode, /* binmode */
4016 PerlIOPending_close,
4017 PerlIOPending_flush,
4021 PerlIOBase_clearerr,
4022 PerlIOBase_setlinebuf,
4027 PerlIOPending_set_ptrcnt,
4032 /*--------------------------------------------------------------------------------------*/
4034 * crlf - translation On read translate CR,LF to "\n" we do this by
4035 * overriding ptr/cnt entries to hand back a line at a time and keeping a
4036 * record of which nl we "lied" about. On write translate "\n" to CR,LF
4040 PerlIOBuf base; /* PerlIOBuf stuff */
4041 STDCHAR *nl; /* Position of crlf we "lied" about in the
4046 PerlIOCrlf_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
4049 PerlIOBase(f)->flags |= PERLIO_F_CRLF;
4050 code = PerlIOBuf_pushed(aTHX_ f, mode, arg, tab);
4052 PerlIO_debug("PerlIOCrlf_pushed f=%p %s %s fl=%08" UVxf "\n",
4053 f, PerlIOBase(f)->tab->name, (mode) ? mode : "(Null)",
4054 PerlIOBase(f)->flags);
4057 /* Enable the first CRLF capable layer you can find, but if none
4058 * found, the one we just pushed is fine. This results in at
4059 * any given moment at most one CRLF-capable layer being enabled
4060 * in the whole layer stack. */
4061 PerlIO *g = PerlIONext(f);
4063 PerlIOl *b = PerlIOBase(g);
4064 if (b && b->tab == &PerlIO_crlf) {
4065 if (!(b->flags & PERLIO_F_CRLF))
4066 b->flags |= PERLIO_F_CRLF;
4067 PerlIO_pop(aTHX_ f);
4078 PerlIOCrlf_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
4080 PerlIOCrlf *c = PerlIOSelf(f, PerlIOCrlf);
4085 if (!(PerlIOBase(f)->flags & PERLIO_F_CRLF))
4086 return PerlIOBuf_unread(aTHX_ f, vbuf, count);
4088 const STDCHAR *buf = (const STDCHAR *) vbuf + count;
4089 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
4091 if (PerlIOBase(f)->flags & PERLIO_F_WRBUF)
4096 if (!(PerlIOBase(f)->flags & PERLIO_F_RDBUF)) {
4097 b->end = b->ptr = b->buf + b->bufsiz;
4098 PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
4099 b->posn -= b->bufsiz;
4101 while (count > 0 && b->ptr > b->buf) {
4104 if (b->ptr - 2 >= b->buf) {
4127 PerlIOCrlf_get_cnt(pTHX_ PerlIO *f)
4129 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
4132 if (PerlIOBase(f)->flags & PERLIO_F_RDBUF) {
4133 PerlIOCrlf *c = PerlIOSelf(f, PerlIOCrlf);
4134 if ((PerlIOBase(f)->flags & PERLIO_F_CRLF) && (!c->nl || *c->nl == 0xd)) {
4135 STDCHAR *nl = (c->nl) ? c->nl : b->ptr;
4137 while (nl < b->end && *nl != 0xd)
4139 if (nl < b->end && *nl == 0xd) {
4141 if (nl + 1 < b->end) {
4148 * Not CR,LF but just CR
4156 * Blast - found CR as last char in buffer
4161 * They may not care, defer work as long as
4165 return (nl - b->ptr);
4169 b->ptr++; /* say we have read it as far as
4170 * flush() is concerned */
4171 b->buf++; /* Leave space in front of buffer */
4172 /* Note as we have moved buf up flush's
4174 will naturally make posn point at CR
4176 b->bufsiz--; /* Buffer is thus smaller */
4177 code = PerlIO_fill(f); /* Fetch some more */
4178 b->bufsiz++; /* Restore size for next time */
4179 b->buf--; /* Point at space */
4180 b->ptr = nl = b->buf; /* Which is what we hand
4182 *nl = 0xd; /* Fill in the CR */
4184 goto test; /* fill() call worked */
4186 * CR at EOF - just fall through
4188 /* Should we clear EOF though ??? */
4193 return (((c->nl) ? (c->nl + 1) : b->end) - b->ptr);
4199 PerlIOCrlf_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, SSize_t cnt)
4201 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
4202 PerlIOCrlf *c = PerlIOSelf(f, PerlIOCrlf);
4208 if (ptr == b->end && *c->nl == 0xd) {
4209 /* Defered CR at end of buffer case - we lied about count */
4221 * Test code - delete when it works ...
4223 IV flags = PerlIOBase(f)->flags;
4224 STDCHAR *chk = (c->nl) ? (c->nl+1) : b->end;
4225 if (ptr+cnt == c->nl && c->nl+1 == b->end && *c->nl == 0xd) {
4226 /* Defered CR at end of buffer case - we lied about count */
4232 Perl_croak(aTHX_ "ptr wrong %p != %p fl=%08" UVxf
4233 " nl=%p e=%p for %d", ptr, chk, flags, c->nl,
4241 * They have taken what we lied about
4249 PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
4253 PerlIOCrlf_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
4255 if (!(PerlIOBase(f)->flags & PERLIO_F_CRLF))
4256 return PerlIOBuf_write(aTHX_ f, vbuf, count);
4258 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
4259 const STDCHAR *buf = (const STDCHAR *) vbuf;
4260 const STDCHAR *ebuf = buf + count;
4263 if (!(PerlIOBase(f)->flags & PERLIO_F_CANWRITE))
4265 while (buf < ebuf) {
4266 STDCHAR *eptr = b->buf + b->bufsiz;
4267 PerlIOBase(f)->flags |= PERLIO_F_WRBUF;
4268 while (buf < ebuf && b->ptr < eptr) {
4270 if ((b->ptr + 2) > eptr) {
4278 *(b->ptr)++ = 0xd; /* CR */
4279 *(b->ptr)++ = 0xa; /* LF */
4281 if (PerlIOBase(f)->flags & PERLIO_F_LINEBUF) {
4291 if (b->ptr >= eptr) {
4297 if (PerlIOBase(f)->flags & PERLIO_F_UNBUF)
4299 return (buf - (STDCHAR *) vbuf);
4304 PerlIOCrlf_flush(pTHX_ PerlIO *f)
4306 PerlIOCrlf *c = PerlIOSelf(f, PerlIOCrlf);
4311 return PerlIOBuf_flush(aTHX_ f);
4315 PerlIOCrlf_binmode(pTHX_ PerlIO *f)
4317 if ((PerlIOBase(f)->flags & PERLIO_F_CRLF)) {
4318 /* In text mode - flush any pending stuff and flip it */
4319 PerlIOBase(f)->flags &= ~PERLIO_F_CRLF;
4320 #ifndef PERLIO_USING_CRLF
4321 /* CRLF is unusual case - if this is just the :crlf layer pop it */
4322 if (PerlIOBase(f)->tab == &PerlIO_crlf) {
4323 PerlIO_pop(aTHX_ f);
4330 PerlIO_funcs PerlIO_crlf = {
4331 sizeof(PerlIO_funcs),
4334 PERLIO_K_BUFFERED | PERLIO_K_CANCRLF | PERLIO_K_RAW,
4336 PerlIOBuf_popped, /* popped */
4338 PerlIOCrlf_binmode, /* binmode */
4342 PerlIOBuf_read, /* generic read works with ptr/cnt lies
4344 PerlIOCrlf_unread, /* Put CR,LF in buffer for each '\n' */
4345 PerlIOCrlf_write, /* Put CR,LF in buffer for each '\n' */
4353 PerlIOBase_clearerr,
4354 PerlIOBase_setlinebuf,
4359 PerlIOCrlf_set_ptrcnt,
4363 /*--------------------------------------------------------------------------------------*/
4365 * mmap as "buffer" layer
4369 PerlIOBuf base; /* PerlIOBuf stuff */
4370 Mmap_t mptr; /* Mapped address */
4371 Size_t len; /* mapped length */
4372 STDCHAR *bbuf; /* malloced buffer if map fails */
4375 static size_t page_size = 0;
4378 PerlIOMmap_map(pTHX_ PerlIO *f)
4380 PerlIOMmap *m = PerlIOSelf(f, PerlIOMmap);
4381 IV flags = PerlIOBase(f)->flags;
4385 if (flags & PERLIO_F_CANREAD) {
4386 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
4387 int fd = PerlIO_fileno(f);
4389 code = Fstat(fd, &st);
4390 if (code == 0 && S_ISREG(st.st_mode)) {
4391 SSize_t len = st.st_size - b->posn;
4395 #if defined(HAS_SYSCONF) && (defined(_SC_PAGESIZE) || defined(_SC_PAGE_SIZE))
4397 SETERRNO(0, SS_NORMAL);
4398 # ifdef _SC_PAGESIZE
4399 page_size = sysconf(_SC_PAGESIZE);
4401 page_size = sysconf(_SC_PAGE_SIZE);
4403 if ((long) page_size < 0) {
4408 (void) SvUPGRADE(error, SVt_PV);
4409 msg = SvPVx(error, n_a);
4410 Perl_croak(aTHX_ "panic: sysconf: %s",
4415 "panic: sysconf: pagesize unknown");
4419 # ifdef HAS_GETPAGESIZE
4420 page_size = getpagesize();
4422 # if defined(I_SYS_PARAM) && defined(PAGESIZE)
4423 page_size = PAGESIZE; /* compiletime, bad */
4427 if ((IV) page_size <= 0)
4428 Perl_croak(aTHX_ "panic: bad pagesize %" IVdf,
4433 * This is a hack - should never happen - open should
4436 b->posn = PerlIO_tell(PerlIONext(f));
4438 posn = (b->posn / page_size) * page_size;
4439 len = st.st_size - posn;
4440 m->mptr = mmap(NULL, len, PROT_READ, MAP_SHARED, fd, posn);
4441 if (m->mptr && m->mptr != (Mmap_t) - 1) {
4442 #if 0 && defined(HAS_MADVISE) && defined(MADV_SEQUENTIAL)
4443 madvise(m->mptr, len, MADV_SEQUENTIAL);
4445 #if 0 && defined(HAS_MADVISE) && defined(MADV_WILLNEED)
4446 madvise(m->mptr, len, MADV_WILLNEED);
4448 PerlIOBase(f)->flags =
4449 (flags & ~PERLIO_F_EOF) | PERLIO_F_RDBUF;
4450 b->end = ((STDCHAR *) m->mptr) + len;
4451 b->buf = ((STDCHAR *) m->mptr) + (b->posn - posn);
4460 PerlIOBase(f)->flags =
4461 flags | PERLIO_F_EOF | PERLIO_F_RDBUF;
4463 b->ptr = b->end = b->ptr;
4472 PerlIOMmap_unmap(pTHX_ PerlIO *f)
4474 PerlIOMmap *m = PerlIOSelf(f, PerlIOMmap);
4475 PerlIOBuf *b = &m->base;
4479 code = munmap(m->mptr, m->len);
4483 if (PerlIO_seek(PerlIONext(f), b->posn, SEEK_SET) != 0)
4486 b->ptr = b->end = b->buf;
4487 PerlIOBase(f)->flags &= ~(PERLIO_F_RDBUF | PERLIO_F_WRBUF);
4493 PerlIOMmap_get_base(pTHX_ PerlIO *f)
4495 PerlIOMmap *m = PerlIOSelf(f, PerlIOMmap);
4496 PerlIOBuf *b = &m->base;
4497 if (b->buf && (PerlIOBase(f)->flags & PERLIO_F_RDBUF)) {
4499 * Already have a readbuffer in progress
4505 * We have a write buffer or flushed PerlIOBuf read buffer
4507 m->bbuf = b->buf; /* save it in case we need it again */
4508 b->buf = NULL; /* Clear to trigger below */
4511 PerlIOMmap_map(aTHX_ f); /* Try and map it */
4514 * Map did not work - recover PerlIOBuf buffer if we have one
4519 b->ptr = b->end = b->buf;
4522 return PerlIOBuf_get_base(aTHX_ f);
4526 PerlIOMmap_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
4528 PerlIOMmap *m = PerlIOSelf(f, PerlIOMmap);
4529 PerlIOBuf *b = &m->base;
4530 if (PerlIOBase(f)->flags & PERLIO_F_WRBUF)
4532 if (b->ptr && (b->ptr - count) >= b->buf
4533 && memEQ(b->ptr - count, vbuf, count)) {
4535 PerlIOBase(f)->flags &= ~PERLIO_F_EOF;
4540 * Loose the unwritable mapped buffer
4544 * If flush took the "buffer" see if we have one from before
4546 if (!b->buf && m->bbuf)
4549 PerlIOBuf_get_base(aTHX_ f);
4553 return PerlIOBuf_unread(aTHX_ f, vbuf, count);
4557 PerlIOMmap_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
4559 PerlIOMmap *m = PerlIOSelf(f, PerlIOMmap);
4560 PerlIOBuf *b = &m->base;
4561 if (!b->buf || !(PerlIOBase(f)->flags & PERLIO_F_WRBUF)) {
4563 * No, or wrong sort of, buffer
4566 if (PerlIOMmap_unmap(aTHX_ f) != 0)
4570 * If unmap took the "buffer" see if we have one from before
4572 if (!b->buf && m->bbuf)
4575 PerlIOBuf_get_base(aTHX_ f);
4579 return PerlIOBuf_write(aTHX_ f, vbuf, count);
4583 PerlIOMmap_flush(pTHX_ PerlIO *f)
4585 PerlIOMmap *m = PerlIOSelf(f, PerlIOMmap);
4586 PerlIOBuf *b = &m->base;
4587 IV code = PerlIOBuf_flush(aTHX_ f);
4589 * Now we are "synced" at PerlIOBuf level
4596 if (PerlIOMmap_unmap(aTHX_ f) != 0)
4601 * We seem to have a PerlIOBuf buffer which was not mapped
4602 * remember it in case we need one later
4611 PerlIOMmap_fill(pTHX_ PerlIO *f)
4613 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
4614 IV code = PerlIO_flush(f);
4615 if (code == 0 && !b->buf) {
4616 code = PerlIOMmap_map(aTHX_ f);
4618 if (code == 0 && !(PerlIOBase(f)->flags & PERLIO_F_RDBUF)) {
4619 code = PerlIOBuf_fill(aTHX_ f);
4625 PerlIOMmap_close(pTHX_ PerlIO *f)
4627 PerlIOMmap *m = PerlIOSelf(f, PerlIOMmap);
4628 PerlIOBuf *b = &m->base;
4629 IV code = PerlIO_flush(f);
4633 b->ptr = b->end = b->buf;
4635 if (PerlIOBuf_close(aTHX_ f) != 0)
4641 PerlIOMmap_dup(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags)
4643 return PerlIOBase_dup(aTHX_ f, o, param, flags);
4647 PerlIO_funcs PerlIO_mmap = {
4648 sizeof(PerlIO_funcs),
4651 PERLIO_K_BUFFERED|PERLIO_K_RAW,
4655 PerlIOBase_binmode, /* binmode */
4669 PerlIOBase_clearerr,
4670 PerlIOBase_setlinebuf,
4671 PerlIOMmap_get_base,
4675 PerlIOBuf_set_ptrcnt,
4678 #endif /* HAS_MMAP */
4681 Perl_PerlIO_stdin(pTHX)
4684 PerlIO_stdstreams(aTHX);
4686 return &PL_perlio[1];
4690 Perl_PerlIO_stdout(pTHX)
4693 PerlIO_stdstreams(aTHX);
4695 return &PL_perlio[2];
4699 Perl_PerlIO_stderr(pTHX)
4702 PerlIO_stdstreams(aTHX);
4704 return &PL_perlio[3];
4707 /*--------------------------------------------------------------------------------------*/
4710 PerlIO_getname(PerlIO *f, char *buf)
4715 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
4717 name = fgetname(stdio, buf);
4719 Perl_croak(aTHX_ "Don't know how to get file name");
4725 /*--------------------------------------------------------------------------------------*/
4727 * Functions which can be called on any kind of PerlIO implemented in
4731 #undef PerlIO_fdopen
4733 PerlIO_fdopen(int fd, const char *mode)
4736 return PerlIO_openn(aTHX_ Nullch, mode, fd, 0, 0, NULL, 0, NULL);
4741 PerlIO_open(const char *path, const char *mode)
4744 SV *name = sv_2mortal(newSVpvn(path, strlen(path)));
4745 return PerlIO_openn(aTHX_ Nullch, mode, -1, 0, 0, NULL, 1, &name);
4748 #undef Perlio_reopen
4750 PerlIO_reopen(const char *path, const char *mode, PerlIO *f)
4753 SV *name = sv_2mortal(newSVpvn(path, strlen(path)));
4754 return PerlIO_openn(aTHX_ Nullch, mode, -1, 0, 0, f, 1, &name);
4759 PerlIO_getc(PerlIO *f)
4763 SSize_t count = PerlIO_read(f, buf, 1);
4765 return (unsigned char) buf[0];
4770 #undef PerlIO_ungetc
4772 PerlIO_ungetc(PerlIO *f, int ch)
4777 if (PerlIO_unread(f, &buf, 1) == 1)
4785 PerlIO_putc(PerlIO *f, int ch)
4789 return PerlIO_write(f, &buf, 1);
4794 PerlIO_puts(PerlIO *f, const char *s)
4797 STRLEN len = strlen(s);
4798 return PerlIO_write(f, s, len);
4801 #undef PerlIO_rewind
4803 PerlIO_rewind(PerlIO *f)
4806 PerlIO_seek(f, (Off_t) 0, SEEK_SET);
4810 #undef PerlIO_vprintf
4812 PerlIO_vprintf(PerlIO *f, const char *fmt, va_list ap)
4815 SV *sv = newSVpvn("", 0);
4821 Perl_va_copy(ap, apc);
4822 sv_vcatpvf(sv, fmt, &apc);
4824 sv_vcatpvf(sv, fmt, &ap);
4827 wrote = PerlIO_write(f, s, len);
4832 #undef PerlIO_printf
4834 PerlIO_printf(PerlIO *f, const char *fmt, ...)
4839 result = PerlIO_vprintf(f, fmt, ap);
4844 #undef PerlIO_stdoutf
4846 PerlIO_stdoutf(const char *fmt, ...)
4852 result = PerlIO_vprintf(PerlIO_stdout(), fmt, ap);
4857 #undef PerlIO_tmpfile
4859 PerlIO_tmpfile(void)
4867 f = PerlIO_fdopen(fd, "w+b");
4869 # if defined(HAS_MKSTEMP) && ! defined(VMS)
4870 SV *sv = newSVpv("/tmp/PerlIO_XXXXXX", 0);
4873 * I have no idea how portable mkstemp() is ... NI-S
4875 fd = mkstemp(SvPVX(sv));
4877 f = PerlIO_fdopen(fd, "w+");
4879 PerlIOBase(f)->flags |= PERLIO_F_TEMP;
4880 PerlLIO_unlink(SvPVX(sv));
4883 # else /* !HAS_MKSTEMP, fallback to stdio tmpfile(). */
4884 FILE *stdio = PerlSIO_tmpfile();
4887 if ((f = PerlIO_push(aTHX_(PerlIO_allocate(aTHX)),
4888 &PerlIO_stdio, "w+", Nullsv))) {
4889 PerlIOStdio *s = PerlIOSelf(f, PerlIOStdio);
4895 # endif /* else HAS_MKSTEMP */
4896 #endif /* else WIN32 */
4903 #endif /* USE_SFIO */
4904 #endif /* PERLIO_IS_STDIO */
4906 /*======================================================================================*/
4908 * Now some functions in terms of above which may be needed even if we are
4909 * not in true PerlIO mode
4913 #undef PerlIO_setpos
4915 PerlIO_setpos(PerlIO *f, SV *pos)
4920 Off_t *posn = (Off_t *) SvPV(pos, len);
4921 if (f && len == sizeof(Off_t))
4922 return PerlIO_seek(f, *posn, SEEK_SET);
4924 SETERRNO(EINVAL, SS_IVCHAN);
4928 #undef PerlIO_setpos
4930 PerlIO_setpos(PerlIO *f, SV *pos)
4935 Fpos_t *fpos = (Fpos_t *) SvPV(pos, len);
4936 if (f && len == sizeof(Fpos_t)) {
4937 #if defined(USE_64_BIT_STDIO) && defined(USE_FSETPOS64)
4938 return fsetpos64(f, fpos);
4940 return fsetpos(f, fpos);
4944 SETERRNO(EINVAL, SS_IVCHAN);
4950 #undef PerlIO_getpos
4952 PerlIO_getpos(PerlIO *f, SV *pos)
4955 Off_t posn = PerlIO_tell(f);
4956 sv_setpvn(pos, (char *) &posn, sizeof(posn));
4957 return (posn == (Off_t) - 1) ? -1 : 0;
4960 #undef PerlIO_getpos
4962 PerlIO_getpos(PerlIO *f, SV *pos)
4967 #if defined(USE_64_BIT_STDIO) && defined(USE_FSETPOS64)
4968 code = fgetpos64(f, &fpos);
4970 code = fgetpos(f, &fpos);
4972 sv_setpvn(pos, (char *) &fpos, sizeof(fpos));
4977 #if (defined(PERLIO_IS_STDIO) || !defined(USE_SFIO)) && !defined(HAS_VPRINTF)
4980 vprintf(char *pat, char *args)
4982 _doprnt(pat, args, stdout);
4983 return 0; /* wrong, but perl doesn't use the return
4988 vfprintf(FILE *fd, char *pat, char *args)
4990 _doprnt(pat, args, fd);
4991 return 0; /* wrong, but perl doesn't use the return
4997 #ifndef PerlIO_vsprintf
4999 PerlIO_vsprintf(char *s, int n, const char *fmt, va_list ap)
5001 int val = vsprintf(s, fmt, ap);
5003 if (strlen(s) >= (STRLEN) n) {
5005 (void) PerlIO_puts(Perl_error_log,
5006 "panic: sprintf overflow - memory corrupted!\n");
5014 #ifndef PerlIO_sprintf
5016 PerlIO_sprintf(char *s, int n, const char *fmt, ...)
5021 result = PerlIO_vsprintf(s, n, fmt, ap);