2 * perlio.c Copyright (c) 1996-2006, 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.
12 /* This file contains the functions needed to implement PerlIO, which
13 * is Perl's private replacement for the C stdio library. This is used
14 * by default unless you compile with -Uuseperlio or run with
15 * PERLIO=:stdio (but don't do this unless you know what you're doing)
19 * If we have ActivePerl-like PERL_IMPLICIT_SYS then we need a dTHX to get
20 * at the dispatch tables, even when we do not need it for other reasons.
21 * Invent a dSYS macro to abstract this out
23 #ifdef PERL_IMPLICIT_SYS
36 #define PERLIO_NOT_STDIO 0
37 #if !defined(PERLIO_IS_STDIO) && !defined(USE_SFIO)
43 * This file provides those parts of PerlIO abstraction
44 * which are not #defined in perlio.h.
45 * Which these are depends on various Configure #ifdef's
49 #define PERL_IN_PERLIO_C
52 #ifdef PERL_IMPLICIT_CONTEXT
60 /* Missing proto on LynxOS */
64 /* Call the callback or PerlIOBase, and return failure. */
65 #define Perl_PerlIO_or_Base(f, callback, base, failure, args) \
66 if (PerlIOValid(f)) { \
67 const PerlIO_funcs * const tab = PerlIOBase(f)->tab;\
68 if (tab && tab->callback) \
69 return (*tab->callback) args; \
71 return PerlIOBase_ ## base args; \
74 SETERRNO(EBADF, SS_IVCHAN); \
77 /* Call the callback or fail, and return failure. */
78 #define Perl_PerlIO_or_fail(f, callback, failure, args) \
79 if (PerlIOValid(f)) { \
80 const PerlIO_funcs * const tab = PerlIOBase(f)->tab;\
81 if (tab && tab->callback) \
82 return (*tab->callback) args; \
83 SETERRNO(EINVAL, LIB_INVARG); \
86 SETERRNO(EBADF, SS_IVCHAN); \
89 /* Call the callback or PerlIOBase, and be void. */
90 #define Perl_PerlIO_or_Base_void(f, callback, base, args) \
91 if (PerlIOValid(f)) { \
92 const PerlIO_funcs * const tab = PerlIOBase(f)->tab;\
93 if (tab && tab->callback) \
94 (*tab->callback) args; \
96 PerlIOBase_ ## base args; \
99 SETERRNO(EBADF, SS_IVCHAN)
101 /* Call the callback or fail, and be void. */
102 #define Perl_PerlIO_or_fail_void(f, callback, args) \
103 if (PerlIOValid(f)) { \
104 const PerlIO_funcs * const tab = PerlIOBase(f)->tab;\
105 if (tab && tab->callback) \
106 (*tab->callback) args; \
108 SETERRNO(EINVAL, LIB_INVARG); \
111 SETERRNO(EBADF, SS_IVCHAN)
115 perlsio_binmode(FILE *fp, int iotype, int mode)
118 * This used to be contents of do_binmode in doio.c
121 # if defined(atarist) || defined(__MINT__)
124 ((FILE *) fp)->_flag |= _IOBIN;
126 ((FILE *) fp)->_flag &= ~_IOBIN;
133 if (PerlLIO_setmode(fp, mode) != -1) {
135 if (PerlLIO_setmode(fileno(fp), mode) != -1) {
137 # if defined(WIN32) && defined(__BORLANDC__)
139 * The translation mode of the stream is maintained independent
141 * the translation mode of the fd in the Borland RTL (heavy
142 * digging through their runtime sources reveal). User has to
144 * the mode explicitly for the stream (though they don't
146 * this anywhere). GSAR 97-5-24
152 fp->flags &= ~_F_BIN;
160 # if defined(USEMYBINMODE)
162 if (my_binmode(fp, iotype, mode) != FALSE)
168 PERL_UNUSED_ARG(iotype);
169 PERL_UNUSED_ARG(mode);
177 #define O_ACCMODE 3 /* Assume traditional implementation */
181 PerlIO_intmode2str(int rawmode, char *mode, int *writing)
183 const int result = rawmode & O_ACCMODE;
188 ptype = IoTYPE_RDONLY;
191 ptype = IoTYPE_WRONLY;
199 *writing = (result != O_RDONLY);
201 if (result == O_RDONLY) {
205 else if (rawmode & O_APPEND) {
207 if (result != O_WRONLY)
212 if (result == O_WRONLY)
219 if (rawmode & O_BINARY)
225 #ifndef PERLIO_LAYERS
227 PerlIO_apply_layers(pTHX_ PerlIO *f, const char *mode, const char *names)
229 if (!names || !*names
230 || strEQ(names, ":crlf")
231 || strEQ(names, ":raw")
232 || strEQ(names, ":bytes")
236 Perl_croak(aTHX_ "Cannot apply \"%s\" in non-PerlIO perl", names);
244 PerlIO_destruct(pTHX)
249 PerlIO_binmode(pTHX_ PerlIO *fp, int iotype, int mode, const char *names)
252 PERL_UNUSED_ARG(iotype);
253 PERL_UNUSED_ARG(mode);
254 PERL_UNUSED_ARG(names);
257 return perlsio_binmode(fp, iotype, mode);
262 PerlIO_fdupopen(pTHX_ PerlIO *f, CLONE_PARAMS *param, int flags)
264 #if defined(PERL_MICRO) || defined(__SYMBIAN32__)
267 #ifdef PERL_IMPLICIT_SYS
268 return PerlSIO_fdupopen(f);
271 return win32_fdupopen(f);
274 const int fd = PerlLIO_dup(PerlIO_fileno(f));
278 const int omode = djgpp_get_stream_mode(f);
280 const int omode = fcntl(fd, F_GETFL);
282 PerlIO_intmode2str(omode,mode,NULL);
283 /* the r+ is a hack */
284 return PerlIO_fdopen(fd, mode);
289 SETERRNO(EBADF, SS_IVCHAN);
299 * De-mux PerlIO_openn() into fdopen, freopen and fopen type entries
303 PerlIO_openn(pTHX_ const char *layers, const char *mode, int fd,
304 int imode, int perm, PerlIO *old, int narg, SV **args)
308 Perl_croak(aTHX_ "More than one argument to open");
310 if (*args == &PL_sv_undef)
311 return PerlIO_tmpfile();
313 const char *name = SvPV_nolen_const(*args);
314 if (*mode == IoTYPE_NUMERIC) {
315 fd = PerlLIO_open3(name, imode, perm);
317 return PerlIO_fdopen(fd, mode + 1);
320 return PerlIO_reopen(name, mode, old);
323 return PerlIO_open(name, mode);
328 return PerlIO_fdopen(fd, (char *) mode);
333 XS(XS_PerlIO__Layer__find)
337 Perl_croak(aTHX_ "Usage class->find(name[,load])");
339 const char * const name = SvPV_nolen_const(ST(1));
340 ST(0) = (strEQ(name, "crlf")
341 || strEQ(name, "raw")) ? &PL_sv_yes : &PL_sv_undef;
348 Perl_boot_core_PerlIO(pTHX)
350 newXS("PerlIO::Layer::find", XS_PerlIO__Layer__find, __FILE__);
356 #ifdef PERLIO_IS_STDIO
363 * Does nothing (yet) except force this file to be included in perl
364 * binary. That allows this file to force inclusion of other functions
365 * that may be required by loadable extensions e.g. for
366 * FileHandle::tmpfile
370 #undef PerlIO_tmpfile
377 #else /* PERLIO_IS_STDIO */
385 * This section is just to make sure these functions get pulled in from
389 #undef PerlIO_tmpfile
401 * Force this file to be included in perl binary. Which allows this
402 * file to force inclusion of other functions that may be required by
403 * loadable extensions e.g. for FileHandle::tmpfile
407 * Hack sfio does its own 'autoflush' on stdout in common cases. Flush
408 * results in a lot of lseek()s to regular files and lot of small
411 sfset(sfstdout, SF_SHARE, 0);
414 /* This is not the reverse of PerlIO_exportFILE(), PerlIO_releaseFILE() is. */
416 PerlIO_importFILE(FILE *stdio, const char *mode)
418 const int fd = fileno(stdio);
419 if (!mode || !*mode) {
422 return PerlIO_fdopen(fd, mode);
426 PerlIO_findFILE(PerlIO *pio)
428 const int fd = PerlIO_fileno(pio);
429 FILE * const f = fdopen(fd, "r+");
431 if (!f && errno == EINVAL)
433 if (!f && errno == EINVAL)
440 /*======================================================================================*/
442 * Implement all the PerlIO interface ourselves.
448 * We _MUST_ have <unistd.h> if we are using lseek() and may have large
455 #include <sys/mman.h>
459 PerlIO_debug(const char *fmt, ...)
464 if (!PL_perlio_debug_fd && !PL_tainting && PL_uid == PL_euid && PL_gid == PL_egid) {
465 const char * const s = PerlEnv_getenv("PERLIO_DEBUG");
467 PL_perlio_debug_fd = PerlLIO_open3(s, O_WRONLY | O_CREAT | O_APPEND, 0666);
469 PL_perlio_debug_fd = -1;
471 if (PL_perlio_debug_fd > 0) {
474 const char * const s = CopFILE(PL_curcop);
475 /* Use fixed buffer as sv_catpvf etc. needs SVs */
477 const STRLEN len = my_sprintf(buffer, "%.40s:%" IVdf " ", s ? s : "(none)", (IV) CopLINE(PL_curcop));
478 # ifdef USE_VSNPRINTF
479 const STRLEN len2 = vsnprintf(buffer+len, sizeof(buffer) - len, fmt, ap);
481 const STRLEN len2 = vsprintf(buffer+len, fmt, ap);
482 # endif /* USE_VSNPRINTF */
483 PerlLIO_write(PL_perlio_debug_fd, buffer, len + len2);
485 const char *s = CopFILE(PL_curcop);
487 SV * const sv = newSVpvs("");
488 Perl_sv_catpvf(aTHX_ sv, "%s:%" IVdf " ", s ? s : "(none)",
489 (IV) CopLINE(PL_curcop));
490 Perl_sv_vcatpvf(aTHX_ sv, fmt, &ap);
492 s = SvPV_const(sv, len);
493 PerlLIO_write(PL_perlio_debug_fd, s, len);
500 /*--------------------------------------------------------------------------------------*/
503 * Inner level routines
507 * Table of pointers to the PerlIO structs (malloc'ed)
509 #define PERLIO_TABLE_SIZE 64
512 PerlIO_allocate(pTHX)
516 * Find a free slot in the table, allocating new table as necessary
521 while ((f = *last)) {
523 last = (PerlIO **) (f);
524 for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
530 Newxz(f,PERLIO_TABLE_SIZE,PerlIO);
538 #undef PerlIO_fdupopen
540 PerlIO_fdupopen(pTHX_ PerlIO *f, CLONE_PARAMS *param, int flags)
542 if (PerlIOValid(f)) {
543 const PerlIO_funcs * const tab = PerlIOBase(f)->tab;
544 PerlIO_debug("fdupopen f=%p param=%p\n",(void*)f,(void*)param);
546 return (*tab->Dup)(aTHX_ PerlIO_allocate(aTHX), f, param, flags);
548 return PerlIOBase_dup(aTHX_ PerlIO_allocate(aTHX), f, param, flags);
552 SETERRNO(EBADF, SS_IVCHAN);
558 PerlIO_cleantable(pTHX_ PerlIO **tablep)
560 PerlIO * const table = *tablep;
563 PerlIO_cleantable(aTHX_(PerlIO **) & (table[0]));
564 for (i = PERLIO_TABLE_SIZE - 1; i > 0; i--) {
565 PerlIO * const f = table + i;
577 PerlIO_list_alloc(pTHX)
581 Newxz(list, 1, PerlIO_list_t);
587 PerlIO_list_free(pTHX_ PerlIO_list_t *list)
590 if (--list->refcnt == 0) {
593 for (i = 0; i < list->cur; i++) {
594 if (list->array[i].arg)
595 SvREFCNT_dec(list->array[i].arg);
597 Safefree(list->array);
605 PerlIO_list_push(pTHX_ PerlIO_list_t *list, PerlIO_funcs *funcs, SV *arg)
611 if (list->cur >= list->len) {
614 Renew(list->array, list->len, PerlIO_pair_t);
616 Newx(list->array, list->len, PerlIO_pair_t);
618 p = &(list->array[list->cur++]);
620 if ((p->arg = arg)) {
621 SvREFCNT_inc_simple_void_NN(arg);
626 PerlIO_clone_list(pTHX_ PerlIO_list_t *proto, CLONE_PARAMS *param)
628 PerlIO_list_t *list = NULL;
631 list = PerlIO_list_alloc(aTHX);
632 for (i=0; i < proto->cur; i++) {
634 if (proto->array[i].arg)
635 arg = PerlIO_sv_dup(aTHX_ proto->array[i].arg,param);
636 PerlIO_list_push(aTHX_ list, proto->array[i].funcs, arg);
643 PerlIO_clone(pTHX_ PerlInterpreter *proto, CLONE_PARAMS *param)
646 PerlIO **table = &proto->Iperlio;
649 PL_known_layers = PerlIO_clone_list(aTHX_ proto->Iknown_layers, param);
650 PL_def_layerlist = PerlIO_clone_list(aTHX_ proto->Idef_layerlist, param);
651 PerlIO_allocate(aTHX); /* root slot is never used */
652 PerlIO_debug("Clone %p from %p\n",aTHX,proto);
653 while ((f = *table)) {
655 table = (PerlIO **) (f++);
656 for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
658 (void) fp_dup(f, 0, param);
664 PERL_UNUSED_ARG(proto);
665 PERL_UNUSED_ARG(param);
670 PerlIO_destruct(pTHX)
673 PerlIO **table = &PL_perlio;
676 PerlIO_debug("Destruct %p\n",aTHX);
678 while ((f = *table)) {
680 table = (PerlIO **) (f++);
681 for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
685 if (l->tab->kind & PERLIO_K_DESTRUCT) {
686 PerlIO_debug("Destruct popping %s\n", l->tab->name);
700 PerlIO_pop(pTHX_ PerlIO *f)
702 const PerlIOl *l = *f;
704 PerlIO_debug("PerlIO_pop f=%p %s\n", (void*)f, l->tab->name);
705 if (l->tab->Popped) {
707 * If popped returns non-zero do not free its layer structure
708 * it has either done so itself, or it is shared and still in
711 if ((*l->tab->Popped) (aTHX_ f) != 0)
719 /* Return as an array the stack of layers on a filehandle. Note that
720 * the stack is returned top-first in the array, and there are three
721 * times as many array elements as there are layers in the stack: the
722 * first element of a layer triplet is the name, the second one is the
723 * arguments, and the third one is the flags. */
726 PerlIO_get_layers(pTHX_ PerlIO *f)
729 AV * const av = newAV();
731 if (PerlIOValid(f)) {
732 PerlIOl *l = PerlIOBase(f);
735 SV * const name = l->tab && l->tab->name ?
736 newSVpv(l->tab->name, 0) : &PL_sv_undef;
737 SV * const arg = l->tab && l->tab->Getarg ?
738 (*l->tab->Getarg)(aTHX_ &l, 0, 0) : &PL_sv_undef;
741 av_push(av, newSViv((IV)l->flags));
749 /*--------------------------------------------------------------------------------------*/
751 * XS Interface for perl code
755 PerlIO_find_layer(pTHX_ const char *name, STRLEN len, int load)
759 if ((SSize_t) len <= 0)
761 for (i = 0; i < PL_known_layers->cur; i++) {
762 PerlIO_funcs * const f = PL_known_layers->array[i].funcs;
763 if (memEQ(f->name, name, len) && f->name[len] == 0) {
764 PerlIO_debug("%.*s => %p\n", (int) len, name, (void*)f);
768 if (load && PL_subname && PL_def_layerlist
769 && PL_def_layerlist->cur >= 2) {
770 if (PL_in_load_module) {
771 Perl_croak(aTHX_ "Recursive call to Perl_load_module in PerlIO_find_layer");
774 SV * const pkgsv = newSVpvs("PerlIO");
775 SV * const layer = newSVpvn(name, len);
776 CV * const cv = get_cv("PerlIO::Layer::NoWarnings", FALSE);
778 SAVEINT(PL_in_load_module);
780 SAVEGENERICSV(PL_warnhook);
781 PL_warnhook = (SV *) (SvREFCNT_inc_simple_NN(cv));
785 * The two SVs are magically freed by load_module
787 Perl_load_module(aTHX_ 0, pkgsv, NULL, layer, NULL);
790 return PerlIO_find_layer(aTHX_ name, len, 0);
793 PerlIO_debug("Cannot find %.*s\n", (int) len, name);
797 #ifdef USE_ATTRIBUTES_FOR_PERLIO
800 perlio_mg_set(pTHX_ SV *sv, MAGIC *mg)
803 IO * const io = GvIOn((GV *) SvRV(sv));
804 PerlIO * const ifp = IoIFP(io);
805 PerlIO * const ofp = IoOFP(io);
806 Perl_warn(aTHX_ "set %" SVf " %p %p %p", sv, io, ifp, ofp);
812 perlio_mg_get(pTHX_ SV *sv, MAGIC *mg)
815 IO * const io = GvIOn((GV *) SvRV(sv));
816 PerlIO * const ifp = IoIFP(io);
817 PerlIO * const ofp = IoOFP(io);
818 Perl_warn(aTHX_ "get %" SVf " %p %p %p", sv, io, ifp, ofp);
824 perlio_mg_clear(pTHX_ SV *sv, MAGIC *mg)
826 Perl_warn(aTHX_ "clear %" SVf, sv);
831 perlio_mg_free(pTHX_ SV *sv, MAGIC *mg)
833 Perl_warn(aTHX_ "free %" SVf, sv);
837 MGVTBL perlio_vtab = {
845 XS(XS_io_MODIFY_SCALAR_ATTRIBUTES)
848 SV * const sv = SvRV(ST(1));
849 AV * const av = newAV();
853 sv_magic(sv, (SV *) av, PERL_MAGIC_ext, NULL, 0);
855 mg = mg_find(sv, PERL_MAGIC_ext);
856 mg->mg_virtual = &perlio_vtab;
858 Perl_warn(aTHX_ "attrib %" SVf, sv);
859 for (i = 2; i < items; i++) {
861 const char * const name = SvPV_const(ST(i), len);
862 SV * const layer = PerlIO_find_layer(aTHX_ name, len, 1);
864 av_push(av, SvREFCNT_inc_simple_NN(layer));
875 #endif /* USE_ATTIBUTES_FOR_PERLIO */
878 PerlIO_tab_sv(pTHX_ PerlIO_funcs *tab)
880 HV * const stash = gv_stashpvs("PerlIO::Layer", TRUE);
881 SV * const sv = sv_bless(newRV_noinc(newSViv(PTR2IV(tab))), stash);
885 XS(XS_PerlIO__Layer__NoWarnings)
887 /* This is used as a %SIG{__WARN__} handler to supress warnings
888 during loading of layers.
893 PerlIO_debug("warning:%s\n",SvPV_nolen_const(ST(0)));
897 XS(XS_PerlIO__Layer__find)
902 Perl_croak(aTHX_ "Usage class->find(name[,load])");
905 const char * const name = SvPV_const(ST(1), len);
906 const bool load = (items > 2) ? SvTRUE(ST(2)) : 0;
907 PerlIO_funcs * const layer = PerlIO_find_layer(aTHX_ name, len, load);
909 (layer) ? sv_2mortal(PerlIO_tab_sv(aTHX_ layer)) :
916 PerlIO_define_layer(pTHX_ PerlIO_funcs *tab)
919 if (!PL_known_layers)
920 PL_known_layers = PerlIO_list_alloc(aTHX);
921 PerlIO_list_push(aTHX_ PL_known_layers, tab, NULL);
922 PerlIO_debug("define %s %p\n", tab->name, (void*)tab);
926 PerlIO_parse_layers(pTHX_ PerlIO_list_t *av, const char *names)
930 const char *s = names;
932 while (isSPACE(*s) || *s == ':')
937 const char *as = NULL;
939 if (!isIDFIRST(*s)) {
941 * Message is consistent with how attribute lists are
942 * passed. Even though this means "foo : : bar" is
943 * seen as an invalid separator character.
945 const char q = ((*s == '\'') ? '"' : '\'');
946 if (ckWARN(WARN_LAYER))
947 Perl_warner(aTHX_ packWARN(WARN_LAYER),
948 "Invalid separator character %c%c%c in PerlIO layer specification %s",
950 SETERRNO(EINVAL, LIB_INVARG);
955 } while (isALNUM(*e));
971 * It's a nul terminated string, not allowed
972 * to \ the terminating null. Anything other
973 * character is passed over.
983 if (ckWARN(WARN_LAYER))
984 Perl_warner(aTHX_ packWARN(WARN_LAYER),
985 "Argument list not closed for PerlIO layer \"%.*s\"",
997 PerlIO_funcs * const layer =
998 PerlIO_find_layer(aTHX_ s, llen, 1);
1000 PerlIO_list_push(aTHX_ av, layer,
1006 if (ckWARN(WARN_LAYER))
1007 Perl_warner(aTHX_ packWARN(WARN_LAYER), "Unknown PerlIO layer \"%.*s\"",
1020 PerlIO_default_buffer(pTHX_ PerlIO_list_t *av)
1023 PERLIO_FUNCS_DECL(*tab) = &PerlIO_perlio;
1024 #ifdef PERLIO_USING_CRLF
1027 if (PerlIO_stdio.Set_ptrcnt)
1028 tab = &PerlIO_stdio;
1030 PerlIO_debug("Pushing %s\n", tab->name);
1031 PerlIO_list_push(aTHX_ av, PerlIO_find_layer(aTHX_ tab->name, 0, 0),
1036 PerlIO_arg_fetch(PerlIO_list_t *av, IV n)
1038 return av->array[n].arg;
1042 PerlIO_layer_fetch(pTHX_ PerlIO_list_t *av, IV n, PerlIO_funcs *def)
1044 if (n >= 0 && n < av->cur) {
1045 PerlIO_debug("Layer %" IVdf " is %s\n", n,
1046 av->array[n].funcs->name);
1047 return av->array[n].funcs;
1050 Perl_croak(aTHX_ "panic: PerlIO layer array corrupt");
1055 PerlIOPop_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
1057 PERL_UNUSED_ARG(mode);
1058 PERL_UNUSED_ARG(arg);
1059 PERL_UNUSED_ARG(tab);
1060 if (PerlIOValid(f)) {
1062 PerlIO_pop(aTHX_ f);
1068 PERLIO_FUNCS_DECL(PerlIO_remove) = {
1069 sizeof(PerlIO_funcs),
1072 PERLIO_K_DUMMY | PERLIO_K_UTF8,
1092 NULL, /* get_base */
1093 NULL, /* get_bufsiz */
1096 NULL, /* set_ptrcnt */
1100 PerlIO_default_layers(pTHX)
1103 if (!PL_def_layerlist) {
1104 const char * const s = (PL_tainting) ? NULL : PerlEnv_getenv("PERLIO");
1105 PERLIO_FUNCS_DECL(*osLayer) = &PerlIO_unix;
1106 PL_def_layerlist = PerlIO_list_alloc(aTHX);
1107 PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_unix));
1109 PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_win32));
1111 osLayer = &PerlIO_win32;
1114 PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_raw));
1115 PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_perlio));
1116 PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_stdio));
1117 PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_crlf));
1119 PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_mmap));
1121 PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_utf8));
1122 PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_remove));
1123 PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_byte));
1124 PerlIO_list_push(aTHX_ PL_def_layerlist,
1125 PerlIO_find_layer(aTHX_ osLayer->name, 0, 0),
1128 PerlIO_parse_layers(aTHX_ PL_def_layerlist, s);
1131 PerlIO_default_buffer(aTHX_ PL_def_layerlist);
1134 if (PL_def_layerlist->cur < 2) {
1135 PerlIO_default_buffer(aTHX_ PL_def_layerlist);
1137 return PL_def_layerlist;
1141 Perl_boot_core_PerlIO(pTHX)
1143 #ifdef USE_ATTRIBUTES_FOR_PERLIO
1144 newXS("io::MODIFY_SCALAR_ATTRIBUTES", XS_io_MODIFY_SCALAR_ATTRIBUTES,
1147 newXS("PerlIO::Layer::find", XS_PerlIO__Layer__find, __FILE__);
1148 newXS("PerlIO::Layer::NoWarnings", XS_PerlIO__Layer__NoWarnings, __FILE__);
1152 PerlIO_default_layer(pTHX_ I32 n)
1155 PerlIO_list_t * const av = PerlIO_default_layers(aTHX);
1158 return PerlIO_layer_fetch(aTHX_ av, n, PERLIO_FUNCS_CAST(&PerlIO_stdio));
1161 #define PerlIO_default_top() PerlIO_default_layer(aTHX_ -1)
1162 #define PerlIO_default_btm() PerlIO_default_layer(aTHX_ 0)
1165 PerlIO_stdstreams(pTHX)
1169 PerlIO_allocate(aTHX);
1170 PerlIO_fdopen(0, "Ir" PERLIO_STDTEXT);
1171 PerlIO_fdopen(1, "Iw" PERLIO_STDTEXT);
1172 PerlIO_fdopen(2, "Iw" PERLIO_STDTEXT);
1177 PerlIO_push(pTHX_ PerlIO *f, PERLIO_FUNCS_DECL(*tab), const char *mode, SV *arg)
1179 if (tab->fsize != sizeof(PerlIO_funcs)) {
1181 Perl_croak(aTHX_ "Layer does not match this perl");
1185 if (tab->size < sizeof(PerlIOl)) {
1188 /* Real layer with a data area */
1191 Newxz(temp, tab->size, char);
1195 l->tab = (PerlIO_funcs*) tab;
1197 PerlIO_debug("PerlIO_push f=%p %s %s %p\n",
1198 (void*)f, tab->name,
1199 (mode) ? mode : "(Null)", (void*)arg);
1200 if (*l->tab->Pushed &&
1202 (aTHX_ f, mode, arg, (PerlIO_funcs*) tab) != 0) {
1203 PerlIO_pop(aTHX_ f);
1212 /* Pseudo-layer where push does its own stack adjust */
1213 PerlIO_debug("PerlIO_push f=%p %s %s %p\n", (void*)f, tab->name,
1214 (mode) ? mode : "(Null)", (void*)arg);
1216 (*tab->Pushed) (aTHX_ f, mode, arg, (PerlIO_funcs*) tab) != 0) {
1224 PerlIOBase_binmode(pTHX_ PerlIO *f)
1226 if (PerlIOValid(f)) {
1227 /* Is layer suitable for raw stream ? */
1228 if (PerlIOBase(f)->tab->kind & PERLIO_K_RAW) {
1229 /* Yes - turn off UTF-8-ness, to undo UTF-8 locale effects */
1230 PerlIOBase(f)->flags &= ~PERLIO_F_UTF8;
1233 /* Not suitable - pop it */
1234 PerlIO_pop(aTHX_ f);
1242 PerlIORaw_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
1244 PERL_UNUSED_ARG(mode);
1245 PERL_UNUSED_ARG(arg);
1246 PERL_UNUSED_ARG(tab);
1248 if (PerlIOValid(f)) {
1253 * Strip all layers that are not suitable for a raw stream
1256 while (t && (l = *t)) {
1257 if (l->tab->Binmode) {
1258 /* Has a handler - normal case */
1259 if ((*l->tab->Binmode)(aTHX_ f) == 0) {
1261 /* Layer still there - move down a layer */
1270 /* No handler - pop it */
1271 PerlIO_pop(aTHX_ t);
1274 if (PerlIOValid(f)) {
1275 PerlIO_debug(":raw f=%p :%s\n", (void*)f, PerlIOBase(f)->tab->name);
1283 PerlIO_apply_layera(pTHX_ PerlIO *f, const char *mode,
1284 PerlIO_list_t *layers, IV n, IV max)
1288 PerlIO_funcs * const tab = PerlIO_layer_fetch(aTHX_ layers, n, NULL);
1290 if (!PerlIO_push(aTHX_ f, tab, mode, PerlIOArg)) {
1301 PerlIO_apply_layers(pTHX_ PerlIO *f, const char *mode, const char *names)
1305 PerlIO_list_t * const layers = PerlIO_list_alloc(aTHX);
1306 code = PerlIO_parse_layers(aTHX_ layers, names);
1308 code = PerlIO_apply_layera(aTHX_ f, mode, layers, 0, layers->cur);
1310 PerlIO_list_free(aTHX_ layers);
1316 /*--------------------------------------------------------------------------------------*/
1318 * Given the abstraction above the public API functions
1322 PerlIO_binmode(pTHX_ PerlIO *f, int iotype, int mode, const char *names)
1324 PerlIO_debug("PerlIO_binmode f=%p %s %c %x %s\n", (void*)f,
1325 (PerlIOBase(f)) ? PerlIOBase(f)->tab->name : "(Null)",
1326 iotype, mode, (names) ? names : "(Null)");
1329 /* Do not flush etc. if (e.g.) switching encodings.
1330 if a pushed layer knows it needs to flush lower layers
1331 (for example :unix which is never going to call them)
1332 it can do the flush when it is pushed.
1334 return PerlIO_apply_layers(aTHX_ f, NULL, names) == 0 ? TRUE : FALSE;
1337 /* Fake 5.6 legacy of using this call to turn ON O_TEXT */
1338 #ifdef PERLIO_USING_CRLF
1339 /* Legacy binmode only has meaning if O_TEXT has a value distinct from
1340 O_BINARY so we can look for it in mode.
1342 if (!(mode & O_BINARY)) {
1344 /* FIXME?: Looking down the layer stack seems wrong,
1345 but is a way of reaching past (say) an encoding layer
1346 to flip CRLF-ness of the layer(s) below
1349 /* Perhaps we should turn on bottom-most aware layer
1350 e.g. Ilya's idea that UNIX TTY could serve
1352 if (PerlIOBase(f)->tab->kind & PERLIO_K_CANCRLF) {
1353 if (!(PerlIOBase(f)->flags & PERLIO_F_CRLF)) {
1354 /* Not in text mode - flush any pending stuff and flip it */
1356 PerlIOBase(f)->flags |= PERLIO_F_CRLF;
1358 /* Only need to turn it on in one layer so we are done */
1363 /* Not finding a CRLF aware layer presumably means we are binary
1364 which is not what was requested - so we failed
1365 We _could_ push :crlf layer but so could caller
1370 /* Legacy binmode is now _defined_ as being equivalent to pushing :raw
1371 So code that used to be here is now in PerlIORaw_pushed().
1373 return PerlIO_push(aTHX_ f, PERLIO_FUNCS_CAST(&PerlIO_raw), NULL, NULL) ? TRUE : FALSE;
1378 PerlIO__close(pTHX_ PerlIO *f)
1380 if (PerlIOValid(f)) {
1381 PerlIO_funcs * const tab = PerlIOBase(f)->tab;
1382 if (tab && tab->Close)
1383 return (*tab->Close)(aTHX_ f);
1385 return PerlIOBase_close(aTHX_ f);
1388 SETERRNO(EBADF, SS_IVCHAN);
1394 Perl_PerlIO_close(pTHX_ PerlIO *f)
1396 const int code = PerlIO__close(aTHX_ f);
1397 while (PerlIOValid(f)) {
1398 PerlIO_pop(aTHX_ f);
1404 Perl_PerlIO_fileno(pTHX_ PerlIO *f)
1407 Perl_PerlIO_or_Base(f, Fileno, fileno, -1, (aTHX_ f));
1411 PerlIO_context_layers(pTHX_ const char *mode)
1414 const char *type = NULL;
1416 * Need to supply default layer info from open.pm
1419 SV * const layers = PL_curcop->cop_io;
1422 type = SvPV_const(layers, len);
1423 if (type && mode[0] != 'r') {
1425 * Skip to write part
1427 const char * const s = strchr(type, 0);
1428 if (s && (STRLEN)(s - type) < len) {
1437 static PerlIO_funcs *
1438 PerlIO_layer_from_ref(pTHX_ SV *sv)
1442 * For any scalar type load the handler which is bundled with perl
1444 if (SvTYPE(sv) < SVt_PVAV)
1445 return PerlIO_find_layer(aTHX_ STR_WITH_LEN("scalar"), 1);
1448 * For other types allow if layer is known but don't try and load it
1450 switch (SvTYPE(sv)) {
1452 return PerlIO_find_layer(aTHX_ STR_WITH_LEN("Array"), 0);
1454 return PerlIO_find_layer(aTHX_ STR_WITH_LEN("Hash"), 0);
1456 return PerlIO_find_layer(aTHX_ STR_WITH_LEN("Code"), 0);
1458 return PerlIO_find_layer(aTHX_ STR_WITH_LEN("Glob"), 0);
1464 PerlIO_resolve_layers(pTHX_ const char *layers,
1465 const char *mode, int narg, SV **args)
1468 PerlIO_list_t *def = PerlIO_default_layers(aTHX);
1471 PerlIO_stdstreams(aTHX);
1473 SV * const arg = *args;
1475 * If it is a reference but not an object see if we have a handler
1478 if (SvROK(arg) && !sv_isobject(arg)) {
1479 PerlIO_funcs * const handler = PerlIO_layer_from_ref(aTHX_ SvRV(arg));
1481 def = PerlIO_list_alloc(aTHX);
1482 PerlIO_list_push(aTHX_ def, handler, &PL_sv_undef);
1486 * Don't fail if handler cannot be found :via(...) etc. may do
1487 * something sensible else we will just stringfy and open
1492 if (!layers || !*layers)
1493 layers = PerlIO_context_layers(aTHX_ mode);
1494 if (layers && *layers) {
1498 av = PerlIO_list_alloc(aTHX);
1499 for (i = 0; i < def->cur; i++) {
1500 PerlIO_list_push(aTHX_ av, def->array[i].funcs,
1507 if (PerlIO_parse_layers(aTHX_ av, layers) == 0) {
1511 PerlIO_list_free(aTHX_ av);
1523 PerlIO_openn(pTHX_ const char *layers, const char *mode, int fd,
1524 int imode, int perm, PerlIO *f, int narg, SV **args)
1527 if (!f && narg == 1 && *args == &PL_sv_undef) {
1528 if ((f = PerlIO_tmpfile())) {
1529 if (!layers || !*layers)
1530 layers = PerlIO_context_layers(aTHX_ mode);
1531 if (layers && *layers)
1532 PerlIO_apply_layers(aTHX_ f, mode, layers);
1536 PerlIO_list_t *layera;
1538 PerlIO_funcs *tab = NULL;
1539 if (PerlIOValid(f)) {
1541 * This is "reopen" - it is not tested as perl does not use it
1545 layera = PerlIO_list_alloc(aTHX);
1547 SV * const arg = (l->tab->Getarg)
1548 ? (*l->tab->Getarg) (aTHX_ &l, NULL, 0)
1550 PerlIO_list_push(aTHX_ layera, l->tab, arg);
1551 l = *PerlIONext(&l);
1555 layera = PerlIO_resolve_layers(aTHX_ layers, mode, narg, args);
1561 * Start at "top" of layer stack
1563 n = layera->cur - 1;
1565 PerlIO_funcs * const t = PerlIO_layer_fetch(aTHX_ layera, n, NULL);
1574 * Found that layer 'n' can do opens - call it
1576 if (narg > 1 && !(tab->kind & PERLIO_K_MULTIARG)) {
1577 Perl_croak(aTHX_ "More than one argument to open(,':%s')",tab->name);
1579 PerlIO_debug("openn(%s,'%s','%s',%d,%x,%o,%p,%d,%p)\n",
1580 tab->name, layers ? layers : "(Null)", mode, fd,
1581 imode, perm, (void*)f, narg, (void*)args);
1583 f = (*tab->Open) (aTHX_ tab, layera, n, mode, fd, imode, perm,
1586 SETERRNO(EINVAL, LIB_INVARG);
1590 if (n + 1 < layera->cur) {
1592 * More layers above the one that we used to open -
1595 if (PerlIO_apply_layera(aTHX_ f, mode, layera, n + 1, layera->cur) != 0) {
1596 /* If pushing layers fails close the file */
1603 PerlIO_list_free(aTHX_ layera);
1610 Perl_PerlIO_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
1612 Perl_PerlIO_or_Base(f, Read, read, -1, (aTHX_ f, vbuf, count));
1616 Perl_PerlIO_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
1618 Perl_PerlIO_or_Base(f, Unread, unread, -1, (aTHX_ f, vbuf, count));
1622 Perl_PerlIO_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
1624 Perl_PerlIO_or_fail(f, Write, -1, (aTHX_ f, vbuf, count));
1628 Perl_PerlIO_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
1630 Perl_PerlIO_or_fail(f, Seek, -1, (aTHX_ f, offset, whence));
1634 Perl_PerlIO_tell(pTHX_ PerlIO *f)
1636 Perl_PerlIO_or_fail(f, Tell, -1, (aTHX_ f));
1640 Perl_PerlIO_flush(pTHX_ PerlIO *f)
1645 const PerlIO_funcs *tab = PerlIOBase(f)->tab;
1647 if (tab && tab->Flush)
1648 return (*tab->Flush) (aTHX_ f);
1650 return 0; /* If no Flush defined, silently succeed. */
1653 PerlIO_debug("Cannot flush f=%p\n", (void*)f);
1654 SETERRNO(EBADF, SS_IVCHAN);
1660 * Is it good API design to do flush-all on NULL, a potentially
1661 * errorneous input? Maybe some magical value (PerlIO*
1662 * PERLIO_FLUSH_ALL = (PerlIO*)-1;)? Yes, stdio does similar
1663 * things on fflush(NULL), but should we be bound by their design
1666 PerlIO **table = &PL_perlio;
1668 while ((f = *table)) {
1670 table = (PerlIO **) (f++);
1671 for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
1672 if (*f && PerlIO_flush(f) != 0)
1682 PerlIOBase_flush_linebuf(pTHX)
1685 PerlIO **table = &PL_perlio;
1687 while ((f = *table)) {
1689 table = (PerlIO **) (f++);
1690 for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
1693 flags & (PERLIO_F_LINEBUF | PERLIO_F_CANWRITE))
1694 == (PERLIO_F_LINEBUF | PERLIO_F_CANWRITE))
1702 Perl_PerlIO_fill(pTHX_ PerlIO *f)
1704 Perl_PerlIO_or_fail(f, Fill, -1, (aTHX_ f));
1708 PerlIO_isutf8(PerlIO *f)
1711 return (PerlIOBase(f)->flags & PERLIO_F_UTF8) != 0;
1713 SETERRNO(EBADF, SS_IVCHAN);
1719 Perl_PerlIO_eof(pTHX_ PerlIO *f)
1721 Perl_PerlIO_or_Base(f, Eof, eof, -1, (aTHX_ f));
1725 Perl_PerlIO_error(pTHX_ PerlIO *f)
1727 Perl_PerlIO_or_Base(f, Error, error, -1, (aTHX_ f));
1731 Perl_PerlIO_clearerr(pTHX_ PerlIO *f)
1733 Perl_PerlIO_or_Base_void(f, Clearerr, clearerr, (aTHX_ f));
1737 Perl_PerlIO_setlinebuf(pTHX_ PerlIO *f)
1739 Perl_PerlIO_or_Base_void(f, Setlinebuf, setlinebuf, (aTHX_ f));
1743 PerlIO_has_base(PerlIO *f)
1745 if (PerlIOValid(f)) {
1746 const PerlIO_funcs * const tab = PerlIOBase(f)->tab;
1749 return (tab->Get_base != NULL);
1750 SETERRNO(EINVAL, LIB_INVARG);
1753 SETERRNO(EBADF, SS_IVCHAN);
1759 PerlIO_fast_gets(PerlIO *f)
1761 if (PerlIOValid(f) && (PerlIOBase(f)->flags & PERLIO_F_FASTGETS)) {
1762 const PerlIO_funcs * const tab = PerlIOBase(f)->tab;
1765 return (tab->Set_ptrcnt != NULL);
1766 SETERRNO(EINVAL, LIB_INVARG);
1769 SETERRNO(EBADF, SS_IVCHAN);
1775 PerlIO_has_cntptr(PerlIO *f)
1777 if (PerlIOValid(f)) {
1778 const PerlIO_funcs * const tab = PerlIOBase(f)->tab;
1781 return (tab->Get_ptr != NULL && tab->Get_cnt != NULL);
1782 SETERRNO(EINVAL, LIB_INVARG);
1785 SETERRNO(EBADF, SS_IVCHAN);
1791 PerlIO_canset_cnt(PerlIO *f)
1793 if (PerlIOValid(f)) {
1794 const PerlIO_funcs * const tab = PerlIOBase(f)->tab;
1797 return (tab->Set_ptrcnt != NULL);
1798 SETERRNO(EINVAL, LIB_INVARG);
1801 SETERRNO(EBADF, SS_IVCHAN);
1807 Perl_PerlIO_get_base(pTHX_ PerlIO *f)
1809 Perl_PerlIO_or_fail(f, Get_base, NULL, (aTHX_ f));
1813 Perl_PerlIO_get_bufsiz(pTHX_ PerlIO *f)
1815 Perl_PerlIO_or_fail(f, Get_bufsiz, -1, (aTHX_ f));
1819 Perl_PerlIO_get_ptr(pTHX_ PerlIO *f)
1821 Perl_PerlIO_or_fail(f, Get_ptr, NULL, (aTHX_ f));
1825 Perl_PerlIO_get_cnt(pTHX_ PerlIO *f)
1827 Perl_PerlIO_or_fail(f, Get_cnt, -1, (aTHX_ f));
1831 Perl_PerlIO_set_cnt(pTHX_ PerlIO *f, int cnt)
1833 Perl_PerlIO_or_fail_void(f, Set_ptrcnt, (aTHX_ f, NULL, cnt));
1837 Perl_PerlIO_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, int cnt)
1839 Perl_PerlIO_or_fail_void(f, Set_ptrcnt, (aTHX_ f, ptr, cnt));
1843 /*--------------------------------------------------------------------------------------*/
1845 * utf8 and raw dummy layers
1849 PerlIOUtf8_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
1851 PERL_UNUSED_CONTEXT;
1852 PERL_UNUSED_ARG(mode);
1853 PERL_UNUSED_ARG(arg);
1854 if (PerlIOValid(f)) {
1855 if (tab->kind & PERLIO_K_UTF8)
1856 PerlIOBase(f)->flags |= PERLIO_F_UTF8;
1858 PerlIOBase(f)->flags &= ~PERLIO_F_UTF8;
1864 PERLIO_FUNCS_DECL(PerlIO_utf8) = {
1865 sizeof(PerlIO_funcs),
1868 PERLIO_K_DUMMY | PERLIO_K_UTF8,
1888 NULL, /* get_base */
1889 NULL, /* get_bufsiz */
1892 NULL, /* set_ptrcnt */
1895 PERLIO_FUNCS_DECL(PerlIO_byte) = {
1896 sizeof(PerlIO_funcs),
1919 NULL, /* get_base */
1920 NULL, /* get_bufsiz */
1923 NULL, /* set_ptrcnt */
1927 PerlIORaw_open(pTHX_ PerlIO_funcs *self, PerlIO_list_t *layers,
1928 IV n, const char *mode, int fd, int imode, int perm,
1929 PerlIO *old, int narg, SV **args)
1931 PerlIO_funcs * const tab = PerlIO_default_btm();
1932 PERL_UNUSED_ARG(self);
1933 if (tab && tab->Open)
1934 return (*tab->Open) (aTHX_ tab, layers, n - 1, mode, fd, imode, perm,
1936 SETERRNO(EINVAL, LIB_INVARG);
1940 PERLIO_FUNCS_DECL(PerlIO_raw) = {
1941 sizeof(PerlIO_funcs),
1964 NULL, /* get_base */
1965 NULL, /* get_bufsiz */
1968 NULL, /* set_ptrcnt */
1970 /*--------------------------------------------------------------------------------------*/
1971 /*--------------------------------------------------------------------------------------*/
1973 * "Methods" of the "base class"
1977 PerlIOBase_fileno(pTHX_ PerlIO *f)
1979 return PerlIOValid(f) ? PerlIO_fileno(PerlIONext(f)) : -1;
1983 PerlIO_modestr(PerlIO * f, char *buf)
1986 if (PerlIOValid(f)) {
1987 const IV flags = PerlIOBase(f)->flags;
1988 if (flags & PERLIO_F_APPEND) {
1990 if (flags & PERLIO_F_CANREAD) {
1994 else if (flags & PERLIO_F_CANREAD) {
1996 if (flags & PERLIO_F_CANWRITE)
1999 else if (flags & PERLIO_F_CANWRITE) {
2001 if (flags & PERLIO_F_CANREAD) {
2005 #ifdef PERLIO_USING_CRLF
2006 if (!(flags & PERLIO_F_CRLF))
2016 PerlIOBase_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
2018 PerlIOl * const l = PerlIOBase(f);
2019 PERL_UNUSED_CONTEXT;
2020 PERL_UNUSED_ARG(arg);
2022 l->flags &= ~(PERLIO_F_CANREAD | PERLIO_F_CANWRITE |
2023 PERLIO_F_TRUNCATE | PERLIO_F_APPEND);
2024 if (tab->Set_ptrcnt != NULL)
2025 l->flags |= PERLIO_F_FASTGETS;
2027 if (*mode == IoTYPE_NUMERIC || *mode == IoTYPE_IMPLICIT)
2031 l->flags |= PERLIO_F_CANREAD;
2034 l->flags |= PERLIO_F_APPEND | PERLIO_F_CANWRITE;
2037 l->flags |= PERLIO_F_TRUNCATE | PERLIO_F_CANWRITE;
2040 SETERRNO(EINVAL, LIB_INVARG);
2046 l->flags |= PERLIO_F_CANREAD | PERLIO_F_CANWRITE;
2049 l->flags &= ~PERLIO_F_CRLF;
2052 l->flags |= PERLIO_F_CRLF;
2055 SETERRNO(EINVAL, LIB_INVARG);
2062 l->flags |= l->next->flags &
2063 (PERLIO_F_CANREAD | PERLIO_F_CANWRITE | PERLIO_F_TRUNCATE |
2068 PerlIO_debug("PerlIOBase_pushed f=%p %s %s fl=%08" UVxf " (%s)\n",
2069 f, PerlIOBase(f)->tab->name, (omode) ? omode : "(Null)",
2070 l->flags, PerlIO_modestr(f, temp));
2076 PerlIOBase_popped(pTHX_ PerlIO *f)
2078 PERL_UNUSED_CONTEXT;
2084 PerlIOBase_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
2087 * Save the position as current head considers it
2089 const Off_t old = PerlIO_tell(f);
2090 PerlIO_push(aTHX_ f, PERLIO_FUNCS_CAST(&PerlIO_pending), "r", NULL);
2091 PerlIOSelf(f, PerlIOBuf)->posn = old;
2092 return PerlIOBuf_unread(aTHX_ f, vbuf, count);
2096 PerlIOBase_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
2098 STDCHAR *buf = (STDCHAR *) vbuf;
2100 if (!(PerlIOBase(f)->flags & PERLIO_F_CANREAD)) {
2101 PerlIOBase(f)->flags |= PERLIO_F_ERROR;
2102 SETERRNO(EBADF, SS_IVCHAN);
2108 SSize_t avail = PerlIO_get_cnt(f);
2111 take = ((SSize_t)count < avail) ? (SSize_t)count : avail;
2113 STDCHAR *ptr = PerlIO_get_ptr(f);
2114 Copy(ptr, buf, take, STDCHAR);
2115 PerlIO_set_ptrcnt(f, ptr + take, (avail -= take));
2118 if (avail == 0) /* set_ptrcnt could have reset avail */
2121 if (count > 0 && avail <= 0) {
2122 if (PerlIO_fill(f) != 0)
2127 return (buf - (STDCHAR *) vbuf);
2133 PerlIOBase_noop_ok(pTHX_ PerlIO *f)
2135 PERL_UNUSED_CONTEXT;
2141 PerlIOBase_noop_fail(pTHX_ PerlIO *f)
2143 PERL_UNUSED_CONTEXT;
2149 PerlIOBase_close(pTHX_ PerlIO *f)
2152 if (PerlIOValid(f)) {
2153 PerlIO *n = PerlIONext(f);
2154 code = PerlIO_flush(f);
2155 PerlIOBase(f)->flags &=
2156 ~(PERLIO_F_CANREAD | PERLIO_F_CANWRITE | PERLIO_F_OPEN);
2157 while (PerlIOValid(n)) {
2158 const PerlIO_funcs * const tab = PerlIOBase(n)->tab;
2159 if (tab && tab->Close) {
2160 if ((*tab->Close)(aTHX_ n) != 0)
2165 PerlIOBase(n)->flags &=
2166 ~(PERLIO_F_CANREAD | PERLIO_F_CANWRITE | PERLIO_F_OPEN);
2172 SETERRNO(EBADF, SS_IVCHAN);
2178 PerlIOBase_eof(pTHX_ PerlIO *f)
2180 PERL_UNUSED_CONTEXT;
2181 if (PerlIOValid(f)) {
2182 return (PerlIOBase(f)->flags & PERLIO_F_EOF) != 0;
2188 PerlIOBase_error(pTHX_ PerlIO *f)
2190 PERL_UNUSED_CONTEXT;
2191 if (PerlIOValid(f)) {
2192 return (PerlIOBase(f)->flags & PERLIO_F_ERROR) != 0;
2198 PerlIOBase_clearerr(pTHX_ PerlIO *f)
2200 if (PerlIOValid(f)) {
2201 PerlIO * const n = PerlIONext(f);
2202 PerlIOBase(f)->flags &= ~(PERLIO_F_ERROR | PERLIO_F_EOF);
2209 PerlIOBase_setlinebuf(pTHX_ PerlIO *f)
2211 PERL_UNUSED_CONTEXT;
2212 if (PerlIOValid(f)) {
2213 PerlIOBase(f)->flags |= PERLIO_F_LINEBUF;
2218 PerlIO_sv_dup(pTHX_ SV *arg, CLONE_PARAMS *param)
2224 return sv_dup(arg, param);
2227 return newSVsv(arg);
2230 PERL_UNUSED_ARG(param);
2231 return newSVsv(arg);
2236 PerlIOBase_dup(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags)
2238 PerlIO * const nexto = PerlIONext(o);
2239 if (PerlIOValid(nexto)) {
2240 const PerlIO_funcs * const tab = PerlIOBase(nexto)->tab;
2241 if (tab && tab->Dup)
2242 f = (*tab->Dup)(aTHX_ f, nexto, param, flags);
2244 f = PerlIOBase_dup(aTHX_ f, nexto, param, flags);
2247 PerlIO_funcs * const self = PerlIOBase(o)->tab;
2250 PerlIO_debug("PerlIOBase_dup %s f=%p o=%p param=%p\n",
2251 self->name, (void*)f, (void*)o, (void*)param);
2253 arg = (*self->Getarg)(aTHX_ o, param, flags);
2257 f = PerlIO_push(aTHX_ f, self, PerlIO_modestr(o,buf), arg);
2266 perl_mutex PerlIO_mutex;
2269 /* PL_perlio_fd_refcnt[] is in intrpvar.h */
2271 /* Must be called with PerlIO_mutex locked. */
2273 S_more_refcounted_fds(pTHX_ const int new_fd) {
2275 const int old_max = PL_perlio_fd_refcnt_size;
2276 const int new_max = 16 + (new_fd & ~15);
2279 PerlIO_debug("More fds - old=%d, need %d, new=%d\n",
2280 old_max, new_fd, new_max);
2282 if (new_fd < old_max) {
2286 assert (new_max > new_fd);
2289 = PerlMemShared_realloc(PL_perlio_fd_refcnt, new_max * sizeof(int));
2293 MUTEX_UNLOCK(&PerlIO_mutex);
2295 /* Can't use PerlIO to write as it allocates memory */
2296 PerlLIO_write(PerlIO_fileno(Perl_error_log),
2297 PL_no_mem, strlen(PL_no_mem));
2301 PL_perlio_fd_refcnt_size = new_max;
2302 PL_perlio_fd_refcnt = new_array;
2304 PerlIO_debug("Zeroing %p, %d\n",
2305 (void*)(new_array + old_max),
2308 Zero(new_array + old_max, new_max - old_max, int);
2315 /* Place holder for stdstreams call ??? */
2317 MUTEX_INIT(&PerlIO_mutex);
2319 PERL_UNUSED_CONTEXT;
2324 PerlIOUnix_refcnt_inc(int fd)
2331 MUTEX_LOCK(&PerlIO_mutex);
2333 if (fd >= PL_perlio_fd_refcnt_size)
2334 S_more_refcounted_fds(aTHX_ fd);
2336 PL_perlio_fd_refcnt[fd]++;
2337 PerlIO_debug("fd %d refcnt=%d\n",fd,PL_perlio_fd_refcnt[fd]);
2340 MUTEX_UNLOCK(&PerlIO_mutex);
2346 PerlIOUnix_refcnt_dec(int fd)
2353 MUTEX_LOCK(&PerlIO_mutex);
2355 /* XXX should this be a panic? */
2356 if (fd >= PL_perlio_fd_refcnt_size)
2357 S_more_refcounted_fds(aTHX_ fd);
2359 /* XXX should this be a panic if it drops below 0? */
2360 cnt = --PL_perlio_fd_refcnt[fd];
2361 PerlIO_debug("fd %d refcnt=%d\n",fd,cnt);
2363 MUTEX_UNLOCK(&PerlIO_mutex);
2370 PerlIO_cleanup(pTHX)
2375 PerlIO_debug("Cleanup layers for %p\n",aTHX);
2377 PerlIO_debug("Cleanup layers\n");
2379 /* Raise STDIN..STDERR refcount so we don't close them */
2380 for (i=0; i < 3; i++)
2381 PerlIOUnix_refcnt_inc(i);
2382 PerlIO_cleantable(aTHX_ &PL_perlio);
2383 /* Restore STDIN..STDERR refcount */
2384 for (i=0; i < 3; i++)
2385 PerlIOUnix_refcnt_dec(i);
2387 if (PL_known_layers) {
2388 PerlIO_list_free(aTHX_ PL_known_layers);
2389 PL_known_layers = NULL;
2391 if (PL_def_layerlist) {
2392 PerlIO_list_free(aTHX_ PL_def_layerlist);
2393 PL_def_layerlist = NULL;
2399 /*--------------------------------------------------------------------------------------*/
2401 * Bottom-most level for UNIX-like case
2405 struct _PerlIO base; /* The generic part */
2406 int fd; /* UNIX like file descriptor */
2407 int oflags; /* open/fcntl flags */
2411 PerlIOUnix_oflags(const char *mode)
2414 if (*mode == IoTYPE_IMPLICIT || *mode == IoTYPE_NUMERIC)
2419 if (*++mode == '+') {
2426 oflags = O_CREAT | O_TRUNC;
2427 if (*++mode == '+') {
2436 oflags = O_CREAT | O_APPEND;
2437 if (*++mode == '+') {
2450 else if (*mode == 't') {
2452 oflags &= ~O_BINARY;
2456 * Always open in binary mode
2459 if (*mode || oflags == -1) {
2460 SETERRNO(EINVAL, LIB_INVARG);
2467 PerlIOUnix_fileno(pTHX_ PerlIO *f)
2469 PERL_UNUSED_CONTEXT;
2470 return PerlIOSelf(f, PerlIOUnix)->fd;
2474 PerlIOUnix_setfd(pTHX_ PerlIO *f, int fd, int imode)
2476 PerlIOUnix * const s = PerlIOSelf(f, PerlIOUnix);
2479 if (PerlLIO_fstat(fd, &st) == 0) {
2480 if (!S_ISREG(st.st_mode)) {
2481 PerlIO_debug("%d is not regular file\n",fd);
2482 PerlIOBase(f)->flags |= PERLIO_F_NOTREG;
2485 PerlIO_debug("%d _is_ a regular file\n",fd);
2491 PerlIOUnix_refcnt_inc(fd);
2492 PERL_UNUSED_CONTEXT;
2496 PerlIOUnix_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
2498 IV code = PerlIOBase_pushed(aTHX_ f, mode, arg, tab);
2499 if (*PerlIONext(f)) {
2500 /* We never call down so do any pending stuff now */
2501 PerlIO_flush(PerlIONext(f));
2503 * XXX could (or should) we retrieve the oflags from the open file
2504 * handle rather than believing the "mode" we are passed in? XXX
2505 * Should the value on NULL mode be 0 or -1?
2507 PerlIOUnix_setfd(aTHX_ f, PerlIO_fileno(PerlIONext(f)),
2508 mode ? PerlIOUnix_oflags(mode) : -1);
2510 PerlIOBase(f)->flags |= PERLIO_F_OPEN;
2516 PerlIOUnix_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
2518 const int fd = PerlIOSelf(f, PerlIOUnix)->fd;
2520 PERL_UNUSED_CONTEXT;
2521 if (PerlIOBase(f)->flags & PERLIO_F_NOTREG) {
2523 SETERRNO(ESPIPE, LIB_INVARG);
2525 SETERRNO(EINVAL, LIB_INVARG);
2529 new_loc = PerlLIO_lseek(fd, offset, whence);
2530 if (new_loc == (Off_t) - 1)
2532 PerlIOBase(f)->flags &= ~PERLIO_F_EOF;
2537 PerlIOUnix_open(pTHX_ PerlIO_funcs *self, PerlIO_list_t *layers,
2538 IV n, const char *mode, int fd, int imode,
2539 int perm, PerlIO *f, int narg, SV **args)
2541 if (PerlIOValid(f)) {
2542 if (PerlIOBase(f)->flags & PERLIO_F_OPEN)
2543 (*PerlIOBase(f)->tab->Close)(aTHX_ f);
2546 if (*mode == IoTYPE_NUMERIC)
2549 imode = PerlIOUnix_oflags(mode);
2553 const char *path = SvPV_nolen_const(*args);
2554 fd = PerlLIO_open3(path, imode, perm);
2558 if (*mode == IoTYPE_IMPLICIT)
2561 f = PerlIO_allocate(aTHX);
2563 if (!PerlIOValid(f)) {
2564 if (!(f = PerlIO_push(aTHX_ f, self, mode, PerlIOArg))) {
2568 PerlIOUnix_setfd(aTHX_ f, fd, imode);
2569 PerlIOBase(f)->flags |= PERLIO_F_OPEN;
2570 if (*mode == IoTYPE_APPEND)
2571 PerlIOUnix_seek(aTHX_ f, 0, SEEK_END);
2578 * FIXME: pop layers ???
2586 PerlIOUnix_dup(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags)
2588 const PerlIOUnix * const os = PerlIOSelf(o, PerlIOUnix);
2590 if (flags & PERLIO_DUP_FD) {
2591 fd = PerlLIO_dup(fd);
2594 f = PerlIOBase_dup(aTHX_ f, o, param, flags);
2596 /* If all went well overwrite fd in dup'ed lay with the dup()'ed fd */
2597 PerlIOUnix_setfd(aTHX_ f, fd, os->oflags);
2606 PerlIOUnix_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
2609 const int fd = PerlIOSelf(f, PerlIOUnix)->fd;
2610 #ifdef PERLIO_STD_SPECIAL
2612 return PERLIO_STD_IN(fd, vbuf, count);
2614 if (!(PerlIOBase(f)->flags & PERLIO_F_CANREAD) ||
2615 PerlIOBase(f)->flags & (PERLIO_F_EOF|PERLIO_F_ERROR)) {
2619 const SSize_t len = PerlLIO_read(fd, vbuf, count);
2620 if (len >= 0 || errno != EINTR) {
2622 if (errno != EAGAIN) {
2623 PerlIOBase(f)->flags |= PERLIO_F_ERROR;
2626 else if (len == 0 && count != 0) {
2627 PerlIOBase(f)->flags |= PERLIO_F_EOF;
2638 PerlIOUnix_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
2641 const int fd = PerlIOSelf(f, PerlIOUnix)->fd;
2642 #ifdef PERLIO_STD_SPECIAL
2643 if (fd == 1 || fd == 2)
2644 return PERLIO_STD_OUT(fd, vbuf, count);
2647 const SSize_t len = PerlLIO_write(fd, vbuf, count);
2648 if (len >= 0 || errno != EINTR) {
2650 if (errno != EAGAIN) {
2651 PerlIOBase(f)->flags |= PERLIO_F_ERROR;
2662 PerlIOUnix_tell(pTHX_ PerlIO *f)
2664 PERL_UNUSED_CONTEXT;
2666 return PerlLIO_lseek(PerlIOSelf(f, PerlIOUnix)->fd, 0, SEEK_CUR);
2671 PerlIOUnix_close(pTHX_ PerlIO *f)
2674 const int fd = PerlIOSelf(f, PerlIOUnix)->fd;
2676 if (PerlIOBase(f)->flags & PERLIO_F_OPEN) {
2677 if (PerlIOUnix_refcnt_dec(fd) > 0) {
2678 PerlIOBase(f)->flags &= ~PERLIO_F_OPEN;
2683 SETERRNO(EBADF,SS_IVCHAN);
2686 while (PerlLIO_close(fd) != 0) {
2687 if (errno != EINTR) {
2694 PerlIOBase(f)->flags &= ~PERLIO_F_OPEN;
2699 PERLIO_FUNCS_DECL(PerlIO_unix) = {
2700 sizeof(PerlIO_funcs),
2707 PerlIOBase_binmode, /* binmode */
2717 PerlIOBase_noop_ok, /* flush */
2718 PerlIOBase_noop_fail, /* fill */
2721 PerlIOBase_clearerr,
2722 PerlIOBase_setlinebuf,
2723 NULL, /* get_base */
2724 NULL, /* get_bufsiz */
2727 NULL, /* set_ptrcnt */
2730 /*--------------------------------------------------------------------------------------*/
2735 #if defined(VMS) && !defined(STDIO_BUFFER_WRITABLE)
2736 /* perl5.8 - This ensures the last minute VMS ungetc fix is not
2737 broken by the last second glibc 2.3 fix
2739 #define STDIO_BUFFER_WRITABLE
2744 struct _PerlIO base;
2745 FILE *stdio; /* The stream */
2749 PerlIOStdio_fileno(pTHX_ PerlIO *f)
2751 PERL_UNUSED_CONTEXT;
2753 if (PerlIOValid(f)) {
2754 FILE * const s = PerlIOSelf(f, PerlIOStdio)->stdio;
2756 return PerlSIO_fileno(s);
2763 PerlIOStdio_mode(const char *mode, char *tmode)
2765 char * const ret = tmode;
2771 #if defined(PERLIO_USING_CRLF) || defined(__CYGWIN__)
2779 PerlIOStdio_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
2782 if (PerlIOValid(f) && PerlIOValid(n = PerlIONext(f))) {
2783 PerlIO_funcs * const toptab = PerlIOBase(n)->tab;
2784 if (toptab == tab) {
2785 /* Top is already stdio - pop self (duplicate) and use original */
2786 PerlIO_pop(aTHX_ f);
2789 const int fd = PerlIO_fileno(n);
2792 if (fd >= 0 && (stdio = PerlSIO_fdopen(fd,
2793 mode = PerlIOStdio_mode(mode, tmode)))) {
2794 PerlIOSelf(f, PerlIOStdio)->stdio = stdio;
2795 /* We never call down so do any pending stuff now */
2796 PerlIO_flush(PerlIONext(f));
2803 return PerlIOBase_pushed(aTHX_ f, mode, arg, tab);
2808 PerlIO_importFILE(FILE *stdio, const char *mode)
2814 if (!mode || !*mode) {
2815 /* We need to probe to see how we can open the stream
2816 so start with read/write and then try write and read
2817 we dup() so that we can fclose without loosing the fd.
2819 Note that the errno value set by a failing fdopen
2820 varies between stdio implementations.
2822 const int fd = PerlLIO_dup(fileno(stdio));
2823 FILE *f2 = PerlSIO_fdopen(fd, (mode = "r+"));
2825 f2 = PerlSIO_fdopen(fd, (mode = "w"));
2828 f2 = PerlSIO_fdopen(fd, (mode = "r"));
2831 /* Don't seem to be able to open */
2837 if ((f = PerlIO_push(aTHX_(f = PerlIO_allocate(aTHX)), PERLIO_FUNCS_CAST(&PerlIO_stdio), mode, NULL))) {
2838 s = PerlIOSelf(f, PerlIOStdio);
2846 PerlIOStdio_open(pTHX_ PerlIO_funcs *self, PerlIO_list_t *layers,
2847 IV n, const char *mode, int fd, int imode,
2848 int perm, PerlIO *f, int narg, SV **args)
2851 if (PerlIOValid(f)) {
2852 const char * const path = SvPV_nolen_const(*args);
2853 PerlIOStdio * const s = PerlIOSelf(f, PerlIOStdio);
2855 PerlIOUnix_refcnt_dec(fileno(s->stdio));
2856 stdio = PerlSIO_freopen(path, (mode = PerlIOStdio_mode(mode, tmode)),
2861 PerlIOUnix_refcnt_inc(fileno(s->stdio));
2866 const char * const path = SvPV_nolen_const(*args);
2867 if (*mode == IoTYPE_NUMERIC) {
2869 fd = PerlLIO_open3(path, imode, perm);
2873 bool appended = FALSE;
2875 /* Cygwin wants its 'b' early. */
2877 mode = PerlIOStdio_mode(mode, tmode);
2879 stdio = PerlSIO_fopen(path, mode);
2882 f = PerlIO_allocate(aTHX);
2885 mode = PerlIOStdio_mode(mode, tmode);
2886 f = PerlIO_push(aTHX_ f, self, mode, PerlIOArg);
2888 PerlIOSelf(f, PerlIOStdio)->stdio = stdio;
2889 PerlIOUnix_refcnt_inc(fileno(stdio));
2891 PerlSIO_fclose(stdio);
2903 if (*mode == IoTYPE_IMPLICIT) {
2910 stdio = PerlSIO_stdin;
2913 stdio = PerlSIO_stdout;
2916 stdio = PerlSIO_stderr;
2921 stdio = PerlSIO_fdopen(fd, mode =
2922 PerlIOStdio_mode(mode, tmode));
2926 f = PerlIO_allocate(aTHX);
2928 if ((f = PerlIO_push(aTHX_ f, self, mode, PerlIOArg))) {
2929 PerlIOSelf(f, PerlIOStdio)->stdio = stdio;
2930 PerlIOUnix_refcnt_inc(fileno(stdio));
2940 PerlIOStdio_dup(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags)
2942 /* This assumes no layers underneath - which is what
2943 happens, but is not how I remember it. NI-S 2001/10/16
2945 if ((f = PerlIOBase_dup(aTHX_ f, o, param, flags))) {
2946 FILE *stdio = PerlIOSelf(o, PerlIOStdio)->stdio;
2947 const int fd = fileno(stdio);
2949 if (flags & PERLIO_DUP_FD) {
2950 const int dfd = PerlLIO_dup(fileno(stdio));
2952 stdio = PerlSIO_fdopen(dfd, PerlIO_modestr(o,mode));
2957 /* FIXME: To avoid messy error recovery if dup fails
2958 re-use the existing stdio as though flag was not set
2962 stdio = PerlSIO_fdopen(fd, PerlIO_modestr(o,mode));
2964 PerlIOSelf(f, PerlIOStdio)->stdio = stdio;
2965 PerlIOUnix_refcnt_inc(fileno(stdio));
2971 PerlIOStdio_invalidate_fileno(pTHX_ FILE *f)
2973 PERL_UNUSED_CONTEXT;
2975 /* XXX this could use PerlIO_canset_fileno() and
2976 * PerlIO_set_fileno() support from Configure
2978 # if defined(__UCLIBC__)
2979 /* uClibc must come before glibc because it defines __GLIBC__ as well. */
2982 # elif defined(__GLIBC__)
2983 /* There may be a better way for GLIBC:
2984 - libio.h defines a flag to not close() on cleanup
2988 # elif defined(__sun__)
2990 # elif defined(__hpux)
2994 /* Next one ->_file seems to be a reasonable fallback, i.e. if
2995 your platform does not have special entry try this one.
2996 [For OSF only have confirmation for Tru64 (alpha)
2997 but assume other OSFs will be similar.]
2999 # elif defined(_AIX) || defined(__osf__) || defined(__irix__)
3002 # elif defined(__FreeBSD__)
3003 /* There may be a better way on FreeBSD:
3004 - we could insert a dummy func in the _close function entry
3005 f->_close = (int (*)(void *)) dummy_close;
3009 # elif defined(__OpenBSD__)
3010 /* There may be a better way on OpenBSD:
3011 - we could insert a dummy func in the _close function entry
3012 f->_close = (int (*)(void *)) dummy_close;
3016 # elif defined(__EMX__)
3017 /* f->_flags &= ~_IOOPEN; */ /* Will leak stream->_buffer */
3020 # elif defined(__CYGWIN__)
3021 /* There may be a better way on CYGWIN:
3022 - we could insert a dummy func in the _close function entry
3023 f->_close = (int (*)(void *)) dummy_close;
3027 # elif defined(WIN32)
3028 # if defined(__BORLANDC__)
3029 f->fd = PerlLIO_dup(fileno(f));
3030 # elif defined(UNDER_CE)
3031 /* WIN_CE does not have access to FILE internals, it hardly has FILE
3040 /* Sarathy's code did this - we fall back to a dup/dup2 hack
3041 (which isn't thread safe) instead
3043 # error "Don't know how to set FILE.fileno on your platform"
3051 PerlIOStdio_close(pTHX_ PerlIO *f)
3053 FILE * const stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3059 const int fd = fileno(stdio);
3064 #ifdef SOCKS5_VERSION_NAME
3065 /* Socks lib overrides close() but stdio isn't linked to
3066 that library (though we are) - so we must call close()
3067 on sockets on stdio's behalf.
3070 Sock_size_t optlen = sizeof(int);
3071 if (getsockopt(fd, SOL_SOCKET, SO_TYPE, (void *) &optval, &optlen) == 0)
3074 if (PerlIOUnix_refcnt_dec(fd) > 0) /* File descriptor still in use */
3077 /* For STD* handles, don't close stdio, since we shared the FILE *, too. */
3078 if (stdio == stdin) /* Some stdios are buggy fflush-ing inputs */
3080 if (stdio == stdout || stdio == stderr)
3081 return PerlIO_flush(f);
3082 /* Tricky - must fclose(stdio) to free memory but not close(fd)
3083 Use Sarathy's trick from maint-5.6 to invalidate the
3084 fileno slot of the FILE *
3086 result = PerlIO_flush(f);
3088 invalidate = PerlIOStdio_invalidate_fileno(aTHX_ stdio);
3090 dupfd = PerlLIO_dup(fd);
3092 result = PerlSIO_fclose(stdio);
3093 /* We treat error from stdio as success if we invalidated
3094 errno may NOT be expected EBADF
3096 if (invalidate && result != 0) {
3100 #ifdef SOCKS5_VERSION_NAME
3101 /* in SOCKS' case, let close() determine return value */
3105 PerlLIO_dup2(dupfd,fd);
3106 PerlLIO_close(dupfd);
3113 PerlIOStdio_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
3116 FILE * const s = PerlIOSelf(f, PerlIOStdio)->stdio;
3120 STDCHAR *buf = (STDCHAR *) vbuf;
3122 * Perl is expecting PerlIO_getc() to fill the buffer Linux's
3123 * stdio does not do that for fread()
3125 const int ch = PerlSIO_fgetc(s);
3132 got = PerlSIO_fread(vbuf, 1, count, s);
3133 if (got == 0 && PerlSIO_ferror(s))
3135 if (got >= 0 || errno != EINTR)
3138 SETERRNO(0,0); /* just in case */
3144 PerlIOStdio_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
3147 FILE * const s = PerlIOSelf(f, PerlIOStdio)->stdio;
3149 #ifdef STDIO_BUFFER_WRITABLE
3150 if (PerlIO_fast_gets(f) && PerlIO_has_base(f)) {
3151 STDCHAR *buf = ((STDCHAR *) vbuf) + count;
3152 STDCHAR *base = PerlIO_get_base(f);
3153 SSize_t cnt = PerlIO_get_cnt(f);
3154 STDCHAR *ptr = PerlIO_get_ptr(f);
3155 SSize_t avail = ptr - base;
3157 if (avail > count) {
3161 Move(buf-avail,ptr,avail,STDCHAR);
3164 PerlIO_set_ptrcnt(f,ptr,cnt+avail);
3165 if (PerlSIO_feof(s) && unread >= 0)
3166 PerlSIO_clearerr(s);
3171 if (PerlIO_has_cntptr(f)) {
3172 /* We can get pointer to buffer but not its base
3173 Do ungetc() but check chars are ending up in the
3176 STDCHAR *eptr = (STDCHAR*)PerlSIO_get_ptr(s);
3177 STDCHAR *buf = ((STDCHAR *) vbuf) + count;
3179 const int ch = *--buf & 0xFF;
3180 if (ungetc(ch,s) != ch) {
3181 /* ungetc did not work */
3184 if ((STDCHAR*)PerlSIO_get_ptr(s) != --eptr || ((*eptr & 0xFF) != ch)) {
3185 /* Did not change pointer as expected */
3186 fgetc(s); /* get char back again */
3196 unread += PerlIOBase_unread(aTHX_ f, vbuf, count);
3202 PerlIOStdio_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
3207 got = PerlSIO_fwrite(vbuf, 1, count,
3208 PerlIOSelf(f, PerlIOStdio)->stdio);
3209 if (got >= 0 || errno != EINTR)
3212 SETERRNO(0,0); /* just in case */
3218 PerlIOStdio_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
3220 FILE * const stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3221 PERL_UNUSED_CONTEXT;
3223 return PerlSIO_fseek(stdio, offset, whence);
3227 PerlIOStdio_tell(pTHX_ PerlIO *f)
3229 FILE * const stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3230 PERL_UNUSED_CONTEXT;
3232 return PerlSIO_ftell(stdio);
3236 PerlIOStdio_flush(pTHX_ PerlIO *f)
3238 FILE * const stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3239 PERL_UNUSED_CONTEXT;
3241 if (PerlIOBase(f)->flags & PERLIO_F_CANWRITE) {
3242 return PerlSIO_fflush(stdio);
3248 * FIXME: This discards ungetc() and pre-read stuff which is not
3249 * right if this is just a "sync" from a layer above Suspect right
3250 * design is to do _this_ but not have layer above flush this
3251 * layer read-to-read
3254 * Not writeable - sync by attempting a seek
3256 const int err = errno;
3257 if (PerlSIO_fseek(stdio, (Off_t) 0, SEEK_CUR) != 0)
3265 PerlIOStdio_eof(pTHX_ PerlIO *f)
3267 PERL_UNUSED_CONTEXT;
3269 return PerlSIO_feof(PerlIOSelf(f, PerlIOStdio)->stdio);
3273 PerlIOStdio_error(pTHX_ PerlIO *f)
3275 PERL_UNUSED_CONTEXT;
3277 return PerlSIO_ferror(PerlIOSelf(f, PerlIOStdio)->stdio);
3281 PerlIOStdio_clearerr(pTHX_ PerlIO *f)
3283 PERL_UNUSED_CONTEXT;
3285 PerlSIO_clearerr(PerlIOSelf(f, PerlIOStdio)->stdio);
3289 PerlIOStdio_setlinebuf(pTHX_ PerlIO *f)
3291 PERL_UNUSED_CONTEXT;
3293 #ifdef HAS_SETLINEBUF
3294 PerlSIO_setlinebuf(PerlIOSelf(f, PerlIOStdio)->stdio);
3296 PerlSIO_setvbuf(PerlIOSelf(f, PerlIOStdio)->stdio, NULL, _IOLBF, 0);
3302 PerlIOStdio_get_base(pTHX_ PerlIO *f)
3304 FILE * const stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3305 return (STDCHAR*)PerlSIO_get_base(stdio);
3309 PerlIOStdio_get_bufsiz(pTHX_ PerlIO *f)
3311 FILE * const stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3312 return PerlSIO_get_bufsiz(stdio);
3316 #ifdef USE_STDIO_PTR
3318 PerlIOStdio_get_ptr(pTHX_ PerlIO *f)
3320 FILE * const stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3321 return (STDCHAR*)PerlSIO_get_ptr(stdio);
3325 PerlIOStdio_get_cnt(pTHX_ PerlIO *f)
3327 FILE * const stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3328 return PerlSIO_get_cnt(stdio);
3332 PerlIOStdio_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, SSize_t cnt)
3334 FILE * const stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3336 #ifdef STDIO_PTR_LVALUE
3337 PerlSIO_set_ptr(stdio, (void*)ptr); /* LHS STDCHAR* cast non-portable */
3338 #ifdef STDIO_PTR_LVAL_SETS_CNT
3339 if (PerlSIO_get_cnt(stdio) != (cnt)) {
3340 assert(PerlSIO_get_cnt(stdio) == (cnt));
3343 #if (!defined(STDIO_PTR_LVAL_NOCHANGE_CNT))
3345 * Setting ptr _does_ change cnt - we are done
3349 #else /* STDIO_PTR_LVALUE */
3351 #endif /* STDIO_PTR_LVALUE */
3354 * Now (or only) set cnt
3356 #ifdef STDIO_CNT_LVALUE
3357 PerlSIO_set_cnt(stdio, cnt);
3358 #else /* STDIO_CNT_LVALUE */
3359 #if (defined(STDIO_PTR_LVALUE) && defined(STDIO_PTR_LVAL_SETS_CNT))
3360 PerlSIO_set_ptr(stdio,
3361 PerlSIO_get_ptr(stdio) + (PerlSIO_get_cnt(stdio) -
3363 #else /* STDIO_PTR_LVAL_SETS_CNT */
3365 #endif /* STDIO_PTR_LVAL_SETS_CNT */
3366 #endif /* STDIO_CNT_LVALUE */
3373 PerlIOStdio_fill(pTHX_ PerlIO *f)
3375 FILE * const stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3377 PERL_UNUSED_CONTEXT;
3380 * fflush()ing read-only streams can cause trouble on some stdio-s
3382 if ((PerlIOBase(f)->flags & PERLIO_F_CANWRITE)) {
3383 if (PerlSIO_fflush(stdio) != 0)
3386 c = PerlSIO_fgetc(stdio);
3390 #if (defined(STDIO_PTR_LVALUE) && (defined(STDIO_CNT_LVALUE) || defined(STDIO_PTR_LVAL_SETS_CNT)))
3392 #ifdef STDIO_BUFFER_WRITABLE
3393 if (PerlIO_fast_gets(f) && PerlIO_has_base(f)) {
3394 /* Fake ungetc() to the real buffer in case system's ungetc
3397 STDCHAR *base = (STDCHAR*)PerlSIO_get_base(stdio);
3398 SSize_t cnt = PerlSIO_get_cnt(stdio);
3399 STDCHAR *ptr = (STDCHAR*)PerlSIO_get_ptr(stdio);
3400 if (ptr == base+1) {
3401 *--ptr = (STDCHAR) c;
3402 PerlIOStdio_set_ptrcnt(aTHX_ f,ptr,cnt+1);
3403 if (PerlSIO_feof(stdio))
3404 PerlSIO_clearerr(stdio);
3410 if (PerlIO_has_cntptr(f)) {
3412 if (PerlIOStdio_unread(aTHX_ f,&ch,1) == 1) {
3419 /* An ungetc()d char is handled separately from the regular
3420 * buffer, so we stuff it in the buffer ourselves.
3421 * Should never get called as should hit code above
3423 *(--((*stdio)->_ptr)) = (unsigned char) c;
3426 /* If buffer snoop scheme above fails fall back to
3429 if (PerlSIO_ungetc(c, stdio) != c)
3437 PERLIO_FUNCS_DECL(PerlIO_stdio) = {
3438 sizeof(PerlIO_funcs),
3440 sizeof(PerlIOStdio),
3441 PERLIO_K_BUFFERED|PERLIO_K_RAW,
3445 PerlIOBase_binmode, /* binmode */
3459 PerlIOStdio_clearerr,
3460 PerlIOStdio_setlinebuf,
3462 PerlIOStdio_get_base,
3463 PerlIOStdio_get_bufsiz,
3468 #ifdef USE_STDIO_PTR
3469 PerlIOStdio_get_ptr,
3470 PerlIOStdio_get_cnt,
3471 # if defined(HAS_FAST_STDIO) && defined(USE_FAST_STDIO)
3472 PerlIOStdio_set_ptrcnt,
3475 # endif /* HAS_FAST_STDIO && USE_FAST_STDIO */
3480 #endif /* USE_STDIO_PTR */
3483 /* Note that calls to PerlIO_exportFILE() are reversed using
3484 * PerlIO_releaseFILE(), not importFILE. */
3486 PerlIO_exportFILE(PerlIO * f, const char *mode)
3490 if (PerlIOValid(f)) {
3493 if (!mode || !*mode) {
3494 mode = PerlIO_modestr(f, buf);
3496 stdio = PerlSIO_fdopen(PerlIO_fileno(f), mode);
3500 /* De-link any lower layers so new :stdio sticks */
3502 if ((f2 = PerlIO_push(aTHX_ f, PERLIO_FUNCS_CAST(&PerlIO_stdio), buf, NULL))) {
3503 PerlIOStdio *s = PerlIOSelf((f = f2), PerlIOStdio);
3505 /* Link previous lower layers under new one */
3509 /* restore layers list */
3519 PerlIO_findFILE(PerlIO *f)
3523 if (l->tab == &PerlIO_stdio) {
3524 PerlIOStdio *s = PerlIOSelf(&l, PerlIOStdio);
3527 l = *PerlIONext(&l);
3529 /* Uses fallback "mode" via PerlIO_modestr() in PerlIO_exportFILE */
3530 return PerlIO_exportFILE(f, NULL);
3533 /* Use this to reverse PerlIO_exportFILE calls. */
3535 PerlIO_releaseFILE(PerlIO *p, FILE *f)
3540 if (l->tab == &PerlIO_stdio) {
3541 PerlIOStdio *s = PerlIOSelf(&l, PerlIOStdio);
3542 if (s->stdio == f) {
3544 PerlIO_pop(aTHX_ p);
3553 /*--------------------------------------------------------------------------------------*/
3555 * perlio buffer layer
3559 PerlIOBuf_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
3561 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3562 const int fd = PerlIO_fileno(f);
3563 if (fd >= 0 && PerlLIO_isatty(fd)) {
3564 PerlIOBase(f)->flags |= PERLIO_F_LINEBUF | PERLIO_F_TTY;
3566 if (*PerlIONext(f)) {
3567 const Off_t posn = PerlIO_tell(PerlIONext(f));
3568 if (posn != (Off_t) - 1) {
3572 return PerlIOBase_pushed(aTHX_ f, mode, arg, tab);
3576 PerlIOBuf_open(pTHX_ PerlIO_funcs *self, PerlIO_list_t *layers,
3577 IV n, const char *mode, int fd, int imode, int perm,
3578 PerlIO *f, int narg, SV **args)
3580 if (PerlIOValid(f)) {
3581 PerlIO *next = PerlIONext(f);
3583 PerlIO_layer_fetch(aTHX_ layers, n - 1, PerlIOBase(next)->tab);
3584 if (tab && tab->Open)
3586 (*tab->Open)(aTHX_ tab, layers, n - 1, mode, fd, imode, perm,
3588 if (!next || (*PerlIOBase(f)->tab->Pushed) (aTHX_ f, mode, PerlIOArg, self) != 0) {
3593 PerlIO_funcs *tab = PerlIO_layer_fetch(aTHX_ layers, n - 1, PerlIO_default_btm());
3595 if (*mode == IoTYPE_IMPLICIT) {
3601 if (tab && tab->Open)
3602 f = (*tab->Open)(aTHX_ tab, layers, n - 1, mode, fd, imode, perm,
3605 SETERRNO(EINVAL, LIB_INVARG);
3607 if (PerlIO_push(aTHX_ f, self, mode, PerlIOArg) == 0) {
3609 * if push fails during open, open fails. close will pop us.
3614 fd = PerlIO_fileno(f);
3615 if (init && fd == 2) {
3617 * Initial stderr is unbuffered
3619 PerlIOBase(f)->flags |= PERLIO_F_UNBUF;
3621 #ifdef PERLIO_USING_CRLF
3622 # ifdef PERLIO_IS_BINMODE_FD
3623 if (PERLIO_IS_BINMODE_FD(fd))
3624 PerlIO_binmode(aTHX_ f, '<'/*not used*/, O_BINARY, NULL);
3628 * do something about failing setmode()? --jhi
3630 PerlLIO_setmode(fd, O_BINARY);
3639 * This "flush" is akin to sfio's sync in that it handles files in either
3640 * read or write state. For write state, we put the postponed data through
3641 * the next layers. For read state, we seek() the next layers to the
3642 * offset given by current position in the buffer, and discard the buffer
3643 * state (XXXX supposed to be for seek()able buffers only, but now it is done
3644 * in any case?). Then the pass the stick further in chain.
3647 PerlIOBuf_flush(pTHX_ PerlIO *f)
3649 PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
3651 PerlIO *n = PerlIONext(f);
3652 if (PerlIOBase(f)->flags & PERLIO_F_WRBUF) {
3654 * write() the buffer
3656 const STDCHAR *buf = b->buf;
3657 const STDCHAR *p = buf;
3658 while (p < b->ptr) {
3659 SSize_t count = PerlIO_write(n, p, b->ptr - p);
3663 else if (count < 0 || PerlIO_error(n)) {
3664 PerlIOBase(f)->flags |= PERLIO_F_ERROR;
3669 b->posn += (p - buf);
3671 else if (PerlIOBase(f)->flags & PERLIO_F_RDBUF) {
3672 STDCHAR *buf = PerlIO_get_base(f);
3674 * Note position change
3676 b->posn += (b->ptr - buf);
3677 if (b->ptr < b->end) {
3678 /* We did not consume all of it - try and seek downstream to
3679 our logical position
3681 if (PerlIOValid(n) && PerlIO_seek(n, b->posn, SEEK_SET) == 0) {
3682 /* Reload n as some layers may pop themselves on seek */
3683 b->posn = PerlIO_tell(n = PerlIONext(f));
3686 /* Seek failed (e.g. pipe or tty). Do NOT clear buffer or pre-read
3687 data is lost for good - so return saying "ok" having undone
3690 b->posn -= (b->ptr - buf);
3695 b->ptr = b->end = b->buf;
3696 PerlIOBase(f)->flags &= ~(PERLIO_F_RDBUF | PERLIO_F_WRBUF);
3697 /* We check for Valid because of dubious decision to make PerlIO_flush(NULL) flush all */
3698 if (PerlIOValid(n) && PerlIO_flush(n) != 0)
3703 /* This discards the content of the buffer after b->ptr, and rereads
3704 * the buffer from the position off in the layer downstream; here off
3705 * is at offset corresponding to b->ptr - b->buf.
3708 PerlIOBuf_fill(pTHX_ PerlIO *f)
3710 PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
3711 PerlIO *n = PerlIONext(f);
3714 * Down-stream flush is defined not to loose read data so is harmless.
3715 * we would not normally be fill'ing if there was data left in anycase.
3717 if (PerlIO_flush(f) != 0) /* XXXX Check that its seek() succeeded?! */
3719 if (PerlIOBase(f)->flags & PERLIO_F_TTY)
3720 PerlIOBase_flush_linebuf(aTHX);
3723 PerlIO_get_base(f); /* allocate via vtable */
3725 assert(b->buf); /* The b->buf does get allocated via the vtable system. */
3727 b->ptr = b->end = b->buf;
3729 if (!PerlIOValid(n)) {
3730 PerlIOBase(f)->flags |= PERLIO_F_EOF;
3734 if (PerlIO_fast_gets(n)) {
3736 * Layer below is also buffered. We do _NOT_ want to call its
3737 * ->Read() because that will loop till it gets what we asked for
3738 * which may hang on a pipe etc. Instead take anything it has to
3739 * hand, or ask it to fill _once_.
3741 avail = PerlIO_get_cnt(n);
3743 avail = PerlIO_fill(n);
3745 avail = PerlIO_get_cnt(n);
3747 if (!PerlIO_error(n) && PerlIO_eof(n))
3752 STDCHAR *ptr = PerlIO_get_ptr(n);
3753 const SSize_t cnt = avail;
3754 if (avail > (SSize_t)b->bufsiz)
3756 Copy(ptr, b->buf, avail, STDCHAR);
3757 PerlIO_set_ptrcnt(n, ptr + avail, cnt - avail);
3761 avail = PerlIO_read(n, b->ptr, b->bufsiz);
3765 PerlIOBase(f)->flags |= PERLIO_F_EOF;
3767 PerlIOBase(f)->flags |= PERLIO_F_ERROR;
3770 b->end = b->buf + avail;
3771 PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
3776 PerlIOBuf_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
3778 if (PerlIOValid(f)) {
3779 const PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
3782 return PerlIOBase_read(aTHX_ f, vbuf, count);
3788 PerlIOBuf_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
3790 const STDCHAR *buf = (const STDCHAR *) vbuf + count;
3791 PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
3794 if (PerlIOBase(f)->flags & PERLIO_F_WRBUF)
3799 if (PerlIOBase(f)->flags & PERLIO_F_RDBUF) {
3801 * Buffer is already a read buffer, we can overwrite any chars
3802 * which have been read back to buffer start
3804 avail = (b->ptr - b->buf);
3808 * Buffer is idle, set it up so whole buffer is available for
3812 b->end = b->buf + avail;
3814 PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
3816 * Buffer extends _back_ from where we are now
3818 b->posn -= b->bufsiz;
3820 if (avail > (SSize_t) count) {
3822 * If we have space for more than count, just move count
3830 * In simple stdio-like ungetc() case chars will be already
3833 if (buf != b->ptr) {
3834 Copy(buf, b->ptr, avail, STDCHAR);
3838 PerlIOBase(f)->flags &= ~PERLIO_F_EOF;
3842 unread += PerlIOBase_unread(aTHX_ f, vbuf, count);
3848 PerlIOBuf_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
3850 PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
3851 const STDCHAR *buf = (const STDCHAR *) vbuf;
3852 const STDCHAR *flushptr = buf;
3856 if (!(PerlIOBase(f)->flags & PERLIO_F_CANWRITE))
3858 if (PerlIOBase(f)->flags & PERLIO_F_RDBUF) {
3859 if (PerlIO_flush(f) != 0) {
3863 if (PerlIOBase(f)->flags & PERLIO_F_LINEBUF) {
3864 flushptr = buf + count;
3865 while (flushptr > buf && *(flushptr - 1) != '\n')
3869 SSize_t avail = b->bufsiz - (b->ptr - b->buf);
3870 if ((SSize_t) count < avail)
3872 if (flushptr > buf && flushptr <= buf + avail)
3873 avail = flushptr - buf;
3874 PerlIOBase(f)->flags |= PERLIO_F_WRBUF;
3876 Copy(buf, b->ptr, avail, STDCHAR);
3881 if (buf == flushptr)
3884 if (b->ptr >= (b->buf + b->bufsiz))
3887 if (PerlIOBase(f)->flags & PERLIO_F_UNBUF)
3893 PerlIOBuf_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
3896 if ((code = PerlIO_flush(f)) == 0) {
3897 PerlIOBase(f)->flags &= ~PERLIO_F_EOF;
3898 code = PerlIO_seek(PerlIONext(f), offset, whence);
3900 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3901 b->posn = PerlIO_tell(PerlIONext(f));
3908 PerlIOBuf_tell(pTHX_ PerlIO *f)
3910 PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
3912 * b->posn is file position where b->buf was read, or will be written
3914 Off_t posn = b->posn;
3915 if ((PerlIOBase(f)->flags & PERLIO_F_APPEND) &&
3916 (PerlIOBase(f)->flags & PERLIO_F_WRBUF)) {
3918 /* As O_APPEND files are normally shared in some sense it is better
3923 /* when file is NOT shared then this is sufficient */
3924 PerlIO_seek(PerlIONext(f),0, SEEK_END);
3926 posn = b->posn = PerlIO_tell(PerlIONext(f));
3930 * If buffer is valid adjust position by amount in buffer
3932 posn += (b->ptr - b->buf);
3938 PerlIOBuf_popped(pTHX_ PerlIO *f)
3940 const IV code = PerlIOBase_popped(aTHX_ f);
3941 PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
3942 if (b->buf && b->buf != (STDCHAR *) & b->oneword) {
3945 b->ptr = b->end = b->buf = NULL;
3946 PerlIOBase(f)->flags &= ~(PERLIO_F_RDBUF | PERLIO_F_WRBUF);
3951 PerlIOBuf_close(pTHX_ PerlIO *f)
3953 const IV code = PerlIOBase_close(aTHX_ f);
3954 PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
3955 if (b->buf && b->buf != (STDCHAR *) & b->oneword) {
3958 b->ptr = b->end = b->buf = NULL;
3959 PerlIOBase(f)->flags &= ~(PERLIO_F_RDBUF | PERLIO_F_WRBUF);
3964 PerlIOBuf_get_ptr(pTHX_ PerlIO *f)
3966 const PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
3973 PerlIOBuf_get_cnt(pTHX_ PerlIO *f)
3975 const PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
3978 if (PerlIOBase(f)->flags & PERLIO_F_RDBUF)
3979 return (b->end - b->ptr);
3984 PerlIOBuf_get_base(pTHX_ PerlIO *f)
3986 PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
3987 PERL_UNUSED_CONTEXT;
3992 b->buf = Newxz(b->buf,b->bufsiz, STDCHAR);
3994 b->buf = (STDCHAR *) & b->oneword;
3995 b->bufsiz = sizeof(b->oneword);
3997 b->end = b->ptr = b->buf;
4003 PerlIOBuf_bufsiz(pTHX_ PerlIO *f)
4005 const PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
4008 return (b->end - b->buf);
4012 PerlIOBuf_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, SSize_t cnt)
4014 PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
4018 if (PerlIO_get_cnt(f) != cnt || b->ptr < b->buf) {
4019 assert(PerlIO_get_cnt(f) == cnt);
4020 assert(b->ptr >= b->buf);
4022 PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
4026 PerlIOBuf_dup(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags)
4028 return PerlIOBase_dup(aTHX_ f, o, param, flags);
4033 PERLIO_FUNCS_DECL(PerlIO_perlio) = {
4034 sizeof(PerlIO_funcs),
4037 PERLIO_K_BUFFERED|PERLIO_K_RAW,
4041 PerlIOBase_binmode, /* binmode */
4055 PerlIOBase_clearerr,
4056 PerlIOBase_setlinebuf,
4061 PerlIOBuf_set_ptrcnt,
4064 /*--------------------------------------------------------------------------------------*/
4066 * Temp layer to hold unread chars when cannot do it any other way
4070 PerlIOPending_fill(pTHX_ PerlIO *f)
4073 * Should never happen
4080 PerlIOPending_close(pTHX_ PerlIO *f)
4083 * A tad tricky - flush pops us, then we close new top
4086 return PerlIO_close(f);
4090 PerlIOPending_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
4093 * A tad tricky - flush pops us, then we seek new top
4096 return PerlIO_seek(f, offset, whence);
4101 PerlIOPending_flush(pTHX_ PerlIO *f)
4103 PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
4104 if (b->buf && b->buf != (STDCHAR *) & b->oneword) {
4108 PerlIO_pop(aTHX_ f);
4113 PerlIOPending_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, SSize_t cnt)
4119 PerlIOBuf_set_ptrcnt(aTHX_ f, ptr, cnt);
4124 PerlIOPending_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
4126 const IV code = PerlIOBase_pushed(aTHX_ f, mode, arg, tab);
4127 PerlIOl * const l = PerlIOBase(f);
4129 * Our PerlIO_fast_gets must match what we are pushed on, or sv_gets()
4130 * etc. get muddled when it changes mid-string when we auto-pop.
4132 l->flags = (l->flags & ~(PERLIO_F_FASTGETS | PERLIO_F_UTF8)) |
4133 (PerlIOBase(PerlIONext(f))->
4134 flags & (PERLIO_F_FASTGETS | PERLIO_F_UTF8));
4139 PerlIOPending_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
4141 SSize_t avail = PerlIO_get_cnt(f);
4143 if ((SSize_t)count < avail)
4146 got = PerlIOBuf_read(aTHX_ f, vbuf, avail);
4147 if (got >= 0 && got < (SSize_t)count) {
4148 const SSize_t more =
4149 PerlIO_read(f, ((STDCHAR *) vbuf) + got, count - got);
4150 if (more >= 0 || got == 0)
4156 PERLIO_FUNCS_DECL(PerlIO_pending) = {
4157 sizeof(PerlIO_funcs),
4160 PERLIO_K_BUFFERED|PERLIO_K_RAW, /* not sure about RAW here */
4161 PerlIOPending_pushed,
4164 PerlIOBase_binmode, /* binmode */
4173 PerlIOPending_close,
4174 PerlIOPending_flush,
4178 PerlIOBase_clearerr,
4179 PerlIOBase_setlinebuf,
4184 PerlIOPending_set_ptrcnt,
4189 /*--------------------------------------------------------------------------------------*/
4191 * crlf - translation On read translate CR,LF to "\n" we do this by
4192 * overriding ptr/cnt entries to hand back a line at a time and keeping a
4193 * record of which nl we "lied" about. On write translate "\n" to CR,LF
4195 * c->nl points on the first byte of CR LF pair when it is temporarily
4196 * replaced by LF, or to the last CR of the buffer. In the former case
4197 * the caller thinks that the buffer ends at c->nl + 1, in the latter
4198 * that it ends at c->nl; these two cases can be distinguished by
4199 * *c->nl. c->nl is set during _getcnt() call, and unset during
4200 * _unread() and _flush() calls.
4201 * It only matters for read operations.
4205 PerlIOBuf base; /* PerlIOBuf stuff */
4206 STDCHAR *nl; /* Position of crlf we "lied" about in the
4211 PerlIOCrlf_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
4214 PerlIOBase(f)->flags |= PERLIO_F_CRLF;
4215 code = PerlIOBuf_pushed(aTHX_ f, mode, arg, tab);
4217 PerlIO_debug("PerlIOCrlf_pushed f=%p %s %s fl=%08" UVxf "\n",
4218 f, PerlIOBase(f)->tab->name, (mode) ? mode : "(Null)",
4219 PerlIOBase(f)->flags);
4222 /* Enable the first CRLF capable layer you can find, but if none
4223 * found, the one we just pushed is fine. This results in at
4224 * any given moment at most one CRLF-capable layer being enabled
4225 * in the whole layer stack. */
4226 PerlIO *g = PerlIONext(f);
4228 PerlIOl *b = PerlIOBase(g);
4229 if (b && b->tab == &PerlIO_crlf) {
4230 if (!(b->flags & PERLIO_F_CRLF))
4231 b->flags |= PERLIO_F_CRLF;
4232 PerlIO_pop(aTHX_ f);
4243 PerlIOCrlf_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
4245 PerlIOCrlf * const c = PerlIOSelf(f, PerlIOCrlf);
4246 if (c->nl) { /* XXXX Shouldn't it be done only if b->ptr > c->nl? */
4250 if (!(PerlIOBase(f)->flags & PERLIO_F_CRLF))
4251 return PerlIOBuf_unread(aTHX_ f, vbuf, count);
4253 const STDCHAR *buf = (const STDCHAR *) vbuf + count;
4254 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
4256 if (PerlIOBase(f)->flags & PERLIO_F_WRBUF)
4261 if (!(PerlIOBase(f)->flags & PERLIO_F_RDBUF)) {
4262 b->end = b->ptr = b->buf + b->bufsiz;
4263 PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
4264 b->posn -= b->bufsiz;
4266 while (count > 0 && b->ptr > b->buf) {
4267 const int ch = *--buf;
4269 if (b->ptr - 2 >= b->buf) {
4276 /* If b->ptr - 1 == b->buf, we are undoing reading 0xa */
4277 *--(b->ptr) = 0xa; /* Works even if 0xa == '\r' */
4293 /* XXXX This code assumes that buffer size >=2, but does not check it... */
4295 PerlIOCrlf_get_cnt(pTHX_ PerlIO *f)
4297 PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
4300 if (PerlIOBase(f)->flags & PERLIO_F_RDBUF) {
4301 PerlIOCrlf * const c = PerlIOSelf(f, PerlIOCrlf);
4302 if ((PerlIOBase(f)->flags & PERLIO_F_CRLF) && (!c->nl || *c->nl == 0xd)) {
4303 STDCHAR *nl = (c->nl) ? c->nl : b->ptr;
4305 while (nl < b->end && *nl != 0xd)
4307 if (nl < b->end && *nl == 0xd) {
4309 if (nl + 1 < b->end) {
4316 * Not CR,LF but just CR
4324 * Blast - found CR as last char in buffer
4329 * They may not care, defer work as long as
4333 return (nl - b->ptr);
4337 b->ptr++; /* say we have read it as far as
4338 * flush() is concerned */
4339 b->buf++; /* Leave space in front of buffer */
4340 /* Note as we have moved buf up flush's
4342 will naturally make posn point at CR
4344 b->bufsiz--; /* Buffer is thus smaller */
4345 code = PerlIO_fill(f); /* Fetch some more */
4346 b->bufsiz++; /* Restore size for next time */
4347 b->buf--; /* Point at space */
4348 b->ptr = nl = b->buf; /* Which is what we hand
4350 *nl = 0xd; /* Fill in the CR */
4352 goto test; /* fill() call worked */
4354 * CR at EOF - just fall through
4356 /* Should we clear EOF though ??? */
4361 return (((c->nl) ? (c->nl + 1) : b->end) - b->ptr);
4367 PerlIOCrlf_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, SSize_t cnt)
4369 PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
4370 PerlIOCrlf * const c = PerlIOSelf(f, PerlIOCrlf);
4376 if (ptr == b->end && *c->nl == 0xd) {
4377 /* Defered CR at end of buffer case - we lied about count */
4390 * Test code - delete when it works ...
4392 IV flags = PerlIOBase(f)->flags;
4393 STDCHAR *chk = (c->nl) ? (c->nl+1) : b->end;
4394 if (ptr+cnt == c->nl && c->nl+1 == b->end && *c->nl == 0xd) {
4395 /* Defered CR at end of buffer case - we lied about count */
4401 Perl_croak(aTHX_ "ptr wrong %p != %p fl=%08" UVxf
4402 " nl=%p e=%p for %d", ptr, chk, flags, c->nl,
4410 * They have taken what we lied about
4418 PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
4422 PerlIOCrlf_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
4424 if (!(PerlIOBase(f)->flags & PERLIO_F_CRLF))
4425 return PerlIOBuf_write(aTHX_ f, vbuf, count);
4427 PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
4428 const STDCHAR *buf = (const STDCHAR *) vbuf;
4429 const STDCHAR * const ebuf = buf + count;
4432 if (!(PerlIOBase(f)->flags & PERLIO_F_CANWRITE))
4434 while (buf < ebuf) {
4435 const STDCHAR * const eptr = b->buf + b->bufsiz;
4436 PerlIOBase(f)->flags |= PERLIO_F_WRBUF;
4437 while (buf < ebuf && b->ptr < eptr) {
4439 if ((b->ptr + 2) > eptr) {
4447 *(b->ptr)++ = 0xd; /* CR */
4448 *(b->ptr)++ = 0xa; /* LF */
4450 if (PerlIOBase(f)->flags & PERLIO_F_LINEBUF) {
4457 *(b->ptr)++ = *buf++;
4459 if (b->ptr >= eptr) {
4465 if (PerlIOBase(f)->flags & PERLIO_F_UNBUF)
4467 return (buf - (STDCHAR *) vbuf);
4472 PerlIOCrlf_flush(pTHX_ PerlIO *f)
4474 PerlIOCrlf * const c = PerlIOSelf(f, PerlIOCrlf);
4479 return PerlIOBuf_flush(aTHX_ f);
4483 PerlIOCrlf_binmode(pTHX_ PerlIO *f)
4485 if ((PerlIOBase(f)->flags & PERLIO_F_CRLF)) {
4486 /* In text mode - flush any pending stuff and flip it */
4487 PerlIOBase(f)->flags &= ~PERLIO_F_CRLF;
4488 #ifndef PERLIO_USING_CRLF
4489 /* CRLF is unusual case - if this is just the :crlf layer pop it */
4490 if (PerlIOBase(f)->tab == &PerlIO_crlf) {
4491 PerlIO_pop(aTHX_ f);
4498 PERLIO_FUNCS_DECL(PerlIO_crlf) = {
4499 sizeof(PerlIO_funcs),
4502 PERLIO_K_BUFFERED | PERLIO_K_CANCRLF | PERLIO_K_RAW,
4504 PerlIOBuf_popped, /* popped */
4506 PerlIOCrlf_binmode, /* binmode */
4510 PerlIOBuf_read, /* generic read works with ptr/cnt lies */
4511 PerlIOCrlf_unread, /* Put CR,LF in buffer for each '\n' */
4512 PerlIOCrlf_write, /* Put CR,LF in buffer for each '\n' */
4520 PerlIOBase_clearerr,
4521 PerlIOBase_setlinebuf,
4526 PerlIOCrlf_set_ptrcnt,
4530 /*--------------------------------------------------------------------------------------*/
4532 * mmap as "buffer" layer
4536 PerlIOBuf base; /* PerlIOBuf stuff */
4537 Mmap_t mptr; /* Mapped address */
4538 Size_t len; /* mapped length */
4539 STDCHAR *bbuf; /* malloced buffer if map fails */
4543 PerlIOMmap_map(pTHX_ PerlIO *f)
4546 PerlIOMmap * const m = PerlIOSelf(f, PerlIOMmap);
4547 const IV flags = PerlIOBase(f)->flags;
4551 if (flags & PERLIO_F_CANREAD) {
4552 PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
4553 const int fd = PerlIO_fileno(f);
4555 code = Fstat(fd, &st);
4556 if (code == 0 && S_ISREG(st.st_mode)) {
4557 SSize_t len = st.st_size - b->posn;
4560 if (PL_mmap_page_size <= 0)
4561 Perl_croak(aTHX_ "panic: bad pagesize %" IVdf,
4565 * This is a hack - should never happen - open should
4568 b->posn = PerlIO_tell(PerlIONext(f));
4570 posn = (b->posn / PL_mmap_page_size) * PL_mmap_page_size;
4571 len = st.st_size - posn;
4572 m->mptr = mmap(NULL, len, PROT_READ, MAP_SHARED, fd, posn);
4573 if (m->mptr && m->mptr != (Mmap_t) - 1) {
4574 #if 0 && defined(HAS_MADVISE) && defined(MADV_SEQUENTIAL)
4575 madvise(m->mptr, len, MADV_SEQUENTIAL);
4577 #if 0 && defined(HAS_MADVISE) && defined(MADV_WILLNEED)
4578 madvise(m->mptr, len, MADV_WILLNEED);
4580 PerlIOBase(f)->flags =
4581 (flags & ~PERLIO_F_EOF) | PERLIO_F_RDBUF;
4582 b->end = ((STDCHAR *) m->mptr) + len;
4583 b->buf = ((STDCHAR *) m->mptr) + (b->posn - posn);
4592 PerlIOBase(f)->flags =
4593 flags | PERLIO_F_EOF | PERLIO_F_RDBUF;
4595 b->ptr = b->end = b->ptr;
4604 PerlIOMmap_unmap(pTHX_ PerlIO *f)
4606 PerlIOMmap * const m = PerlIOSelf(f, PerlIOMmap);
4609 PerlIOBuf * const b = &m->base;
4611 code = munmap(m->mptr, m->len);
4615 if (PerlIO_seek(PerlIONext(f), b->posn, SEEK_SET) != 0)
4618 b->ptr = b->end = b->buf;
4619 PerlIOBase(f)->flags &= ~(PERLIO_F_RDBUF | PERLIO_F_WRBUF);
4625 PerlIOMmap_get_base(pTHX_ PerlIO *f)
4627 PerlIOMmap * const m = PerlIOSelf(f, PerlIOMmap);
4628 PerlIOBuf * const b = &m->base;
4629 if (b->buf && (PerlIOBase(f)->flags & PERLIO_F_RDBUF)) {
4631 * Already have a readbuffer in progress
4637 * We have a write buffer or flushed PerlIOBuf read buffer
4639 m->bbuf = b->buf; /* save it in case we need it again */
4640 b->buf = NULL; /* Clear to trigger below */
4643 PerlIOMmap_map(aTHX_ f); /* Try and map it */
4646 * Map did not work - recover PerlIOBuf buffer if we have one
4651 b->ptr = b->end = b->buf;
4654 return PerlIOBuf_get_base(aTHX_ f);
4658 PerlIOMmap_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
4660 PerlIOMmap * const m = PerlIOSelf(f, PerlIOMmap);
4661 PerlIOBuf * const b = &m->base;
4662 if (PerlIOBase(f)->flags & PERLIO_F_WRBUF)
4664 if (b->ptr && (b->ptr - count) >= b->buf
4665 && memEQ(b->ptr - count, vbuf, count)) {
4667 PerlIOBase(f)->flags &= ~PERLIO_F_EOF;
4672 * Loose the unwritable mapped buffer
4676 * If flush took the "buffer" see if we have one from before
4678 if (!b->buf && m->bbuf)
4681 PerlIOBuf_get_base(aTHX_ f);
4685 return PerlIOBuf_unread(aTHX_ f, vbuf, count);
4689 PerlIOMmap_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
4691 PerlIOMmap * const m = PerlIOSelf(f, PerlIOMmap);
4692 PerlIOBuf * const b = &m->base;
4694 if (!b->buf || !(PerlIOBase(f)->flags & PERLIO_F_WRBUF)) {
4696 * No, or wrong sort of, buffer
4699 if (PerlIOMmap_unmap(aTHX_ f) != 0)
4703 * If unmap took the "buffer" see if we have one from before
4705 if (!b->buf && m->bbuf)
4708 PerlIOBuf_get_base(aTHX_ f);
4712 return PerlIOBuf_write(aTHX_ f, vbuf, count);
4716 PerlIOMmap_flush(pTHX_ PerlIO *f)
4718 PerlIOMmap * const m = PerlIOSelf(f, PerlIOMmap);
4719 PerlIOBuf * const b = &m->base;
4720 IV code = PerlIOBuf_flush(aTHX_ f);
4722 * Now we are "synced" at PerlIOBuf level
4729 if (PerlIOMmap_unmap(aTHX_ f) != 0)
4734 * We seem to have a PerlIOBuf buffer which was not mapped
4735 * remember it in case we need one later
4744 PerlIOMmap_fill(pTHX_ PerlIO *f)
4746 PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
4747 IV code = PerlIO_flush(f);
4748 if (code == 0 && !b->buf) {
4749 code = PerlIOMmap_map(aTHX_ f);
4751 if (code == 0 && !(PerlIOBase(f)->flags & PERLIO_F_RDBUF)) {
4752 code = PerlIOBuf_fill(aTHX_ f);
4758 PerlIOMmap_close(pTHX_ PerlIO *f)
4760 PerlIOMmap * const m = PerlIOSelf(f, PerlIOMmap);
4761 PerlIOBuf * const b = &m->base;
4762 IV code = PerlIO_flush(f);
4766 b->ptr = b->end = b->buf;
4768 if (PerlIOBuf_close(aTHX_ f) != 0)
4774 PerlIOMmap_dup(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags)
4776 return PerlIOBase_dup(aTHX_ f, o, param, flags);
4780 PERLIO_FUNCS_DECL(PerlIO_mmap) = {
4781 sizeof(PerlIO_funcs),
4784 PERLIO_K_BUFFERED|PERLIO_K_RAW,
4788 PerlIOBase_binmode, /* binmode */
4802 PerlIOBase_clearerr,
4803 PerlIOBase_setlinebuf,
4804 PerlIOMmap_get_base,
4808 PerlIOBuf_set_ptrcnt,
4811 #endif /* HAS_MMAP */
4814 Perl_PerlIO_stdin(pTHX)
4818 PerlIO_stdstreams(aTHX);
4820 return &PL_perlio[1];
4824 Perl_PerlIO_stdout(pTHX)
4828 PerlIO_stdstreams(aTHX);
4830 return &PL_perlio[2];
4834 Perl_PerlIO_stderr(pTHX)
4838 PerlIO_stdstreams(aTHX);
4840 return &PL_perlio[3];
4843 /*--------------------------------------------------------------------------------------*/
4846 PerlIO_getname(PerlIO *f, char *buf)
4851 bool exported = FALSE;
4852 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
4854 stdio = PerlIO_exportFILE(f,0);
4858 name = fgetname(stdio, buf);
4859 if (exported) PerlIO_releaseFILE(f,stdio);
4864 PERL_UNUSED_ARG(buf);
4865 Perl_croak(aTHX_ "Don't know how to get file name");
4871 /*--------------------------------------------------------------------------------------*/
4873 * Functions which can be called on any kind of PerlIO implemented in
4877 #undef PerlIO_fdopen
4879 PerlIO_fdopen(int fd, const char *mode)
4882 return PerlIO_openn(aTHX_ NULL, mode, fd, 0, 0, NULL, 0, NULL);
4887 PerlIO_open(const char *path, const char *mode)
4890 SV *name = sv_2mortal(newSVpv(path, 0));
4891 return PerlIO_openn(aTHX_ NULL, mode, -1, 0, 0, NULL, 1, &name);
4894 #undef Perlio_reopen
4896 PerlIO_reopen(const char *path, const char *mode, PerlIO *f)
4899 SV *name = sv_2mortal(newSVpv(path,0));
4900 return PerlIO_openn(aTHX_ NULL, mode, -1, 0, 0, f, 1, &name);
4905 PerlIO_getc(PerlIO *f)
4909 if ( 1 == PerlIO_read(f, buf, 1) ) {
4910 return (unsigned char) buf[0];
4915 #undef PerlIO_ungetc