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);
1073 #if defined(WIN32) && !defined(UNDER_CE)
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 || errno != EINTR)
2986 SETERRNO(0,0); /* just in case */
2992 PerlIOStdio_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
2995 FILE *s = PerlIOSelf(f, PerlIOStdio)->stdio;
2997 #ifdef STDIO_BUFFER_WRITABLE
2998 if (PerlIO_fast_gets(f) && PerlIO_has_base(f)) {
2999 STDCHAR *buf = ((STDCHAR *) vbuf) + count;
3000 STDCHAR *base = PerlIO_get_base(f);
3001 SSize_t cnt = PerlIO_get_cnt(f);
3002 STDCHAR *ptr = PerlIO_get_ptr(f);
3003 SSize_t avail = ptr - base;
3005 if (avail > count) {
3009 Move(buf-avail,ptr,avail,STDCHAR);
3012 PerlIO_set_ptrcnt(f,ptr,cnt+avail);
3013 if (PerlSIO_feof(s) && unread >= 0)
3014 PerlSIO_clearerr(s);
3019 if (PerlIO_has_cntptr(f)) {
3020 /* We can get pointer to buffer but not its base
3021 Do ungetc() but check chars are ending up in the
3024 STDCHAR *eptr = (STDCHAR*)PerlSIO_get_ptr(s);
3025 STDCHAR *buf = ((STDCHAR *) vbuf) + count;
3027 int ch = *--buf & 0xFF;
3028 if (ungetc(ch,s) != ch) {
3029 /* ungetc did not work */
3032 if ((STDCHAR*)PerlSIO_get_ptr(s) != --eptr || ((*eptr & 0xFF) != ch)) {
3033 /* Did not change pointer as expected */
3034 fgetc(s); /* get char back again */
3044 unread += PerlIOBase_unread(aTHX_ f, vbuf, count);
3050 PerlIOStdio_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
3054 got = PerlSIO_fwrite(vbuf, 1, count,
3055 PerlIOSelf(f, PerlIOStdio)->stdio);
3056 if (got >= 0 || errno != EINTR)
3059 SETERRNO(0,0); /* just in case */
3065 PerlIOStdio_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
3067 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3068 return PerlSIO_fseek(stdio, offset, whence);
3072 PerlIOStdio_tell(pTHX_ PerlIO *f)
3074 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3075 return PerlSIO_ftell(stdio);
3079 PerlIOStdio_flush(pTHX_ PerlIO *f)
3081 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3082 if (PerlIOBase(f)->flags & PERLIO_F_CANWRITE) {
3083 return PerlSIO_fflush(stdio);
3088 * FIXME: This discards ungetc() and pre-read stuff which is not
3089 * right if this is just a "sync" from a layer above Suspect right
3090 * design is to do _this_ but not have layer above flush this
3091 * layer read-to-read
3094 * Not writeable - sync by attempting a seek
3097 if (PerlSIO_fseek(stdio, (Off_t) 0, SEEK_CUR) != 0)
3105 PerlIOStdio_eof(pTHX_ PerlIO *f)
3107 return PerlSIO_feof(PerlIOSelf(f, PerlIOStdio)->stdio);
3111 PerlIOStdio_error(pTHX_ PerlIO *f)
3113 return PerlSIO_ferror(PerlIOSelf(f, PerlIOStdio)->stdio);
3117 PerlIOStdio_clearerr(pTHX_ PerlIO *f)
3119 PerlSIO_clearerr(PerlIOSelf(f, PerlIOStdio)->stdio);
3123 PerlIOStdio_setlinebuf(pTHX_ PerlIO *f)
3125 #ifdef HAS_SETLINEBUF
3126 PerlSIO_setlinebuf(PerlIOSelf(f, PerlIOStdio)->stdio);
3128 PerlSIO_setvbuf(PerlIOSelf(f, PerlIOStdio)->stdio, Nullch, _IOLBF, 0);
3134 PerlIOStdio_get_base(pTHX_ PerlIO *f)
3136 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3137 return (STDCHAR*)PerlSIO_get_base(stdio);
3141 PerlIOStdio_get_bufsiz(pTHX_ PerlIO *f)
3143 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3144 return PerlSIO_get_bufsiz(stdio);
3148 #ifdef USE_STDIO_PTR
3150 PerlIOStdio_get_ptr(pTHX_ PerlIO *f)
3152 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3153 return (STDCHAR*)PerlSIO_get_ptr(stdio);
3157 PerlIOStdio_get_cnt(pTHX_ PerlIO *f)
3159 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3160 return PerlSIO_get_cnt(stdio);
3164 PerlIOStdio_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, SSize_t cnt)
3166 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3168 #ifdef STDIO_PTR_LVALUE
3169 PerlSIO_set_ptr(stdio, (void*)ptr); /* LHS STDCHAR* cast non-portable */
3170 #ifdef STDIO_PTR_LVAL_SETS_CNT
3171 if (PerlSIO_get_cnt(stdio) != (cnt)) {
3172 assert(PerlSIO_get_cnt(stdio) == (cnt));
3175 #if (!defined(STDIO_PTR_LVAL_NOCHANGE_CNT))
3177 * Setting ptr _does_ change cnt - we are done
3181 #else /* STDIO_PTR_LVALUE */
3183 #endif /* STDIO_PTR_LVALUE */
3186 * Now (or only) set cnt
3188 #ifdef STDIO_CNT_LVALUE
3189 PerlSIO_set_cnt(stdio, cnt);
3190 #else /* STDIO_CNT_LVALUE */
3191 #if (defined(STDIO_PTR_LVALUE) && defined(STDIO_PTR_LVAL_SETS_CNT))
3192 PerlSIO_set_ptr(stdio,
3193 PerlSIO_get_ptr(stdio) + (PerlSIO_get_cnt(stdio) -
3195 #else /* STDIO_PTR_LVAL_SETS_CNT */
3197 #endif /* STDIO_PTR_LVAL_SETS_CNT */
3198 #endif /* STDIO_CNT_LVALUE */
3205 PerlIOStdio_fill(pTHX_ PerlIO *f)
3207 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3210 * fflush()ing read-only streams can cause trouble on some stdio-s
3212 if ((PerlIOBase(f)->flags & PERLIO_F_CANWRITE)) {
3213 if (PerlSIO_fflush(stdio) != 0)
3216 c = PerlSIO_fgetc(stdio);
3220 #if (defined(STDIO_PTR_LVALUE) && (defined(STDIO_CNT_LVALUE) || defined(STDIO_PTR_LVAL_SETS_CNT)))
3222 #ifdef STDIO_BUFFER_WRITABLE
3223 if (PerlIO_fast_gets(f) && PerlIO_has_base(f)) {
3224 /* Fake ungetc() to the real buffer in case system's ungetc
3227 STDCHAR *base = (STDCHAR*)PerlSIO_get_base(stdio);
3228 SSize_t cnt = PerlSIO_get_cnt(stdio);
3229 STDCHAR *ptr = (STDCHAR*)PerlSIO_get_ptr(stdio);
3230 if (ptr == base+1) {
3231 *--ptr = (STDCHAR) c;
3232 PerlIOStdio_set_ptrcnt(aTHX_ f,ptr,cnt+1);
3233 if (PerlSIO_feof(stdio))
3234 PerlSIO_clearerr(stdio);
3240 if (PerlIO_has_cntptr(f)) {
3242 if (PerlIOStdio_unread(aTHX_ f,&ch,1) == 1) {
3249 /* An ungetc()d char is handled separately from the regular
3250 * buffer, so we stuff it in the buffer ourselves.
3251 * Should never get called as should hit code above
3253 *(--((*stdio)->_ptr)) = (unsigned char) c;
3256 /* If buffer snoop scheme above fails fall back to
3259 if (PerlSIO_ungetc(c, stdio) != c)
3267 PerlIO_funcs PerlIO_stdio = {
3268 sizeof(PerlIO_funcs),
3270 sizeof(PerlIOStdio),
3271 PERLIO_K_BUFFERED|PERLIO_K_RAW,
3275 PerlIOBase_binmode, /* binmode */
3289 PerlIOStdio_clearerr,
3290 PerlIOStdio_setlinebuf,
3292 PerlIOStdio_get_base,
3293 PerlIOStdio_get_bufsiz,
3298 #ifdef USE_STDIO_PTR
3299 PerlIOStdio_get_ptr,
3300 PerlIOStdio_get_cnt,
3301 # if defined(HAS_FAST_STDIO) && defined(USE_FAST_STDIO)
3302 PerlIOStdio_set_ptrcnt,
3305 # endif /* HAS_FAST_STDIO && USE_FAST_STDIO */
3310 #endif /* USE_STDIO_PTR */
3313 /* Note that calls to PerlIO_exportFILE() are reversed using
3314 * PerlIO_releaseFILE(), not importFILE. */
3316 PerlIO_exportFILE(PerlIO * f, const char *mode)
3320 if (PerlIOValid(f)) {
3323 if (!mode || !*mode) {
3324 mode = PerlIO_modestr(f, buf);
3326 stdio = PerlSIO_fdopen(PerlIO_fileno(f), mode);
3330 /* De-link any lower layers so new :stdio sticks */
3332 if ((f2 = PerlIO_push(aTHX_ f, &PerlIO_stdio, buf, Nullsv))) {
3333 PerlIOStdio *s = PerlIOSelf((f = f2), PerlIOStdio);
3335 /* Link previous lower layers under new one */
3339 /* restore layers list */
3349 PerlIO_findFILE(PerlIO *f)
3353 if (l->tab == &PerlIO_stdio) {
3354 PerlIOStdio *s = PerlIOSelf(&l, PerlIOStdio);
3357 l = *PerlIONext(&l);
3359 /* Uses fallback "mode" via PerlIO_modestr() in PerlIO_exportFILE */
3360 return PerlIO_exportFILE(f, Nullch);
3363 /* Use this to reverse PerlIO_exportFILE calls. */
3365 PerlIO_releaseFILE(PerlIO *p, FILE *f)
3369 if (l->tab == &PerlIO_stdio) {
3370 PerlIOStdio *s = PerlIOSelf(&l, PerlIOStdio);
3371 if (s->stdio == f) {
3373 PerlIO_pop(aTHX_ p);
3382 /*--------------------------------------------------------------------------------------*/
3384 * perlio buffer layer
3388 PerlIOBuf_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
3390 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3391 int fd = PerlIO_fileno(f);
3392 if (fd >= 0 && PerlLIO_isatty(fd)) {
3393 PerlIOBase(f)->flags |= PERLIO_F_LINEBUF | PERLIO_F_TTY;
3395 if (*PerlIONext(f)) {
3396 Off_t posn = PerlIO_tell(PerlIONext(f));
3397 if (posn != (Off_t) - 1) {
3401 return PerlIOBase_pushed(aTHX_ f, mode, arg, tab);
3405 PerlIOBuf_open(pTHX_ PerlIO_funcs *self, PerlIO_list_t *layers,
3406 IV n, const char *mode, int fd, int imode, int perm,
3407 PerlIO *f, int narg, SV **args)
3409 if (PerlIOValid(f)) {
3410 PerlIO *next = PerlIONext(f);
3412 PerlIO_layer_fetch(aTHX_ layers, n - 1, PerlIOBase(next)->tab);
3413 if (tab && tab->Open)
3415 (*tab->Open)(aTHX_ tab, layers, n - 1, mode, fd, imode, perm,
3417 if (!next || (*PerlIOBase(f)->tab->Pushed) (aTHX_ f, mode, PerlIOArg, self) != 0) {
3422 PerlIO_funcs *tab = PerlIO_layer_fetch(aTHX_ layers, n - 1, PerlIO_default_btm());
3430 if (tab && tab->Open)
3431 f = (*tab->Open)(aTHX_ tab, layers, n - 1, mode, fd, imode, perm,
3434 SETERRNO(EINVAL, LIB_INVARG);
3436 if (PerlIO_push(aTHX_ f, self, mode, PerlIOArg) == 0) {
3438 * if push fails during open, open fails. close will pop us.
3443 fd = PerlIO_fileno(f);
3444 if (init && fd == 2) {
3446 * Initial stderr is unbuffered
3448 PerlIOBase(f)->flags |= PERLIO_F_UNBUF;
3450 #ifdef PERLIO_USING_CRLF
3451 # ifdef PERLIO_IS_BINMODE_FD
3452 if (PERLIO_IS_BINMODE_FD(fd))
3453 PerlIO_binmode(aTHX_ f, '<'/*not used*/, O_BINARY, Nullch);
3457 * do something about failing setmode()? --jhi
3459 PerlLIO_setmode(fd, O_BINARY);
3468 * This "flush" is akin to sfio's sync in that it handles files in either
3469 * read or write state
3472 PerlIOBuf_flush(pTHX_ PerlIO *f)
3474 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3476 PerlIO *n = PerlIONext(f);
3477 if (PerlIOBase(f)->flags & PERLIO_F_WRBUF) {
3479 * write() the buffer
3481 STDCHAR *buf = b->buf;
3483 while (p < b->ptr) {
3484 SSize_t count = PerlIO_write(n, p, b->ptr - p);
3488 else if (count < 0 || PerlIO_error(n)) {
3489 PerlIOBase(f)->flags |= PERLIO_F_ERROR;
3494 b->posn += (p - buf);
3496 else if (PerlIOBase(f)->flags & PERLIO_F_RDBUF) {
3497 STDCHAR *buf = PerlIO_get_base(f);
3499 * Note position change
3501 b->posn += (b->ptr - buf);
3502 if (b->ptr < b->end) {
3503 /* We did not consume all of it - try and seek downstream to
3504 our logical position
3506 if (PerlIOValid(n) && PerlIO_seek(n, b->posn, SEEK_SET) == 0) {
3507 /* Reload n as some layers may pop themselves on seek */
3508 b->posn = PerlIO_tell(n = PerlIONext(f));
3511 /* Seek failed (e.g. pipe or tty). Do NOT clear buffer or pre-read
3512 data is lost for good - so return saying "ok" having undone
3515 b->posn -= (b->ptr - buf);
3520 b->ptr = b->end = b->buf;
3521 PerlIOBase(f)->flags &= ~(PERLIO_F_RDBUF | PERLIO_F_WRBUF);
3522 /* We check for Valid because of dubious decision to make PerlIO_flush(NULL) flush all */
3523 if (PerlIOValid(n) && PerlIO_flush(n) != 0)
3529 PerlIOBuf_fill(pTHX_ PerlIO *f)
3531 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3532 PerlIO *n = PerlIONext(f);
3535 * Down-stream flush is defined not to loose read data so is harmless.
3536 * we would not normally be fill'ing if there was data left in anycase.
3538 if (PerlIO_flush(f) != 0)
3540 if (PerlIOBase(f)->flags & PERLIO_F_TTY)
3541 PerlIOBase_flush_linebuf(aTHX);
3544 PerlIO_get_base(f); /* allocate via vtable */
3546 b->ptr = b->end = b->buf;
3548 if (!PerlIOValid(n)) {
3549 PerlIOBase(f)->flags |= PERLIO_F_EOF;
3553 if (PerlIO_fast_gets(n)) {
3555 * Layer below is also buffered. We do _NOT_ want to call its
3556 * ->Read() because that will loop till it gets what we asked for
3557 * which may hang on a pipe etc. Instead take anything it has to
3558 * hand, or ask it to fill _once_.
3560 avail = PerlIO_get_cnt(n);
3562 avail = PerlIO_fill(n);
3564 avail = PerlIO_get_cnt(n);
3566 if (!PerlIO_error(n) && PerlIO_eof(n))
3571 STDCHAR *ptr = PerlIO_get_ptr(n);
3572 SSize_t cnt = avail;
3573 if (avail > (SSize_t)b->bufsiz)
3575 Copy(ptr, b->buf, avail, STDCHAR);
3576 PerlIO_set_ptrcnt(n, ptr + avail, cnt - avail);
3580 avail = PerlIO_read(n, b->ptr, b->bufsiz);
3584 PerlIOBase(f)->flags |= PERLIO_F_EOF;
3586 PerlIOBase(f)->flags |= PERLIO_F_ERROR;
3589 b->end = b->buf + avail;
3590 PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
3595 PerlIOBuf_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
3597 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3598 if (PerlIOValid(f)) {
3601 return PerlIOBase_read(aTHX_ f, vbuf, count);
3607 PerlIOBuf_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
3609 const STDCHAR *buf = (const STDCHAR *) vbuf + count;
3610 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3613 if (PerlIOBase(f)->flags & PERLIO_F_WRBUF)
3618 if (PerlIOBase(f)->flags & PERLIO_F_RDBUF) {
3620 * Buffer is already a read buffer, we can overwrite any chars
3621 * which have been read back to buffer start
3623 avail = (b->ptr - b->buf);
3627 * Buffer is idle, set it up so whole buffer is available for
3631 b->end = b->buf + avail;
3633 PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
3635 * Buffer extends _back_ from where we are now
3637 b->posn -= b->bufsiz;
3639 if (avail > (SSize_t) count) {
3641 * If we have space for more than count, just move count
3649 * In simple stdio-like ungetc() case chars will be already
3652 if (buf != b->ptr) {
3653 Copy(buf, b->ptr, avail, STDCHAR);
3657 PerlIOBase(f)->flags &= ~PERLIO_F_EOF;
3661 unread += PerlIOBase_unread(aTHX_ f, vbuf, count);
3667 PerlIOBuf_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
3669 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3670 const STDCHAR *buf = (const STDCHAR *) vbuf;
3674 if (!(PerlIOBase(f)->flags & PERLIO_F_CANWRITE))
3676 if (PerlIOBase(f)->flags & PERLIO_F_RDBUF) {
3677 if (PerlIO_flush(f) != 0) {
3682 SSize_t avail = b->bufsiz - (b->ptr - b->buf);
3683 if ((SSize_t) count < avail)
3685 PerlIOBase(f)->flags |= PERLIO_F_WRBUF;
3686 if (PerlIOBase(f)->flags & PERLIO_F_LINEBUF) {
3701 Copy(buf, b->ptr, avail, STDCHAR);
3708 if (b->ptr >= (b->buf + b->bufsiz))
3711 if (PerlIOBase(f)->flags & PERLIO_F_UNBUF)
3717 PerlIOBuf_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
3720 if ((code = PerlIO_flush(f)) == 0) {
3721 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3722 PerlIOBase(f)->flags &= ~PERLIO_F_EOF;
3723 code = PerlIO_seek(PerlIONext(f), offset, whence);
3725 b->posn = PerlIO_tell(PerlIONext(f));
3732 PerlIOBuf_tell(pTHX_ PerlIO *f)
3734 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3736 * b->posn is file position where b->buf was read, or will be written
3738 Off_t posn = b->posn;
3739 if ((PerlIOBase(f)->flags & PERLIO_F_APPEND) &&
3740 (PerlIOBase(f)->flags & PERLIO_F_WRBUF)) {
3742 /* As O_APPEND files are normally shared in some sense it is better
3747 /* when file is NOT shared then this is sufficient */
3748 PerlIO_seek(PerlIONext(f),0, SEEK_END);
3750 posn = b->posn = PerlIO_tell(PerlIONext(f));
3754 * If buffer is valid adjust position by amount in buffer
3756 posn += (b->ptr - b->buf);
3762 PerlIOBuf_popped(pTHX_ PerlIO *f)
3764 IV code = PerlIOBase_popped(aTHX_ f);
3765 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3766 if (b->buf && b->buf != (STDCHAR *) & b->oneword) {
3770 b->ptr = b->end = b->buf;
3771 PerlIOBase(f)->flags &= ~(PERLIO_F_RDBUF | PERLIO_F_WRBUF);
3776 PerlIOBuf_close(pTHX_ PerlIO *f)
3778 IV code = PerlIOBase_close(aTHX_ f);
3779 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3780 if (b->buf && b->buf != (STDCHAR *) & b->oneword) {
3784 b->ptr = b->end = b->buf;
3785 PerlIOBase(f)->flags &= ~(PERLIO_F_RDBUF | PERLIO_F_WRBUF);
3790 PerlIOBuf_get_ptr(pTHX_ PerlIO *f)
3792 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3799 PerlIOBuf_get_cnt(pTHX_ PerlIO *f)
3801 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3804 if (PerlIOBase(f)->flags & PERLIO_F_RDBUF)
3805 return (b->end - b->ptr);
3810 PerlIOBuf_get_base(pTHX_ PerlIO *f)
3812 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3817 Newz('B',b->buf,b->bufsiz, STDCHAR);
3819 b->buf = (STDCHAR *) & b->oneword;
3820 b->bufsiz = sizeof(b->oneword);
3829 PerlIOBuf_bufsiz(pTHX_ PerlIO *f)
3831 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3834 return (b->end - b->buf);
3838 PerlIOBuf_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, SSize_t cnt)
3840 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3844 if (PerlIO_get_cnt(f) != cnt || b->ptr < b->buf) {
3845 assert(PerlIO_get_cnt(f) == cnt);
3846 assert(b->ptr >= b->buf);
3848 PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
3852 PerlIOBuf_dup(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags)
3854 return PerlIOBase_dup(aTHX_ f, o, param, flags);
3859 PerlIO_funcs PerlIO_perlio = {
3860 sizeof(PerlIO_funcs),
3863 PERLIO_K_BUFFERED|PERLIO_K_RAW,
3867 PerlIOBase_binmode, /* binmode */
3881 PerlIOBase_clearerr,
3882 PerlIOBase_setlinebuf,
3887 PerlIOBuf_set_ptrcnt,
3890 /*--------------------------------------------------------------------------------------*/
3892 * Temp layer to hold unread chars when cannot do it any other way
3896 PerlIOPending_fill(pTHX_ PerlIO *f)
3899 * Should never happen
3906 PerlIOPending_close(pTHX_ PerlIO *f)
3909 * A tad tricky - flush pops us, then we close new top
3912 return PerlIO_close(f);
3916 PerlIOPending_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
3919 * A tad tricky - flush pops us, then we seek new top
3922 return PerlIO_seek(f, offset, whence);
3927 PerlIOPending_flush(pTHX_ PerlIO *f)
3929 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3930 if (b->buf && b->buf != (STDCHAR *) & b->oneword) {
3934 PerlIO_pop(aTHX_ f);
3939 PerlIOPending_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, SSize_t cnt)
3945 PerlIOBuf_set_ptrcnt(aTHX_ f, ptr, cnt);
3950 PerlIOPending_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
3952 IV code = PerlIOBase_pushed(aTHX_ f, mode, arg, tab);
3953 PerlIOl *l = PerlIOBase(f);
3955 * Our PerlIO_fast_gets must match what we are pushed on, or sv_gets()
3956 * etc. get muddled when it changes mid-string when we auto-pop.
3958 l->flags = (l->flags & ~(PERLIO_F_FASTGETS | PERLIO_F_UTF8)) |
3959 (PerlIOBase(PerlIONext(f))->
3960 flags & (PERLIO_F_FASTGETS | PERLIO_F_UTF8));
3965 PerlIOPending_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
3967 SSize_t avail = PerlIO_get_cnt(f);
3969 if ((SSize_t)count < avail)
3972 got = PerlIOBuf_read(aTHX_ f, vbuf, avail);
3973 if (got >= 0 && got < (SSize_t)count) {
3975 PerlIO_read(f, ((STDCHAR *) vbuf) + got, count - got);
3976 if (more >= 0 || got == 0)
3982 PerlIO_funcs PerlIO_pending = {
3983 sizeof(PerlIO_funcs),
3986 PERLIO_K_BUFFERED|PERLIO_K_RAW, /* not sure about RAW here */
3987 PerlIOPending_pushed,
3990 PerlIOBase_binmode, /* binmode */
3999 PerlIOPending_close,
4000 PerlIOPending_flush,
4004 PerlIOBase_clearerr,
4005 PerlIOBase_setlinebuf,
4010 PerlIOPending_set_ptrcnt,
4015 /*--------------------------------------------------------------------------------------*/
4017 * crlf - translation On read translate CR,LF to "\n" we do this by
4018 * overriding ptr/cnt entries to hand back a line at a time and keeping a
4019 * record of which nl we "lied" about. On write translate "\n" to CR,LF
4023 PerlIOBuf base; /* PerlIOBuf stuff */
4024 STDCHAR *nl; /* Position of crlf we "lied" about in the
4029 PerlIOCrlf_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
4032 PerlIOBase(f)->flags |= PERLIO_F_CRLF;
4033 code = PerlIOBuf_pushed(aTHX_ f, mode, arg, tab);
4035 PerlIO_debug("PerlIOCrlf_pushed f=%p %s %s fl=%08" UVxf "\n",
4036 f, PerlIOBase(f)->tab->name, (mode) ? mode : "(Null)",
4037 PerlIOBase(f)->flags);
4044 PerlIOCrlf_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
4046 PerlIOCrlf *c = PerlIOSelf(f, PerlIOCrlf);
4051 if (!(PerlIOBase(f)->flags & PERLIO_F_CRLF))
4052 return PerlIOBuf_unread(aTHX_ f, vbuf, count);
4054 const STDCHAR *buf = (const STDCHAR *) vbuf + count;
4055 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
4057 if (PerlIOBase(f)->flags & PERLIO_F_WRBUF)
4062 if (!(PerlIOBase(f)->flags & PERLIO_F_RDBUF)) {
4063 b->end = b->ptr = b->buf + b->bufsiz;
4064 PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
4065 b->posn -= b->bufsiz;
4067 while (count > 0 && b->ptr > b->buf) {
4070 if (b->ptr - 2 >= b->buf) {
4093 PerlIOCrlf_get_cnt(pTHX_ PerlIO *f)
4095 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
4098 if (PerlIOBase(f)->flags & PERLIO_F_RDBUF) {
4099 PerlIOCrlf *c = PerlIOSelf(f, PerlIOCrlf);
4100 if ((PerlIOBase(f)->flags & PERLIO_F_CRLF) && (!c->nl || *c->nl == 0xd)) {
4101 STDCHAR *nl = (c->nl) ? c->nl : b->ptr;
4103 while (nl < b->end && *nl != 0xd)
4105 if (nl < b->end && *nl == 0xd) {
4107 if (nl + 1 < b->end) {
4114 * Not CR,LF but just CR
4122 * Blast - found CR as last char in buffer
4127 * They may not care, defer work as long as
4131 return (nl - b->ptr);
4135 b->ptr++; /* say we have read it as far as
4136 * flush() is concerned */
4137 b->buf++; /* Leave space in front of buffer */
4138 /* Note as we have moved buf up flush's
4140 will naturally make posn point at CR
4142 b->bufsiz--; /* Buffer is thus smaller */
4143 code = PerlIO_fill(f); /* Fetch some more */
4144 b->bufsiz++; /* Restore size for next time */
4145 b->buf--; /* Point at space */
4146 b->ptr = nl = b->buf; /* Which is what we hand
4148 *nl = 0xd; /* Fill in the CR */
4150 goto test; /* fill() call worked */
4152 * CR at EOF - just fall through
4154 /* Should we clear EOF though ??? */
4159 return (((c->nl) ? (c->nl + 1) : b->end) - b->ptr);
4165 PerlIOCrlf_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, SSize_t cnt)
4167 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
4168 PerlIOCrlf *c = PerlIOSelf(f, PerlIOCrlf);
4174 if (ptr == b->end && *c->nl == 0xd) {
4175 /* Defered CR at end of buffer case - we lied about count */
4187 * Test code - delete when it works ...
4189 IV flags = PerlIOBase(f)->flags;
4190 STDCHAR *chk = (c->nl) ? (c->nl+1) : b->end;
4191 if (ptr+cnt == c->nl && c->nl+1 == b->end && *c->nl == 0xd) {
4192 /* Defered CR at end of buffer case - we lied about count */
4198 Perl_croak(aTHX_ "ptr wrong %p != %p fl=%08" UVxf
4199 " nl=%p e=%p for %d", ptr, chk, flags, c->nl,
4207 * They have taken what we lied about
4215 PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
4219 PerlIOCrlf_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
4221 if (!(PerlIOBase(f)->flags & PERLIO_F_CRLF))
4222 return PerlIOBuf_write(aTHX_ f, vbuf, count);
4224 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
4225 const STDCHAR *buf = (const STDCHAR *) vbuf;
4226 const STDCHAR *ebuf = buf + count;
4229 if (!(PerlIOBase(f)->flags & PERLIO_F_CANWRITE))
4231 while (buf < ebuf) {
4232 STDCHAR *eptr = b->buf + b->bufsiz;
4233 PerlIOBase(f)->flags |= PERLIO_F_WRBUF;
4234 while (buf < ebuf && b->ptr < eptr) {
4236 if ((b->ptr + 2) > eptr) {
4244 *(b->ptr)++ = 0xd; /* CR */
4245 *(b->ptr)++ = 0xa; /* LF */
4247 if (PerlIOBase(f)->flags & PERLIO_F_LINEBUF) {
4257 if (b->ptr >= eptr) {
4263 if (PerlIOBase(f)->flags & PERLIO_F_UNBUF)
4265 return (buf - (STDCHAR *) vbuf);
4270 PerlIOCrlf_flush(pTHX_ PerlIO *f)
4272 PerlIOCrlf *c = PerlIOSelf(f, PerlIOCrlf);
4277 return PerlIOBuf_flush(aTHX_ f);
4281 PerlIOCrlf_binmode(pTHX_ PerlIO *f)
4283 if ((PerlIOBase(f)->flags & PERLIO_F_CRLF)) {
4284 /* In text mode - flush any pending stuff and flip it */
4285 PerlIOBase(f)->flags &= ~PERLIO_F_CRLF;
4286 #ifndef PERLIO_USING_CRLF
4287 /* CRLF is unusual case - if this is just the :crlf layer pop it */
4288 if (PerlIOBase(f)->tab == &PerlIO_crlf) {
4289 PerlIO_pop(aTHX_ f);
4296 PerlIO_funcs PerlIO_crlf = {
4297 sizeof(PerlIO_funcs),
4300 PERLIO_K_BUFFERED | PERLIO_K_CANCRLF | PERLIO_K_RAW,
4302 PerlIOBuf_popped, /* popped */
4304 PerlIOCrlf_binmode, /* binmode */
4308 PerlIOBuf_read, /* generic read works with ptr/cnt lies
4310 PerlIOCrlf_unread, /* Put CR,LF in buffer for each '\n' */
4311 PerlIOCrlf_write, /* Put CR,LF in buffer for each '\n' */
4319 PerlIOBase_clearerr,
4320 PerlIOBase_setlinebuf,
4325 PerlIOCrlf_set_ptrcnt,
4329 /*--------------------------------------------------------------------------------------*/
4331 * mmap as "buffer" layer
4335 PerlIOBuf base; /* PerlIOBuf stuff */
4336 Mmap_t mptr; /* Mapped address */
4337 Size_t len; /* mapped length */
4338 STDCHAR *bbuf; /* malloced buffer if map fails */
4341 static size_t page_size = 0;
4344 PerlIOMmap_map(pTHX_ PerlIO *f)
4346 PerlIOMmap *m = PerlIOSelf(f, PerlIOMmap);
4347 IV flags = PerlIOBase(f)->flags;
4351 if (flags & PERLIO_F_CANREAD) {
4352 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
4353 int fd = PerlIO_fileno(f);
4355 code = Fstat(fd, &st);
4356 if (code == 0 && S_ISREG(st.st_mode)) {
4357 SSize_t len = st.st_size - b->posn;
4361 #if defined(HAS_SYSCONF) && (defined(_SC_PAGESIZE) || defined(_SC_PAGE_SIZE))
4363 SETERRNO(0, SS_NORMAL);
4364 # ifdef _SC_PAGESIZE
4365 page_size = sysconf(_SC_PAGESIZE);
4367 page_size = sysconf(_SC_PAGE_SIZE);
4369 if ((long) page_size < 0) {
4374 (void) SvUPGRADE(error, SVt_PV);
4375 msg = SvPVx(error, n_a);
4376 Perl_croak(aTHX_ "panic: sysconf: %s",
4381 "panic: sysconf: pagesize unknown");
4385 # ifdef HAS_GETPAGESIZE
4386 page_size = getpagesize();
4388 # if defined(I_SYS_PARAM) && defined(PAGESIZE)
4389 page_size = PAGESIZE; /* compiletime, bad */
4393 if ((IV) page_size <= 0)
4394 Perl_croak(aTHX_ "panic: bad pagesize %" IVdf,
4399 * This is a hack - should never happen - open should
4402 b->posn = PerlIO_tell(PerlIONext(f));
4404 posn = (b->posn / page_size) * page_size;
4405 len = st.st_size - posn;
4406 m->mptr = mmap(NULL, len, PROT_READ, MAP_SHARED, fd, posn);
4407 if (m->mptr && m->mptr != (Mmap_t) - 1) {
4408 #if 0 && defined(HAS_MADVISE) && defined(MADV_SEQUENTIAL)
4409 madvise(m->mptr, len, MADV_SEQUENTIAL);
4411 #if 0 && defined(HAS_MADVISE) && defined(MADV_WILLNEED)
4412 madvise(m->mptr, len, MADV_WILLNEED);
4414 PerlIOBase(f)->flags =
4415 (flags & ~PERLIO_F_EOF) | PERLIO_F_RDBUF;
4416 b->end = ((STDCHAR *) m->mptr) + len;
4417 b->buf = ((STDCHAR *) m->mptr) + (b->posn - posn);
4426 PerlIOBase(f)->flags =
4427 flags | PERLIO_F_EOF | PERLIO_F_RDBUF;
4429 b->ptr = b->end = b->ptr;
4438 PerlIOMmap_unmap(pTHX_ PerlIO *f)
4440 PerlIOMmap *m = PerlIOSelf(f, PerlIOMmap);
4441 PerlIOBuf *b = &m->base;
4445 code = munmap(m->mptr, m->len);
4449 if (PerlIO_seek(PerlIONext(f), b->posn, SEEK_SET) != 0)
4452 b->ptr = b->end = b->buf;
4453 PerlIOBase(f)->flags &= ~(PERLIO_F_RDBUF | PERLIO_F_WRBUF);
4459 PerlIOMmap_get_base(pTHX_ PerlIO *f)
4461 PerlIOMmap *m = PerlIOSelf(f, PerlIOMmap);
4462 PerlIOBuf *b = &m->base;
4463 if (b->buf && (PerlIOBase(f)->flags & PERLIO_F_RDBUF)) {
4465 * Already have a readbuffer in progress
4471 * We have a write buffer or flushed PerlIOBuf read buffer
4473 m->bbuf = b->buf; /* save it in case we need it again */
4474 b->buf = NULL; /* Clear to trigger below */
4477 PerlIOMmap_map(aTHX_ f); /* Try and map it */
4480 * Map did not work - recover PerlIOBuf buffer if we have one
4485 b->ptr = b->end = b->buf;
4488 return PerlIOBuf_get_base(aTHX_ f);
4492 PerlIOMmap_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
4494 PerlIOMmap *m = PerlIOSelf(f, PerlIOMmap);
4495 PerlIOBuf *b = &m->base;
4496 if (PerlIOBase(f)->flags & PERLIO_F_WRBUF)
4498 if (b->ptr && (b->ptr - count) >= b->buf
4499 && memEQ(b->ptr - count, vbuf, count)) {
4501 PerlIOBase(f)->flags &= ~PERLIO_F_EOF;
4506 * Loose the unwritable mapped buffer
4510 * If flush took the "buffer" see if we have one from before
4512 if (!b->buf && m->bbuf)
4515 PerlIOBuf_get_base(aTHX_ f);
4519 return PerlIOBuf_unread(aTHX_ f, vbuf, count);
4523 PerlIOMmap_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
4525 PerlIOMmap *m = PerlIOSelf(f, PerlIOMmap);
4526 PerlIOBuf *b = &m->base;
4527 if (!b->buf || !(PerlIOBase(f)->flags & PERLIO_F_WRBUF)) {
4529 * No, or wrong sort of, buffer
4532 if (PerlIOMmap_unmap(aTHX_ f) != 0)
4536 * If unmap took the "buffer" see if we have one from before
4538 if (!b->buf && m->bbuf)
4541 PerlIOBuf_get_base(aTHX_ f);
4545 return PerlIOBuf_write(aTHX_ f, vbuf, count);
4549 PerlIOMmap_flush(pTHX_ PerlIO *f)
4551 PerlIOMmap *m = PerlIOSelf(f, PerlIOMmap);
4552 PerlIOBuf *b = &m->base;
4553 IV code = PerlIOBuf_flush(aTHX_ f);
4555 * Now we are "synced" at PerlIOBuf level
4562 if (PerlIOMmap_unmap(aTHX_ f) != 0)
4567 * We seem to have a PerlIOBuf buffer which was not mapped
4568 * remember it in case we need one later
4577 PerlIOMmap_fill(pTHX_ PerlIO *f)
4579 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
4580 IV code = PerlIO_flush(f);
4581 if (code == 0 && !b->buf) {
4582 code = PerlIOMmap_map(aTHX_ f);
4584 if (code == 0 && !(PerlIOBase(f)->flags & PERLIO_F_RDBUF)) {
4585 code = PerlIOBuf_fill(aTHX_ f);
4591 PerlIOMmap_close(pTHX_ PerlIO *f)
4593 PerlIOMmap *m = PerlIOSelf(f, PerlIOMmap);
4594 PerlIOBuf *b = &m->base;
4595 IV code = PerlIO_flush(f);
4599 b->ptr = b->end = b->buf;
4601 if (PerlIOBuf_close(aTHX_ f) != 0)
4607 PerlIOMmap_dup(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags)
4609 return PerlIOBase_dup(aTHX_ f, o, param, flags);
4613 PerlIO_funcs PerlIO_mmap = {
4614 sizeof(PerlIO_funcs),
4617 PERLIO_K_BUFFERED|PERLIO_K_RAW,
4621 PerlIOBase_binmode, /* binmode */
4635 PerlIOBase_clearerr,
4636 PerlIOBase_setlinebuf,
4637 PerlIOMmap_get_base,
4641 PerlIOBuf_set_ptrcnt,
4644 #endif /* HAS_MMAP */
4647 Perl_PerlIO_stdin(pTHX)
4650 PerlIO_stdstreams(aTHX);
4652 return &PL_perlio[1];
4656 Perl_PerlIO_stdout(pTHX)
4659 PerlIO_stdstreams(aTHX);
4661 return &PL_perlio[2];
4665 Perl_PerlIO_stderr(pTHX)
4668 PerlIO_stdstreams(aTHX);
4670 return &PL_perlio[3];
4673 /*--------------------------------------------------------------------------------------*/
4676 PerlIO_getname(PerlIO *f, char *buf)
4681 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
4683 name = fgetname(stdio, buf);
4685 Perl_croak(aTHX_ "Don't know how to get file name");
4691 /*--------------------------------------------------------------------------------------*/
4693 * Functions which can be called on any kind of PerlIO implemented in
4697 #undef PerlIO_fdopen
4699 PerlIO_fdopen(int fd, const char *mode)
4702 return PerlIO_openn(aTHX_ Nullch, mode, fd, 0, 0, NULL, 0, NULL);
4707 PerlIO_open(const char *path, const char *mode)
4710 SV *name = sv_2mortal(newSVpvn(path, strlen(path)));
4711 return PerlIO_openn(aTHX_ Nullch, mode, -1, 0, 0, NULL, 1, &name);
4714 #undef Perlio_reopen
4716 PerlIO_reopen(const char *path, const char *mode, PerlIO *f)
4719 SV *name = sv_2mortal(newSVpvn(path, strlen(path)));
4720 return PerlIO_openn(aTHX_ Nullch, mode, -1, 0, 0, f, 1, &name);
4725 PerlIO_getc(PerlIO *f)
4729 SSize_t count = PerlIO_read(f, buf, 1);
4731 return (unsigned char) buf[0];
4736 #undef PerlIO_ungetc
4738 PerlIO_ungetc(PerlIO *f, int ch)
4743 if (PerlIO_unread(f, &buf, 1) == 1)
4751 PerlIO_putc(PerlIO *f, int ch)
4755 return PerlIO_write(f, &buf, 1);
4760 PerlIO_puts(PerlIO *f, const char *s)
4763 STRLEN len = strlen(s);
4764 return PerlIO_write(f, s, len);
4767 #undef PerlIO_rewind
4769 PerlIO_rewind(PerlIO *f)
4772 PerlIO_seek(f, (Off_t) 0, SEEK_SET);
4776 #undef PerlIO_vprintf
4778 PerlIO_vprintf(PerlIO *f, const char *fmt, va_list ap)
4781 SV *sv = newSVpvn("", 0);
4787 Perl_va_copy(ap, apc);
4788 sv_vcatpvf(sv, fmt, &apc);
4790 sv_vcatpvf(sv, fmt, &ap);
4793 wrote = PerlIO_write(f, s, len);
4798 #undef PerlIO_printf
4800 PerlIO_printf(PerlIO *f, const char *fmt, ...)
4805 result = PerlIO_vprintf(f, fmt, ap);
4810 #undef PerlIO_stdoutf
4812 PerlIO_stdoutf(const char *fmt, ...)
4818 result = PerlIO_vprintf(PerlIO_stdout(), fmt, ap);
4823 #undef PerlIO_tmpfile
4825 PerlIO_tmpfile(void)
4833 f = PerlIO_fdopen(fd, "w+b");
4836 SV *sv = newSVpv("/tmp/PerlIO_XXXXXX", 0);
4839 * I have no idea how portable mkstemp() is ... NI-S
4841 fd = mkstemp(SvPVX(sv));
4843 f = PerlIO_fdopen(fd, "w+");
4845 PerlIOBase(f)->flags |= PERLIO_F_TEMP;
4846 PerlLIO_unlink(SvPVX(sv));
4849 # else /* !HAS_MKSTEMP, fallback to stdio tmpfile(). */
4850 FILE *stdio = PerlSIO_tmpfile();
4853 if ((f = PerlIO_push(aTHX_(PerlIO_allocate(aTHX)),
4854 &PerlIO_stdio, "w+", Nullsv))) {
4855 PerlIOStdio *s = PerlIOSelf(f, PerlIOStdio);
4861 # endif /* else HAS_MKSTEMP */
4862 #endif /* else WIN32 */
4869 #endif /* USE_SFIO */
4870 #endif /* PERLIO_IS_STDIO */
4872 /*======================================================================================*/
4874 * Now some functions in terms of above which may be needed even if we are
4875 * not in true PerlIO mode
4879 #undef PerlIO_setpos
4881 PerlIO_setpos(PerlIO *f, SV *pos)
4886 Off_t *posn = (Off_t *) SvPV(pos, len);
4887 if (f && len == sizeof(Off_t))
4888 return PerlIO_seek(f, *posn, SEEK_SET);
4890 SETERRNO(EINVAL, SS_IVCHAN);
4894 #undef PerlIO_setpos
4896 PerlIO_setpos(PerlIO *f, SV *pos)
4901 Fpos_t *fpos = (Fpos_t *) SvPV(pos, len);
4902 if (f && len == sizeof(Fpos_t)) {
4903 #if defined(USE_64_BIT_STDIO) && defined(USE_FSETPOS64)
4904 return fsetpos64(f, fpos);
4906 return fsetpos(f, fpos);
4910 SETERRNO(EINVAL, SS_IVCHAN);
4916 #undef PerlIO_getpos
4918 PerlIO_getpos(PerlIO *f, SV *pos)
4921 Off_t posn = PerlIO_tell(f);
4922 sv_setpvn(pos, (char *) &posn, sizeof(posn));
4923 return (posn == (Off_t) - 1) ? -1 : 0;
4926 #undef PerlIO_getpos
4928 PerlIO_getpos(PerlIO *f, SV *pos)
4933 #if defined(USE_64_BIT_STDIO) && defined(USE_FSETPOS64)
4934 code = fgetpos64(f, &fpos);
4936 code = fgetpos(f, &fpos);
4938 sv_setpvn(pos, (char *) &fpos, sizeof(fpos));
4943 #if (defined(PERLIO_IS_STDIO) || !defined(USE_SFIO)) && !defined(HAS_VPRINTF)
4946 vprintf(char *pat, char *args)
4948 _doprnt(pat, args, stdout);
4949 return 0; /* wrong, but perl doesn't use the return
4954 vfprintf(FILE *fd, char *pat, char *args)
4956 _doprnt(pat, args, fd);
4957 return 0; /* wrong, but perl doesn't use the return
4963 #ifndef PerlIO_vsprintf
4965 PerlIO_vsprintf(char *s, int n, const char *fmt, va_list ap)
4967 int val = vsprintf(s, fmt, ap);
4969 if (strlen(s) >= (STRLEN) n) {
4971 (void) PerlIO_puts(Perl_error_log,
4972 "panic: sprintf overflow - memory corrupted!\n");
4980 #ifndef PerlIO_sprintf
4982 PerlIO_sprintf(char *s, int n, const char *fmt, ...)
4987 result = PerlIO_vsprintf(s, n, fmt, ap);