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
53 /* Call the callback or PerlIOBase, and return failure. */
54 #define Perl_PerlIO_or_Base(f, callback, base, failure, args) \
55 if (PerlIOValid(f)) { \
56 PerlIO_funcs *tab = PerlIOBase(f)->tab; \
57 if (tab && tab->callback) \
58 return (*tab->callback) args; \
60 return PerlIOBase_ ## base args; \
63 SETERRNO(EBADF, SS_IVCHAN); \
66 /* Call the callback or fail, and return failure. */
67 #define Perl_PerlIO_or_fail(f, callback, failure, args) \
68 if (PerlIOValid(f)) { \
69 PerlIO_funcs *tab = PerlIOBase(f)->tab; \
70 if (tab && tab->callback) \
71 return (*tab->callback) args; \
72 SETERRNO(EINVAL, LIB_INVARG); \
75 SETERRNO(EBADF, SS_IVCHAN); \
78 /* Call the callback or PerlIOBase, and be void. */
79 #define Perl_PerlIO_or_Base_void(f, callback, base, args) \
80 if (PerlIOValid(f)) { \
81 PerlIO_funcs *tab = PerlIOBase(f)->tab; \
82 if (tab && tab->callback) \
83 (*tab->callback) args; \
85 PerlIOBase_ ## base args; \
88 SETERRNO(EBADF, SS_IVCHAN)
90 /* Call the callback or fail, and be void. */
91 #define Perl_PerlIO_or_fail_void(f, callback, args) \
92 if (PerlIOValid(f)) { \
93 PerlIO_funcs *tab = PerlIOBase(f)->tab; \
94 if (tab && tab->callback) \
95 (*tab->callback) args; \
97 SETERRNO(EINVAL, LIB_INVARG); \
100 SETERRNO(EBADF, SS_IVCHAN)
103 perlsio_binmode(FILE *fp, int iotype, int mode)
106 * This used to be contents of do_binmode in doio.c
109 # if defined(atarist) || defined(__MINT__)
112 ((FILE *) fp)->_flag |= _IOBIN;
114 ((FILE *) fp)->_flag &= ~_IOBIN;
121 if (PerlLIO_setmode(fp, mode) != -1) {
123 if (PerlLIO_setmode(fileno(fp), mode) != -1) {
125 # if defined(WIN32) && defined(__BORLANDC__)
127 * The translation mode of the stream is maintained independent of
128 * the translation mode of the fd in the Borland RTL (heavy
129 * digging through their runtime sources reveal). User has to set
130 * the mode explicitly for the stream (though they don't document
131 * this anywhere). GSAR 97-5-24
137 fp->flags &= ~_F_BIN;
145 # if defined(USEMYBINMODE)
147 if (my_binmode(fp, iotype, mode) != FALSE)
158 #define O_ACCMODE 3 /* Assume traditional implementation */
162 PerlIO_intmode2str(int rawmode, char *mode, int *writing)
164 int result = rawmode & O_ACCMODE;
169 ptype = IoTYPE_RDONLY;
172 ptype = IoTYPE_WRONLY;
180 *writing = (result != O_RDONLY);
182 if (result == O_RDONLY) {
186 else if (rawmode & O_APPEND) {
188 if (result != O_WRONLY)
193 if (result == O_WRONLY)
200 if (rawmode & O_BINARY)
206 #ifndef PERLIO_LAYERS
208 PerlIO_apply_layers(pTHX_ PerlIO *f, const char *mode, const char *names)
210 if (!names || !*names
211 || strEQ(names, ":crlf")
212 || strEQ(names, ":raw")
213 || strEQ(names, ":bytes")
217 Perl_croak(aTHX_ "Cannot apply \"%s\" in non-PerlIO perl", names);
225 PerlIO_destruct(pTHX)
230 PerlIO_binmode(pTHX_ PerlIO *fp, int iotype, int mode, const char *names)
235 return perlsio_binmode(fp, iotype, mode);
240 PerlIO_fdupopen(pTHX_ PerlIO *f, CLONE_PARAMS *param, int flags)
245 #ifdef PERL_IMPLICIT_SYS
246 return PerlSIO_fdupopen(f);
249 return win32_fdupopen(f);
252 int fd = PerlLIO_dup(PerlIO_fileno(f));
255 int omode = fcntl(fd, F_GETFL);
257 omode = djgpp_get_stream_mode(f);
259 PerlIO_intmode2str(omode,mode,NULL);
260 /* the r+ is a hack */
261 return PerlIO_fdopen(fd, mode);
266 SETERRNO(EBADF, SS_IVCHAN);
276 * De-mux PerlIO_openn() into fdopen, freopen and fopen type entries
280 PerlIO_openn(pTHX_ const char *layers, const char *mode, int fd,
281 int imode, int perm, PerlIO *old, int narg, SV **args)
285 Perl_croak(aTHX_ "More than one argument to open");
287 if (*args == &PL_sv_undef)
288 return PerlIO_tmpfile();
290 char *name = SvPV_nolen(*args);
292 fd = PerlLIO_open3(name, imode, perm);
294 return PerlIO_fdopen(fd, (char *) mode + 1);
297 return PerlIO_reopen(name, mode, old);
300 return PerlIO_open(name, mode);
305 return PerlIO_fdopen(fd, (char *) mode);
310 XS(XS_PerlIO__Layer__find)
314 Perl_croak(aTHX_ "Usage class->find(name[,load])");
316 char *name = SvPV_nolen(ST(1));
317 ST(0) = (strEQ(name, "crlf")
318 || strEQ(name, "raw")) ? &PL_sv_yes : &PL_sv_undef;
325 Perl_boot_core_PerlIO(pTHX)
327 newXS("PerlIO::Layer::find", XS_PerlIO__Layer__find, __FILE__);
333 #ifdef PERLIO_IS_STDIO
339 * Does nothing (yet) except force this file to be included in perl
340 * binary. That allows this file to force inclusion of other functions
341 * that may be required by loadable extensions e.g. for
342 * FileHandle::tmpfile
346 #undef PerlIO_tmpfile
353 #else /* PERLIO_IS_STDIO */
361 * This section is just to make sure these functions get pulled in from
365 #undef PerlIO_tmpfile
376 * Force this file to be included in perl binary. Which allows this
377 * file to force inclusion of other functions that may be required by
378 * loadable extensions e.g. for FileHandle::tmpfile
382 * Hack sfio does its own 'autoflush' on stdout in common cases. Flush
383 * results in a lot of lseek()s to regular files and lot of small
386 sfset(sfstdout, SF_SHARE, 0);
389 /* This is not the reverse of PerlIO_exportFILE(), PerlIO_releaseFILE() is. */
391 PerlIO_importFILE(FILE *stdio, const char *mode)
393 int fd = fileno(stdio);
394 if (!mode || !*mode) {
397 return PerlIO_fdopen(fd, mode);
401 PerlIO_findFILE(PerlIO *pio)
403 int fd = PerlIO_fileno(pio);
404 FILE *f = fdopen(fd, "r+");
406 if (!f && errno == EINVAL)
408 if (!f && errno == EINVAL)
415 /*======================================================================================*/
417 * Implement all the PerlIO interface ourselves.
423 * We _MUST_ have <unistd.h> if we are using lseek() and may have large
430 #include <sys/mman.h>
434 * Why is this here - not in perlio.h? RMB
436 void PerlIO_debug(const char *fmt, ...)
437 __attribute__format__(__printf__, 1, 2);
440 PerlIO_debug(const char *fmt, ...)
447 char *s = PerlEnv_getenv("PERLIO_DEBUG");
449 dbg = PerlLIO_open3(s, O_WRONLY | O_CREAT | O_APPEND, 0666);
456 /* Use fixed buffer as sv_catpvf etc. needs SVs */
460 s = CopFILE(PL_curcop);
463 sprintf(buffer, "%s:%" IVdf " ", s, (IV) CopLINE(PL_curcop));
464 len = strlen(buffer);
465 vsprintf(buffer+len, fmt, ap);
466 PerlLIO_write(dbg, buffer, strlen(buffer));
468 SV *sv = newSVpvn("", 0);
471 s = CopFILE(PL_curcop);
474 Perl_sv_catpvf(aTHX_ sv, "%s:%" IVdf " ", s,
475 (IV) CopLINE(PL_curcop));
476 Perl_sv_vcatpvf(aTHX_ sv, fmt, &ap);
479 PerlLIO_write(dbg, s, len);
486 /*--------------------------------------------------------------------------------------*/
489 * Inner level routines
493 * Table of pointers to the PerlIO structs (malloc'ed)
495 #define PERLIO_TABLE_SIZE 64
498 PerlIO_allocate(pTHX)
501 * Find a free slot in the table, allocating new table as necessary
506 while ((f = *last)) {
508 last = (PerlIO **) (f);
509 for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
515 Newz('I',f,PERLIO_TABLE_SIZE,PerlIO);
523 #undef PerlIO_fdupopen
525 PerlIO_fdupopen(pTHX_ PerlIO *f, CLONE_PARAMS *param, int flags)
527 if (PerlIOValid(f)) {
528 PerlIO_funcs *tab = PerlIOBase(f)->tab;
529 PerlIO_debug("fdupopen f=%p param=%p\n",(void*)f,(void*)param);
531 return (*tab->Dup)(aTHX_ PerlIO_allocate(aTHX), f, param, flags);
533 return PerlIOBase_dup(aTHX_ PerlIO_allocate(aTHX), f, param, flags);
537 SETERRNO(EBADF, SS_IVCHAN);
543 PerlIO_cleantable(pTHX_ PerlIO **tablep)
545 PerlIO *table = *tablep;
548 PerlIO_cleantable(aTHX_(PerlIO **) & (table[0]));
549 for (i = PERLIO_TABLE_SIZE - 1; i > 0; i--) {
550 PerlIO *f = table + i;
562 PerlIO_list_alloc(pTHX)
565 Newz('L', list, 1, PerlIO_list_t);
571 PerlIO_list_free(pTHX_ PerlIO_list_t *list)
574 if (--list->refcnt == 0) {
577 for (i = 0; i < list->cur; i++) {
578 if (list->array[i].arg)
579 SvREFCNT_dec(list->array[i].arg);
581 Safefree(list->array);
589 PerlIO_list_push(pTHX_ PerlIO_list_t *list, PerlIO_funcs *funcs, SV *arg)
592 if (list->cur >= list->len) {
595 Renew(list->array, list->len, PerlIO_pair_t);
597 New('l', list->array, list->len, PerlIO_pair_t);
599 p = &(list->array[list->cur++]);
601 if ((p->arg = arg)) {
607 PerlIO_clone_list(pTHX_ PerlIO_list_t *proto, CLONE_PARAMS *param)
609 PerlIO_list_t *list = (PerlIO_list_t *) NULL;
612 list = PerlIO_list_alloc(aTHX);
613 for (i=0; i < proto->cur; i++) {
615 if (proto->array[i].arg)
616 arg = PerlIO_sv_dup(aTHX_ proto->array[i].arg,param);
617 PerlIO_list_push(aTHX_ list, proto->array[i].funcs, arg);
624 PerlIO_clone(pTHX_ PerlInterpreter *proto, CLONE_PARAMS *param)
627 PerlIO **table = &proto->Iperlio;
630 PL_known_layers = PerlIO_clone_list(aTHX_ proto->Iknown_layers, param);
631 PL_def_layerlist = PerlIO_clone_list(aTHX_ proto->Idef_layerlist, param);
632 PerlIO_allocate(aTHX); /* root slot is never used */
633 PerlIO_debug("Clone %p from %p\n",aTHX,proto);
634 while ((f = *table)) {
636 table = (PerlIO **) (f++);
637 for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
639 (void) fp_dup(f, 0, param);
648 PerlIO_destruct(pTHX)
650 PerlIO **table = &PL_perlio;
653 PerlIO_debug("Destruct %p\n",aTHX);
655 while ((f = *table)) {
657 table = (PerlIO **) (f++);
658 for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
662 if (l->tab->kind & PERLIO_K_DESTRUCT) {
663 PerlIO_debug("Destruct popping %s\n", l->tab->name);
677 PerlIO_pop(pTHX_ PerlIO *f)
681 PerlIO_debug("PerlIO_pop f=%p %s\n", (void*)f, l->tab->name);
682 if (l->tab->Popped) {
684 * If popped returns non-zero do not free its layer structure
685 * it has either done so itself, or it is shared and still in
688 if ((*l->tab->Popped) (aTHX_ f) != 0)
696 /* Return as an array the stack of layers on a filehandle. Note that
697 * the stack is returned top-first in the array, and there are three
698 * times as many array elements as there are layers in the stack: the
699 * first element of a layer triplet is the name, the second one is the
700 * arguments, and the third one is the flags. */
703 PerlIO_get_layers(pTHX_ PerlIO *f)
707 if (PerlIOValid(f)) {
708 PerlIOl *l = PerlIOBase(f);
711 SV *name = l->tab && l->tab->name ?
712 newSVpv(l->tab->name, 0) : &PL_sv_undef;
713 SV *arg = l->tab && l->tab->Getarg ?
714 (*l->tab->Getarg)(aTHX_ &l, 0, 0) : &PL_sv_undef;
717 av_push(av, newSViv((IV)l->flags));
725 /*--------------------------------------------------------------------------------------*/
727 * XS Interface for perl code
731 PerlIO_find_layer(pTHX_ const char *name, STRLEN len, int load)
734 if ((SSize_t) len <= 0)
736 for (i = 0; i < PL_known_layers->cur; i++) {
737 PerlIO_funcs *f = PL_known_layers->array[i].funcs;
738 if (memEQ(f->name, name, len)) {
739 PerlIO_debug("%.*s => %p\n", (int) len, name, (void*)f);
743 if (load && PL_subname && PL_def_layerlist
744 && PL_def_layerlist->cur >= 2) {
745 if (PL_in_load_module) {
746 Perl_croak(aTHX_ "Recursive call to Perl_load_module in PerlIO_find_layer");
749 SV *pkgsv = newSVpvn("PerlIO", 6);
750 SV *layer = newSVpvn(name, len);
751 CV *cv = get_cv("PerlIO::Layer::NoWarnings", FALSE);
753 SAVEINT(PL_in_load_module);
755 SAVESPTR(PL_warnhook);
756 PL_warnhook = (SV *) cv;
760 * The two SVs are magically freed by load_module
762 Perl_load_module(aTHX_ 0, pkgsv, Nullsv, layer, Nullsv);
765 return PerlIO_find_layer(aTHX_ name, len, 0);
768 PerlIO_debug("Cannot find %.*s\n", (int) len, name);
772 #ifdef USE_ATTRIBUTES_FOR_PERLIO
775 perlio_mg_set(pTHX_ SV *sv, MAGIC *mg)
778 IO *io = GvIOn((GV *) SvRV(sv));
779 PerlIO *ifp = IoIFP(io);
780 PerlIO *ofp = IoOFP(io);
781 Perl_warn(aTHX_ "set %" SVf " %p %p %p", sv, io, ifp, ofp);
787 perlio_mg_get(pTHX_ SV *sv, MAGIC *mg)
790 IO *io = GvIOn((GV *) SvRV(sv));
791 PerlIO *ifp = IoIFP(io);
792 PerlIO *ofp = IoOFP(io);
793 Perl_warn(aTHX_ "get %" SVf " %p %p %p", sv, io, ifp, ofp);
799 perlio_mg_clear(pTHX_ SV *sv, MAGIC *mg)
801 Perl_warn(aTHX_ "clear %" SVf, sv);
806 perlio_mg_free(pTHX_ SV *sv, MAGIC *mg)
808 Perl_warn(aTHX_ "free %" SVf, sv);
812 MGVTBL perlio_vtab = {
820 XS(XS_io_MODIFY_SCALAR_ATTRIBUTES)
823 SV *sv = SvRV(ST(1));
828 sv_magic(sv, (SV *) av, PERL_MAGIC_ext, NULL, 0);
830 mg = mg_find(sv, PERL_MAGIC_ext);
831 mg->mg_virtual = &perlio_vtab;
833 Perl_warn(aTHX_ "attrib %" SVf, sv);
834 for (i = 2; i < items; i++) {
836 const char *name = SvPV(ST(i), len);
837 SV *layer = PerlIO_find_layer(aTHX_ name, len, 1);
839 av_push(av, SvREFCNT_inc(layer));
850 #endif /* USE_ATTIBUTES_FOR_PERLIO */
853 PerlIO_tab_sv(pTHX_ PerlIO_funcs *tab)
855 HV *stash = gv_stashpv("PerlIO::Layer", TRUE);
856 SV *sv = sv_bless(newRV_noinc(newSViv(PTR2IV(tab))), stash);
860 XS(XS_PerlIO__Layer__NoWarnings)
862 /* This is used as a %SIG{__WARN__} handler to supress warnings
863 during loading of layers.
867 PerlIO_debug("warning:%s\n",SvPV_nolen(ST(0)));
871 XS(XS_PerlIO__Layer__find)
875 Perl_croak(aTHX_ "Usage class->find(name[,load])");
878 char *name = SvPV(ST(1), len);
879 bool load = (items > 2) ? SvTRUE(ST(2)) : 0;
880 PerlIO_funcs *layer = PerlIO_find_layer(aTHX_ name, len, load);
882 (layer) ? sv_2mortal(PerlIO_tab_sv(aTHX_ layer)) :
889 PerlIO_define_layer(pTHX_ PerlIO_funcs *tab)
891 if (!PL_known_layers)
892 PL_known_layers = PerlIO_list_alloc(aTHX);
893 PerlIO_list_push(aTHX_ PL_known_layers, tab, Nullsv);
894 PerlIO_debug("define %s %p\n", tab->name, (void*)tab);
898 PerlIO_parse_layers(pTHX_ PerlIO_list_t *av, const char *names)
901 const char *s = names;
903 while (isSPACE(*s) || *s == ':')
908 const char *as = Nullch;
910 if (!isIDFIRST(*s)) {
912 * Message is consistent with how attribute lists are
913 * passed. Even though this means "foo : : bar" is
914 * seen as an invalid separator character.
916 char q = ((*s == '\'') ? '"' : '\'');
917 if (ckWARN(WARN_LAYER))
918 Perl_warner(aTHX_ packWARN(WARN_LAYER),
919 "perlio: invalid separator character %c%c%c in layer specification list %s",
921 SETERRNO(EINVAL, LIB_INVARG);
926 } while (isALNUM(*e));
942 * It's a nul terminated string, not allowed
943 * to \ the terminating null. Anything other
944 * character is passed over.
954 if (ckWARN(WARN_LAYER))
955 Perl_warner(aTHX_ packWARN(WARN_LAYER),
956 "perlio: argument list not closed for layer \"%.*s\"",
968 bool warn_layer = ckWARN(WARN_LAYER);
969 PerlIO_funcs *layer =
970 PerlIO_find_layer(aTHX_ s, llen, 1);
972 PerlIO_list_push(aTHX_ av, layer,
979 Perl_warner(aTHX_ packWARN(WARN_LAYER), "perlio: unknown layer \"%.*s\"",
992 PerlIO_default_buffer(pTHX_ PerlIO_list_t *av)
994 PerlIO_funcs *tab = &PerlIO_perlio;
995 #ifdef PERLIO_USING_CRLF
998 if (PerlIO_stdio.Set_ptrcnt)
1001 PerlIO_debug("Pushing %s\n", tab->name);
1002 PerlIO_list_push(aTHX_ av, PerlIO_find_layer(aTHX_ tab->name, 0, 0),
1007 PerlIO_arg_fetch(PerlIO_list_t *av, IV n)
1009 return av->array[n].arg;
1013 PerlIO_layer_fetch(pTHX_ PerlIO_list_t *av, IV n, PerlIO_funcs *def)
1015 if (n >= 0 && n < av->cur) {
1016 PerlIO_debug("Layer %" IVdf " is %s\n", n,
1017 av->array[n].funcs->name);
1018 return av->array[n].funcs;
1021 Perl_croak(aTHX_ "panic: PerlIO layer array corrupt");
1026 PerlIOPop_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
1028 if (PerlIOValid(f)) {
1030 PerlIO_pop(aTHX_ f);
1036 PerlIO_funcs PerlIO_remove = {
1037 sizeof(PerlIO_funcs),
1040 PERLIO_K_DUMMY | PERLIO_K_UTF8,
1058 NULL, /* get_base */
1059 NULL, /* get_bufsiz */
1062 NULL, /* set_ptrcnt */
1066 PerlIO_default_layers(pTHX)
1068 if (!PL_def_layerlist) {
1069 const char *s = (PL_tainting) ? Nullch : PerlEnv_getenv("PERLIO");
1070 PerlIO_funcs *osLayer = &PerlIO_unix;
1071 PL_def_layerlist = PerlIO_list_alloc(aTHX);
1072 PerlIO_define_layer(aTHX_ & PerlIO_unix);
1074 PerlIO_define_layer(aTHX_ & PerlIO_win32);
1076 osLayer = &PerlIO_win32;
1079 PerlIO_define_layer(aTHX_ & PerlIO_raw);
1080 PerlIO_define_layer(aTHX_ & PerlIO_perlio);
1081 PerlIO_define_layer(aTHX_ & PerlIO_stdio);
1082 PerlIO_define_layer(aTHX_ & PerlIO_crlf);
1084 PerlIO_define_layer(aTHX_ & PerlIO_mmap);
1086 PerlIO_define_layer(aTHX_ & PerlIO_utf8);
1087 PerlIO_define_layer(aTHX_ & PerlIO_remove);
1088 PerlIO_define_layer(aTHX_ & PerlIO_byte);
1089 PerlIO_list_push(aTHX_ PL_def_layerlist,
1090 PerlIO_find_layer(aTHX_ osLayer->name, 0, 0),
1093 PerlIO_parse_layers(aTHX_ PL_def_layerlist, s);
1096 PerlIO_default_buffer(aTHX_ PL_def_layerlist);
1099 if (PL_def_layerlist->cur < 2) {
1100 PerlIO_default_buffer(aTHX_ PL_def_layerlist);
1102 return PL_def_layerlist;
1106 Perl_boot_core_PerlIO(pTHX)
1108 #ifdef USE_ATTRIBUTES_FOR_PERLIO
1109 newXS("io::MODIFY_SCALAR_ATTRIBUTES", XS_io_MODIFY_SCALAR_ATTRIBUTES,
1112 newXS("PerlIO::Layer::find", XS_PerlIO__Layer__find, __FILE__);
1113 newXS("PerlIO::Layer::NoWarnings", XS_PerlIO__Layer__NoWarnings, __FILE__);
1117 PerlIO_default_layer(pTHX_ I32 n)
1119 PerlIO_list_t *av = PerlIO_default_layers(aTHX);
1122 return PerlIO_layer_fetch(aTHX_ av, n, &PerlIO_stdio);
1125 #define PerlIO_default_top() PerlIO_default_layer(aTHX_ -1)
1126 #define PerlIO_default_btm() PerlIO_default_layer(aTHX_ 0)
1129 PerlIO_stdstreams(pTHX)
1132 PerlIO_allocate(aTHX);
1133 PerlIO_fdopen(0, "Ir" PERLIO_STDTEXT);
1134 PerlIO_fdopen(1, "Iw" PERLIO_STDTEXT);
1135 PerlIO_fdopen(2, "Iw" PERLIO_STDTEXT);
1140 PerlIO_push(pTHX_ PerlIO *f, PerlIO_funcs *tab, const char *mode, SV *arg)
1142 if (tab->fsize != sizeof(PerlIO_funcs)) {
1144 Perl_croak(aTHX_ "Layer does not match this perl");
1148 if (tab->size < sizeof(PerlIOl)) {
1151 /* Real layer with a data area */
1152 Newc('L',l,tab->size,char,PerlIOl);
1154 Zero(l, tab->size, char);
1158 PerlIO_debug("PerlIO_push f=%p %s %s %p\n", (void*)f, tab->name,
1159 (mode) ? mode : "(Null)", (void*)arg);
1160 if (*l->tab->Pushed &&
1161 (*l->tab->Pushed) (aTHX_ f, mode, arg, tab) != 0) {
1162 PerlIO_pop(aTHX_ f);
1168 /* Pseudo-layer where push does its own stack adjust */
1169 PerlIO_debug("PerlIO_push f=%p %s %s %p\n", (void*)f, tab->name,
1170 (mode) ? mode : "(Null)", (void*)arg);
1172 (*tab->Pushed) (aTHX_ f, mode, arg, tab) != 0) {
1180 PerlIOBase_binmode(pTHX_ PerlIO *f)
1182 if (PerlIOValid(f)) {
1183 /* Is layer suitable for raw stream ? */
1184 if (PerlIOBase(f)->tab->kind & PERLIO_K_RAW) {
1185 /* Yes - turn off UTF-8-ness, to undo UTF-8 locale effects */
1186 PerlIOBase(f)->flags &= ~PERLIO_F_UTF8;
1189 /* Not suitable - pop it */
1190 PerlIO_pop(aTHX_ f);
1198 PerlIORaw_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
1201 if (PerlIOValid(f)) {
1206 * Strip all layers that are not suitable for a raw stream
1209 while (t && (l = *t)) {
1210 if (l->tab->Binmode) {
1211 /* Has a handler - normal case */
1212 if ((*l->tab->Binmode)(aTHX_ f) == 0) {
1214 /* Layer still there - move down a layer */
1223 /* No handler - pop it */
1224 PerlIO_pop(aTHX_ t);
1227 if (PerlIOValid(f)) {
1228 PerlIO_debug(":raw f=%p :%s\n", (void*)f, PerlIOBase(f)->tab->name);
1236 PerlIO_apply_layera(pTHX_ PerlIO *f, const char *mode,
1237 PerlIO_list_t *layers, IV n, IV max)
1241 PerlIO_funcs *tab = PerlIO_layer_fetch(aTHX_ layers, n, NULL);
1243 if (!PerlIO_push(aTHX_ f, tab, mode, PerlIOArg)) {
1254 PerlIO_apply_layers(pTHX_ PerlIO *f, const char *mode, const char *names)
1258 PerlIO_list_t *layers = PerlIO_list_alloc(aTHX);
1259 code = PerlIO_parse_layers(aTHX_ layers, names);
1261 code = PerlIO_apply_layera(aTHX_ f, mode, layers, 0, layers->cur);
1263 PerlIO_list_free(aTHX_ layers);
1269 /*--------------------------------------------------------------------------------------*/
1271 * Given the abstraction above the public API functions
1275 PerlIO_binmode(pTHX_ PerlIO *f, int iotype, int mode, const char *names)
1277 PerlIO_debug("PerlIO_binmode f=%p %s %c %x %s\n",
1278 (void*)f, PerlIOBase(f)->tab->name, iotype, mode,
1279 (names) ? names : "(Null)");
1281 /* Do not flush etc. if (e.g.) switching encodings.
1282 if a pushed layer knows it needs to flush lower layers
1283 (for example :unix which is never going to call them)
1284 it can do the flush when it is pushed.
1286 return PerlIO_apply_layers(aTHX_ f, NULL, names) == 0 ? TRUE : FALSE;
1289 /* Fake 5.6 legacy of using this call to turn ON O_TEXT */
1290 #ifdef PERLIO_USING_CRLF
1291 /* Legacy binmode only has meaning if O_TEXT has a value distinct from
1292 O_BINARY so we can look for it in mode.
1294 if (!(mode & O_BINARY)) {
1296 /* FIXME?: Looking down the layer stack seems wrong,
1297 but is a way of reaching past (say) an encoding layer
1298 to flip CRLF-ness of the layer(s) below
1301 /* Perhaps we should turn on bottom-most aware layer
1302 e.g. Ilya's idea that UNIX TTY could serve
1304 if (PerlIOBase(f)->tab->kind & PERLIO_K_CANCRLF) {
1305 if (!(PerlIOBase(f)->flags & PERLIO_F_CRLF)) {
1306 /* Not in text mode - flush any pending stuff and flip it */
1308 PerlIOBase(f)->flags |= PERLIO_F_CRLF;
1310 /* Only need to turn it on in one layer so we are done */
1315 /* Not finding a CRLF aware layer presumably means we are binary
1316 which is not what was requested - so we failed
1317 We _could_ push :crlf layer but so could caller
1322 /* Legacy binmode is now _defined_ as being equivalent to pushing :raw
1323 So code that used to be here is now in PerlIORaw_pushed().
1325 return PerlIO_push(aTHX_ f, &PerlIO_raw, Nullch, Nullsv) ? TRUE : FALSE;
1330 PerlIO__close(pTHX_ PerlIO *f)
1332 if (PerlIOValid(f)) {
1333 PerlIO_funcs *tab = PerlIOBase(f)->tab;
1334 if (tab && tab->Close)
1335 return (*tab->Close)(aTHX_ f);
1337 return PerlIOBase_close(aTHX_ f);
1340 SETERRNO(EBADF, SS_IVCHAN);
1346 Perl_PerlIO_close(pTHX_ PerlIO *f)
1348 int code = PerlIO__close(aTHX_ f);
1349 while (PerlIOValid(f)) {
1350 PerlIO_pop(aTHX_ f);
1356 Perl_PerlIO_fileno(pTHX_ PerlIO *f)
1358 Perl_PerlIO_or_Base(f, Fileno, fileno, -1, (aTHX_ f));
1362 PerlIO_context_layers(pTHX_ const char *mode)
1364 const char *type = NULL;
1366 * Need to supply default layer info from open.pm
1369 SV *layers = PL_curcop->cop_io;
1372 type = SvPV(layers, len);
1373 if (type && mode[0] != 'r') {
1375 * Skip to write part
1377 const char *s = strchr(type, 0);
1378 if (s && (STRLEN)(s - type) < len) {
1387 static PerlIO_funcs *
1388 PerlIO_layer_from_ref(pTHX_ SV *sv)
1391 * For any scalar type load the handler which is bundled with perl
1393 if (SvTYPE(sv) < SVt_PVAV)
1394 return PerlIO_find_layer(aTHX_ "scalar", 6, 1);
1397 * For other types allow if layer is known but don't try and load it
1399 switch (SvTYPE(sv)) {
1401 return PerlIO_find_layer(aTHX_ "Array", 5, 0);
1403 return PerlIO_find_layer(aTHX_ "Hash", 4, 0);
1405 return PerlIO_find_layer(aTHX_ "Code", 4, 0);
1407 return PerlIO_find_layer(aTHX_ "Glob", 4, 0);
1413 PerlIO_resolve_layers(pTHX_ const char *layers,
1414 const char *mode, int narg, SV **args)
1416 PerlIO_list_t *def = PerlIO_default_layers(aTHX);
1419 PerlIO_stdstreams(aTHX);
1423 * If it is a reference but not an object see if we have a handler
1426 if (SvROK(arg) && !sv_isobject(arg)) {
1427 PerlIO_funcs *handler = PerlIO_layer_from_ref(aTHX_ SvRV(arg));
1429 def = PerlIO_list_alloc(aTHX);
1430 PerlIO_list_push(aTHX_ def, handler, &PL_sv_undef);
1434 * Don't fail if handler cannot be found :via(...) etc. may do
1435 * something sensible else we will just stringfy and open
1441 layers = PerlIO_context_layers(aTHX_ mode);
1442 if (layers && *layers) {
1446 av = PerlIO_list_alloc(aTHX);
1447 for (i = 0; i < def->cur; i++) {
1448 PerlIO_list_push(aTHX_ av, def->array[i].funcs,
1455 if (PerlIO_parse_layers(aTHX_ av, layers) == 0) {
1459 PerlIO_list_free(aTHX_ av);
1460 return (PerlIO_list_t *) NULL;
1471 PerlIO_openn(pTHX_ const char *layers, const char *mode, int fd,
1472 int imode, int perm, PerlIO *f, int narg, SV **args)
1474 if (!f && narg == 1 && *args == &PL_sv_undef) {
1475 if ((f = PerlIO_tmpfile())) {
1477 layers = PerlIO_context_layers(aTHX_ mode);
1478 if (layers && *layers)
1479 PerlIO_apply_layers(aTHX_ f, mode, layers);
1483 PerlIO_list_t *layera = NULL;
1485 PerlIO_funcs *tab = NULL;
1486 if (PerlIOValid(f)) {
1488 * This is "reopen" - it is not tested as perl does not use it
1492 layera = PerlIO_list_alloc(aTHX);
1494 SV *arg = (l->tab->Getarg)
1495 ? (*l->tab->Getarg) (aTHX_ &l, NULL, 0)
1497 PerlIO_list_push(aTHX_ layera, l->tab, arg);
1498 l = *PerlIONext(&l);
1502 layera = PerlIO_resolve_layers(aTHX_ layers, mode, narg, args);
1508 * Start at "top" of layer stack
1510 n = layera->cur - 1;
1512 PerlIO_funcs *t = PerlIO_layer_fetch(aTHX_ layera, n, NULL);
1521 * Found that layer 'n' can do opens - call it
1523 if (narg > 1 && !(tab->kind & PERLIO_K_MULTIARG)) {
1524 Perl_croak(aTHX_ "More than one argument to open(,':%s')",tab->name);
1526 PerlIO_debug("openn(%s,'%s','%s',%d,%x,%o,%p,%d,%p)\n",
1527 tab->name, layers, mode, fd, imode, perm,
1528 (void*)f, narg, (void*)args);
1530 f = (*tab->Open) (aTHX_ tab, layera, n, mode, fd, imode, perm,
1533 SETERRNO(EINVAL, LIB_INVARG);
1537 if (n + 1 < layera->cur) {
1539 * More layers above the one that we used to open -
1542 if (PerlIO_apply_layera(aTHX_ f, mode, layera, n + 1, layera->cur) != 0) {
1543 /* If pushing layers fails close the file */
1550 PerlIO_list_free(aTHX_ layera);
1557 Perl_PerlIO_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
1559 Perl_PerlIO_or_Base(f, Read, read, -1, (aTHX_ f, vbuf, count));
1563 Perl_PerlIO_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
1565 Perl_PerlIO_or_Base(f, Unread, unread, -1, (aTHX_ f, vbuf, count));
1569 Perl_PerlIO_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
1571 Perl_PerlIO_or_fail(f, Write, -1, (aTHX_ f, vbuf, count));
1575 Perl_PerlIO_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
1577 Perl_PerlIO_or_fail(f, Seek, -1, (aTHX_ f, offset, whence));
1581 Perl_PerlIO_tell(pTHX_ PerlIO *f)
1583 Perl_PerlIO_or_fail(f, Tell, -1, (aTHX_ f));
1587 Perl_PerlIO_flush(pTHX_ PerlIO *f)
1591 PerlIO_funcs *tab = PerlIOBase(f)->tab;
1593 if (tab && tab->Flush)
1594 return (*tab->Flush) (aTHX_ f);
1596 return 0; /* If no Flush defined, silently succeed. */
1599 PerlIO_debug("Cannot flush f=%p\n", (void*)f);
1600 SETERRNO(EBADF, SS_IVCHAN);
1606 * Is it good API design to do flush-all on NULL, a potentially
1607 * errorneous input? Maybe some magical value (PerlIO*
1608 * PERLIO_FLUSH_ALL = (PerlIO*)-1;)? Yes, stdio does similar
1609 * things on fflush(NULL), but should we be bound by their design
1612 PerlIO **table = &PL_perlio;
1614 while ((f = *table)) {
1616 table = (PerlIO **) (f++);
1617 for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
1618 if (*f && PerlIO_flush(f) != 0)
1628 PerlIOBase_flush_linebuf(pTHX)
1630 PerlIO **table = &PL_perlio;
1632 while ((f = *table)) {
1634 table = (PerlIO **) (f++);
1635 for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
1638 flags & (PERLIO_F_LINEBUF | PERLIO_F_CANWRITE))
1639 == (PERLIO_F_LINEBUF | PERLIO_F_CANWRITE))
1647 Perl_PerlIO_fill(pTHX_ PerlIO *f)
1649 Perl_PerlIO_or_fail(f, Fill, -1, (aTHX_ f));
1653 PerlIO_isutf8(PerlIO *f)
1656 return (PerlIOBase(f)->flags & PERLIO_F_UTF8) != 0;
1658 SETERRNO(EBADF, SS_IVCHAN);
1664 Perl_PerlIO_eof(pTHX_ PerlIO *f)
1666 Perl_PerlIO_or_Base(f, Eof, eof, -1, (aTHX_ f));
1670 Perl_PerlIO_error(pTHX_ PerlIO *f)
1672 Perl_PerlIO_or_Base(f, Error, error, -1, (aTHX_ f));
1676 Perl_PerlIO_clearerr(pTHX_ PerlIO *f)
1678 Perl_PerlIO_or_Base_void(f, Clearerr, clearerr, (aTHX_ f));
1682 Perl_PerlIO_setlinebuf(pTHX_ PerlIO *f)
1684 Perl_PerlIO_or_Base_void(f, Setlinebuf, setlinebuf, (aTHX_ f));
1688 PerlIO_has_base(PerlIO *f)
1690 if (PerlIOValid(f)) {
1691 PerlIO_funcs *tab = PerlIOBase(f)->tab;
1694 return (tab->Get_base != NULL);
1695 SETERRNO(EINVAL, LIB_INVARG);
1698 SETERRNO(EBADF, SS_IVCHAN);
1704 PerlIO_fast_gets(PerlIO *f)
1706 if (PerlIOValid(f) && (PerlIOBase(f)->flags & PERLIO_F_FASTGETS)) {
1707 PerlIO_funcs *tab = PerlIOBase(f)->tab;
1710 return (tab->Set_ptrcnt != NULL);
1711 SETERRNO(EINVAL, LIB_INVARG);
1714 SETERRNO(EBADF, SS_IVCHAN);
1720 PerlIO_has_cntptr(PerlIO *f)
1722 if (PerlIOValid(f)) {
1723 PerlIO_funcs *tab = PerlIOBase(f)->tab;
1726 return (tab->Get_ptr != NULL && tab->Get_cnt != NULL);
1727 SETERRNO(EINVAL, LIB_INVARG);
1730 SETERRNO(EBADF, SS_IVCHAN);
1736 PerlIO_canset_cnt(PerlIO *f)
1738 if (PerlIOValid(f)) {
1739 PerlIO_funcs *tab = PerlIOBase(f)->tab;
1742 return (tab->Set_ptrcnt != NULL);
1743 SETERRNO(EINVAL, LIB_INVARG);
1746 SETERRNO(EBADF, SS_IVCHAN);
1752 Perl_PerlIO_get_base(pTHX_ PerlIO *f)
1754 Perl_PerlIO_or_fail(f, Get_base, NULL, (aTHX_ f));
1758 Perl_PerlIO_get_bufsiz(pTHX_ PerlIO *f)
1760 Perl_PerlIO_or_fail(f, Get_bufsiz, -1, (aTHX_ f));
1764 Perl_PerlIO_get_ptr(pTHX_ PerlIO *f)
1766 Perl_PerlIO_or_fail(f, Get_ptr, NULL, (aTHX_ f));
1770 Perl_PerlIO_get_cnt(pTHX_ PerlIO *f)
1772 Perl_PerlIO_or_fail(f, Get_cnt, -1, (aTHX_ f));
1776 Perl_PerlIO_set_cnt(pTHX_ PerlIO *f, int cnt)
1778 Perl_PerlIO_or_fail_void(f, Set_ptrcnt, (aTHX_ f, NULL, cnt));
1782 Perl_PerlIO_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, int cnt)
1784 Perl_PerlIO_or_fail_void(f, Set_ptrcnt, (aTHX_ f, ptr, cnt));
1788 /*--------------------------------------------------------------------------------------*/
1790 * utf8 and raw dummy layers
1794 PerlIOUtf8_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
1796 if (PerlIOValid(f)) {
1797 if (tab->kind & PERLIO_K_UTF8)
1798 PerlIOBase(f)->flags |= PERLIO_F_UTF8;
1800 PerlIOBase(f)->flags &= ~PERLIO_F_UTF8;
1806 PerlIO_funcs PerlIO_utf8 = {
1807 sizeof(PerlIO_funcs),
1810 PERLIO_K_DUMMY | PERLIO_K_UTF8,
1828 NULL, /* get_base */
1829 NULL, /* get_bufsiz */
1832 NULL, /* set_ptrcnt */
1835 PerlIO_funcs PerlIO_byte = {
1836 sizeof(PerlIO_funcs),
1857 NULL, /* get_base */
1858 NULL, /* get_bufsiz */
1861 NULL, /* set_ptrcnt */
1865 PerlIORaw_open(pTHX_ PerlIO_funcs *self, PerlIO_list_t *layers,
1866 IV n, const char *mode, int fd, int imode, int perm,
1867 PerlIO *old, int narg, SV **args)
1869 PerlIO_funcs *tab = PerlIO_default_btm();
1870 if (tab && tab->Open)
1871 return (*tab->Open) (aTHX_ tab, layers, n - 1, mode, fd, imode, perm,
1873 SETERRNO(EINVAL, LIB_INVARG);
1877 PerlIO_funcs PerlIO_raw = {
1878 sizeof(PerlIO_funcs),
1899 NULL, /* get_base */
1900 NULL, /* get_bufsiz */
1903 NULL, /* set_ptrcnt */
1905 /*--------------------------------------------------------------------------------------*/
1906 /*--------------------------------------------------------------------------------------*/
1908 * "Methods" of the "base class"
1912 PerlIOBase_fileno(pTHX_ PerlIO *f)
1914 return PerlIOValid(f) ? PerlIO_fileno(PerlIONext(f)) : -1;
1918 PerlIO_modestr(PerlIO * f, char *buf)
1921 if (PerlIOValid(f)) {
1922 IV flags = PerlIOBase(f)->flags;
1923 if (flags & PERLIO_F_APPEND) {
1925 if (flags & PERLIO_F_CANREAD) {
1929 else if (flags & PERLIO_F_CANREAD) {
1931 if (flags & PERLIO_F_CANWRITE)
1934 else if (flags & PERLIO_F_CANWRITE) {
1936 if (flags & PERLIO_F_CANREAD) {
1940 #ifdef PERLIO_USING_CRLF
1941 if (!(flags & PERLIO_F_CRLF))
1951 PerlIOBase_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
1953 PerlIOl *l = PerlIOBase(f);
1955 const char *omode = mode;
1958 l->flags &= ~(PERLIO_F_CANREAD | PERLIO_F_CANWRITE |
1959 PERLIO_F_TRUNCATE | PERLIO_F_APPEND);
1960 if (tab->Set_ptrcnt != NULL)
1961 l->flags |= PERLIO_F_FASTGETS;
1963 if (*mode == '#' || *mode == 'I')
1967 l->flags |= PERLIO_F_CANREAD;
1970 l->flags |= PERLIO_F_APPEND | PERLIO_F_CANWRITE;
1973 l->flags |= PERLIO_F_TRUNCATE | PERLIO_F_CANWRITE;
1976 SETERRNO(EINVAL, LIB_INVARG);
1982 l->flags |= PERLIO_F_CANREAD | PERLIO_F_CANWRITE;
1985 l->flags &= ~PERLIO_F_CRLF;
1988 l->flags |= PERLIO_F_CRLF;
1991 SETERRNO(EINVAL, LIB_INVARG);
1998 l->flags |= l->next->flags &
1999 (PERLIO_F_CANREAD | PERLIO_F_CANWRITE | PERLIO_F_TRUNCATE |
2004 PerlIO_debug("PerlIOBase_pushed f=%p %s %s fl=%08" UVxf " (%s)\n",
2005 f, PerlIOBase(f)->tab->name, (omode) ? omode : "(Null)",
2006 l->flags, PerlIO_modestr(f, temp));
2012 PerlIOBase_popped(pTHX_ PerlIO *f)
2018 PerlIOBase_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
2021 * Save the position as current head considers it
2023 Off_t old = PerlIO_tell(f);
2025 PerlIO_push(aTHX_ f, &PerlIO_pending, "r", Nullsv);
2026 PerlIOSelf(f, PerlIOBuf)->posn = old;
2027 done = PerlIOBuf_unread(aTHX_ f, vbuf, count);
2032 PerlIOBase_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
2034 STDCHAR *buf = (STDCHAR *) vbuf;
2036 if (!(PerlIOBase(f)->flags & PERLIO_F_CANREAD)) {
2037 PerlIOBase(f)->flags |= PERLIO_F_ERROR;
2038 SETERRNO(EBADF, SS_IVCHAN);
2042 SSize_t avail = PerlIO_get_cnt(f);
2045 take = ((SSize_t)count < avail) ? count : avail;
2047 STDCHAR *ptr = PerlIO_get_ptr(f);
2048 Copy(ptr, buf, take, STDCHAR);
2049 PerlIO_set_ptrcnt(f, ptr + take, (avail -= take));
2053 if (count > 0 && avail <= 0) {
2054 if (PerlIO_fill(f) != 0)
2058 return (buf - (STDCHAR *) vbuf);
2064 PerlIOBase_noop_ok(pTHX_ PerlIO *f)
2070 PerlIOBase_noop_fail(pTHX_ PerlIO *f)
2076 PerlIOBase_close(pTHX_ PerlIO *f)
2079 if (PerlIOValid(f)) {
2080 PerlIO *n = PerlIONext(f);
2081 code = PerlIO_flush(f);
2082 PerlIOBase(f)->flags &=
2083 ~(PERLIO_F_CANREAD | PERLIO_F_CANWRITE | PERLIO_F_OPEN);
2084 while (PerlIOValid(n)) {
2085 PerlIO_funcs *tab = PerlIOBase(n)->tab;
2086 if (tab && tab->Close) {
2087 if ((*tab->Close)(aTHX_ n) != 0)
2092 PerlIOBase(n)->flags &=
2093 ~(PERLIO_F_CANREAD | PERLIO_F_CANWRITE | PERLIO_F_OPEN);
2099 SETERRNO(EBADF, SS_IVCHAN);
2105 PerlIOBase_eof(pTHX_ PerlIO *f)
2107 if (PerlIOValid(f)) {
2108 return (PerlIOBase(f)->flags & PERLIO_F_EOF) != 0;
2114 PerlIOBase_error(pTHX_ PerlIO *f)
2116 if (PerlIOValid(f)) {
2117 return (PerlIOBase(f)->flags & PERLIO_F_ERROR) != 0;
2123 PerlIOBase_clearerr(pTHX_ PerlIO *f)
2125 if (PerlIOValid(f)) {
2126 PerlIO *n = PerlIONext(f);
2127 PerlIOBase(f)->flags &= ~(PERLIO_F_ERROR | PERLIO_F_EOF);
2134 PerlIOBase_setlinebuf(pTHX_ PerlIO *f)
2136 if (PerlIOValid(f)) {
2137 PerlIOBase(f)->flags |= PERLIO_F_LINEBUF;
2142 PerlIO_sv_dup(pTHX_ SV *arg, CLONE_PARAMS *param)
2148 return sv_dup(arg, param);
2151 return newSVsv(arg);
2154 return newSVsv(arg);
2159 PerlIOBase_dup(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags)
2161 PerlIO *nexto = PerlIONext(o);
2162 if (PerlIOValid(nexto)) {
2163 PerlIO_funcs *tab = PerlIOBase(nexto)->tab;
2164 if (tab && tab->Dup)
2165 f = (*tab->Dup)(aTHX_ f, nexto, param, flags);
2167 f = PerlIOBase_dup(aTHX_ f, nexto, param, flags);
2170 PerlIO_funcs *self = PerlIOBase(o)->tab;
2173 PerlIO_debug("PerlIOBase_dup %s f=%p o=%p param=%p\n",
2174 self->name, (void*)f, (void*)o, (void*)param);
2176 arg = (*self->Getarg)(aTHX_ o, param, flags);
2180 f = PerlIO_push(aTHX_ f, self, PerlIO_modestr(o,buf), arg);
2188 #define PERLIO_MAX_REFCOUNTABLE_FD 2048
2190 perl_mutex PerlIO_mutex;
2192 int PerlIO_fd_refcnt[PERLIO_MAX_REFCOUNTABLE_FD];
2197 /* Place holder for stdstreams call ??? */
2199 MUTEX_INIT(&PerlIO_mutex);
2204 PerlIOUnix_refcnt_inc(int fd)
2206 if (fd >= 0 && fd < PERLIO_MAX_REFCOUNTABLE_FD) {
2208 MUTEX_LOCK(&PerlIO_mutex);
2210 PerlIO_fd_refcnt[fd]++;
2211 PerlIO_debug("fd %d refcnt=%d\n",fd,PerlIO_fd_refcnt[fd]);
2213 MUTEX_UNLOCK(&PerlIO_mutex);
2219 PerlIOUnix_refcnt_dec(int fd)
2222 if (fd >= 0 && fd < PERLIO_MAX_REFCOUNTABLE_FD) {
2224 MUTEX_LOCK(&PerlIO_mutex);
2226 cnt = --PerlIO_fd_refcnt[fd];
2227 PerlIO_debug("fd %d refcnt=%d\n",fd,cnt);
2229 MUTEX_UNLOCK(&PerlIO_mutex);
2236 PerlIO_cleanup(pTHX)
2240 PerlIO_debug("Cleanup layers for %p\n",aTHX);
2242 PerlIO_debug("Cleanup layers\n");
2244 /* Raise STDIN..STDERR refcount so we don't close them */
2245 for (i=0; i < 3; i++)
2246 PerlIOUnix_refcnt_inc(i);
2247 PerlIO_cleantable(aTHX_ &PL_perlio);
2248 /* Restore STDIN..STDERR refcount */
2249 for (i=0; i < 3; i++)
2250 PerlIOUnix_refcnt_dec(i);
2252 if (PL_known_layers) {
2253 PerlIO_list_free(aTHX_ PL_known_layers);
2254 PL_known_layers = NULL;
2256 if(PL_def_layerlist) {
2257 PerlIO_list_free(aTHX_ PL_def_layerlist);
2258 PL_def_layerlist = NULL;
2264 /*--------------------------------------------------------------------------------------*/
2266 * Bottom-most level for UNIX-like case
2270 struct _PerlIO base; /* The generic part */
2271 int fd; /* UNIX like file descriptor */
2272 int oflags; /* open/fcntl flags */
2276 PerlIOUnix_oflags(const char *mode)
2279 if (*mode == 'I' || *mode == '#')
2284 if (*++mode == '+') {
2291 oflags = O_CREAT | O_TRUNC;
2292 if (*++mode == '+') {
2301 oflags = O_CREAT | O_APPEND;
2302 if (*++mode == '+') {
2315 else if (*mode == 't') {
2317 oflags &= ~O_BINARY;
2321 * Always open in binary mode
2324 if (*mode || oflags == -1) {
2325 SETERRNO(EINVAL, LIB_INVARG);
2332 PerlIOUnix_fileno(pTHX_ PerlIO *f)
2334 return PerlIOSelf(f, PerlIOUnix)->fd;
2338 PerlIOUnix_setfd(pTHX_ PerlIO *f, int fd, int imode)
2340 PerlIOUnix *s = PerlIOSelf(f, PerlIOUnix);
2343 if (PerlLIO_fstat(fd, &st) == 0) {
2344 if (!S_ISREG(st.st_mode)) {
2345 PerlIO_debug("%d is not regular file\n",fd);
2346 PerlIOBase(f)->flags |= PERLIO_F_NOTREG;
2349 PerlIO_debug("%d _is_ a regular file\n",fd);
2355 PerlIOUnix_refcnt_inc(fd);
2359 PerlIOUnix_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
2361 IV code = PerlIOBase_pushed(aTHX_ f, mode, arg, tab);
2362 if (*PerlIONext(f)) {
2363 /* We never call down so do any pending stuff now */
2364 PerlIO_flush(PerlIONext(f));
2366 * XXX could (or should) we retrieve the oflags from the open file
2367 * handle rather than believing the "mode" we are passed in? XXX
2368 * Should the value on NULL mode be 0 or -1?
2370 PerlIOUnix_setfd(aTHX_ f, PerlIO_fileno(PerlIONext(f)),
2371 mode ? PerlIOUnix_oflags(mode) : -1);
2373 PerlIOBase(f)->flags |= PERLIO_F_OPEN;
2379 PerlIOUnix_open(pTHX_ PerlIO_funcs *self, PerlIO_list_t *layers,
2380 IV n, const char *mode, int fd, int imode,
2381 int perm, PerlIO *f, int narg, SV **args)
2383 if (PerlIOValid(f)) {
2384 if (PerlIOBase(f)->flags & PERLIO_F_OPEN)
2385 (*PerlIOBase(f)->tab->Close)(aTHX_ f);
2388 char *path = SvPV_nolen(*args);
2392 imode = PerlIOUnix_oflags(mode);
2396 fd = PerlLIO_open3(path, imode, perm);
2403 f = PerlIO_allocate(aTHX);
2405 if (!PerlIOValid(f)) {
2406 if (!(f = PerlIO_push(aTHX_ f, self, mode, PerlIOArg))) {
2410 PerlIOUnix_setfd(aTHX_ f, fd, imode);
2411 PerlIOBase(f)->flags |= PERLIO_F_OPEN;
2417 * FIXME: pop layers ???
2425 PerlIOUnix_dup(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags)
2427 PerlIOUnix *os = PerlIOSelf(o, PerlIOUnix);
2429 if (flags & PERLIO_DUP_FD) {
2430 fd = PerlLIO_dup(fd);
2432 if (fd >= 0 && fd < PERLIO_MAX_REFCOUNTABLE_FD) {
2433 f = PerlIOBase_dup(aTHX_ f, o, param, flags);
2435 /* If all went well overwrite fd in dup'ed lay with the dup()'ed fd */
2436 PerlIOUnix_setfd(aTHX_ f, fd, os->oflags);
2445 PerlIOUnix_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
2447 int fd = PerlIOSelf(f, PerlIOUnix)->fd;
2448 if (!(PerlIOBase(f)->flags & PERLIO_F_CANREAD) ||
2449 PerlIOBase(f)->flags & (PERLIO_F_EOF|PERLIO_F_ERROR)) {
2453 SSize_t len = PerlLIO_read(fd, vbuf, count);
2454 if (len >= 0 || errno != EINTR) {
2456 if (errno != EAGAIN) {
2457 PerlIOBase(f)->flags |= PERLIO_F_ERROR;
2460 else if (len == 0 && count != 0) {
2461 PerlIOBase(f)->flags |= PERLIO_F_EOF;
2471 PerlIOUnix_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
2473 int fd = PerlIOSelf(f, PerlIOUnix)->fd;
2475 SSize_t len = PerlLIO_write(fd, vbuf, count);
2476 if (len >= 0 || errno != EINTR) {
2478 if (errno != EAGAIN) {
2479 PerlIOBase(f)->flags |= PERLIO_F_ERROR;
2489 PerlIOUnix_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
2491 int fd = PerlIOSelf(f, PerlIOUnix)->fd;
2493 if (PerlIOBase(f)->flags & PERLIO_F_NOTREG) {
2495 SETERRNO(ESPIPE, LIB_INVARG);
2497 SETERRNO(EINVAL, LIB_INVARG);
2501 new = PerlLIO_lseek(fd, offset, whence);
2502 if (new == (Off_t) - 1)
2506 PerlIOBase(f)->flags &= ~PERLIO_F_EOF;
2511 PerlIOUnix_tell(pTHX_ PerlIO *f)
2513 return PerlLIO_lseek(PerlIOSelf(f, PerlIOUnix)->fd, 0, SEEK_CUR);
2518 PerlIOUnix_close(pTHX_ PerlIO *f)
2520 int fd = PerlIOSelf(f, PerlIOUnix)->fd;
2522 if (PerlIOBase(f)->flags & PERLIO_F_OPEN) {
2523 if (PerlIOUnix_refcnt_dec(fd) > 0) {
2524 PerlIOBase(f)->flags &= ~PERLIO_F_OPEN;
2529 SETERRNO(EBADF,SS_IVCHAN);
2532 while (PerlLIO_close(fd) != 0) {
2533 if (errno != EINTR) {
2540 PerlIOBase(f)->flags &= ~PERLIO_F_OPEN;
2545 PerlIO_funcs PerlIO_unix = {
2546 sizeof(PerlIO_funcs),
2553 PerlIOBase_binmode, /* binmode */
2563 PerlIOBase_noop_ok, /* flush */
2564 PerlIOBase_noop_fail, /* fill */
2567 PerlIOBase_clearerr,
2568 PerlIOBase_setlinebuf,
2569 NULL, /* get_base */
2570 NULL, /* get_bufsiz */
2573 NULL, /* set_ptrcnt */
2576 /*--------------------------------------------------------------------------------------*/
2581 #if defined(VMS) && !defined(STDIO_BUFFER_WRITABLE)
2582 /* perl5.8 - This ensures the last minute VMS ungetc fix is not
2583 broken by the last second glibc 2.3 fix
2585 #define STDIO_BUFFER_WRITABLE
2590 struct _PerlIO base;
2591 FILE *stdio; /* The stream */
2595 PerlIOStdio_fileno(pTHX_ PerlIO *f)
2598 if (PerlIOValid(f) && (s = PerlIOSelf(f, PerlIOStdio)->stdio)) {
2599 return PerlSIO_fileno(s);
2606 PerlIOStdio_mode(const char *mode, char *tmode)
2612 #ifdef PERLIO_USING_CRLF
2620 PerlIOStdio_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
2623 if (PerlIOValid(f) && PerlIOValid(n = PerlIONext(f))) {
2624 PerlIO_funcs *toptab = PerlIOBase(n)->tab;
2625 if (toptab == tab) {
2626 /* Top is already stdio - pop self (duplicate) and use original */
2627 PerlIO_pop(aTHX_ f);
2630 int fd = PerlIO_fileno(n);
2633 if (fd >= 0 && (stdio = PerlSIO_fdopen(fd,
2634 mode = PerlIOStdio_mode(mode, tmode)))) {
2635 PerlIOSelf(f, PerlIOStdio)->stdio = stdio;
2636 /* We never call down so do any pending stuff now */
2637 PerlIO_flush(PerlIONext(f));
2644 return PerlIOBase_pushed(aTHX_ f, mode, arg, tab);
2649 PerlIO_importFILE(FILE *stdio, const char *mode)
2655 if (!mode || !*mode) {
2656 /* We need to probe to see how we can open the stream
2657 so start with read/write and then try write and read
2658 we dup() so that we can fclose without loosing the fd.
2660 Note that the errno value set by a failing fdopen
2661 varies between stdio implementations.
2663 int fd = PerlLIO_dup(fileno(stdio));
2664 FILE *f2 = PerlSIO_fdopen(fd, (mode = "r+"));
2666 f2 = PerlSIO_fdopen(fd, (mode = "w"));
2669 f2 = PerlSIO_fdopen(fd, (mode = "r"));
2672 /* Don't seem to be able to open */
2678 if ((f = PerlIO_push(aTHX_(f = PerlIO_allocate(aTHX)), &PerlIO_stdio, mode, Nullsv))) {
2679 s = PerlIOSelf(f, PerlIOStdio);
2687 PerlIOStdio_open(pTHX_ PerlIO_funcs *self, PerlIO_list_t *layers,
2688 IV n, const char *mode, int fd, int imode,
2689 int perm, PerlIO *f, int narg, SV **args)
2692 if (PerlIOValid(f)) {
2693 char *path = SvPV_nolen(*args);
2694 PerlIOStdio *s = PerlIOSelf(f, PerlIOStdio);
2696 PerlIOUnix_refcnt_dec(fileno(s->stdio));
2697 stdio = PerlSIO_freopen(path, (mode = PerlIOStdio_mode(mode, tmode)),
2702 PerlIOUnix_refcnt_inc(fileno(s->stdio));
2707 char *path = SvPV_nolen(*args);
2710 fd = PerlLIO_open3(path, imode, perm);
2713 FILE *stdio = PerlSIO_fopen(path, mode);
2717 f = PerlIO_allocate(aTHX);
2719 if ((f = PerlIO_push(aTHX_ f, self,
2720 (mode = PerlIOStdio_mode(mode, tmode)),
2722 s = PerlIOSelf(f, PerlIOStdio);
2724 PerlIOUnix_refcnt_inc(fileno(s->stdio));
2743 stdio = PerlSIO_stdin;
2746 stdio = PerlSIO_stdout;
2749 stdio = PerlSIO_stderr;
2754 stdio = PerlSIO_fdopen(fd, mode =
2755 PerlIOStdio_mode(mode, tmode));
2760 f = PerlIO_allocate(aTHX);
2762 if ((f = PerlIO_push(aTHX_ f, self, mode, PerlIOArg))) {
2763 s = PerlIOSelf(f, PerlIOStdio);
2765 PerlIOUnix_refcnt_inc(fileno(s->stdio));
2775 PerlIOStdio_dup(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags)
2777 /* This assumes no layers underneath - which is what
2778 happens, but is not how I remember it. NI-S 2001/10/16
2780 if ((f = PerlIOBase_dup(aTHX_ f, o, param, flags))) {
2781 FILE *stdio = PerlIOSelf(o, PerlIOStdio)->stdio;
2782 int fd = fileno(stdio);
2784 if (flags & PERLIO_DUP_FD) {
2785 int dfd = PerlLIO_dup(fileno(stdio));
2787 stdio = PerlSIO_fdopen(dfd, PerlIO_modestr(o,mode));
2791 /* FIXME: To avoid messy error recovery if dup fails
2792 re-use the existing stdio as though flag was not set
2796 stdio = PerlSIO_fdopen(fd, PerlIO_modestr(o,mode));
2798 PerlIOSelf(f, PerlIOStdio)->stdio = stdio;
2799 PerlIOUnix_refcnt_inc(fileno(stdio));
2805 PerlIOStdio_invalidate_fileno(pTHX_ FILE *f)
2807 /* XXX this could use PerlIO_canset_fileno() and
2808 * PerlIO_set_fileno() support from Configure
2810 # if defined(__GLIBC__)
2811 /* There may be a better way for GLIBC:
2812 - libio.h defines a flag to not close() on cleanup
2816 # elif defined(__sun__)
2818 /* On solaris, if _LP64 is defined, the FILE structure is this:
2824 * It turns out that the fd is stored in the top 32 bits of
2825 * file->__pad[4]. The lower 32 bits contain flags. file->pad[5] appears
2826 * to contain a pointer or offset into another structure. All the
2827 * remaining fields are zero.
2829 * We set the top bits to -1 (0xFFFFFFFF).
2831 f->__pad[4] |= 0xffffffff00000000L;
2832 assert(fileno(f) == 0xffffffff);
2833 # else /* !defined(_LP64) */
2834 /* _file is just a unsigned char :-(
2835 Not clear why we dup() rather than using -1
2836 even if that would be treated as 0xFF - so will
2839 f->_file = PerlLIO_dup(fileno(f));
2840 # endif /* defined(_LP64) */
2842 # elif defined(__hpux)
2846 /* Next one ->_file seems to be a reasonable fallback, i.e. if
2847 your platform does not have special entry try this one.
2848 [For OSF only have confirmation for Tru64 (alpha)
2849 but assume other OSFs will be similar.]
2851 # elif defined(_AIX) || defined(__osf__) || defined(__irix__)
2854 # elif defined(__FreeBSD__)
2855 /* There may be a better way on FreeBSD:
2856 - we could insert a dummy func in the _close function entry
2857 f->_close = (int (*)(void *)) dummy_close;
2861 # elif defined(__CYGWIN__)
2862 /* There may be a better way on CYGWIN:
2863 - we could insert a dummy func in the _close function entry
2864 f->_close = (int (*)(void *)) dummy_close;
2868 # elif defined(WIN32)
2869 # if defined(__BORLANDC__)
2870 f->fd = PerlLIO_dup(fileno(f));
2871 # elif defined(UNDER_CE)
2872 /* WIN_CE does not have access to FILE internals, it hardly has FILE
2881 /* Sarathy's code did this - we fall back to a dup/dup2 hack
2882 (which isn't thread safe) instead
2884 # error "Don't know how to set FILE.fileno on your platform"
2891 PerlIOStdio_close(pTHX_ PerlIO *f)
2893 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
2899 int fd = fileno(stdio);
2905 #ifdef SOCKS5_VERSION_NAME
2906 /* Socks lib overrides close() but stdio isn't linked to
2907 that library (though we are) - so we must call close()
2908 on sockets on stdio's behalf.
2911 Sock_size_t optlen = sizeof(int);
2912 if (getsockopt(fd, SOL_SOCKET, SO_TYPE, (void *) &optval, &optlen) == 0) {
2917 if (PerlIOUnix_refcnt_dec(fd) > 0) {
2918 /* File descriptor still in use */
2923 /* For STD* handles don't close the stdio at all
2924 this is because we have shared the FILE * too
2926 if (stdio == stdin) {
2927 /* Some stdios are buggy fflush-ing inputs */
2930 else if (stdio == stdout || stdio == stderr) {
2931 return PerlIO_flush(f);
2933 /* Tricky - must fclose(stdio) to free memory but not close(fd)
2934 Use Sarathy's trick from maint-5.6 to invalidate the
2935 fileno slot of the FILE *
2937 result = PerlIO_flush(f);
2939 if (!(invalidate = PerlIOStdio_invalidate_fileno(aTHX_ stdio))) {
2940 dupfd = PerlLIO_dup(fd);
2943 result = PerlSIO_fclose(stdio);
2944 /* We treat error from stdio as success if we invalidated
2945 errno may NOT be expected EBADF
2947 if (invalidate && result != 0) {
2952 /* in SOCKS case let close() determine return value */
2956 PerlLIO_dup2(dupfd,fd);
2957 PerlLIO_close(dupfd);
2964 PerlIOStdio_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
2966 FILE *s = PerlIOSelf(f, PerlIOStdio)->stdio;
2970 STDCHAR *buf = (STDCHAR *) vbuf;
2972 * Perl is expecting PerlIO_getc() to fill the buffer Linux's
2973 * stdio does not do that for fread()
2975 int ch = PerlSIO_fgetc(s);
2982 got = PerlSIO_fread(vbuf, 1, count, s);
2983 if (got == 0 && PerlSIO_ferror(s))
2985 if (got >= 0 || errno != EINTR)
2988 SETERRNO(0,0); /* just in case */
2994 PerlIOStdio_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
2997 FILE *s = PerlIOSelf(f, PerlIOStdio)->stdio;
2999 #ifdef STDIO_BUFFER_WRITABLE
3000 if (PerlIO_fast_gets(f) && PerlIO_has_base(f)) {
3001 STDCHAR *buf = ((STDCHAR *) vbuf) + count;
3002 STDCHAR *base = PerlIO_get_base(f);
3003 SSize_t cnt = PerlIO_get_cnt(f);
3004 STDCHAR *ptr = PerlIO_get_ptr(f);
3005 SSize_t avail = ptr - base;
3007 if (avail > count) {
3011 Move(buf-avail,ptr,avail,STDCHAR);
3014 PerlIO_set_ptrcnt(f,ptr,cnt+avail);
3015 if (PerlSIO_feof(s) && unread >= 0)
3016 PerlSIO_clearerr(s);
3021 if (PerlIO_has_cntptr(f)) {
3022 /* We can get pointer to buffer but not its base
3023 Do ungetc() but check chars are ending up in the
3026 STDCHAR *eptr = (STDCHAR*)PerlSIO_get_ptr(s);
3027 STDCHAR *buf = ((STDCHAR *) vbuf) + count;
3029 int ch = *--buf & 0xFF;
3030 if (ungetc(ch,s) != ch) {
3031 /* ungetc did not work */
3034 if ((STDCHAR*)PerlSIO_get_ptr(s) != --eptr || ((*eptr & 0xFF) != ch)) {
3035 /* Did not change pointer as expected */
3036 fgetc(s); /* get char back again */
3046 unread += PerlIOBase_unread(aTHX_ f, vbuf, count);
3052 PerlIOStdio_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
3056 got = PerlSIO_fwrite(vbuf, 1, count,
3057 PerlIOSelf(f, PerlIOStdio)->stdio);
3058 if (got >= 0 || errno != EINTR)
3061 SETERRNO(0,0); /* just in case */
3067 PerlIOStdio_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
3069 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3070 return PerlSIO_fseek(stdio, offset, whence);
3074 PerlIOStdio_tell(pTHX_ PerlIO *f)
3076 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3077 return PerlSIO_ftell(stdio);
3081 PerlIOStdio_flush(pTHX_ PerlIO *f)
3083 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3084 if (PerlIOBase(f)->flags & PERLIO_F_CANWRITE) {
3085 return PerlSIO_fflush(stdio);
3090 * FIXME: This discards ungetc() and pre-read stuff which is not
3091 * right if this is just a "sync" from a layer above Suspect right
3092 * design is to do _this_ but not have layer above flush this
3093 * layer read-to-read
3096 * Not writeable - sync by attempting a seek
3099 if (PerlSIO_fseek(stdio, (Off_t) 0, SEEK_CUR) != 0)
3107 PerlIOStdio_eof(pTHX_ PerlIO *f)
3109 return PerlSIO_feof(PerlIOSelf(f, PerlIOStdio)->stdio);
3113 PerlIOStdio_error(pTHX_ PerlIO *f)
3115 return PerlSIO_ferror(PerlIOSelf(f, PerlIOStdio)->stdio);
3119 PerlIOStdio_clearerr(pTHX_ PerlIO *f)
3121 PerlSIO_clearerr(PerlIOSelf(f, PerlIOStdio)->stdio);
3125 PerlIOStdio_setlinebuf(pTHX_ PerlIO *f)
3127 #ifdef HAS_SETLINEBUF
3128 PerlSIO_setlinebuf(PerlIOSelf(f, PerlIOStdio)->stdio);
3130 PerlSIO_setvbuf(PerlIOSelf(f, PerlIOStdio)->stdio, Nullch, _IOLBF, 0);
3136 PerlIOStdio_get_base(pTHX_ PerlIO *f)
3138 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3139 return (STDCHAR*)PerlSIO_get_base(stdio);
3143 PerlIOStdio_get_bufsiz(pTHX_ PerlIO *f)
3145 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3146 return PerlSIO_get_bufsiz(stdio);
3150 #ifdef USE_STDIO_PTR
3152 PerlIOStdio_get_ptr(pTHX_ PerlIO *f)
3154 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3155 return (STDCHAR*)PerlSIO_get_ptr(stdio);
3159 PerlIOStdio_get_cnt(pTHX_ PerlIO *f)
3161 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3162 return PerlSIO_get_cnt(stdio);
3166 PerlIOStdio_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, SSize_t cnt)
3168 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3170 #ifdef STDIO_PTR_LVALUE
3171 PerlSIO_set_ptr(stdio, (void*)ptr); /* LHS STDCHAR* cast non-portable */
3172 #ifdef STDIO_PTR_LVAL_SETS_CNT
3173 if (PerlSIO_get_cnt(stdio) != (cnt)) {
3174 assert(PerlSIO_get_cnt(stdio) == (cnt));
3177 #if (!defined(STDIO_PTR_LVAL_NOCHANGE_CNT))
3179 * Setting ptr _does_ change cnt - we are done
3183 #else /* STDIO_PTR_LVALUE */
3185 #endif /* STDIO_PTR_LVALUE */
3188 * Now (or only) set cnt
3190 #ifdef STDIO_CNT_LVALUE
3191 PerlSIO_set_cnt(stdio, cnt);
3192 #else /* STDIO_CNT_LVALUE */
3193 #if (defined(STDIO_PTR_LVALUE) && defined(STDIO_PTR_LVAL_SETS_CNT))
3194 PerlSIO_set_ptr(stdio,
3195 PerlSIO_get_ptr(stdio) + (PerlSIO_get_cnt(stdio) -
3197 #else /* STDIO_PTR_LVAL_SETS_CNT */
3199 #endif /* STDIO_PTR_LVAL_SETS_CNT */
3200 #endif /* STDIO_CNT_LVALUE */
3207 PerlIOStdio_fill(pTHX_ PerlIO *f)
3209 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3212 * fflush()ing read-only streams can cause trouble on some stdio-s
3214 if ((PerlIOBase(f)->flags & PERLIO_F_CANWRITE)) {
3215 if (PerlSIO_fflush(stdio) != 0)
3218 c = PerlSIO_fgetc(stdio);
3222 #if (defined(STDIO_PTR_LVALUE) && (defined(STDIO_CNT_LVALUE) || defined(STDIO_PTR_LVAL_SETS_CNT)))
3224 #ifdef STDIO_BUFFER_WRITABLE
3225 if (PerlIO_fast_gets(f) && PerlIO_has_base(f)) {
3226 /* Fake ungetc() to the real buffer in case system's ungetc
3229 STDCHAR *base = (STDCHAR*)PerlSIO_get_base(stdio);
3230 SSize_t cnt = PerlSIO_get_cnt(stdio);
3231 STDCHAR *ptr = (STDCHAR*)PerlSIO_get_ptr(stdio);
3232 if (ptr == base+1) {
3233 *--ptr = (STDCHAR) c;
3234 PerlIOStdio_set_ptrcnt(aTHX_ f,ptr,cnt+1);
3235 if (PerlSIO_feof(stdio))
3236 PerlSIO_clearerr(stdio);
3242 if (PerlIO_has_cntptr(f)) {
3244 if (PerlIOStdio_unread(aTHX_ f,&ch,1) == 1) {
3251 /* An ungetc()d char is handled separately from the regular
3252 * buffer, so we stuff it in the buffer ourselves.
3253 * Should never get called as should hit code above
3255 *(--((*stdio)->_ptr)) = (unsigned char) c;
3258 /* If buffer snoop scheme above fails fall back to
3261 if (PerlSIO_ungetc(c, stdio) != c)
3269 PerlIO_funcs PerlIO_stdio = {
3270 sizeof(PerlIO_funcs),
3272 sizeof(PerlIOStdio),
3273 PERLIO_K_BUFFERED|PERLIO_K_RAW,
3277 PerlIOBase_binmode, /* binmode */
3291 PerlIOStdio_clearerr,
3292 PerlIOStdio_setlinebuf,
3294 PerlIOStdio_get_base,
3295 PerlIOStdio_get_bufsiz,
3300 #ifdef USE_STDIO_PTR
3301 PerlIOStdio_get_ptr,
3302 PerlIOStdio_get_cnt,
3303 # if defined(HAS_FAST_STDIO) && defined(USE_FAST_STDIO)
3304 PerlIOStdio_set_ptrcnt,
3307 # endif /* HAS_FAST_STDIO && USE_FAST_STDIO */
3312 #endif /* USE_STDIO_PTR */
3315 /* Note that calls to PerlIO_exportFILE() are reversed using
3316 * PerlIO_releaseFILE(), not importFILE. */
3318 PerlIO_exportFILE(PerlIO * f, const char *mode)
3322 if (PerlIOValid(f)) {
3325 if (!mode || !*mode) {
3326 mode = PerlIO_modestr(f, buf);
3328 stdio = PerlSIO_fdopen(PerlIO_fileno(f), mode);
3332 /* De-link any lower layers so new :stdio sticks */
3334 if ((f2 = PerlIO_push(aTHX_ f, &PerlIO_stdio, buf, Nullsv))) {
3335 PerlIOStdio *s = PerlIOSelf((f = f2), PerlIOStdio);
3337 /* Link previous lower layers under new one */
3341 /* restore layers list */
3351 PerlIO_findFILE(PerlIO *f)
3355 if (l->tab == &PerlIO_stdio) {
3356 PerlIOStdio *s = PerlIOSelf(&l, PerlIOStdio);
3359 l = *PerlIONext(&l);
3361 /* Uses fallback "mode" via PerlIO_modestr() in PerlIO_exportFILE */
3362 return PerlIO_exportFILE(f, Nullch);
3365 /* Use this to reverse PerlIO_exportFILE calls. */
3367 PerlIO_releaseFILE(PerlIO *p, FILE *f)
3371 if (l->tab == &PerlIO_stdio) {
3372 PerlIOStdio *s = PerlIOSelf(&l, PerlIOStdio);
3373 if (s->stdio == f) {
3375 PerlIO_pop(aTHX_ p);
3384 /*--------------------------------------------------------------------------------------*/
3386 * perlio buffer layer
3390 PerlIOBuf_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
3392 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3393 int fd = PerlIO_fileno(f);
3394 if (fd >= 0 && PerlLIO_isatty(fd)) {
3395 PerlIOBase(f)->flags |= PERLIO_F_LINEBUF | PERLIO_F_TTY;
3397 if (*PerlIONext(f)) {
3398 Off_t posn = PerlIO_tell(PerlIONext(f));
3399 if (posn != (Off_t) - 1) {
3403 return PerlIOBase_pushed(aTHX_ f, mode, arg, tab);
3407 PerlIOBuf_open(pTHX_ PerlIO_funcs *self, PerlIO_list_t *layers,
3408 IV n, const char *mode, int fd, int imode, int perm,
3409 PerlIO *f, int narg, SV **args)
3411 if (PerlIOValid(f)) {
3412 PerlIO *next = PerlIONext(f);
3414 PerlIO_layer_fetch(aTHX_ layers, n - 1, PerlIOBase(next)->tab);
3415 if (tab && tab->Open)
3417 (*tab->Open)(aTHX_ tab, layers, n - 1, mode, fd, imode, perm,
3419 if (!next || (*PerlIOBase(f)->tab->Pushed) (aTHX_ f, mode, PerlIOArg, self) != 0) {
3424 PerlIO_funcs *tab = PerlIO_layer_fetch(aTHX_ layers, n - 1, PerlIO_default_btm());
3432 if (tab && tab->Open)
3433 f = (*tab->Open)(aTHX_ tab, layers, n - 1, mode, fd, imode, perm,
3436 SETERRNO(EINVAL, LIB_INVARG);
3438 if (PerlIO_push(aTHX_ f, self, mode, PerlIOArg) == 0) {
3440 * if push fails during open, open fails. close will pop us.
3445 fd = PerlIO_fileno(f);
3446 if (init && fd == 2) {
3448 * Initial stderr is unbuffered
3450 PerlIOBase(f)->flags |= PERLIO_F_UNBUF;
3452 #ifdef PERLIO_USING_CRLF
3453 # ifdef PERLIO_IS_BINMODE_FD
3454 if (PERLIO_IS_BINMODE_FD(fd))
3455 PerlIO_binmode(aTHX_ f, '<'/*not used*/, O_BINARY, Nullch);
3459 * do something about failing setmode()? --jhi
3461 PerlLIO_setmode(fd, O_BINARY);
3470 * This "flush" is akin to sfio's sync in that it handles files in either
3471 * read or write state
3474 PerlIOBuf_flush(pTHX_ PerlIO *f)
3476 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3478 PerlIO *n = PerlIONext(f);
3479 if (PerlIOBase(f)->flags & PERLIO_F_WRBUF) {
3481 * write() the buffer
3483 STDCHAR *buf = b->buf;
3485 while (p < b->ptr) {
3486 SSize_t count = PerlIO_write(n, p, b->ptr - p);
3490 else if (count < 0 || PerlIO_error(n)) {
3491 PerlIOBase(f)->flags |= PERLIO_F_ERROR;
3496 b->posn += (p - buf);
3498 else if (PerlIOBase(f)->flags & PERLIO_F_RDBUF) {
3499 STDCHAR *buf = PerlIO_get_base(f);
3501 * Note position change
3503 b->posn += (b->ptr - buf);
3504 if (b->ptr < b->end) {
3505 /* We did not consume all of it - try and seek downstream to
3506 our logical position
3508 if (PerlIOValid(n) && PerlIO_seek(n, b->posn, SEEK_SET) == 0) {
3509 /* Reload n as some layers may pop themselves on seek */
3510 b->posn = PerlIO_tell(n = PerlIONext(f));
3513 /* Seek failed (e.g. pipe or tty). Do NOT clear buffer or pre-read
3514 data is lost for good - so return saying "ok" having undone
3517 b->posn -= (b->ptr - buf);
3522 b->ptr = b->end = b->buf;
3523 PerlIOBase(f)->flags &= ~(PERLIO_F_RDBUF | PERLIO_F_WRBUF);
3524 /* We check for Valid because of dubious decision to make PerlIO_flush(NULL) flush all */
3525 if (PerlIOValid(n) && PerlIO_flush(n) != 0)
3531 PerlIOBuf_fill(pTHX_ PerlIO *f)
3533 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3534 PerlIO *n = PerlIONext(f);
3537 * Down-stream flush is defined not to loose read data so is harmless.
3538 * we would not normally be fill'ing if there was data left in anycase.
3540 if (PerlIO_flush(f) != 0)
3542 if (PerlIOBase(f)->flags & PERLIO_F_TTY)
3543 PerlIOBase_flush_linebuf(aTHX);
3546 PerlIO_get_base(f); /* allocate via vtable */
3548 b->ptr = b->end = b->buf;
3550 if (!PerlIOValid(n)) {
3551 PerlIOBase(f)->flags |= PERLIO_F_EOF;
3555 if (PerlIO_fast_gets(n)) {
3557 * Layer below is also buffered. We do _NOT_ want to call its
3558 * ->Read() because that will loop till it gets what we asked for
3559 * which may hang on a pipe etc. Instead take anything it has to
3560 * hand, or ask it to fill _once_.
3562 avail = PerlIO_get_cnt(n);
3564 avail = PerlIO_fill(n);
3566 avail = PerlIO_get_cnt(n);
3568 if (!PerlIO_error(n) && PerlIO_eof(n))
3573 STDCHAR *ptr = PerlIO_get_ptr(n);
3574 SSize_t cnt = avail;
3575 if (avail > (SSize_t)b->bufsiz)
3577 Copy(ptr, b->buf, avail, STDCHAR);
3578 PerlIO_set_ptrcnt(n, ptr + avail, cnt - avail);
3582 avail = PerlIO_read(n, b->ptr, b->bufsiz);
3586 PerlIOBase(f)->flags |= PERLIO_F_EOF;
3588 PerlIOBase(f)->flags |= PERLIO_F_ERROR;
3591 b->end = b->buf + avail;
3592 PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
3597 PerlIOBuf_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
3599 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3600 if (PerlIOValid(f)) {
3603 return PerlIOBase_read(aTHX_ f, vbuf, count);
3609 PerlIOBuf_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
3611 const STDCHAR *buf = (const STDCHAR *) vbuf + count;
3612 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3615 if (PerlIOBase(f)->flags & PERLIO_F_WRBUF)
3620 if (PerlIOBase(f)->flags & PERLIO_F_RDBUF) {
3622 * Buffer is already a read buffer, we can overwrite any chars
3623 * which have been read back to buffer start
3625 avail = (b->ptr - b->buf);
3629 * Buffer is idle, set it up so whole buffer is available for
3633 b->end = b->buf + avail;
3635 PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
3637 * Buffer extends _back_ from where we are now
3639 b->posn -= b->bufsiz;
3641 if (avail > (SSize_t) count) {
3643 * If we have space for more than count, just move count
3651 * In simple stdio-like ungetc() case chars will be already
3654 if (buf != b->ptr) {
3655 Copy(buf, b->ptr, avail, STDCHAR);
3659 PerlIOBase(f)->flags &= ~PERLIO_F_EOF;
3663 unread += PerlIOBase_unread(aTHX_ f, vbuf, count);
3669 PerlIOBuf_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
3671 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3672 const STDCHAR *buf = (const STDCHAR *) vbuf;
3676 if (!(PerlIOBase(f)->flags & PERLIO_F_CANWRITE))
3678 if (PerlIOBase(f)->flags & PERLIO_F_RDBUF) {
3679 if (PerlIO_flush(f) != 0) {
3684 SSize_t avail = b->bufsiz - (b->ptr - b->buf);
3685 if ((SSize_t) count < avail)
3687 PerlIOBase(f)->flags |= PERLIO_F_WRBUF;
3688 if (PerlIOBase(f)->flags & PERLIO_F_LINEBUF) {
3703 Copy(buf, b->ptr, avail, STDCHAR);
3710 if (b->ptr >= (b->buf + b->bufsiz))
3713 if (PerlIOBase(f)->flags & PERLIO_F_UNBUF)
3719 PerlIOBuf_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
3722 if ((code = PerlIO_flush(f)) == 0) {
3723 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3724 PerlIOBase(f)->flags &= ~PERLIO_F_EOF;
3725 code = PerlIO_seek(PerlIONext(f), offset, whence);
3727 b->posn = PerlIO_tell(PerlIONext(f));
3734 PerlIOBuf_tell(pTHX_ PerlIO *f)
3736 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3738 * b->posn is file position where b->buf was read, or will be written
3740 Off_t posn = b->posn;
3741 if ((PerlIOBase(f)->flags & PERLIO_F_APPEND) &&
3742 (PerlIOBase(f)->flags & PERLIO_F_WRBUF)) {
3744 /* As O_APPEND files are normally shared in some sense it is better
3749 /* when file is NOT shared then this is sufficient */
3750 PerlIO_seek(PerlIONext(f),0, SEEK_END);
3752 posn = b->posn = PerlIO_tell(PerlIONext(f));
3756 * If buffer is valid adjust position by amount in buffer
3758 posn += (b->ptr - b->buf);
3764 PerlIOBuf_popped(pTHX_ PerlIO *f)
3766 IV code = PerlIOBase_popped(aTHX_ f);
3767 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3768 if (b->buf && b->buf != (STDCHAR *) & b->oneword) {
3772 b->ptr = b->end = b->buf;
3773 PerlIOBase(f)->flags &= ~(PERLIO_F_RDBUF | PERLIO_F_WRBUF);
3778 PerlIOBuf_close(pTHX_ PerlIO *f)
3780 IV code = PerlIOBase_close(aTHX_ f);
3781 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3782 if (b->buf && b->buf != (STDCHAR *) & b->oneword) {
3786 b->ptr = b->end = b->buf;
3787 PerlIOBase(f)->flags &= ~(PERLIO_F_RDBUF | PERLIO_F_WRBUF);
3792 PerlIOBuf_get_ptr(pTHX_ PerlIO *f)
3794 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3801 PerlIOBuf_get_cnt(pTHX_ PerlIO *f)
3803 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3806 if (PerlIOBase(f)->flags & PERLIO_F_RDBUF)
3807 return (b->end - b->ptr);
3812 PerlIOBuf_get_base(pTHX_ PerlIO *f)
3814 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3819 Newz('B',b->buf,b->bufsiz, STDCHAR);
3821 b->buf = (STDCHAR *) & b->oneword;
3822 b->bufsiz = sizeof(b->oneword);
3831 PerlIOBuf_bufsiz(pTHX_ PerlIO *f)
3833 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3836 return (b->end - b->buf);
3840 PerlIOBuf_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, SSize_t cnt)
3842 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3846 if (PerlIO_get_cnt(f) != cnt || b->ptr < b->buf) {
3847 assert(PerlIO_get_cnt(f) == cnt);
3848 assert(b->ptr >= b->buf);
3850 PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
3854 PerlIOBuf_dup(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags)
3856 return PerlIOBase_dup(aTHX_ f, o, param, flags);
3861 PerlIO_funcs PerlIO_perlio = {
3862 sizeof(PerlIO_funcs),
3865 PERLIO_K_BUFFERED|PERLIO_K_RAW,
3869 PerlIOBase_binmode, /* binmode */
3883 PerlIOBase_clearerr,
3884 PerlIOBase_setlinebuf,
3889 PerlIOBuf_set_ptrcnt,
3892 /*--------------------------------------------------------------------------------------*/
3894 * Temp layer to hold unread chars when cannot do it any other way
3898 PerlIOPending_fill(pTHX_ PerlIO *f)
3901 * Should never happen
3908 PerlIOPending_close(pTHX_ PerlIO *f)
3911 * A tad tricky - flush pops us, then we close new top
3914 return PerlIO_close(f);
3918 PerlIOPending_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
3921 * A tad tricky - flush pops us, then we seek new top
3924 return PerlIO_seek(f, offset, whence);
3929 PerlIOPending_flush(pTHX_ PerlIO *f)
3931 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3932 if (b->buf && b->buf != (STDCHAR *) & b->oneword) {
3936 PerlIO_pop(aTHX_ f);
3941 PerlIOPending_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, SSize_t cnt)
3947 PerlIOBuf_set_ptrcnt(aTHX_ f, ptr, cnt);
3952 PerlIOPending_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
3954 IV code = PerlIOBase_pushed(aTHX_ f, mode, arg, tab);
3955 PerlIOl *l = PerlIOBase(f);
3957 * Our PerlIO_fast_gets must match what we are pushed on, or sv_gets()
3958 * etc. get muddled when it changes mid-string when we auto-pop.
3960 l->flags = (l->flags & ~(PERLIO_F_FASTGETS | PERLIO_F_UTF8)) |
3961 (PerlIOBase(PerlIONext(f))->
3962 flags & (PERLIO_F_FASTGETS | PERLIO_F_UTF8));
3967 PerlIOPending_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
3969 SSize_t avail = PerlIO_get_cnt(f);
3971 if ((SSize_t)count < avail)
3974 got = PerlIOBuf_read(aTHX_ f, vbuf, avail);
3975 if (got >= 0 && got < (SSize_t)count) {
3977 PerlIO_read(f, ((STDCHAR *) vbuf) + got, count - got);
3978 if (more >= 0 || got == 0)
3984 PerlIO_funcs PerlIO_pending = {
3985 sizeof(PerlIO_funcs),
3988 PERLIO_K_BUFFERED|PERLIO_K_RAW, /* not sure about RAW here */
3989 PerlIOPending_pushed,
3992 PerlIOBase_binmode, /* binmode */
4001 PerlIOPending_close,
4002 PerlIOPending_flush,
4006 PerlIOBase_clearerr,
4007 PerlIOBase_setlinebuf,
4012 PerlIOPending_set_ptrcnt,
4017 /*--------------------------------------------------------------------------------------*/
4019 * crlf - translation On read translate CR,LF to "\n" we do this by
4020 * overriding ptr/cnt entries to hand back a line at a time and keeping a
4021 * record of which nl we "lied" about. On write translate "\n" to CR,LF
4025 PerlIOBuf base; /* PerlIOBuf stuff */
4026 STDCHAR *nl; /* Position of crlf we "lied" about in the
4031 PerlIOCrlf_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
4034 PerlIOBase(f)->flags |= PERLIO_F_CRLF;
4035 code = PerlIOBuf_pushed(aTHX_ f, mode, arg, tab);
4037 PerlIO_debug("PerlIOCrlf_pushed f=%p %s %s fl=%08" UVxf "\n",
4038 f, PerlIOBase(f)->tab->name, (mode) ? mode : "(Null)",
4039 PerlIOBase(f)->flags);
4042 /* Enable the first CRLF capable layer you can find, but if none
4043 * found, the one we just pushed is fine. This results in at
4044 * any given moment at most one CRLF-capable layer being enabled
4045 * in the whole layer stack. */
4046 PerlIO *g = PerlIONext(f);
4048 PerlIOl *b = PerlIOBase(g);
4049 if (b && b->tab == &PerlIO_crlf) {
4050 if (!(b->flags & PERLIO_F_CRLF))
4051 b->flags |= PERLIO_F_CRLF;
4052 PerlIO_pop(aTHX_ f);
4063 PerlIOCrlf_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
4065 PerlIOCrlf *c = PerlIOSelf(f, PerlIOCrlf);
4070 if (!(PerlIOBase(f)->flags & PERLIO_F_CRLF))
4071 return PerlIOBuf_unread(aTHX_ f, vbuf, count);
4073 const STDCHAR *buf = (const STDCHAR *) vbuf + count;
4074 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
4076 if (PerlIOBase(f)->flags & PERLIO_F_WRBUF)
4081 if (!(PerlIOBase(f)->flags & PERLIO_F_RDBUF)) {
4082 b->end = b->ptr = b->buf + b->bufsiz;
4083 PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
4084 b->posn -= b->bufsiz;
4086 while (count > 0 && b->ptr > b->buf) {
4089 if (b->ptr - 2 >= b->buf) {
4112 PerlIOCrlf_get_cnt(pTHX_ PerlIO *f)
4114 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
4117 if (PerlIOBase(f)->flags & PERLIO_F_RDBUF) {
4118 PerlIOCrlf *c = PerlIOSelf(f, PerlIOCrlf);
4119 if ((PerlIOBase(f)->flags & PERLIO_F_CRLF) && (!c->nl || *c->nl == 0xd)) {
4120 STDCHAR *nl = (c->nl) ? c->nl : b->ptr;
4122 while (nl < b->end && *nl != 0xd)
4124 if (nl < b->end && *nl == 0xd) {
4126 if (nl + 1 < b->end) {
4133 * Not CR,LF but just CR
4141 * Blast - found CR as last char in buffer
4146 * They may not care, defer work as long as
4150 return (nl - b->ptr);
4154 b->ptr++; /* say we have read it as far as
4155 * flush() is concerned */
4156 b->buf++; /* Leave space in front of buffer */
4157 /* Note as we have moved buf up flush's
4159 will naturally make posn point at CR
4161 b->bufsiz--; /* Buffer is thus smaller */
4162 code = PerlIO_fill(f); /* Fetch some more */
4163 b->bufsiz++; /* Restore size for next time */
4164 b->buf--; /* Point at space */
4165 b->ptr = nl = b->buf; /* Which is what we hand
4167 *nl = 0xd; /* Fill in the CR */
4169 goto test; /* fill() call worked */
4171 * CR at EOF - just fall through
4173 /* Should we clear EOF though ??? */
4178 return (((c->nl) ? (c->nl + 1) : b->end) - b->ptr);
4184 PerlIOCrlf_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, SSize_t cnt)
4186 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
4187 PerlIOCrlf *c = PerlIOSelf(f, PerlIOCrlf);
4193 if (ptr == b->end && *c->nl == 0xd) {
4194 /* Defered CR at end of buffer case - we lied about count */
4206 * Test code - delete when it works ...
4208 IV flags = PerlIOBase(f)->flags;
4209 STDCHAR *chk = (c->nl) ? (c->nl+1) : b->end;
4210 if (ptr+cnt == c->nl && c->nl+1 == b->end && *c->nl == 0xd) {
4211 /* Defered CR at end of buffer case - we lied about count */
4217 Perl_croak(aTHX_ "ptr wrong %p != %p fl=%08" UVxf
4218 " nl=%p e=%p for %d", ptr, chk, flags, c->nl,
4226 * They have taken what we lied about
4234 PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
4238 PerlIOCrlf_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
4240 if (!(PerlIOBase(f)->flags & PERLIO_F_CRLF))
4241 return PerlIOBuf_write(aTHX_ f, vbuf, count);
4243 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
4244 const STDCHAR *buf = (const STDCHAR *) vbuf;
4245 const STDCHAR *ebuf = buf + count;
4248 if (!(PerlIOBase(f)->flags & PERLIO_F_CANWRITE))
4250 while (buf < ebuf) {
4251 STDCHAR *eptr = b->buf + b->bufsiz;
4252 PerlIOBase(f)->flags |= PERLIO_F_WRBUF;
4253 while (buf < ebuf && b->ptr < eptr) {
4255 if ((b->ptr + 2) > eptr) {
4263 *(b->ptr)++ = 0xd; /* CR */
4264 *(b->ptr)++ = 0xa; /* LF */
4266 if (PerlIOBase(f)->flags & PERLIO_F_LINEBUF) {
4276 if (b->ptr >= eptr) {
4282 if (PerlIOBase(f)->flags & PERLIO_F_UNBUF)
4284 return (buf - (STDCHAR *) vbuf);
4289 PerlIOCrlf_flush(pTHX_ PerlIO *f)
4291 PerlIOCrlf *c = PerlIOSelf(f, PerlIOCrlf);
4296 return PerlIOBuf_flush(aTHX_ f);
4300 PerlIOCrlf_binmode(pTHX_ PerlIO *f)
4302 if ((PerlIOBase(f)->flags & PERLIO_F_CRLF)) {
4303 /* In text mode - flush any pending stuff and flip it */
4304 PerlIOBase(f)->flags &= ~PERLIO_F_CRLF;
4305 #ifndef PERLIO_USING_CRLF
4306 /* CRLF is unusual case - if this is just the :crlf layer pop it */
4307 if (PerlIOBase(f)->tab == &PerlIO_crlf) {
4308 PerlIO_pop(aTHX_ f);
4315 PerlIO_funcs PerlIO_crlf = {
4316 sizeof(PerlIO_funcs),
4319 PERLIO_K_BUFFERED | PERLIO_K_CANCRLF | PERLIO_K_RAW,
4321 PerlIOBuf_popped, /* popped */
4323 PerlIOCrlf_binmode, /* binmode */
4327 PerlIOBuf_read, /* generic read works with ptr/cnt lies
4329 PerlIOCrlf_unread, /* Put CR,LF in buffer for each '\n' */
4330 PerlIOCrlf_write, /* Put CR,LF in buffer for each '\n' */
4338 PerlIOBase_clearerr,
4339 PerlIOBase_setlinebuf,
4344 PerlIOCrlf_set_ptrcnt,
4348 /*--------------------------------------------------------------------------------------*/
4350 * mmap as "buffer" layer
4354 PerlIOBuf base; /* PerlIOBuf stuff */
4355 Mmap_t mptr; /* Mapped address */
4356 Size_t len; /* mapped length */
4357 STDCHAR *bbuf; /* malloced buffer if map fails */
4360 static size_t page_size = 0;
4363 PerlIOMmap_map(pTHX_ PerlIO *f)
4365 PerlIOMmap *m = PerlIOSelf(f, PerlIOMmap);
4366 IV flags = PerlIOBase(f)->flags;
4370 if (flags & PERLIO_F_CANREAD) {
4371 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
4372 int fd = PerlIO_fileno(f);
4374 code = Fstat(fd, &st);
4375 if (code == 0 && S_ISREG(st.st_mode)) {
4376 SSize_t len = st.st_size - b->posn;
4380 #if defined(HAS_SYSCONF) && (defined(_SC_PAGESIZE) || defined(_SC_PAGE_SIZE))
4382 SETERRNO(0, SS_NORMAL);
4383 # ifdef _SC_PAGESIZE
4384 page_size = sysconf(_SC_PAGESIZE);
4386 page_size = sysconf(_SC_PAGE_SIZE);
4388 if ((long) page_size < 0) {
4393 (void) SvUPGRADE(error, SVt_PV);
4394 msg = SvPVx(error, n_a);
4395 Perl_croak(aTHX_ "panic: sysconf: %s",
4400 "panic: sysconf: pagesize unknown");
4404 # ifdef HAS_GETPAGESIZE
4405 page_size = getpagesize();
4407 # if defined(I_SYS_PARAM) && defined(PAGESIZE)
4408 page_size = PAGESIZE; /* compiletime, bad */
4412 if ((IV) page_size <= 0)
4413 Perl_croak(aTHX_ "panic: bad pagesize %" IVdf,
4418 * This is a hack - should never happen - open should
4421 b->posn = PerlIO_tell(PerlIONext(f));
4423 posn = (b->posn / page_size) * page_size;
4424 len = st.st_size - posn;
4425 m->mptr = mmap(NULL, len, PROT_READ, MAP_SHARED, fd, posn);
4426 if (m->mptr && m->mptr != (Mmap_t) - 1) {
4427 #if 0 && defined(HAS_MADVISE) && defined(MADV_SEQUENTIAL)
4428 madvise(m->mptr, len, MADV_SEQUENTIAL);
4430 #if 0 && defined(HAS_MADVISE) && defined(MADV_WILLNEED)
4431 madvise(m->mptr, len, MADV_WILLNEED);
4433 PerlIOBase(f)->flags =
4434 (flags & ~PERLIO_F_EOF) | PERLIO_F_RDBUF;
4435 b->end = ((STDCHAR *) m->mptr) + len;
4436 b->buf = ((STDCHAR *) m->mptr) + (b->posn - posn);
4445 PerlIOBase(f)->flags =
4446 flags | PERLIO_F_EOF | PERLIO_F_RDBUF;
4448 b->ptr = b->end = b->ptr;
4457 PerlIOMmap_unmap(pTHX_ PerlIO *f)
4459 PerlIOMmap *m = PerlIOSelf(f, PerlIOMmap);
4460 PerlIOBuf *b = &m->base;
4464 code = munmap(m->mptr, m->len);
4468 if (PerlIO_seek(PerlIONext(f), b->posn, SEEK_SET) != 0)
4471 b->ptr = b->end = b->buf;
4472 PerlIOBase(f)->flags &= ~(PERLIO_F_RDBUF | PERLIO_F_WRBUF);
4478 PerlIOMmap_get_base(pTHX_ PerlIO *f)
4480 PerlIOMmap *m = PerlIOSelf(f, PerlIOMmap);
4481 PerlIOBuf *b = &m->base;
4482 if (b->buf && (PerlIOBase(f)->flags & PERLIO_F_RDBUF)) {
4484 * Already have a readbuffer in progress
4490 * We have a write buffer or flushed PerlIOBuf read buffer
4492 m->bbuf = b->buf; /* save it in case we need it again */
4493 b->buf = NULL; /* Clear to trigger below */
4496 PerlIOMmap_map(aTHX_ f); /* Try and map it */
4499 * Map did not work - recover PerlIOBuf buffer if we have one
4504 b->ptr = b->end = b->buf;
4507 return PerlIOBuf_get_base(aTHX_ f);
4511 PerlIOMmap_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
4513 PerlIOMmap *m = PerlIOSelf(f, PerlIOMmap);
4514 PerlIOBuf *b = &m->base;
4515 if (PerlIOBase(f)->flags & PERLIO_F_WRBUF)
4517 if (b->ptr && (b->ptr - count) >= b->buf
4518 && memEQ(b->ptr - count, vbuf, count)) {
4520 PerlIOBase(f)->flags &= ~PERLIO_F_EOF;
4525 * Loose the unwritable mapped buffer
4529 * If flush took the "buffer" see if we have one from before
4531 if (!b->buf && m->bbuf)
4534 PerlIOBuf_get_base(aTHX_ f);
4538 return PerlIOBuf_unread(aTHX_ f, vbuf, count);
4542 PerlIOMmap_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
4544 PerlIOMmap *m = PerlIOSelf(f, PerlIOMmap);
4545 PerlIOBuf *b = &m->base;
4546 if (!b->buf || !(PerlIOBase(f)->flags & PERLIO_F_WRBUF)) {
4548 * No, or wrong sort of, buffer
4551 if (PerlIOMmap_unmap(aTHX_ f) != 0)
4555 * If unmap took the "buffer" see if we have one from before
4557 if (!b->buf && m->bbuf)
4560 PerlIOBuf_get_base(aTHX_ f);
4564 return PerlIOBuf_write(aTHX_ f, vbuf, count);
4568 PerlIOMmap_flush(pTHX_ PerlIO *f)
4570 PerlIOMmap *m = PerlIOSelf(f, PerlIOMmap);
4571 PerlIOBuf *b = &m->base;
4572 IV code = PerlIOBuf_flush(aTHX_ f);
4574 * Now we are "synced" at PerlIOBuf level
4581 if (PerlIOMmap_unmap(aTHX_ f) != 0)
4586 * We seem to have a PerlIOBuf buffer which was not mapped
4587 * remember it in case we need one later
4596 PerlIOMmap_fill(pTHX_ PerlIO *f)
4598 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
4599 IV code = PerlIO_flush(f);
4600 if (code == 0 && !b->buf) {
4601 code = PerlIOMmap_map(aTHX_ f);
4603 if (code == 0 && !(PerlIOBase(f)->flags & PERLIO_F_RDBUF)) {
4604 code = PerlIOBuf_fill(aTHX_ f);
4610 PerlIOMmap_close(pTHX_ PerlIO *f)
4612 PerlIOMmap *m = PerlIOSelf(f, PerlIOMmap);
4613 PerlIOBuf *b = &m->base;
4614 IV code = PerlIO_flush(f);
4618 b->ptr = b->end = b->buf;
4620 if (PerlIOBuf_close(aTHX_ f) != 0)
4626 PerlIOMmap_dup(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags)
4628 return PerlIOBase_dup(aTHX_ f, o, param, flags);
4632 PerlIO_funcs PerlIO_mmap = {
4633 sizeof(PerlIO_funcs),
4636 PERLIO_K_BUFFERED|PERLIO_K_RAW,
4640 PerlIOBase_binmode, /* binmode */
4654 PerlIOBase_clearerr,
4655 PerlIOBase_setlinebuf,
4656 PerlIOMmap_get_base,
4660 PerlIOBuf_set_ptrcnt,
4663 #endif /* HAS_MMAP */
4666 Perl_PerlIO_stdin(pTHX)
4669 PerlIO_stdstreams(aTHX);
4671 return &PL_perlio[1];
4675 Perl_PerlIO_stdout(pTHX)
4678 PerlIO_stdstreams(aTHX);
4680 return &PL_perlio[2];
4684 Perl_PerlIO_stderr(pTHX)
4687 PerlIO_stdstreams(aTHX);
4689 return &PL_perlio[3];
4692 /*--------------------------------------------------------------------------------------*/
4695 PerlIO_getname(PerlIO *f, char *buf)
4700 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
4702 name = fgetname(stdio, buf);
4704 Perl_croak(aTHX_ "Don't know how to get file name");
4710 /*--------------------------------------------------------------------------------------*/
4712 * Functions which can be called on any kind of PerlIO implemented in
4716 #undef PerlIO_fdopen
4718 PerlIO_fdopen(int fd, const char *mode)
4721 return PerlIO_openn(aTHX_ Nullch, mode, fd, 0, 0, NULL, 0, NULL);
4726 PerlIO_open(const char *path, const char *mode)
4729 SV *name = sv_2mortal(newSVpvn(path, strlen(path)));
4730 return PerlIO_openn(aTHX_ Nullch, mode, -1, 0, 0, NULL, 1, &name);
4733 #undef Perlio_reopen
4735 PerlIO_reopen(const char *path, const char *mode, PerlIO *f)
4738 SV *name = sv_2mortal(newSVpvn(path, strlen(path)));
4739 return PerlIO_openn(aTHX_ Nullch, mode, -1, 0, 0, f, 1, &name);
4744 PerlIO_getc(PerlIO *f)
4748 SSize_t count = PerlIO_read(f, buf, 1);
4750 return (unsigned char) buf[0];
4755 #undef PerlIO_ungetc
4757 PerlIO_ungetc(PerlIO *f, int ch)
4762 if (PerlIO_unread(f, &buf, 1) == 1)
4770 PerlIO_putc(PerlIO *f, int ch)
4774 return PerlIO_write(f, &buf, 1);
4779 PerlIO_puts(PerlIO *f, const char *s)
4782 STRLEN len = strlen(s);
4783 return PerlIO_write(f, s, len);
4786 #undef PerlIO_rewind
4788 PerlIO_rewind(PerlIO *f)
4791 PerlIO_seek(f, (Off_t) 0, SEEK_SET);
4795 #undef PerlIO_vprintf
4797 PerlIO_vprintf(PerlIO *f, const char *fmt, va_list ap)
4800 SV *sv = newSVpvn("", 0);
4806 Perl_va_copy(ap, apc);
4807 sv_vcatpvf(sv, fmt, &apc);
4809 sv_vcatpvf(sv, fmt, &ap);
4812 wrote = PerlIO_write(f, s, len);
4817 #undef PerlIO_printf
4819 PerlIO_printf(PerlIO *f, const char *fmt, ...)
4824 result = PerlIO_vprintf(f, fmt, ap);
4829 #undef PerlIO_stdoutf
4831 PerlIO_stdoutf(const char *fmt, ...)
4837 result = PerlIO_vprintf(PerlIO_stdout(), fmt, ap);
4842 #undef PerlIO_tmpfile
4844 PerlIO_tmpfile(void)
4852 f = PerlIO_fdopen(fd, "w+b");
4855 SV *sv = newSVpv("/tmp/PerlIO_XXXXXX", 0);
4858 * I have no idea how portable mkstemp() is ... NI-S
4860 fd = mkstemp(SvPVX(sv));
4862 f = PerlIO_fdopen(fd, "w+");
4864 PerlIOBase(f)->flags |= PERLIO_F_TEMP;
4865 PerlLIO_unlink(SvPVX(sv));
4868 # else /* !HAS_MKSTEMP, fallback to stdio tmpfile(). */
4869 FILE *stdio = PerlSIO_tmpfile();
4872 if ((f = PerlIO_push(aTHX_(PerlIO_allocate(aTHX)),
4873 &PerlIO_stdio, "w+", Nullsv))) {
4874 PerlIOStdio *s = PerlIOSelf(f, PerlIOStdio);
4880 # endif /* else HAS_MKSTEMP */
4881 #endif /* else WIN32 */
4888 #endif /* USE_SFIO */
4889 #endif /* PERLIO_IS_STDIO */
4891 /*======================================================================================*/
4893 * Now some functions in terms of above which may be needed even if we are
4894 * not in true PerlIO mode
4898 #undef PerlIO_setpos
4900 PerlIO_setpos(PerlIO *f, SV *pos)
4905 Off_t *posn = (Off_t *) SvPV(pos, len);
4906 if (f && len == sizeof(Off_t))
4907 return PerlIO_seek(f, *posn, SEEK_SET);
4909 SETERRNO(EINVAL, SS_IVCHAN);
4913 #undef PerlIO_setpos
4915 PerlIO_setpos(PerlIO *f, SV *pos)
4920 Fpos_t *fpos = (Fpos_t *) SvPV(pos, len);
4921 if (f && len == sizeof(Fpos_t)) {
4922 #if defined(USE_64_BIT_STDIO) && defined(USE_FSETPOS64)
4923 return fsetpos64(f, fpos);
4925 return fsetpos(f, fpos);
4929 SETERRNO(EINVAL, SS_IVCHAN);
4935 #undef PerlIO_getpos
4937 PerlIO_getpos(PerlIO *f, SV *pos)
4940 Off_t posn = PerlIO_tell(f);
4941 sv_setpvn(pos, (char *) &posn, sizeof(posn));
4942 return (posn == (Off_t) - 1) ? -1 : 0;
4945 #undef PerlIO_getpos
4947 PerlIO_getpos(PerlIO *f, SV *pos)
4952 #if defined(USE_64_BIT_STDIO) && defined(USE_FSETPOS64)
4953 code = fgetpos64(f, &fpos);
4955 code = fgetpos(f, &fpos);
4957 sv_setpvn(pos, (char *) &fpos, sizeof(fpos));
4962 #if (defined(PERLIO_IS_STDIO) || !defined(USE_SFIO)) && !defined(HAS_VPRINTF)
4965 vprintf(char *pat, char *args)
4967 _doprnt(pat, args, stdout);
4968 return 0; /* wrong, but perl doesn't use the return
4973 vfprintf(FILE *fd, char *pat, char *args)
4975 _doprnt(pat, args, fd);
4976 return 0; /* wrong, but perl doesn't use the return
4982 #ifndef PerlIO_vsprintf
4984 PerlIO_vsprintf(char *s, int n, const char *fmt, va_list ap)
4986 int val = vsprintf(s, fmt, ap);
4988 if (strlen(s) >= (STRLEN) n) {
4990 (void) PerlIO_puts(Perl_error_log,
4991 "panic: sprintf overflow - memory corrupted!\n");
4999 #ifndef PerlIO_sprintf
5001 PerlIO_sprintf(char *s, int n, const char *fmt, ...)
5006 result = PerlIO_vsprintf(s, n, fmt, ap);