2 * perlio.c Copyright (c) 1996-2005, Nick Ing-Simmons You may distribute
3 * under the terms of either the GNU General Public License or the
4 * Artistic License, as specified in the README file.
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
59 #define PERLIO_MAX_REFCOUNTABLE_FD 2048
62 /* Missing proto on LynxOS */
66 /* Call the callback or PerlIOBase, and return failure. */
67 #define Perl_PerlIO_or_Base(f, callback, base, failure, args) \
68 if (PerlIOValid(f)) { \
69 const PerlIO_funcs * const tab = PerlIOBase(f)->tab;\
70 if (tab && tab->callback) \
71 return (*tab->callback) args; \
73 return PerlIOBase_ ## base args; \
76 SETERRNO(EBADF, SS_IVCHAN); \
79 /* Call the callback or fail, and return failure. */
80 #define Perl_PerlIO_or_fail(f, callback, failure, args) \
81 if (PerlIOValid(f)) { \
82 const PerlIO_funcs * const tab = PerlIOBase(f)->tab;\
83 if (tab && tab->callback) \
84 return (*tab->callback) args; \
85 SETERRNO(EINVAL, LIB_INVARG); \
88 SETERRNO(EBADF, SS_IVCHAN); \
91 /* Call the callback or PerlIOBase, and be void. */
92 #define Perl_PerlIO_or_Base_void(f, callback, base, args) \
93 if (PerlIOValid(f)) { \
94 const PerlIO_funcs * const tab = PerlIOBase(f)->tab;\
95 if (tab && tab->callback) \
96 (*tab->callback) args; \
98 PerlIOBase_ ## base args; \
101 SETERRNO(EBADF, SS_IVCHAN)
103 /* Call the callback or fail, and be void. */
104 #define Perl_PerlIO_or_fail_void(f, callback, args) \
105 if (PerlIOValid(f)) { \
106 const PerlIO_funcs * const tab = PerlIOBase(f)->tab;\
107 if (tab && tab->callback) \
108 (*tab->callback) args; \
110 SETERRNO(EINVAL, LIB_INVARG); \
113 SETERRNO(EBADF, SS_IVCHAN)
117 perlsio_binmode(FILE *fp, int iotype, int mode)
120 * This used to be contents of do_binmode in doio.c
123 # if defined(atarist) || defined(__MINT__)
126 ((FILE *) fp)->_flag |= _IOBIN;
128 ((FILE *) fp)->_flag &= ~_IOBIN;
135 if (PerlLIO_setmode(fp, mode) != -1) {
137 if (PerlLIO_setmode(fileno(fp), mode) != -1) {
139 # if defined(WIN32) && defined(__BORLANDC__)
141 * The translation mode of the stream is maintained independent of
142 * the translation mode of the fd in the Borland RTL (heavy
143 * digging through their runtime sources reveal). User has to set
144 * the mode explicitly for the stream (though they don't document
145 * this anywhere). GSAR 97-5-24
151 fp->flags &= ~_F_BIN;
159 # if defined(USEMYBINMODE)
161 if (my_binmode(fp, iotype, mode) != FALSE)
167 PERL_UNUSED_ARG(iotype);
168 PERL_UNUSED_ARG(mode);
176 #define O_ACCMODE 3 /* Assume traditional implementation */
180 PerlIO_intmode2str(int rawmode, char *mode, int *writing)
182 const int result = rawmode & O_ACCMODE;
187 ptype = IoTYPE_RDONLY;
190 ptype = IoTYPE_WRONLY;
198 *writing = (result != O_RDONLY);
200 if (result == O_RDONLY) {
204 else if (rawmode & O_APPEND) {
206 if (result != O_WRONLY)
211 if (result == O_WRONLY)
218 if (rawmode & O_BINARY)
224 #ifndef PERLIO_LAYERS
226 PerlIO_apply_layers(pTHX_ PerlIO *f, const char *mode, const char *names)
228 if (!names || !*names
229 || strEQ(names, ":crlf")
230 || strEQ(names, ":raw")
231 || strEQ(names, ":bytes")
235 Perl_croak(aTHX_ "Cannot apply \"%s\" in non-PerlIO perl", names);
243 PerlIO_destruct(pTHX)
248 PerlIO_binmode(pTHX_ PerlIO *fp, int iotype, int mode, const char *names)
251 PERL_UNUSED_ARG(iotype);
252 PERL_UNUSED_ARG(mode);
253 PERL_UNUSED_ARG(names);
256 return perlsio_binmode(fp, iotype, mode);
261 PerlIO_fdupopen(pTHX_ PerlIO *f, CLONE_PARAMS *param, int flags)
263 #if defined(PERL_MICRO) || defined(SYMBIAN)
266 #ifdef PERL_IMPLICIT_SYS
267 return PerlSIO_fdupopen(f);
270 return win32_fdupopen(f);
273 const int fd = PerlLIO_dup(PerlIO_fileno(f));
276 int omode = fcntl(fd, F_GETFL);
278 omode = djgpp_get_stream_mode(f);
280 PerlIO_intmode2str(omode,mode,NULL);
281 /* the r+ is a hack */
282 return PerlIO_fdopen(fd, mode);
287 SETERRNO(EBADF, SS_IVCHAN);
297 * De-mux PerlIO_openn() into fdopen, freopen and fopen type entries
301 PerlIO_openn(pTHX_ const char *layers, const char *mode, int fd,
302 int imode, int perm, PerlIO *old, int narg, SV **args)
306 Perl_croak(aTHX_ "More than one argument to open");
308 if (*args == &PL_sv_undef)
309 return PerlIO_tmpfile();
311 const char *name = SvPV_nolen_const(*args);
312 if (*mode == IoTYPE_NUMERIC) {
313 fd = PerlLIO_open3(name, imode, perm);
315 return PerlIO_fdopen(fd, mode + 1);
318 return PerlIO_reopen(name, mode, old);
321 return PerlIO_open(name, mode);
326 return PerlIO_fdopen(fd, (char *) mode);
331 XS(XS_PerlIO__Layer__find)
335 Perl_croak(aTHX_ "Usage class->find(name[,load])");
337 const char *name = SvPV_nolen_const(ST(1));
338 ST(0) = (strEQ(name, "crlf")
339 || strEQ(name, "raw")) ? &PL_sv_yes : &PL_sv_undef;
346 Perl_boot_core_PerlIO(pTHX)
348 newXS("PerlIO::Layer::find", XS_PerlIO__Layer__find, __FILE__);
354 #ifdef PERLIO_IS_STDIO
360 * Does nothing (yet) except force this file to be included in perl
361 * binary. That allows this file to force inclusion of other functions
362 * that may be required by loadable extensions e.g. for
363 * FileHandle::tmpfile
367 #undef PerlIO_tmpfile
374 #else /* PERLIO_IS_STDIO */
382 * This section is just to make sure these functions get pulled in from
386 #undef PerlIO_tmpfile
397 * Force this file to be included in perl binary. Which allows this
398 * file to force inclusion of other functions that may be required by
399 * loadable extensions e.g. for FileHandle::tmpfile
403 * Hack sfio does its own 'autoflush' on stdout in common cases. Flush
404 * results in a lot of lseek()s to regular files and lot of small
407 sfset(sfstdout, SF_SHARE, 0);
410 /* This is not the reverse of PerlIO_exportFILE(), PerlIO_releaseFILE() is. */
412 PerlIO_importFILE(FILE *stdio, const char *mode)
414 const int fd = fileno(stdio);
415 if (!mode || !*mode) {
418 return PerlIO_fdopen(fd, mode);
422 PerlIO_findFILE(PerlIO *pio)
424 const int fd = PerlIO_fileno(pio);
425 FILE * const f = fdopen(fd, "r+");
427 if (!f && errno == EINVAL)
429 if (!f && errno == EINVAL)
436 /*======================================================================================*/
438 * Implement all the PerlIO interface ourselves.
444 * We _MUST_ have <unistd.h> if we are using lseek() and may have large
451 #include <sys/mman.h>
455 PerlIO_debug(const char *fmt, ...)
460 if (!PL_perlio_debug_fd && !PL_tainting && PL_uid == PL_euid && PL_gid == PL_egid) {
461 const char *s = PerlEnv_getenv("PERLIO_DEBUG");
463 PL_perlio_debug_fd = PerlLIO_open3(s, O_WRONLY | O_CREAT | O_APPEND, 0666);
465 PL_perlio_debug_fd = -1;
467 if (PL_perlio_debug_fd > 0) {
469 const char *s = CopFILE(PL_curcop);
472 /* Use fixed buffer as sv_catpvf etc. needs SVs */
476 len = sprintf(buffer, "%.40s:%" IVdf " ", s, (IV) CopLINE(PL_curcop));
477 vsprintf(buffer+len, fmt, ap);
478 PerlLIO_write(PL_perlio_debug_fd, buffer, strlen(buffer));
480 SV *sv = newSVpvn("", 0);
483 Perl_sv_catpvf(aTHX_ sv, "%s:%" IVdf " ", s,
484 (IV) CopLINE(PL_curcop));
485 Perl_sv_vcatpvf(aTHX_ sv, fmt, &ap);
487 s = SvPV_const(sv, len);
488 PerlLIO_write(PL_perlio_debug_fd, s, len);
495 /*--------------------------------------------------------------------------------------*/
498 * Inner level routines
502 * Table of pointers to the PerlIO structs (malloc'ed)
504 #define PERLIO_TABLE_SIZE 64
507 PerlIO_allocate(pTHX)
510 * Find a free slot in the table, allocating new table as necessary
515 while ((f = *last)) {
517 last = (PerlIO **) (f);
518 for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
524 Newxz(f,PERLIO_TABLE_SIZE,PerlIO);
532 #undef PerlIO_fdupopen
534 PerlIO_fdupopen(pTHX_ PerlIO *f, CLONE_PARAMS *param, int flags)
536 if (PerlIOValid(f)) {
537 const PerlIO_funcs * const tab = PerlIOBase(f)->tab;
538 PerlIO_debug("fdupopen f=%p param=%p\n",(void*)f,(void*)param);
540 return (*tab->Dup)(aTHX_ PerlIO_allocate(aTHX), f, param, flags);
542 return PerlIOBase_dup(aTHX_ PerlIO_allocate(aTHX), f, param, flags);
546 SETERRNO(EBADF, SS_IVCHAN);
552 PerlIO_cleantable(pTHX_ PerlIO **tablep)
554 PerlIO *table = *tablep;
557 PerlIO_cleantable(aTHX_(PerlIO **) & (table[0]));
558 for (i = PERLIO_TABLE_SIZE - 1; i > 0; i--) {
559 PerlIO *f = table + i;
571 PerlIO_list_alloc(pTHX)
574 Newxz(list, 1, PerlIO_list_t);
580 PerlIO_list_free(pTHX_ PerlIO_list_t *list)
583 if (--list->refcnt == 0) {
586 for (i = 0; i < list->cur; i++) {
587 if (list->array[i].arg)
588 SvREFCNT_dec(list->array[i].arg);
590 Safefree(list->array);
598 PerlIO_list_push(pTHX_ PerlIO_list_t *list, PerlIO_funcs *funcs, SV *arg)
601 if (list->cur >= list->len) {
604 Renew(list->array, list->len, PerlIO_pair_t);
606 Newx(list->array, list->len, PerlIO_pair_t);
608 p = &(list->array[list->cur++]);
610 if ((p->arg = arg)) {
611 (void)SvREFCNT_inc(arg);
616 PerlIO_clone_list(pTHX_ PerlIO_list_t *proto, CLONE_PARAMS *param)
618 PerlIO_list_t *list = (PerlIO_list_t *) NULL;
621 list = PerlIO_list_alloc(aTHX);
622 for (i=0; i < proto->cur; i++) {
624 if (proto->array[i].arg)
625 arg = PerlIO_sv_dup(aTHX_ proto->array[i].arg,param);
626 PerlIO_list_push(aTHX_ list, proto->array[i].funcs, arg);
633 PerlIO_clone(pTHX_ PerlInterpreter *proto, CLONE_PARAMS *param)
636 PerlIO **table = &proto->Iperlio;
639 PL_known_layers = PerlIO_clone_list(aTHX_ proto->Iknown_layers, param);
640 PL_def_layerlist = PerlIO_clone_list(aTHX_ proto->Idef_layerlist, param);
641 PerlIO_allocate(aTHX); /* root slot is never used */
642 PerlIO_debug("Clone %p from %p\n",aTHX,proto);
643 while ((f = *table)) {
645 table = (PerlIO **) (f++);
646 for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
648 (void) fp_dup(f, 0, param);
654 PERL_UNUSED_ARG(proto);
655 PERL_UNUSED_ARG(param);
660 PerlIO_destruct(pTHX)
662 PerlIO **table = &PL_perlio;
665 PerlIO_debug("Destruct %p\n",aTHX);
667 while ((f = *table)) {
669 table = (PerlIO **) (f++);
670 for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
674 if (l->tab->kind & PERLIO_K_DESTRUCT) {
675 PerlIO_debug("Destruct popping %s\n", l->tab->name);
689 PerlIO_pop(pTHX_ PerlIO *f)
693 PerlIO_debug("PerlIO_pop f=%p %s\n", (void*)f, l->tab->name);
694 if (l->tab->Popped) {
696 * If popped returns non-zero do not free its layer structure
697 * it has either done so itself, or it is shared and still in
700 if ((*l->tab->Popped) (aTHX_ f) != 0)
708 /* Return as an array the stack of layers on a filehandle. Note that
709 * the stack is returned top-first in the array, and there are three
710 * times as many array elements as there are layers in the stack: the
711 * first element of a layer triplet is the name, the second one is the
712 * arguments, and the third one is the flags. */
715 PerlIO_get_layers(pTHX_ PerlIO *f)
719 if (PerlIOValid(f)) {
720 PerlIOl *l = PerlIOBase(f);
723 SV *name = l->tab && l->tab->name ?
724 newSVpv(l->tab->name, 0) : &PL_sv_undef;
725 SV *arg = l->tab && l->tab->Getarg ?
726 (*l->tab->Getarg)(aTHX_ &l, 0, 0) : &PL_sv_undef;
729 av_push(av, newSViv((IV)l->flags));
737 /*--------------------------------------------------------------------------------------*/
739 * XS Interface for perl code
743 PerlIO_find_layer(pTHX_ const char *name, STRLEN len, int load)
747 if ((SSize_t) len <= 0)
749 for (i = 0; i < PL_known_layers->cur; i++) {
750 PerlIO_funcs * const f = PL_known_layers->array[i].funcs;
751 if (memEQ(f->name, name, len) && f->name[len] == 0) {
752 PerlIO_debug("%.*s => %p\n", (int) len, name, (void*)f);
756 if (load && PL_subname && PL_def_layerlist
757 && PL_def_layerlist->cur >= 2) {
758 if (PL_in_load_module) {
759 Perl_croak(aTHX_ "Recursive call to Perl_load_module in PerlIO_find_layer");
762 SV * const pkgsv = newSVpvn("PerlIO", 6);
763 SV * const layer = newSVpvn(name, len);
764 CV * const cv = get_cv("PerlIO::Layer::NoWarnings", FALSE);
766 SAVEINT(PL_in_load_module);
768 SAVEGENERICSV(PL_warnhook);
769 (void)SvREFCNT_inc(cv);
770 PL_warnhook = (SV *) cv;
774 * The two SVs are magically freed by load_module
776 Perl_load_module(aTHX_ 0, pkgsv, Nullsv, layer, Nullsv);
779 return PerlIO_find_layer(aTHX_ name, len, 0);
782 PerlIO_debug("Cannot find %.*s\n", (int) len, name);
786 #ifdef USE_ATTRIBUTES_FOR_PERLIO
789 perlio_mg_set(pTHX_ SV *sv, MAGIC *mg)
792 IO *io = GvIOn((GV *) SvRV(sv));
793 PerlIO *ifp = IoIFP(io);
794 PerlIO *ofp = IoOFP(io);
795 Perl_warn(aTHX_ "set %" SVf " %p %p %p", sv, io, ifp, ofp);
801 perlio_mg_get(pTHX_ SV *sv, MAGIC *mg)
804 IO *io = GvIOn((GV *) SvRV(sv));
805 PerlIO *ifp = IoIFP(io);
806 PerlIO *ofp = IoOFP(io);
807 Perl_warn(aTHX_ "get %" SVf " %p %p %p", sv, io, ifp, ofp);
813 perlio_mg_clear(pTHX_ SV *sv, MAGIC *mg)
815 Perl_warn(aTHX_ "clear %" SVf, sv);
820 perlio_mg_free(pTHX_ SV *sv, MAGIC *mg)
822 Perl_warn(aTHX_ "free %" SVf, sv);
826 MGVTBL perlio_vtab = {
834 XS(XS_io_MODIFY_SCALAR_ATTRIBUTES)
837 SV *sv = SvRV(ST(1));
842 sv_magic(sv, (SV *) av, PERL_MAGIC_ext, NULL, 0);
844 mg = mg_find(sv, PERL_MAGIC_ext);
845 mg->mg_virtual = &perlio_vtab;
847 Perl_warn(aTHX_ "attrib %" SVf, sv);
848 for (i = 2; i < items; i++) {
850 const char *name = SvPV_const(ST(i), len);
851 SV *layer = PerlIO_find_layer(aTHX_ name, len, 1);
853 av_push(av, SvREFCNT_inc(layer));
864 #endif /* USE_ATTIBUTES_FOR_PERLIO */
867 PerlIO_tab_sv(pTHX_ PerlIO_funcs *tab)
869 HV * const stash = gv_stashpv("PerlIO::Layer", TRUE);
870 SV * const sv = sv_bless(newRV_noinc(newSViv(PTR2IV(tab))), stash);
874 XS(XS_PerlIO__Layer__NoWarnings)
876 /* This is used as a %SIG{__WARN__} handler to supress warnings
877 during loading of layers.
881 PerlIO_debug("warning:%s\n",SvPV_nolen_const(ST(0)));
885 XS(XS_PerlIO__Layer__find)
889 Perl_croak(aTHX_ "Usage class->find(name[,load])");
892 const char * const name = SvPV_const(ST(1), len);
893 const bool load = (items > 2) ? SvTRUE(ST(2)) : 0;
894 PerlIO_funcs * const layer = PerlIO_find_layer(aTHX_ name, len, load);
896 (layer) ? sv_2mortal(PerlIO_tab_sv(aTHX_ layer)) :
903 PerlIO_define_layer(pTHX_ PerlIO_funcs *tab)
905 if (!PL_known_layers)
906 PL_known_layers = PerlIO_list_alloc(aTHX);
907 PerlIO_list_push(aTHX_ PL_known_layers, tab, Nullsv);
908 PerlIO_debug("define %s %p\n", tab->name, (void*)tab);
912 PerlIO_parse_layers(pTHX_ PerlIO_list_t *av, const char *names)
915 const char *s = names;
917 while (isSPACE(*s) || *s == ':')
922 const char *as = Nullch;
924 if (!isIDFIRST(*s)) {
926 * Message is consistent with how attribute lists are
927 * passed. Even though this means "foo : : bar" is
928 * seen as an invalid separator character.
930 const char q = ((*s == '\'') ? '"' : '\'');
931 if (ckWARN(WARN_LAYER))
932 Perl_warner(aTHX_ packWARN(WARN_LAYER),
933 "Invalid separator character %c%c%c in PerlIO layer specification %s",
935 SETERRNO(EINVAL, LIB_INVARG);
940 } while (isALNUM(*e));
956 * It's a nul terminated string, not allowed
957 * to \ the terminating null. Anything other
958 * character is passed over.
968 if (ckWARN(WARN_LAYER))
969 Perl_warner(aTHX_ packWARN(WARN_LAYER),
970 "Argument list not closed for PerlIO layer \"%.*s\"",
982 PerlIO_funcs * const layer =
983 PerlIO_find_layer(aTHX_ s, llen, 1);
985 PerlIO_list_push(aTHX_ av, layer,
991 if (ckWARN(WARN_LAYER))
992 Perl_warner(aTHX_ packWARN(WARN_LAYER), "Unknown PerlIO layer \"%.*s\"",
1005 PerlIO_default_buffer(pTHX_ PerlIO_list_t *av)
1007 PERLIO_FUNCS_DECL(*tab) = &PerlIO_perlio;
1008 #ifdef PERLIO_USING_CRLF
1011 if (PerlIO_stdio.Set_ptrcnt)
1012 tab = &PerlIO_stdio;
1014 PerlIO_debug("Pushing %s\n", tab->name);
1015 PerlIO_list_push(aTHX_ av, PerlIO_find_layer(aTHX_ tab->name, 0, 0),
1020 PerlIO_arg_fetch(PerlIO_list_t *av, IV n)
1022 return av->array[n].arg;
1026 PerlIO_layer_fetch(pTHX_ PerlIO_list_t *av, IV n, PerlIO_funcs *def)
1028 if (n >= 0 && n < av->cur) {
1029 PerlIO_debug("Layer %" IVdf " is %s\n", n,
1030 av->array[n].funcs->name);
1031 return av->array[n].funcs;
1034 Perl_croak(aTHX_ "panic: PerlIO layer array corrupt");
1039 PerlIOPop_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
1041 PERL_UNUSED_ARG(mode);
1042 PERL_UNUSED_ARG(arg);
1043 PERL_UNUSED_ARG(tab);
1044 if (PerlIOValid(f)) {
1046 PerlIO_pop(aTHX_ f);
1052 PERLIO_FUNCS_DECL(PerlIO_remove) = {
1053 sizeof(PerlIO_funcs),
1056 PERLIO_K_DUMMY | PERLIO_K_UTF8,
1076 NULL, /* get_base */
1077 NULL, /* get_bufsiz */
1080 NULL, /* set_ptrcnt */
1084 PerlIO_default_layers(pTHX)
1086 if (!PL_def_layerlist) {
1087 const char *s = (PL_tainting) ? Nullch : PerlEnv_getenv("PERLIO");
1088 PERLIO_FUNCS_DECL(*osLayer) = &PerlIO_unix;
1089 PL_def_layerlist = PerlIO_list_alloc(aTHX);
1090 PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_unix));
1092 PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_win32));
1094 osLayer = &PerlIO_win32;
1097 PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_raw));
1098 PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_perlio));
1099 PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_stdio));
1100 PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_crlf));
1102 PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_mmap));
1104 PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_utf8));
1105 PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_remove));
1106 PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_byte));
1107 PerlIO_list_push(aTHX_ PL_def_layerlist,
1108 PerlIO_find_layer(aTHX_ osLayer->name, 0, 0),
1111 PerlIO_parse_layers(aTHX_ PL_def_layerlist, s);
1114 PerlIO_default_buffer(aTHX_ PL_def_layerlist);
1117 if (PL_def_layerlist->cur < 2) {
1118 PerlIO_default_buffer(aTHX_ PL_def_layerlist);
1120 return PL_def_layerlist;
1124 Perl_boot_core_PerlIO(pTHX)
1126 #ifdef USE_ATTRIBUTES_FOR_PERLIO
1127 newXS("io::MODIFY_SCALAR_ATTRIBUTES", XS_io_MODIFY_SCALAR_ATTRIBUTES,
1130 newXS("PerlIO::Layer::find", XS_PerlIO__Layer__find, __FILE__);
1131 newXS("PerlIO::Layer::NoWarnings", XS_PerlIO__Layer__NoWarnings, __FILE__);
1135 PerlIO_default_layer(pTHX_ I32 n)
1137 PerlIO_list_t * const av = PerlIO_default_layers(aTHX);
1140 return PerlIO_layer_fetch(aTHX_ av, n, PERLIO_FUNCS_CAST(&PerlIO_stdio));
1143 #define PerlIO_default_top() PerlIO_default_layer(aTHX_ -1)
1144 #define PerlIO_default_btm() PerlIO_default_layer(aTHX_ 0)
1147 PerlIO_stdstreams(pTHX)
1150 PerlIO_allocate(aTHX);
1151 PerlIO_fdopen(0, "Ir" PERLIO_STDTEXT);
1152 PerlIO_fdopen(1, "Iw" PERLIO_STDTEXT);
1153 PerlIO_fdopen(2, "Iw" PERLIO_STDTEXT);
1158 PerlIO_push(pTHX_ PerlIO *f, PERLIO_FUNCS_DECL(*tab), const char *mode, SV *arg)
1160 if (tab->fsize != sizeof(PerlIO_funcs)) {
1162 Perl_croak(aTHX_ "Layer does not match this perl");
1166 if (tab->size < sizeof(PerlIOl)) {
1169 /* Real layer with a data area */
1170 Newxc(l,tab->size,char,PerlIOl);
1172 Zero(l, tab->size, char);
1174 l->tab = (PerlIO_funcs*) tab;
1176 PerlIO_debug("PerlIO_push f=%p %s %s %p\n", (void*)f, tab->name,
1177 (mode) ? mode : "(Null)", (void*)arg);
1178 if (*l->tab->Pushed &&
1179 (*l->tab->Pushed) (aTHX_ f, mode, arg, (PerlIO_funcs*) tab) != 0) {
1180 PerlIO_pop(aTHX_ f);
1186 /* Pseudo-layer where push does its own stack adjust */
1187 PerlIO_debug("PerlIO_push f=%p %s %s %p\n", (void*)f, tab->name,
1188 (mode) ? mode : "(Null)", (void*)arg);
1190 (*tab->Pushed) (aTHX_ f, mode, arg, (PerlIO_funcs*) tab) != 0) {
1198 PerlIOBase_binmode(pTHX_ PerlIO *f)
1200 if (PerlIOValid(f)) {
1201 /* Is layer suitable for raw stream ? */
1202 if (PerlIOBase(f)->tab->kind & PERLIO_K_RAW) {
1203 /* Yes - turn off UTF-8-ness, to undo UTF-8 locale effects */
1204 PerlIOBase(f)->flags &= ~PERLIO_F_UTF8;
1207 /* Not suitable - pop it */
1208 PerlIO_pop(aTHX_ f);
1216 PerlIORaw_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
1218 PERL_UNUSED_ARG(mode);
1219 PERL_UNUSED_ARG(arg);
1220 PERL_UNUSED_ARG(tab);
1222 if (PerlIOValid(f)) {
1227 * Strip all layers that are not suitable for a raw stream
1230 while (t && (l = *t)) {
1231 if (l->tab->Binmode) {
1232 /* Has a handler - normal case */
1233 if ((*l->tab->Binmode)(aTHX_ f) == 0) {
1235 /* Layer still there - move down a layer */
1244 /* No handler - pop it */
1245 PerlIO_pop(aTHX_ t);
1248 if (PerlIOValid(f)) {
1249 PerlIO_debug(":raw f=%p :%s\n", (void*)f, PerlIOBase(f)->tab->name);
1257 PerlIO_apply_layera(pTHX_ PerlIO *f, const char *mode,
1258 PerlIO_list_t *layers, IV n, IV max)
1262 PerlIO_funcs * const tab = PerlIO_layer_fetch(aTHX_ layers, n, NULL);
1264 if (!PerlIO_push(aTHX_ f, tab, mode, PerlIOArg)) {
1275 PerlIO_apply_layers(pTHX_ PerlIO *f, const char *mode, const char *names)
1279 PerlIO_list_t * const layers = PerlIO_list_alloc(aTHX);
1280 code = PerlIO_parse_layers(aTHX_ layers, names);
1282 code = PerlIO_apply_layera(aTHX_ f, mode, layers, 0, layers->cur);
1284 PerlIO_list_free(aTHX_ layers);
1290 /*--------------------------------------------------------------------------------------*/
1292 * Given the abstraction above the public API functions
1296 PerlIO_binmode(pTHX_ PerlIO *f, int iotype, int mode, const char *names)
1298 PerlIO_debug("PerlIO_binmode f=%p %s %c %x %s\n",
1299 (void*)f, PerlIOBase(f)->tab->name, iotype, mode,
1300 (names) ? names : "(Null)");
1302 /* Do not flush etc. if (e.g.) switching encodings.
1303 if a pushed layer knows it needs to flush lower layers
1304 (for example :unix which is never going to call them)
1305 it can do the flush when it is pushed.
1307 return PerlIO_apply_layers(aTHX_ f, NULL, names) == 0 ? TRUE : FALSE;
1310 /* Fake 5.6 legacy of using this call to turn ON O_TEXT */
1311 #ifdef PERLIO_USING_CRLF
1312 /* Legacy binmode only has meaning if O_TEXT has a value distinct from
1313 O_BINARY so we can look for it in mode.
1315 if (!(mode & O_BINARY)) {
1317 /* FIXME?: Looking down the layer stack seems wrong,
1318 but is a way of reaching past (say) an encoding layer
1319 to flip CRLF-ness of the layer(s) below
1322 /* Perhaps we should turn on bottom-most aware layer
1323 e.g. Ilya's idea that UNIX TTY could serve
1325 if (PerlIOBase(f)->tab->kind & PERLIO_K_CANCRLF) {
1326 if (!(PerlIOBase(f)->flags & PERLIO_F_CRLF)) {
1327 /* Not in text mode - flush any pending stuff and flip it */
1329 PerlIOBase(f)->flags |= PERLIO_F_CRLF;
1331 /* Only need to turn it on in one layer so we are done */
1336 /* Not finding a CRLF aware layer presumably means we are binary
1337 which is not what was requested - so we failed
1338 We _could_ push :crlf layer but so could caller
1343 /* Legacy binmode is now _defined_ as being equivalent to pushing :raw
1344 So code that used to be here is now in PerlIORaw_pushed().
1346 return PerlIO_push(aTHX_ f, PERLIO_FUNCS_CAST(&PerlIO_raw), Nullch, Nullsv) ? TRUE : FALSE;
1351 PerlIO__close(pTHX_ PerlIO *f)
1353 if (PerlIOValid(f)) {
1354 PerlIO_funcs * const tab = PerlIOBase(f)->tab;
1355 if (tab && tab->Close)
1356 return (*tab->Close)(aTHX_ f);
1358 return PerlIOBase_close(aTHX_ f);
1361 SETERRNO(EBADF, SS_IVCHAN);
1367 Perl_PerlIO_close(pTHX_ PerlIO *f)
1369 const int code = PerlIO__close(aTHX_ f);
1370 while (PerlIOValid(f)) {
1371 PerlIO_pop(aTHX_ f);
1377 Perl_PerlIO_fileno(pTHX_ PerlIO *f)
1379 Perl_PerlIO_or_Base(f, Fileno, fileno, -1, (aTHX_ f));
1383 PerlIO_context_layers(pTHX_ const char *mode)
1385 const char *type = NULL;
1387 * Need to supply default layer info from open.pm
1390 SV *layers = PL_curcop->cop_io;
1393 type = SvPV_const(layers, len);
1394 if (type && mode[0] != 'r') {
1396 * Skip to write part
1398 const char *s = strchr(type, 0);
1399 if (s && (STRLEN)(s - type) < len) {
1408 static PerlIO_funcs *
1409 PerlIO_layer_from_ref(pTHX_ SV *sv)
1412 * For any scalar type load the handler which is bundled with perl
1414 if (SvTYPE(sv) < SVt_PVAV)
1415 return PerlIO_find_layer(aTHX_ "scalar", 6, 1);
1418 * For other types allow if layer is known but don't try and load it
1420 switch (SvTYPE(sv)) {
1422 return PerlIO_find_layer(aTHX_ "Array", 5, 0);
1424 return PerlIO_find_layer(aTHX_ "Hash", 4, 0);
1426 return PerlIO_find_layer(aTHX_ "Code", 4, 0);
1428 return PerlIO_find_layer(aTHX_ "Glob", 4, 0);
1434 PerlIO_resolve_layers(pTHX_ const char *layers,
1435 const char *mode, int narg, SV **args)
1437 PerlIO_list_t *def = PerlIO_default_layers(aTHX);
1440 PerlIO_stdstreams(aTHX);
1444 * If it is a reference but not an object see if we have a handler
1447 if (SvROK(arg) && !sv_isobject(arg)) {
1448 PerlIO_funcs * const handler = PerlIO_layer_from_ref(aTHX_ SvRV(arg));
1450 def = PerlIO_list_alloc(aTHX);
1451 PerlIO_list_push(aTHX_ def, handler, &PL_sv_undef);
1455 * Don't fail if handler cannot be found :via(...) etc. may do
1456 * something sensible else we will just stringfy and open
1462 layers = PerlIO_context_layers(aTHX_ mode);
1463 if (layers && *layers) {
1467 av = PerlIO_list_alloc(aTHX);
1468 for (i = 0; i < def->cur; i++) {
1469 PerlIO_list_push(aTHX_ av, def->array[i].funcs,
1476 if (PerlIO_parse_layers(aTHX_ av, layers) == 0) {
1480 PerlIO_list_free(aTHX_ av);
1481 return (PerlIO_list_t *) NULL;
1492 PerlIO_openn(pTHX_ const char *layers, const char *mode, int fd,
1493 int imode, int perm, PerlIO *f, int narg, SV **args)
1495 if (!f && narg == 1 && *args == &PL_sv_undef) {
1496 if ((f = PerlIO_tmpfile())) {
1498 layers = PerlIO_context_layers(aTHX_ mode);
1499 if (layers && *layers)
1500 PerlIO_apply_layers(aTHX_ f, mode, layers);
1504 PerlIO_list_t *layera;
1506 PerlIO_funcs *tab = NULL;
1507 if (PerlIOValid(f)) {
1509 * This is "reopen" - it is not tested as perl does not use it
1513 layera = PerlIO_list_alloc(aTHX);
1515 SV * const arg = (l->tab->Getarg)
1516 ? (*l->tab->Getarg) (aTHX_ &l, NULL, 0)
1518 PerlIO_list_push(aTHX_ layera, l->tab, arg);
1519 l = *PerlIONext(&l);
1523 layera = PerlIO_resolve_layers(aTHX_ layers, mode, narg, args);
1529 * Start at "top" of layer stack
1531 n = layera->cur - 1;
1533 PerlIO_funcs * const t = PerlIO_layer_fetch(aTHX_ layera, n, NULL);
1542 * Found that layer 'n' can do opens - call it
1544 if (narg > 1 && !(tab->kind & PERLIO_K_MULTIARG)) {
1545 Perl_croak(aTHX_ "More than one argument to open(,':%s')",tab->name);
1547 PerlIO_debug("openn(%s,'%s','%s',%d,%x,%o,%p,%d,%p)\n",
1548 tab->name, layers, mode, fd, imode, perm,
1549 (void*)f, narg, (void*)args);
1551 f = (*tab->Open) (aTHX_ tab, layera, n, mode, fd, imode, perm,
1554 SETERRNO(EINVAL, LIB_INVARG);
1558 if (n + 1 < layera->cur) {
1560 * More layers above the one that we used to open -
1563 if (PerlIO_apply_layera(aTHX_ f, mode, layera, n + 1, layera->cur) != 0) {
1564 /* If pushing layers fails close the file */
1571 PerlIO_list_free(aTHX_ layera);
1578 Perl_PerlIO_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
1580 Perl_PerlIO_or_Base(f, Read, read, -1, (aTHX_ f, vbuf, count));
1584 Perl_PerlIO_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
1586 Perl_PerlIO_or_Base(f, Unread, unread, -1, (aTHX_ f, vbuf, count));
1590 Perl_PerlIO_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
1592 Perl_PerlIO_or_fail(f, Write, -1, (aTHX_ f, vbuf, count));
1596 Perl_PerlIO_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
1598 Perl_PerlIO_or_fail(f, Seek, -1, (aTHX_ f, offset, whence));
1602 Perl_PerlIO_tell(pTHX_ PerlIO *f)
1604 Perl_PerlIO_or_fail(f, Tell, -1, (aTHX_ f));
1608 Perl_PerlIO_flush(pTHX_ PerlIO *f)
1612 const PerlIO_funcs *tab = PerlIOBase(f)->tab;
1614 if (tab && tab->Flush)
1615 return (*tab->Flush) (aTHX_ f);
1617 return 0; /* If no Flush defined, silently succeed. */
1620 PerlIO_debug("Cannot flush f=%p\n", (void*)f);
1621 SETERRNO(EBADF, SS_IVCHAN);
1627 * Is it good API design to do flush-all on NULL, a potentially
1628 * errorneous input? Maybe some magical value (PerlIO*
1629 * PERLIO_FLUSH_ALL = (PerlIO*)-1;)? Yes, stdio does similar
1630 * things on fflush(NULL), but should we be bound by their design
1633 PerlIO **table = &PL_perlio;
1635 while ((f = *table)) {
1637 table = (PerlIO **) (f++);
1638 for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
1639 if (*f && PerlIO_flush(f) != 0)
1649 PerlIOBase_flush_linebuf(pTHX)
1651 PerlIO **table = &PL_perlio;
1653 while ((f = *table)) {
1655 table = (PerlIO **) (f++);
1656 for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
1659 flags & (PERLIO_F_LINEBUF | PERLIO_F_CANWRITE))
1660 == (PERLIO_F_LINEBUF | PERLIO_F_CANWRITE))
1668 Perl_PerlIO_fill(pTHX_ PerlIO *f)
1670 Perl_PerlIO_or_fail(f, Fill, -1, (aTHX_ f));
1674 PerlIO_isutf8(PerlIO *f)
1677 return (PerlIOBase(f)->flags & PERLIO_F_UTF8) != 0;
1679 SETERRNO(EBADF, SS_IVCHAN);
1685 Perl_PerlIO_eof(pTHX_ PerlIO *f)
1687 Perl_PerlIO_or_Base(f, Eof, eof, -1, (aTHX_ f));
1691 Perl_PerlIO_error(pTHX_ PerlIO *f)
1693 Perl_PerlIO_or_Base(f, Error, error, -1, (aTHX_ f));
1697 Perl_PerlIO_clearerr(pTHX_ PerlIO *f)
1699 Perl_PerlIO_or_Base_void(f, Clearerr, clearerr, (aTHX_ f));
1703 Perl_PerlIO_setlinebuf(pTHX_ PerlIO *f)
1705 Perl_PerlIO_or_Base_void(f, Setlinebuf, setlinebuf, (aTHX_ f));
1709 PerlIO_has_base(PerlIO *f)
1711 if (PerlIOValid(f)) {
1712 const PerlIO_funcs * const tab = PerlIOBase(f)->tab;
1715 return (tab->Get_base != NULL);
1716 SETERRNO(EINVAL, LIB_INVARG);
1719 SETERRNO(EBADF, SS_IVCHAN);
1725 PerlIO_fast_gets(PerlIO *f)
1727 if (PerlIOValid(f) && (PerlIOBase(f)->flags & PERLIO_F_FASTGETS)) {
1728 const PerlIO_funcs * const tab = PerlIOBase(f)->tab;
1731 return (tab->Set_ptrcnt != NULL);
1732 SETERRNO(EINVAL, LIB_INVARG);
1735 SETERRNO(EBADF, SS_IVCHAN);
1741 PerlIO_has_cntptr(PerlIO *f)
1743 if (PerlIOValid(f)) {
1744 const PerlIO_funcs * const tab = PerlIOBase(f)->tab;
1747 return (tab->Get_ptr != NULL && tab->Get_cnt != NULL);
1748 SETERRNO(EINVAL, LIB_INVARG);
1751 SETERRNO(EBADF, SS_IVCHAN);
1757 PerlIO_canset_cnt(PerlIO *f)
1759 if (PerlIOValid(f)) {
1760 const PerlIO_funcs * const tab = PerlIOBase(f)->tab;
1763 return (tab->Set_ptrcnt != NULL);
1764 SETERRNO(EINVAL, LIB_INVARG);
1767 SETERRNO(EBADF, SS_IVCHAN);
1773 Perl_PerlIO_get_base(pTHX_ PerlIO *f)
1775 Perl_PerlIO_or_fail(f, Get_base, NULL, (aTHX_ f));
1779 Perl_PerlIO_get_bufsiz(pTHX_ PerlIO *f)
1781 Perl_PerlIO_or_fail(f, Get_bufsiz, -1, (aTHX_ f));
1785 Perl_PerlIO_get_ptr(pTHX_ PerlIO *f)
1787 Perl_PerlIO_or_fail(f, Get_ptr, NULL, (aTHX_ f));
1791 Perl_PerlIO_get_cnt(pTHX_ PerlIO *f)
1793 Perl_PerlIO_or_fail(f, Get_cnt, -1, (aTHX_ f));
1797 Perl_PerlIO_set_cnt(pTHX_ PerlIO *f, int cnt)
1799 Perl_PerlIO_or_fail_void(f, Set_ptrcnt, (aTHX_ f, NULL, cnt));
1803 Perl_PerlIO_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, int cnt)
1805 Perl_PerlIO_or_fail_void(f, Set_ptrcnt, (aTHX_ f, ptr, cnt));
1809 /*--------------------------------------------------------------------------------------*/
1811 * utf8 and raw dummy layers
1815 PerlIOUtf8_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
1817 PERL_UNUSED_ARG(mode);
1818 PERL_UNUSED_ARG(arg);
1819 if (PerlIOValid(f)) {
1820 if (tab->kind & PERLIO_K_UTF8)
1821 PerlIOBase(f)->flags |= PERLIO_F_UTF8;
1823 PerlIOBase(f)->flags &= ~PERLIO_F_UTF8;
1829 PERLIO_FUNCS_DECL(PerlIO_utf8) = {
1830 sizeof(PerlIO_funcs),
1833 PERLIO_K_DUMMY | PERLIO_K_UTF8,
1853 NULL, /* get_base */
1854 NULL, /* get_bufsiz */
1857 NULL, /* set_ptrcnt */
1860 PERLIO_FUNCS_DECL(PerlIO_byte) = {
1861 sizeof(PerlIO_funcs),
1884 NULL, /* get_base */
1885 NULL, /* get_bufsiz */
1888 NULL, /* set_ptrcnt */
1892 PerlIORaw_open(pTHX_ PerlIO_funcs *self, PerlIO_list_t *layers,
1893 IV n, const char *mode, int fd, int imode, int perm,
1894 PerlIO *old, int narg, SV **args)
1896 PerlIO_funcs * const tab = PerlIO_default_btm();
1897 PERL_UNUSED_ARG(self);
1898 if (tab && tab->Open)
1899 return (*tab->Open) (aTHX_ tab, layers, n - 1, mode, fd, imode, perm,
1901 SETERRNO(EINVAL, LIB_INVARG);
1905 PERLIO_FUNCS_DECL(PerlIO_raw) = {
1906 sizeof(PerlIO_funcs),
1929 NULL, /* get_base */
1930 NULL, /* get_bufsiz */
1933 NULL, /* set_ptrcnt */
1935 /*--------------------------------------------------------------------------------------*/
1936 /*--------------------------------------------------------------------------------------*/
1938 * "Methods" of the "base class"
1942 PerlIOBase_fileno(pTHX_ PerlIO *f)
1944 return PerlIOValid(f) ? PerlIO_fileno(PerlIONext(f)) : -1;
1948 PerlIO_modestr(PerlIO * f, char *buf)
1951 if (PerlIOValid(f)) {
1952 const IV flags = PerlIOBase(f)->flags;
1953 if (flags & PERLIO_F_APPEND) {
1955 if (flags & PERLIO_F_CANREAD) {
1959 else if (flags & PERLIO_F_CANREAD) {
1961 if (flags & PERLIO_F_CANWRITE)
1964 else if (flags & PERLIO_F_CANWRITE) {
1966 if (flags & PERLIO_F_CANREAD) {
1970 #ifdef PERLIO_USING_CRLF
1971 if (!(flags & PERLIO_F_CRLF))
1981 PerlIOBase_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
1983 PerlIOl * const l = PerlIOBase(f);
1984 PERL_UNUSED_ARG(arg);
1986 l->flags &= ~(PERLIO_F_CANREAD | PERLIO_F_CANWRITE |
1987 PERLIO_F_TRUNCATE | PERLIO_F_APPEND);
1988 if (tab->Set_ptrcnt != NULL)
1989 l->flags |= PERLIO_F_FASTGETS;
1991 if (*mode == IoTYPE_NUMERIC || *mode == IoTYPE_IMPLICIT)
1995 l->flags |= PERLIO_F_CANREAD;
1998 l->flags |= PERLIO_F_APPEND | PERLIO_F_CANWRITE;
2001 l->flags |= PERLIO_F_TRUNCATE | PERLIO_F_CANWRITE;
2004 SETERRNO(EINVAL, LIB_INVARG);
2010 l->flags |= PERLIO_F_CANREAD | PERLIO_F_CANWRITE;
2013 l->flags &= ~PERLIO_F_CRLF;
2016 l->flags |= PERLIO_F_CRLF;
2019 SETERRNO(EINVAL, LIB_INVARG);
2026 l->flags |= l->next->flags &
2027 (PERLIO_F_CANREAD | PERLIO_F_CANWRITE | PERLIO_F_TRUNCATE |
2032 PerlIO_debug("PerlIOBase_pushed f=%p %s %s fl=%08" UVxf " (%s)\n",
2033 f, PerlIOBase(f)->tab->name, (omode) ? omode : "(Null)",
2034 l->flags, PerlIO_modestr(f, temp));
2040 PerlIOBase_popped(pTHX_ PerlIO *f)
2047 PerlIOBase_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
2050 * Save the position as current head considers it
2052 const Off_t old = PerlIO_tell(f);
2053 PerlIO_push(aTHX_ f, PERLIO_FUNCS_CAST(&PerlIO_pending), "r", Nullsv);
2054 PerlIOSelf(f, PerlIOBuf)->posn = old;
2055 return PerlIOBuf_unread(aTHX_ f, vbuf, count);
2059 PerlIOBase_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
2061 STDCHAR *buf = (STDCHAR *) vbuf;
2063 if (!(PerlIOBase(f)->flags & PERLIO_F_CANREAD)) {
2064 PerlIOBase(f)->flags |= PERLIO_F_ERROR;
2065 SETERRNO(EBADF, SS_IVCHAN);
2069 SSize_t avail = PerlIO_get_cnt(f);
2072 take = ((SSize_t)count < avail) ? count : avail;
2074 STDCHAR *ptr = PerlIO_get_ptr(f);
2075 Copy(ptr, buf, take, STDCHAR);
2076 PerlIO_set_ptrcnt(f, ptr + take, (avail -= take));
2080 if (count > 0 && avail <= 0) {
2081 if (PerlIO_fill(f) != 0)
2085 return (buf - (STDCHAR *) vbuf);
2091 PerlIOBase_noop_ok(pTHX_ PerlIO *f)
2098 PerlIOBase_noop_fail(pTHX_ PerlIO *f)
2105 PerlIOBase_close(pTHX_ PerlIO *f)
2108 if (PerlIOValid(f)) {
2109 PerlIO *n = PerlIONext(f);
2110 code = PerlIO_flush(f);
2111 PerlIOBase(f)->flags &=
2112 ~(PERLIO_F_CANREAD | PERLIO_F_CANWRITE | PERLIO_F_OPEN);
2113 while (PerlIOValid(n)) {
2114 const PerlIO_funcs * const tab = PerlIOBase(n)->tab;
2115 if (tab && tab->Close) {
2116 if ((*tab->Close)(aTHX_ n) != 0)
2121 PerlIOBase(n)->flags &=
2122 ~(PERLIO_F_CANREAD | PERLIO_F_CANWRITE | PERLIO_F_OPEN);
2128 SETERRNO(EBADF, SS_IVCHAN);
2134 PerlIOBase_eof(pTHX_ PerlIO *f)
2136 if (PerlIOValid(f)) {
2137 return (PerlIOBase(f)->flags & PERLIO_F_EOF) != 0;
2143 PerlIOBase_error(pTHX_ PerlIO *f)
2145 if (PerlIOValid(f)) {
2146 return (PerlIOBase(f)->flags & PERLIO_F_ERROR) != 0;
2152 PerlIOBase_clearerr(pTHX_ PerlIO *f)
2154 if (PerlIOValid(f)) {
2155 PerlIO *n = PerlIONext(f);
2156 PerlIOBase(f)->flags &= ~(PERLIO_F_ERROR | PERLIO_F_EOF);
2163 PerlIOBase_setlinebuf(pTHX_ PerlIO *f)
2165 if (PerlIOValid(f)) {
2166 PerlIOBase(f)->flags |= PERLIO_F_LINEBUF;
2171 PerlIO_sv_dup(pTHX_ SV *arg, CLONE_PARAMS *param)
2177 return sv_dup(arg, param);
2180 return newSVsv(arg);
2183 PERL_UNUSED_ARG(param);
2184 return newSVsv(arg);
2189 PerlIOBase_dup(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags)
2191 PerlIO * const nexto = PerlIONext(o);
2192 if (PerlIOValid(nexto)) {
2193 const PerlIO_funcs * const tab = PerlIOBase(nexto)->tab;
2194 if (tab && tab->Dup)
2195 f = (*tab->Dup)(aTHX_ f, nexto, param, flags);
2197 f = PerlIOBase_dup(aTHX_ f, nexto, param, flags);
2200 PerlIO_funcs *self = PerlIOBase(o)->tab;
2203 PerlIO_debug("PerlIOBase_dup %s f=%p o=%p param=%p\n",
2204 self->name, (void*)f, (void*)o, (void*)param);
2206 arg = (*self->Getarg)(aTHX_ o, param, flags);
2210 f = PerlIO_push(aTHX_ f, self, PerlIO_modestr(o,buf), arg);
2219 perl_mutex PerlIO_mutex;
2222 /* PL_perlio_fd_refcnt[] is in intrpvar.h */
2227 /* Place holder for stdstreams call ??? */
2229 MUTEX_INIT(&PerlIO_mutex);
2234 PerlIOUnix_refcnt_inc(int fd)
2237 if (fd >= 0 && fd < PERLIO_MAX_REFCOUNTABLE_FD) {
2239 MUTEX_LOCK(&PerlIO_mutex);
2241 PL_perlio_fd_refcnt[fd]++;
2242 PerlIO_debug("fd %d refcnt=%d\n",fd,PL_perlio_fd_refcnt[fd]);
2244 MUTEX_UNLOCK(&PerlIO_mutex);
2250 PerlIOUnix_refcnt_dec(int fd)
2254 if (fd >= 0 && fd < PERLIO_MAX_REFCOUNTABLE_FD) {
2256 MUTEX_LOCK(&PerlIO_mutex);
2258 cnt = --PL_perlio_fd_refcnt[fd];
2259 PerlIO_debug("fd %d refcnt=%d\n",fd,cnt);
2261 MUTEX_UNLOCK(&PerlIO_mutex);
2268 PerlIO_cleanup(pTHX)
2272 PerlIO_debug("Cleanup layers for %p\n",aTHX);
2274 PerlIO_debug("Cleanup layers\n");
2276 /* Raise STDIN..STDERR refcount so we don't close them */
2277 for (i=0; i < 3; i++)
2278 PerlIOUnix_refcnt_inc(i);
2279 PerlIO_cleantable(aTHX_ &PL_perlio);
2280 /* Restore STDIN..STDERR refcount */
2281 for (i=0; i < 3; i++)
2282 PerlIOUnix_refcnt_dec(i);
2284 if (PL_known_layers) {
2285 PerlIO_list_free(aTHX_ PL_known_layers);
2286 PL_known_layers = NULL;
2288 if (PL_def_layerlist) {
2289 PerlIO_list_free(aTHX_ PL_def_layerlist);
2290 PL_def_layerlist = NULL;
2296 /*--------------------------------------------------------------------------------------*/
2298 * Bottom-most level for UNIX-like case
2302 struct _PerlIO base; /* The generic part */
2303 int fd; /* UNIX like file descriptor */
2304 int oflags; /* open/fcntl flags */
2308 PerlIOUnix_oflags(const char *mode)
2311 if (*mode == IoTYPE_IMPLICIT || *mode == IoTYPE_NUMERIC)
2316 if (*++mode == '+') {
2323 oflags = O_CREAT | O_TRUNC;
2324 if (*++mode == '+') {
2333 oflags = O_CREAT | O_APPEND;
2334 if (*++mode == '+') {
2347 else if (*mode == 't') {
2349 oflags &= ~O_BINARY;
2353 * Always open in binary mode
2356 if (*mode || oflags == -1) {
2357 SETERRNO(EINVAL, LIB_INVARG);
2364 PerlIOUnix_fileno(pTHX_ PerlIO *f)
2366 return PerlIOSelf(f, PerlIOUnix)->fd;
2370 PerlIOUnix_setfd(pTHX_ PerlIO *f, int fd, int imode)
2372 PerlIOUnix * const s = PerlIOSelf(f, PerlIOUnix);
2375 if (PerlLIO_fstat(fd, &st) == 0) {
2376 if (!S_ISREG(st.st_mode)) {
2377 PerlIO_debug("%d is not regular file\n",fd);
2378 PerlIOBase(f)->flags |= PERLIO_F_NOTREG;
2381 PerlIO_debug("%d _is_ a regular file\n",fd);
2387 PerlIOUnix_refcnt_inc(fd);
2391 PerlIOUnix_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
2393 IV code = PerlIOBase_pushed(aTHX_ f, mode, arg, tab);
2394 if (*PerlIONext(f)) {
2395 /* We never call down so do any pending stuff now */
2396 PerlIO_flush(PerlIONext(f));
2398 * XXX could (or should) we retrieve the oflags from the open file
2399 * handle rather than believing the "mode" we are passed in? XXX
2400 * Should the value on NULL mode be 0 or -1?
2402 PerlIOUnix_setfd(aTHX_ f, PerlIO_fileno(PerlIONext(f)),
2403 mode ? PerlIOUnix_oflags(mode) : -1);
2405 PerlIOBase(f)->flags |= PERLIO_F_OPEN;
2411 PerlIOUnix_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
2413 const int fd = PerlIOSelf(f, PerlIOUnix)->fd;
2415 if (PerlIOBase(f)->flags & PERLIO_F_NOTREG) {
2417 SETERRNO(ESPIPE, LIB_INVARG);
2419 SETERRNO(EINVAL, LIB_INVARG);
2423 new_loc = PerlLIO_lseek(fd, offset, whence);
2424 if (new_loc == (Off_t) - 1)
2428 PerlIOBase(f)->flags &= ~PERLIO_F_EOF;
2433 PerlIOUnix_open(pTHX_ PerlIO_funcs *self, PerlIO_list_t *layers,
2434 IV n, const char *mode, int fd, int imode,
2435 int perm, PerlIO *f, int narg, SV **args)
2437 if (PerlIOValid(f)) {
2438 if (PerlIOBase(f)->flags & PERLIO_F_OPEN)
2439 (*PerlIOBase(f)->tab->Close)(aTHX_ f);
2442 if (*mode == IoTYPE_NUMERIC)
2445 imode = PerlIOUnix_oflags(mode);
2449 const char *path = SvPV_nolen_const(*args);
2450 fd = PerlLIO_open3(path, imode, perm);
2454 if (*mode == IoTYPE_IMPLICIT)
2457 f = PerlIO_allocate(aTHX);
2459 if (!PerlIOValid(f)) {
2460 if (!(f = PerlIO_push(aTHX_ f, self, mode, PerlIOArg))) {
2464 PerlIOUnix_setfd(aTHX_ f, fd, imode);
2465 PerlIOBase(f)->flags |= PERLIO_F_OPEN;
2466 if (*mode == IoTYPE_APPEND)
2467 PerlIOUnix_seek(aTHX_ f, 0, SEEK_END);
2473 * FIXME: pop layers ???
2481 PerlIOUnix_dup(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags)
2483 PerlIOUnix *os = PerlIOSelf(o, PerlIOUnix);
2485 if (flags & PERLIO_DUP_FD) {
2486 fd = PerlLIO_dup(fd);
2488 if (fd >= 0 && fd < PERLIO_MAX_REFCOUNTABLE_FD) {
2489 f = PerlIOBase_dup(aTHX_ f, o, param, flags);
2491 /* If all went well overwrite fd in dup'ed lay with the dup()'ed fd */
2492 PerlIOUnix_setfd(aTHX_ f, fd, os->oflags);
2501 PerlIOUnix_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
2503 const int fd = PerlIOSelf(f, PerlIOUnix)->fd;
2504 #ifdef PERLIO_STD_SPECIAL
2506 return PERLIO_STD_IN(fd, vbuf, count);
2508 if (!(PerlIOBase(f)->flags & PERLIO_F_CANREAD) ||
2509 PerlIOBase(f)->flags & (PERLIO_F_EOF|PERLIO_F_ERROR)) {
2513 const SSize_t len = PerlLIO_read(fd, vbuf, count);
2514 if (len >= 0 || errno != EINTR) {
2516 if (errno != EAGAIN) {
2517 PerlIOBase(f)->flags |= PERLIO_F_ERROR;
2520 else if (len == 0 && count != 0) {
2521 PerlIOBase(f)->flags |= PERLIO_F_EOF;
2532 PerlIOUnix_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
2534 const int fd = PerlIOSelf(f, PerlIOUnix)->fd;
2535 #ifdef PERLIO_STD_SPECIAL
2536 if (fd == 1 || fd == 2)
2537 return PERLIO_STD_OUT(fd, vbuf, count);
2540 const SSize_t len = PerlLIO_write(fd, vbuf, count);
2541 if (len >= 0 || errno != EINTR) {
2543 if (errno != EAGAIN) {
2544 PerlIOBase(f)->flags |= PERLIO_F_ERROR;
2555 PerlIOUnix_tell(pTHX_ PerlIO *f)
2557 return PerlLIO_lseek(PerlIOSelf(f, PerlIOUnix)->fd, 0, SEEK_CUR);
2562 PerlIOUnix_close(pTHX_ PerlIO *f)
2564 const int fd = PerlIOSelf(f, PerlIOUnix)->fd;
2566 if (PerlIOBase(f)->flags & PERLIO_F_OPEN) {
2567 if (PerlIOUnix_refcnt_dec(fd) > 0) {
2568 PerlIOBase(f)->flags &= ~PERLIO_F_OPEN;
2573 SETERRNO(EBADF,SS_IVCHAN);
2576 while (PerlLIO_close(fd) != 0) {
2577 if (errno != EINTR) {
2584 PerlIOBase(f)->flags &= ~PERLIO_F_OPEN;
2589 PERLIO_FUNCS_DECL(PerlIO_unix) = {
2590 sizeof(PerlIO_funcs),
2597 PerlIOBase_binmode, /* binmode */
2607 PerlIOBase_noop_ok, /* flush */
2608 PerlIOBase_noop_fail, /* fill */
2611 PerlIOBase_clearerr,
2612 PerlIOBase_setlinebuf,
2613 NULL, /* get_base */
2614 NULL, /* get_bufsiz */
2617 NULL, /* set_ptrcnt */
2620 /*--------------------------------------------------------------------------------------*/
2625 #if defined(VMS) && !defined(STDIO_BUFFER_WRITABLE)
2626 /* perl5.8 - This ensures the last minute VMS ungetc fix is not
2627 broken by the last second glibc 2.3 fix
2629 #define STDIO_BUFFER_WRITABLE
2634 struct _PerlIO base;
2635 FILE *stdio; /* The stream */
2639 PerlIOStdio_fileno(pTHX_ PerlIO *f)
2642 if (PerlIOValid(f) && (s = PerlIOSelf(f, PerlIOStdio)->stdio)) {
2643 return PerlSIO_fileno(s);
2650 PerlIOStdio_mode(const char *mode, char *tmode)
2652 char * const ret = tmode;
2658 #if defined(PERLIO_USING_CRLF) || defined(__CYGWIN__)
2666 PerlIOStdio_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
2669 if (PerlIOValid(f) && PerlIOValid(n = PerlIONext(f))) {
2670 PerlIO_funcs * const toptab = PerlIOBase(n)->tab;
2671 if (toptab == tab) {
2672 /* Top is already stdio - pop self (duplicate) and use original */
2673 PerlIO_pop(aTHX_ f);
2676 const int fd = PerlIO_fileno(n);
2679 if (fd >= 0 && (stdio = PerlSIO_fdopen(fd,
2680 mode = PerlIOStdio_mode(mode, tmode)))) {
2681 PerlIOSelf(f, PerlIOStdio)->stdio = stdio;
2682 /* We never call down so do any pending stuff now */
2683 PerlIO_flush(PerlIONext(f));
2690 return PerlIOBase_pushed(aTHX_ f, mode, arg, tab);
2695 PerlIO_importFILE(FILE *stdio, const char *mode)
2701 if (!mode || !*mode) {
2702 /* We need to probe to see how we can open the stream
2703 so start with read/write and then try write and read
2704 we dup() so that we can fclose without loosing the fd.
2706 Note that the errno value set by a failing fdopen
2707 varies between stdio implementations.
2709 const int fd = PerlLIO_dup(fileno(stdio));
2710 FILE *f2 = PerlSIO_fdopen(fd, (mode = "r+"));
2712 f2 = PerlSIO_fdopen(fd, (mode = "w"));
2715 f2 = PerlSIO_fdopen(fd, (mode = "r"));
2718 /* Don't seem to be able to open */
2724 if ((f = PerlIO_push(aTHX_(f = PerlIO_allocate(aTHX)), PERLIO_FUNCS_CAST(&PerlIO_stdio), mode, Nullsv))) {
2725 s = PerlIOSelf(f, PerlIOStdio);
2733 PerlIOStdio_open(pTHX_ PerlIO_funcs *self, PerlIO_list_t *layers,
2734 IV n, const char *mode, int fd, int imode,
2735 int perm, PerlIO *f, int narg, SV **args)
2738 if (PerlIOValid(f)) {
2739 const char *path = SvPV_nolen_const(*args);
2740 PerlIOStdio *s = PerlIOSelf(f, PerlIOStdio);
2742 PerlIOUnix_refcnt_dec(fileno(s->stdio));
2743 stdio = PerlSIO_freopen(path, (mode = PerlIOStdio_mode(mode, tmode)),
2748 PerlIOUnix_refcnt_inc(fileno(s->stdio));
2753 const char *path = SvPV_nolen_const(*args);
2754 if (*mode == IoTYPE_NUMERIC) {
2756 fd = PerlLIO_open3(path, imode, perm);
2760 bool appended = FALSE;
2762 /* Cygwin wants its 'b' early. */
2764 mode = PerlIOStdio_mode(mode, tmode);
2766 stdio = PerlSIO_fopen(path, mode);
2770 f = PerlIO_allocate(aTHX);
2773 mode = PerlIOStdio_mode(mode, tmode);
2774 f = PerlIO_push(aTHX_ f, self, mode, PerlIOArg);
2776 s = PerlIOSelf(f, PerlIOStdio);
2778 PerlIOUnix_refcnt_inc(fileno(s->stdio));
2790 if (*mode == IoTYPE_IMPLICIT) {
2797 stdio = PerlSIO_stdin;
2800 stdio = PerlSIO_stdout;
2803 stdio = PerlSIO_stderr;
2808 stdio = PerlSIO_fdopen(fd, mode =
2809 PerlIOStdio_mode(mode, tmode));
2813 f = PerlIO_allocate(aTHX);
2815 if ((f = PerlIO_push(aTHX_ f, self, mode, PerlIOArg))) {
2816 PerlIOStdio *s = PerlIOSelf(f, PerlIOStdio);
2818 PerlIOUnix_refcnt_inc(fileno(s->stdio));
2828 PerlIOStdio_dup(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags)
2830 /* This assumes no layers underneath - which is what
2831 happens, but is not how I remember it. NI-S 2001/10/16
2833 if ((f = PerlIOBase_dup(aTHX_ f, o, param, flags))) {
2834 FILE *stdio = PerlIOSelf(o, PerlIOStdio)->stdio;
2835 const int fd = fileno(stdio);
2837 if (flags & PERLIO_DUP_FD) {
2838 const int dfd = PerlLIO_dup(fileno(stdio));
2840 stdio = PerlSIO_fdopen(dfd, PerlIO_modestr(o,mode));
2844 /* FIXME: To avoid messy error recovery if dup fails
2845 re-use the existing stdio as though flag was not set
2849 stdio = PerlSIO_fdopen(fd, PerlIO_modestr(o,mode));
2851 PerlIOSelf(f, PerlIOStdio)->stdio = stdio;
2852 PerlIOUnix_refcnt_inc(fileno(stdio));
2858 PerlIOStdio_invalidate_fileno(pTHX_ FILE *f)
2860 /* XXX this could use PerlIO_canset_fileno() and
2861 * PerlIO_set_fileno() support from Configure
2863 # if defined(__UCLIBC__)
2864 /* uClibc must come before glibc because it defines __GLIBC__ as well. */
2867 # elif defined(__GLIBC__)
2868 /* There may be a better way for GLIBC:
2869 - libio.h defines a flag to not close() on cleanup
2873 # elif defined(__sun__)
2875 /* On solaris, if _LP64 is defined, the FILE structure is this:
2881 * It turns out that the fd is stored in the top 32 bits of
2882 * file->__pad[4]. The lower 32 bits contain flags. file->pad[5] appears
2883 * to contain a pointer or offset into another structure. All the
2884 * remaining fields are zero.
2886 * We set the top bits to -1 (0xFFFFFFFF).
2888 f->__pad[4] |= 0xffffffff00000000L;
2889 assert(fileno(f) == 0xffffffff);
2890 # else /* !defined(_LP64) */
2891 /* _file is just a unsigned char :-(
2892 Not clear why we dup() rather than using -1
2893 even if that would be treated as 0xFF - so will
2896 f->_file = PerlLIO_dup(fileno(f));
2897 # endif /* defined(_LP64) */
2899 # elif defined(__hpux)
2903 /* Next one ->_file seems to be a reasonable fallback, i.e. if
2904 your platform does not have special entry try this one.
2905 [For OSF only have confirmation for Tru64 (alpha)
2906 but assume other OSFs will be similar.]
2908 # elif defined(_AIX) || defined(__osf__) || defined(__irix__)
2911 # elif defined(__FreeBSD__)
2912 /* There may be a better way on FreeBSD:
2913 - we could insert a dummy func in the _close function entry
2914 f->_close = (int (*)(void *)) dummy_close;
2918 # elif defined(__OpenBSD__)
2919 /* There may be a better way on OpenBSD:
2920 - we could insert a dummy func in the _close function entry
2921 f->_close = (int (*)(void *)) dummy_close;
2925 # elif defined(__EMX__)
2926 /* f->_flags &= ~_IOOPEN; */ /* Will leak stream->_buffer */
2929 # elif defined(__CYGWIN__)
2930 /* There may be a better way on CYGWIN:
2931 - we could insert a dummy func in the _close function entry
2932 f->_close = (int (*)(void *)) dummy_close;
2936 # elif defined(WIN32)
2937 # if defined(__BORLANDC__)
2938 f->fd = PerlLIO_dup(fileno(f));
2939 # elif defined(UNDER_CE)
2940 /* WIN_CE does not have access to FILE internals, it hardly has FILE
2949 /* Sarathy's code did this - we fall back to a dup/dup2 hack
2950 (which isn't thread safe) instead
2952 # error "Don't know how to set FILE.fileno on your platform"
2960 PerlIOStdio_close(pTHX_ PerlIO *f)
2962 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
2968 const int fd = fileno(stdio);
2974 #ifdef SOCKS5_VERSION_NAME
2975 /* Socks lib overrides close() but stdio isn't linked to
2976 that library (though we are) - so we must call close()
2977 on sockets on stdio's behalf.
2980 Sock_size_t optlen = sizeof(int);
2981 if (getsockopt(fd, SOL_SOCKET, SO_TYPE, (void *) &optval, &optlen) == 0) {
2986 if (PerlIOUnix_refcnt_dec(fd) > 0) {
2987 /* File descriptor still in use */
2992 /* For STD* handles don't close the stdio at all
2993 this is because we have shared the FILE * too
2995 if (stdio == stdin) {
2996 /* Some stdios are buggy fflush-ing inputs */
2999 else if (stdio == stdout || stdio == stderr) {
3000 return PerlIO_flush(f);
3002 /* Tricky - must fclose(stdio) to free memory but not close(fd)
3003 Use Sarathy's trick from maint-5.6 to invalidate the
3004 fileno slot of the FILE *
3006 result = PerlIO_flush(f);
3008 if (!(invalidate = PerlIOStdio_invalidate_fileno(aTHX_ stdio))) {
3009 dupfd = PerlLIO_dup(fd);
3012 result = PerlSIO_fclose(stdio);
3013 /* We treat error from stdio as success if we invalidated
3014 errno may NOT be expected EBADF
3016 if (invalidate && result != 0) {
3021 /* in SOCKS case let close() determine return value */
3025 PerlLIO_dup2(dupfd,fd);
3026 PerlLIO_close(dupfd);
3033 PerlIOStdio_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
3035 FILE *s = PerlIOSelf(f, PerlIOStdio)->stdio;
3039 STDCHAR *buf = (STDCHAR *) vbuf;
3041 * Perl is expecting PerlIO_getc() to fill the buffer Linux's
3042 * stdio does not do that for fread()
3044 const int ch = PerlSIO_fgetc(s);
3051 got = PerlSIO_fread(vbuf, 1, count, s);
3052 if (got == 0 && PerlSIO_ferror(s))
3054 if (got >= 0 || errno != EINTR)
3057 SETERRNO(0,0); /* just in case */
3063 PerlIOStdio_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
3066 FILE *s = PerlIOSelf(f, PerlIOStdio)->stdio;
3068 #ifdef STDIO_BUFFER_WRITABLE
3069 if (PerlIO_fast_gets(f) && PerlIO_has_base(f)) {
3070 STDCHAR *buf = ((STDCHAR *) vbuf) + count;
3071 STDCHAR *base = PerlIO_get_base(f);
3072 SSize_t cnt = PerlIO_get_cnt(f);
3073 STDCHAR *ptr = PerlIO_get_ptr(f);
3074 SSize_t avail = ptr - base;
3076 if (avail > count) {
3080 Move(buf-avail,ptr,avail,STDCHAR);
3083 PerlIO_set_ptrcnt(f,ptr,cnt+avail);
3084 if (PerlSIO_feof(s) && unread >= 0)
3085 PerlSIO_clearerr(s);
3090 if (PerlIO_has_cntptr(f)) {
3091 /* We can get pointer to buffer but not its base
3092 Do ungetc() but check chars are ending up in the
3095 STDCHAR *eptr = (STDCHAR*)PerlSIO_get_ptr(s);
3096 STDCHAR *buf = ((STDCHAR *) vbuf) + count;
3098 const int ch = *--buf & 0xFF;
3099 if (ungetc(ch,s) != ch) {
3100 /* ungetc did not work */
3103 if ((STDCHAR*)PerlSIO_get_ptr(s) != --eptr || ((*eptr & 0xFF) != ch)) {
3104 /* Did not change pointer as expected */
3105 fgetc(s); /* get char back again */
3115 unread += PerlIOBase_unread(aTHX_ f, vbuf, count);
3121 PerlIOStdio_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
3125 got = PerlSIO_fwrite(vbuf, 1, count,
3126 PerlIOSelf(f, PerlIOStdio)->stdio);
3127 if (got >= 0 || errno != EINTR)
3130 SETERRNO(0,0); /* just in case */
3136 PerlIOStdio_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
3138 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3139 return PerlSIO_fseek(stdio, offset, whence);
3143 PerlIOStdio_tell(pTHX_ PerlIO *f)
3145 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3146 return PerlSIO_ftell(stdio);
3150 PerlIOStdio_flush(pTHX_ PerlIO *f)
3152 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3153 if (PerlIOBase(f)->flags & PERLIO_F_CANWRITE) {
3154 return PerlSIO_fflush(stdio);
3159 * FIXME: This discards ungetc() and pre-read stuff which is not
3160 * right if this is just a "sync" from a layer above Suspect right
3161 * design is to do _this_ but not have layer above flush this
3162 * layer read-to-read
3165 * Not writeable - sync by attempting a seek
3168 if (PerlSIO_fseek(stdio, (Off_t) 0, SEEK_CUR) != 0)
3176 PerlIOStdio_eof(pTHX_ PerlIO *f)
3178 return PerlSIO_feof(PerlIOSelf(f, PerlIOStdio)->stdio);
3182 PerlIOStdio_error(pTHX_ PerlIO *f)
3184 return PerlSIO_ferror(PerlIOSelf(f, PerlIOStdio)->stdio);
3188 PerlIOStdio_clearerr(pTHX_ PerlIO *f)
3190 PerlSIO_clearerr(PerlIOSelf(f, PerlIOStdio)->stdio);
3194 PerlIOStdio_setlinebuf(pTHX_ PerlIO *f)
3196 #ifdef HAS_SETLINEBUF
3197 PerlSIO_setlinebuf(PerlIOSelf(f, PerlIOStdio)->stdio);
3199 PerlSIO_setvbuf(PerlIOSelf(f, PerlIOStdio)->stdio, Nullch, _IOLBF, 0);
3205 PerlIOStdio_get_base(pTHX_ PerlIO *f)
3207 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3208 return (STDCHAR*)PerlSIO_get_base(stdio);
3212 PerlIOStdio_get_bufsiz(pTHX_ PerlIO *f)
3214 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3215 return PerlSIO_get_bufsiz(stdio);
3219 #ifdef USE_STDIO_PTR
3221 PerlIOStdio_get_ptr(pTHX_ PerlIO *f)
3223 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3224 return (STDCHAR*)PerlSIO_get_ptr(stdio);
3228 PerlIOStdio_get_cnt(pTHX_ PerlIO *f)
3230 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3231 return PerlSIO_get_cnt(stdio);
3235 PerlIOStdio_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, SSize_t cnt)
3237 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3239 #ifdef STDIO_PTR_LVALUE
3240 PerlSIO_set_ptr(stdio, (void*)ptr); /* LHS STDCHAR* cast non-portable */
3241 #ifdef STDIO_PTR_LVAL_SETS_CNT
3242 if (PerlSIO_get_cnt(stdio) != (cnt)) {
3243 assert(PerlSIO_get_cnt(stdio) == (cnt));
3246 #if (!defined(STDIO_PTR_LVAL_NOCHANGE_CNT))
3248 * Setting ptr _does_ change cnt - we are done
3252 #else /* STDIO_PTR_LVALUE */
3254 #endif /* STDIO_PTR_LVALUE */
3257 * Now (or only) set cnt
3259 #ifdef STDIO_CNT_LVALUE
3260 PerlSIO_set_cnt(stdio, cnt);
3261 #else /* STDIO_CNT_LVALUE */
3262 #if (defined(STDIO_PTR_LVALUE) && defined(STDIO_PTR_LVAL_SETS_CNT))
3263 PerlSIO_set_ptr(stdio,
3264 PerlSIO_get_ptr(stdio) + (PerlSIO_get_cnt(stdio) -
3266 #else /* STDIO_PTR_LVAL_SETS_CNT */
3268 #endif /* STDIO_PTR_LVAL_SETS_CNT */
3269 #endif /* STDIO_CNT_LVALUE */
3276 PerlIOStdio_fill(pTHX_ PerlIO *f)
3278 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3281 * fflush()ing read-only streams can cause trouble on some stdio-s
3283 if ((PerlIOBase(f)->flags & PERLIO_F_CANWRITE)) {
3284 if (PerlSIO_fflush(stdio) != 0)
3287 c = PerlSIO_fgetc(stdio);
3291 #if (defined(STDIO_PTR_LVALUE) && (defined(STDIO_CNT_LVALUE) || defined(STDIO_PTR_LVAL_SETS_CNT)))
3293 #ifdef STDIO_BUFFER_WRITABLE
3294 if (PerlIO_fast_gets(f) && PerlIO_has_base(f)) {
3295 /* Fake ungetc() to the real buffer in case system's ungetc
3298 STDCHAR *base = (STDCHAR*)PerlSIO_get_base(stdio);
3299 SSize_t cnt = PerlSIO_get_cnt(stdio);
3300 STDCHAR *ptr = (STDCHAR*)PerlSIO_get_ptr(stdio);
3301 if (ptr == base+1) {
3302 *--ptr = (STDCHAR) c;
3303 PerlIOStdio_set_ptrcnt(aTHX_ f,ptr,cnt+1);
3304 if (PerlSIO_feof(stdio))
3305 PerlSIO_clearerr(stdio);
3311 if (PerlIO_has_cntptr(f)) {
3313 if (PerlIOStdio_unread(aTHX_ f,&ch,1) == 1) {
3320 /* An ungetc()d char is handled separately from the regular
3321 * buffer, so we stuff it in the buffer ourselves.
3322 * Should never get called as should hit code above
3324 *(--((*stdio)->_ptr)) = (unsigned char) c;
3327 /* If buffer snoop scheme above fails fall back to
3330 if (PerlSIO_ungetc(c, stdio) != c)
3338 PERLIO_FUNCS_DECL(PerlIO_stdio) = {
3339 sizeof(PerlIO_funcs),
3341 sizeof(PerlIOStdio),
3342 PERLIO_K_BUFFERED|PERLIO_K_RAW,
3346 PerlIOBase_binmode, /* binmode */
3360 PerlIOStdio_clearerr,
3361 PerlIOStdio_setlinebuf,
3363 PerlIOStdio_get_base,
3364 PerlIOStdio_get_bufsiz,
3369 #ifdef USE_STDIO_PTR
3370 PerlIOStdio_get_ptr,
3371 PerlIOStdio_get_cnt,
3372 # if defined(HAS_FAST_STDIO) && defined(USE_FAST_STDIO)
3373 PerlIOStdio_set_ptrcnt,
3376 # endif /* HAS_FAST_STDIO && USE_FAST_STDIO */
3381 #endif /* USE_STDIO_PTR */
3384 /* Note that calls to PerlIO_exportFILE() are reversed using
3385 * PerlIO_releaseFILE(), not importFILE. */
3387 PerlIO_exportFILE(PerlIO * f, const char *mode)
3391 if (PerlIOValid(f)) {
3394 if (!mode || !*mode) {
3395 mode = PerlIO_modestr(f, buf);
3397 stdio = PerlSIO_fdopen(PerlIO_fileno(f), mode);
3401 /* De-link any lower layers so new :stdio sticks */
3403 if ((f2 = PerlIO_push(aTHX_ f, PERLIO_FUNCS_CAST(&PerlIO_stdio), buf, Nullsv))) {
3404 PerlIOStdio *s = PerlIOSelf((f = f2), PerlIOStdio);
3406 /* Link previous lower layers under new one */
3410 /* restore layers list */
3420 PerlIO_findFILE(PerlIO *f)
3424 if (l->tab == &PerlIO_stdio) {
3425 PerlIOStdio *s = PerlIOSelf(&l, PerlIOStdio);
3428 l = *PerlIONext(&l);
3430 /* Uses fallback "mode" via PerlIO_modestr() in PerlIO_exportFILE */
3431 return PerlIO_exportFILE(f, Nullch);
3434 /* Use this to reverse PerlIO_exportFILE calls. */
3436 PerlIO_releaseFILE(PerlIO *p, FILE *f)
3441 if (l->tab == &PerlIO_stdio) {
3442 PerlIOStdio *s = PerlIOSelf(&l, PerlIOStdio);
3443 if (s->stdio == f) {
3445 PerlIO_pop(aTHX_ p);
3454 /*--------------------------------------------------------------------------------------*/
3456 * perlio buffer layer
3460 PerlIOBuf_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
3462 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3463 const int fd = PerlIO_fileno(f);
3464 if (fd >= 0 && PerlLIO_isatty(fd)) {
3465 PerlIOBase(f)->flags |= PERLIO_F_LINEBUF | PERLIO_F_TTY;
3467 if (*PerlIONext(f)) {
3468 const Off_t posn = PerlIO_tell(PerlIONext(f));
3469 if (posn != (Off_t) - 1) {
3473 return PerlIOBase_pushed(aTHX_ f, mode, arg, tab);
3477 PerlIOBuf_open(pTHX_ PerlIO_funcs *self, PerlIO_list_t *layers,
3478 IV n, const char *mode, int fd, int imode, int perm,
3479 PerlIO *f, int narg, SV **args)
3481 if (PerlIOValid(f)) {
3482 PerlIO *next = PerlIONext(f);
3484 PerlIO_layer_fetch(aTHX_ layers, n - 1, PerlIOBase(next)->tab);
3485 if (tab && tab->Open)
3487 (*tab->Open)(aTHX_ tab, layers, n - 1, mode, fd, imode, perm,
3489 if (!next || (*PerlIOBase(f)->tab->Pushed) (aTHX_ f, mode, PerlIOArg, self) != 0) {
3494 PerlIO_funcs *tab = PerlIO_layer_fetch(aTHX_ layers, n - 1, PerlIO_default_btm());
3496 if (*mode == IoTYPE_IMPLICIT) {
3502 if (tab && tab->Open)
3503 f = (*tab->Open)(aTHX_ tab, layers, n - 1, mode, fd, imode, perm,
3506 SETERRNO(EINVAL, LIB_INVARG);
3508 if (PerlIO_push(aTHX_ f, self, mode, PerlIOArg) == 0) {
3510 * if push fails during open, open fails. close will pop us.
3515 fd = PerlIO_fileno(f);
3516 if (init && fd == 2) {
3518 * Initial stderr is unbuffered
3520 PerlIOBase(f)->flags |= PERLIO_F_UNBUF;
3522 #ifdef PERLIO_USING_CRLF
3523 # ifdef PERLIO_IS_BINMODE_FD
3524 if (PERLIO_IS_BINMODE_FD(fd))
3525 PerlIO_binmode(aTHX_ f, '<'/*not used*/, O_BINARY, Nullch);
3529 * do something about failing setmode()? --jhi
3531 PerlLIO_setmode(fd, O_BINARY);
3540 * This "flush" is akin to sfio's sync in that it handles files in either
3541 * read or write state
3544 PerlIOBuf_flush(pTHX_ PerlIO *f)
3546 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3548 PerlIO *n = PerlIONext(f);
3549 if (PerlIOBase(f)->flags & PERLIO_F_WRBUF) {
3551 * write() the buffer
3553 const STDCHAR *buf = b->buf;
3554 const STDCHAR *p = buf;
3555 while (p < b->ptr) {
3556 SSize_t count = PerlIO_write(n, p, b->ptr - p);
3560 else if (count < 0 || PerlIO_error(n)) {
3561 PerlIOBase(f)->flags |= PERLIO_F_ERROR;
3566 b->posn += (p - buf);
3568 else if (PerlIOBase(f)->flags & PERLIO_F_RDBUF) {
3569 STDCHAR *buf = PerlIO_get_base(f);
3571 * Note position change
3573 b->posn += (b->ptr - buf);
3574 if (b->ptr < b->end) {
3575 /* We did not consume all of it - try and seek downstream to
3576 our logical position
3578 if (PerlIOValid(n) && PerlIO_seek(n, b->posn, SEEK_SET) == 0) {
3579 /* Reload n as some layers may pop themselves on seek */
3580 b->posn = PerlIO_tell(n = PerlIONext(f));
3583 /* Seek failed (e.g. pipe or tty). Do NOT clear buffer or pre-read
3584 data is lost for good - so return saying "ok" having undone
3587 b->posn -= (b->ptr - buf);
3592 b->ptr = b->end = b->buf;
3593 PerlIOBase(f)->flags &= ~(PERLIO_F_RDBUF | PERLIO_F_WRBUF);
3594 /* We check for Valid because of dubious decision to make PerlIO_flush(NULL) flush all */
3595 if (PerlIOValid(n) && PerlIO_flush(n) != 0)
3601 PerlIOBuf_fill(pTHX_ PerlIO *f)
3603 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3604 PerlIO *n = PerlIONext(f);
3607 * Down-stream flush is defined not to loose read data so is harmless.
3608 * we would not normally be fill'ing if there was data left in anycase.
3610 if (PerlIO_flush(f) != 0)
3612 if (PerlIOBase(f)->flags & PERLIO_F_TTY)
3613 PerlIOBase_flush_linebuf(aTHX);
3616 PerlIO_get_base(f); /* allocate via vtable */
3618 b->ptr = b->end = b->buf;
3620 if (!PerlIOValid(n)) {
3621 PerlIOBase(f)->flags |= PERLIO_F_EOF;
3625 if (PerlIO_fast_gets(n)) {
3627 * Layer below is also buffered. We do _NOT_ want to call its
3628 * ->Read() because that will loop till it gets what we asked for
3629 * which may hang on a pipe etc. Instead take anything it has to
3630 * hand, or ask it to fill _once_.
3632 avail = PerlIO_get_cnt(n);
3634 avail = PerlIO_fill(n);
3636 avail = PerlIO_get_cnt(n);
3638 if (!PerlIO_error(n) && PerlIO_eof(n))
3643 STDCHAR *ptr = PerlIO_get_ptr(n);
3644 SSize_t cnt = avail;
3645 if (avail > (SSize_t)b->bufsiz)
3647 Copy(ptr, b->buf, avail, STDCHAR);
3648 PerlIO_set_ptrcnt(n, ptr + avail, cnt - avail);
3652 avail = PerlIO_read(n, b->ptr, b->bufsiz);
3656 PerlIOBase(f)->flags |= PERLIO_F_EOF;
3658 PerlIOBase(f)->flags |= PERLIO_F_ERROR;
3661 b->end = b->buf + avail;
3662 PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
3667 PerlIOBuf_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
3669 if (PerlIOValid(f)) {
3670 const PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3673 return PerlIOBase_read(aTHX_ f, vbuf, count);
3679 PerlIOBuf_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
3681 const STDCHAR *buf = (const STDCHAR *) vbuf + count;
3682 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3685 if (PerlIOBase(f)->flags & PERLIO_F_WRBUF)
3690 if (PerlIOBase(f)->flags & PERLIO_F_RDBUF) {
3692 * Buffer is already a read buffer, we can overwrite any chars
3693 * which have been read back to buffer start
3695 avail = (b->ptr - b->buf);
3699 * Buffer is idle, set it up so whole buffer is available for
3703 b->end = b->buf + avail;
3705 PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
3707 * Buffer extends _back_ from where we are now
3709 b->posn -= b->bufsiz;
3711 if (avail > (SSize_t) count) {
3713 * If we have space for more than count, just move count
3721 * In simple stdio-like ungetc() case chars will be already
3724 if (buf != b->ptr) {
3725 Copy(buf, b->ptr, avail, STDCHAR);
3729 PerlIOBase(f)->flags &= ~PERLIO_F_EOF;
3733 unread += PerlIOBase_unread(aTHX_ f, vbuf, count);
3739 PerlIOBuf_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
3741 PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
3742 const STDCHAR *buf = (const STDCHAR *) vbuf;
3743 const STDCHAR *flushptr = buf;
3747 if (!(PerlIOBase(f)->flags & PERLIO_F_CANWRITE))
3749 if (PerlIOBase(f)->flags & PERLIO_F_RDBUF) {
3750 if (PerlIO_flush(f) != 0) {
3754 if (PerlIOBase(f)->flags & PERLIO_F_LINEBUF) {
3755 flushptr = buf + count;
3756 while (flushptr > buf && *(flushptr - 1) != '\n')
3760 SSize_t avail = b->bufsiz - (b->ptr - b->buf);
3761 if ((SSize_t) count < avail)
3763 if (flushptr > buf && flushptr <= buf + avail)
3764 avail = flushptr - buf;
3765 PerlIOBase(f)->flags |= PERLIO_F_WRBUF;
3767 Copy(buf, b->ptr, avail, STDCHAR);
3772 if (buf == flushptr)
3775 if (b->ptr >= (b->buf + b->bufsiz))
3778 if (PerlIOBase(f)->flags & PERLIO_F_UNBUF)
3784 PerlIOBuf_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
3787 if ((code = PerlIO_flush(f)) == 0) {
3788 PerlIOBase(f)->flags &= ~PERLIO_F_EOF;
3789 code = PerlIO_seek(PerlIONext(f), offset, whence);
3791 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3792 b->posn = PerlIO_tell(PerlIONext(f));
3799 PerlIOBuf_tell(pTHX_ PerlIO *f)
3801 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3803 * b->posn is file position where b->buf was read, or will be written
3805 Off_t posn = b->posn;
3806 if ((PerlIOBase(f)->flags & PERLIO_F_APPEND) &&
3807 (PerlIOBase(f)->flags & PERLIO_F_WRBUF)) {
3809 /* As O_APPEND files are normally shared in some sense it is better
3814 /* when file is NOT shared then this is sufficient */
3815 PerlIO_seek(PerlIONext(f),0, SEEK_END);
3817 posn = b->posn = PerlIO_tell(PerlIONext(f));
3821 * If buffer is valid adjust position by amount in buffer
3823 posn += (b->ptr - b->buf);
3829 PerlIOBuf_popped(pTHX_ PerlIO *f)
3831 const IV code = PerlIOBase_popped(aTHX_ f);
3832 PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
3833 if (b->buf && b->buf != (STDCHAR *) & b->oneword) {
3837 b->ptr = b->end = b->buf;
3838 PerlIOBase(f)->flags &= ~(PERLIO_F_RDBUF | PERLIO_F_WRBUF);
3843 PerlIOBuf_close(pTHX_ PerlIO *f)
3845 const IV code = PerlIOBase_close(aTHX_ f);
3846 PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
3847 if (b->buf && b->buf != (STDCHAR *) & b->oneword) {
3851 b->ptr = b->end = b->buf;
3852 PerlIOBase(f)->flags &= ~(PERLIO_F_RDBUF | PERLIO_F_WRBUF);
3857 PerlIOBuf_get_ptr(pTHX_ PerlIO *f)
3859 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3866 PerlIOBuf_get_cnt(pTHX_ PerlIO *f)
3868 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3871 if (PerlIOBase(f)->flags & PERLIO_F_RDBUF)
3872 return (b->end - b->ptr);
3877 PerlIOBuf_get_base(pTHX_ PerlIO *f)
3879 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3883 b->buf = Newxz(b->buf,b->bufsiz, STDCHAR);
3885 b->buf = (STDCHAR *) & b->oneword;
3886 b->bufsiz = sizeof(b->oneword);
3895 PerlIOBuf_bufsiz(pTHX_ PerlIO *f)
3897 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3900 return (b->end - b->buf);
3904 PerlIOBuf_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, SSize_t cnt)
3906 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3910 if (PerlIO_get_cnt(f) != cnt || b->ptr < b->buf) {
3911 assert(PerlIO_get_cnt(f) == cnt);
3912 assert(b->ptr >= b->buf);
3914 PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
3918 PerlIOBuf_dup(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags)
3920 return PerlIOBase_dup(aTHX_ f, o, param, flags);
3925 PERLIO_FUNCS_DECL(PerlIO_perlio) = {
3926 sizeof(PerlIO_funcs),
3929 PERLIO_K_BUFFERED|PERLIO_K_RAW,
3933 PerlIOBase_binmode, /* binmode */
3947 PerlIOBase_clearerr,
3948 PerlIOBase_setlinebuf,
3953 PerlIOBuf_set_ptrcnt,
3956 /*--------------------------------------------------------------------------------------*/
3958 * Temp layer to hold unread chars when cannot do it any other way
3962 PerlIOPending_fill(pTHX_ PerlIO *f)
3965 * Should never happen
3972 PerlIOPending_close(pTHX_ PerlIO *f)
3975 * A tad tricky - flush pops us, then we close new top
3978 return PerlIO_close(f);
3982 PerlIOPending_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
3985 * A tad tricky - flush pops us, then we seek new top
3988 return PerlIO_seek(f, offset, whence);
3993 PerlIOPending_flush(pTHX_ PerlIO *f)
3995 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3996 if (b->buf && b->buf != (STDCHAR *) & b->oneword) {
4000 PerlIO_pop(aTHX_ f);
4005 PerlIOPending_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, SSize_t cnt)
4011 PerlIOBuf_set_ptrcnt(aTHX_ f, ptr, cnt);
4016 PerlIOPending_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
4018 const IV code = PerlIOBase_pushed(aTHX_ f, mode, arg, tab);
4019 PerlIOl *l = PerlIOBase(f);
4021 * Our PerlIO_fast_gets must match what we are pushed on, or sv_gets()
4022 * etc. get muddled when it changes mid-string when we auto-pop.
4024 l->flags = (l->flags & ~(PERLIO_F_FASTGETS | PERLIO_F_UTF8)) |
4025 (PerlIOBase(PerlIONext(f))->
4026 flags & (PERLIO_F_FASTGETS | PERLIO_F_UTF8));
4031 PerlIOPending_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
4033 SSize_t avail = PerlIO_get_cnt(f);
4035 if ((SSize_t)count < avail)
4038 got = PerlIOBuf_read(aTHX_ f, vbuf, avail);
4039 if (got >= 0 && got < (SSize_t)count) {
4040 const SSize_t more =
4041 PerlIO_read(f, ((STDCHAR *) vbuf) + got, count - got);
4042 if (more >= 0 || got == 0)
4048 PERLIO_FUNCS_DECL(PerlIO_pending) = {
4049 sizeof(PerlIO_funcs),
4052 PERLIO_K_BUFFERED|PERLIO_K_RAW, /* not sure about RAW here */
4053 PerlIOPending_pushed,
4056 PerlIOBase_binmode, /* binmode */
4065 PerlIOPending_close,
4066 PerlIOPending_flush,
4070 PerlIOBase_clearerr,
4071 PerlIOBase_setlinebuf,
4076 PerlIOPending_set_ptrcnt,
4081 /*--------------------------------------------------------------------------------------*/
4083 * crlf - translation On read translate CR,LF to "\n" we do this by
4084 * overriding ptr/cnt entries to hand back a line at a time and keeping a
4085 * record of which nl we "lied" about. On write translate "\n" to CR,LF
4089 PerlIOBuf base; /* PerlIOBuf stuff */
4090 STDCHAR *nl; /* Position of crlf we "lied" about in the
4095 PerlIOCrlf_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
4098 PerlIOBase(f)->flags |= PERLIO_F_CRLF;
4099 code = PerlIOBuf_pushed(aTHX_ f, mode, arg, tab);
4101 PerlIO_debug("PerlIOCrlf_pushed f=%p %s %s fl=%08" UVxf "\n",
4102 f, PerlIOBase(f)->tab->name, (mode) ? mode : "(Null)",
4103 PerlIOBase(f)->flags);
4106 /* Enable the first CRLF capable layer you can find, but if none
4107 * found, the one we just pushed is fine. This results in at
4108 * any given moment at most one CRLF-capable layer being enabled
4109 * in the whole layer stack. */
4110 PerlIO *g = PerlIONext(f);
4112 PerlIOl *b = PerlIOBase(g);
4113 if (b && b->tab == &PerlIO_crlf) {
4114 if (!(b->flags & PERLIO_F_CRLF))
4115 b->flags |= PERLIO_F_CRLF;
4116 PerlIO_pop(aTHX_ f);
4127 PerlIOCrlf_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
4129 PerlIOCrlf *c = PerlIOSelf(f, PerlIOCrlf);
4134 if (!(PerlIOBase(f)->flags & PERLIO_F_CRLF))
4135 return PerlIOBuf_unread(aTHX_ f, vbuf, count);
4137 const STDCHAR *buf = (const STDCHAR *) vbuf + count;
4138 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
4140 if (PerlIOBase(f)->flags & PERLIO_F_WRBUF)
4145 if (!(PerlIOBase(f)->flags & PERLIO_F_RDBUF)) {
4146 b->end = b->ptr = b->buf + b->bufsiz;
4147 PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
4148 b->posn -= b->bufsiz;
4150 while (count > 0 && b->ptr > b->buf) {
4153 if (b->ptr - 2 >= b->buf) {
4176 PerlIOCrlf_get_cnt(pTHX_ PerlIO *f)
4178 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
4181 if (PerlIOBase(f)->flags & PERLIO_F_RDBUF) {
4182 PerlIOCrlf *c = PerlIOSelf(f, PerlIOCrlf);
4183 if ((PerlIOBase(f)->flags & PERLIO_F_CRLF) && (!c->nl || *c->nl == 0xd)) {
4184 STDCHAR *nl = (c->nl) ? c->nl : b->ptr;
4186 while (nl < b->end && *nl != 0xd)
4188 if (nl < b->end && *nl == 0xd) {
4190 if (nl + 1 < b->end) {
4197 * Not CR,LF but just CR
4205 * Blast - found CR as last char in buffer
4210 * They may not care, defer work as long as
4214 return (nl - b->ptr);
4218 b->ptr++; /* say we have read it as far as
4219 * flush() is concerned */
4220 b->buf++; /* Leave space in front of buffer */
4221 /* Note as we have moved buf up flush's
4223 will naturally make posn point at CR
4225 b->bufsiz--; /* Buffer is thus smaller */
4226 code = PerlIO_fill(f); /* Fetch some more */
4227 b->bufsiz++; /* Restore size for next time */
4228 b->buf--; /* Point at space */
4229 b->ptr = nl = b->buf; /* Which is what we hand
4231 *nl = 0xd; /* Fill in the CR */
4233 goto test; /* fill() call worked */
4235 * CR at EOF - just fall through
4237 /* Should we clear EOF though ??? */
4242 return (((c->nl) ? (c->nl + 1) : b->end) - b->ptr);
4248 PerlIOCrlf_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, SSize_t cnt)
4250 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
4251 PerlIOCrlf *c = PerlIOSelf(f, PerlIOCrlf);
4257 if (ptr == b->end && *c->nl == 0xd) {
4258 /* Defered CR at end of buffer case - we lied about count */
4270 * Test code - delete when it works ...
4272 IV flags = PerlIOBase(f)->flags;
4273 STDCHAR *chk = (c->nl) ? (c->nl+1) : b->end;
4274 if (ptr+cnt == c->nl && c->nl+1 == b->end && *c->nl == 0xd) {
4275 /* Defered CR at end of buffer case - we lied about count */
4281 Perl_croak(aTHX_ "ptr wrong %p != %p fl=%08" UVxf
4282 " nl=%p e=%p for %d", ptr, chk, flags, c->nl,
4290 * They have taken what we lied about
4298 PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
4302 PerlIOCrlf_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
4304 if (!(PerlIOBase(f)->flags & PERLIO_F_CRLF))
4305 return PerlIOBuf_write(aTHX_ f, vbuf, count);
4307 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
4308 const STDCHAR *buf = (const STDCHAR *) vbuf;
4309 const STDCHAR *ebuf = buf + count;
4312 if (!(PerlIOBase(f)->flags & PERLIO_F_CANWRITE))
4314 while (buf < ebuf) {
4315 STDCHAR *eptr = b->buf + b->bufsiz;
4316 PerlIOBase(f)->flags |= PERLIO_F_WRBUF;
4317 while (buf < ebuf && b->ptr < eptr) {
4319 if ((b->ptr + 2) > eptr) {
4327 *(b->ptr)++ = 0xd; /* CR */
4328 *(b->ptr)++ = 0xa; /* LF */
4330 if (PerlIOBase(f)->flags & PERLIO_F_LINEBUF) {
4340 if (b->ptr >= eptr) {
4346 if (PerlIOBase(f)->flags & PERLIO_F_UNBUF)
4348 return (buf - (STDCHAR *) vbuf);
4353 PerlIOCrlf_flush(pTHX_ PerlIO *f)
4355 PerlIOCrlf *c = PerlIOSelf(f, PerlIOCrlf);
4360 return PerlIOBuf_flush(aTHX_ f);
4364 PerlIOCrlf_binmode(pTHX_ PerlIO *f)
4366 if ((PerlIOBase(f)->flags & PERLIO_F_CRLF)) {
4367 /* In text mode - flush any pending stuff and flip it */
4368 PerlIOBase(f)->flags &= ~PERLIO_F_CRLF;
4369 #ifndef PERLIO_USING_CRLF
4370 /* CRLF is unusual case - if this is just the :crlf layer pop it */
4371 if (PerlIOBase(f)->tab == &PerlIO_crlf) {
4372 PerlIO_pop(aTHX_ f);
4379 PERLIO_FUNCS_DECL(PerlIO_crlf) = {
4380 sizeof(PerlIO_funcs),
4383 PERLIO_K_BUFFERED | PERLIO_K_CANCRLF | PERLIO_K_RAW,
4385 PerlIOBuf_popped, /* popped */
4387 PerlIOCrlf_binmode, /* binmode */
4391 PerlIOBuf_read, /* generic read works with ptr/cnt lies */
4392 PerlIOCrlf_unread, /* Put CR,LF in buffer for each '\n' */
4393 PerlIOCrlf_write, /* Put CR,LF in buffer for each '\n' */
4401 PerlIOBase_clearerr,
4402 PerlIOBase_setlinebuf,
4407 PerlIOCrlf_set_ptrcnt,
4411 /*--------------------------------------------------------------------------------------*/
4413 * mmap as "buffer" layer
4417 PerlIOBuf base; /* PerlIOBuf stuff */
4418 Mmap_t mptr; /* Mapped address */
4419 Size_t len; /* mapped length */
4420 STDCHAR *bbuf; /* malloced buffer if map fails */
4424 PerlIOMmap_map(pTHX_ PerlIO *f)
4427 PerlIOMmap * const m = PerlIOSelf(f, PerlIOMmap);
4428 const IV flags = PerlIOBase(f)->flags;
4432 if (flags & PERLIO_F_CANREAD) {
4433 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
4434 const int fd = PerlIO_fileno(f);
4436 code = Fstat(fd, &st);
4437 if (code == 0 && S_ISREG(st.st_mode)) {
4438 SSize_t len = st.st_size - b->posn;
4441 if (PL_mmap_page_size <= 0)
4442 Perl_croak(aTHX_ "panic: bad pagesize %" IVdf,
4446 * This is a hack - should never happen - open should
4449 b->posn = PerlIO_tell(PerlIONext(f));
4451 posn = (b->posn / PL_mmap_page_size) * PL_mmap_page_size;
4452 len = st.st_size - posn;
4453 m->mptr = mmap(NULL, len, PROT_READ, MAP_SHARED, fd, posn);
4454 if (m->mptr && m->mptr != (Mmap_t) - 1) {
4455 #if 0 && defined(HAS_MADVISE) && defined(MADV_SEQUENTIAL)
4456 madvise(m->mptr, len, MADV_SEQUENTIAL);
4458 #if 0 && defined(HAS_MADVISE) && defined(MADV_WILLNEED)
4459 madvise(m->mptr, len, MADV_WILLNEED);
4461 PerlIOBase(f)->flags =
4462 (flags & ~PERLIO_F_EOF) | PERLIO_F_RDBUF;
4463 b->end = ((STDCHAR *) m->mptr) + len;
4464 b->buf = ((STDCHAR *) m->mptr) + (b->posn - posn);
4473 PerlIOBase(f)->flags =
4474 flags | PERLIO_F_EOF | PERLIO_F_RDBUF;
4476 b->ptr = b->end = b->ptr;
4485 PerlIOMmap_unmap(pTHX_ PerlIO *f)
4487 PerlIOMmap *m = PerlIOSelf(f, PerlIOMmap);
4488 PerlIOBuf *b = &m->base;
4492 code = munmap(m->mptr, m->len);
4496 if (PerlIO_seek(PerlIONext(f), b->posn, SEEK_SET) != 0)
4499 b->ptr = b->end = b->buf;
4500 PerlIOBase(f)->flags &= ~(PERLIO_F_RDBUF | PERLIO_F_WRBUF);
4506 PerlIOMmap_get_base(pTHX_ PerlIO *f)
4508 PerlIOMmap *m = PerlIOSelf(f, PerlIOMmap);
4509 PerlIOBuf *b = &m->base;
4510 if (b->buf && (PerlIOBase(f)->flags & PERLIO_F_RDBUF)) {
4512 * Already have a readbuffer in progress
4518 * We have a write buffer or flushed PerlIOBuf read buffer
4520 m->bbuf = b->buf; /* save it in case we need it again */
4521 b->buf = NULL; /* Clear to trigger below */
4524 PerlIOMmap_map(aTHX_ f); /* Try and map it */
4527 * Map did not work - recover PerlIOBuf buffer if we have one
4532 b->ptr = b->end = b->buf;
4535 return PerlIOBuf_get_base(aTHX_ f);
4539 PerlIOMmap_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
4541 PerlIOMmap *m = PerlIOSelf(f, PerlIOMmap);
4542 PerlIOBuf *b = &m->base;
4543 if (PerlIOBase(f)->flags & PERLIO_F_WRBUF)
4545 if (b->ptr && (b->ptr - count) >= b->buf
4546 && memEQ(b->ptr - count, vbuf, count)) {
4548 PerlIOBase(f)->flags &= ~PERLIO_F_EOF;
4553 * Loose the unwritable mapped buffer
4557 * If flush took the "buffer" see if we have one from before
4559 if (!b->buf && m->bbuf)
4562 PerlIOBuf_get_base(aTHX_ f);
4566 return PerlIOBuf_unread(aTHX_ f, vbuf, count);
4570 PerlIOMmap_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
4572 PerlIOMmap * const m = PerlIOSelf(f, PerlIOMmap);
4573 PerlIOBuf * const b = &m->base;
4575 if (!b->buf || !(PerlIOBase(f)->flags & PERLIO_F_WRBUF)) {
4577 * No, or wrong sort of, buffer
4580 if (PerlIOMmap_unmap(aTHX_ f) != 0)
4584 * If unmap took the "buffer" see if we have one from before
4586 if (!b->buf && m->bbuf)
4589 PerlIOBuf_get_base(aTHX_ f);
4593 return PerlIOBuf_write(aTHX_ f, vbuf, count);
4597 PerlIOMmap_flush(pTHX_ PerlIO *f)
4599 PerlIOMmap *m = PerlIOSelf(f, PerlIOMmap);
4600 PerlIOBuf *b = &m->base;
4601 IV code = PerlIOBuf_flush(aTHX_ f);
4603 * Now we are "synced" at PerlIOBuf level
4610 if (PerlIOMmap_unmap(aTHX_ f) != 0)
4615 * We seem to have a PerlIOBuf buffer which was not mapped
4616 * remember it in case we need one later
4625 PerlIOMmap_fill(pTHX_ PerlIO *f)
4627 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
4628 IV code = PerlIO_flush(f);
4629 if (code == 0 && !b->buf) {
4630 code = PerlIOMmap_map(aTHX_ f);
4632 if (code == 0 && !(PerlIOBase(f)->flags & PERLIO_F_RDBUF)) {
4633 code = PerlIOBuf_fill(aTHX_ f);
4639 PerlIOMmap_close(pTHX_ PerlIO *f)
4641 PerlIOMmap *m = PerlIOSelf(f, PerlIOMmap);
4642 PerlIOBuf *b = &m->base;
4643 IV code = PerlIO_flush(f);
4647 b->ptr = b->end = b->buf;
4649 if (PerlIOBuf_close(aTHX_ f) != 0)
4655 PerlIOMmap_dup(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags)
4657 return PerlIOBase_dup(aTHX_ f, o, param, flags);
4661 PERLIO_FUNCS_DECL(PerlIO_mmap) = {
4662 sizeof(PerlIO_funcs),
4665 PERLIO_K_BUFFERED|PERLIO_K_RAW,
4669 PerlIOBase_binmode, /* binmode */
4683 PerlIOBase_clearerr,
4684 PerlIOBase_setlinebuf,
4685 PerlIOMmap_get_base,
4689 PerlIOBuf_set_ptrcnt,
4692 #endif /* HAS_MMAP */
4695 Perl_PerlIO_stdin(pTHX)
4698 PerlIO_stdstreams(aTHX);
4700 return &PL_perlio[1];
4704 Perl_PerlIO_stdout(pTHX)
4707 PerlIO_stdstreams(aTHX);
4709 return &PL_perlio[2];
4713 Perl_PerlIO_stderr(pTHX)
4716 PerlIO_stdstreams(aTHX);
4718 return &PL_perlio[3];
4721 /*--------------------------------------------------------------------------------------*/
4724 PerlIO_getname(PerlIO *f, char *buf)
4729 bool exported = FALSE;
4730 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
4732 stdio = PerlIO_exportFILE(f,0);
4736 name = fgetname(stdio, buf);
4737 if (exported) PerlIO_releaseFILE(f,stdio);
4742 PERL_UNUSED_ARG(buf);
4743 Perl_croak(aTHX_ "Don't know how to get file name");
4749 /*--------------------------------------------------------------------------------------*/
4751 * Functions which can be called on any kind of PerlIO implemented in
4755 #undef PerlIO_fdopen
4757 PerlIO_fdopen(int fd, const char *mode)
4760 return PerlIO_openn(aTHX_ Nullch, mode, fd, 0, 0, NULL, 0, NULL);
4765 PerlIO_open(const char *path, const char *mode)
4768 SV *name = sv_2mortal(newSVpvn(path, strlen(path)));
4769 return PerlIO_openn(aTHX_ Nullch, mode, -1, 0, 0, NULL, 1, &name);
4772 #undef Perlio_reopen
4774 PerlIO_reopen(const char *path, const char *mode, PerlIO *f)
4777 SV *name = sv_2mortal(newSVpvn(path, strlen(path)));
4778 return PerlIO_openn(aTHX_ Nullch, mode, -1, 0, 0, f, 1, &name);
4783 PerlIO_getc(PerlIO *f)
4787 if ( 1 == PerlIO_read(f, buf, 1) ) {
4788 return (unsigned char) buf[0];
4793 #undef PerlIO_ungetc
4795 PerlIO_ungetc(PerlIO *f, int ch)
4800 if (PerlIO_unread(f, &buf, 1) == 1)
4808 PerlIO_putc(PerlIO *f, int ch)
4812 return PerlIO_write(f, &buf, 1);
4817 PerlIO_puts(PerlIO *f, const char *s)
4820 STRLEN len = strlen(s);
4821 return PerlIO_write(f, s, len);
4824 #undef PerlIO_rewind
4826 PerlIO_rewind(PerlIO *f)
4829 PerlIO_seek(f, (Off_t) 0, SEEK_SET);
4833 #undef PerlIO_vprintf
4835 PerlIO_vprintf(PerlIO *f, const char *fmt, va_list ap)
4838 SV *sv = newSVpvn("", 0);
4844 Perl_va_copy(ap, apc);
4845 sv_vcatpvf(sv, fmt, &apc);
4847 sv_vcatpvf(sv, fmt, &ap);
4849 s = SvPV_const(sv, len);
4850 wrote = PerlIO_write(f, s, len);
4855 #undef PerlIO_printf
4857 PerlIO_printf(PerlIO *f, const char *fmt, ...)
4862 result = PerlIO_vprintf(f, fmt, ap);
4867 #undef PerlIO_stdoutf
4869 PerlIO_stdoutf(const char *fmt, ...)
4875 result = PerlIO_vprintf(PerlIO_stdout(), fmt, ap);
4880 #undef PerlIO_tmpfile
4882 PerlIO_tmpfile(void)
4887 const int fd = win32_tmpfd();
4889 f = PerlIO_fdopen(fd, "w+b");
4891 # if defined(HAS_MKSTEMP) && ! defined(VMS) && ! defined(OS2)
4892 SV *sv = newSVpv("/tmp/PerlIO_XXXXXX", 0);
4894 * I have no idea how portable mkstemp() is ... NI-S
4896 const int fd = mkstemp(SvPVX(sv));
4898 f = PerlIO_fdopen(fd, "w+");
4900 PerlIOBase(f)->flags |= PERLIO_F_TEMP;
4901 PerlLIO_unlink(SvPVX_const(sv));
4904 # else /* !HAS_MKSTEMP, fallback to stdio tmpfile(). */
4905 FILE *stdio = PerlSIO_tmpfile();
4908 if ((f = PerlIO_push(aTHX_(PerlIO_allocate(aTHX)),
4909 PERLIO_FUNCS_CAST(&PerlIO_stdio),
4911 PerlIOStdio *s = PerlIOSelf(f, PerlIOStdio);
4917 # endif /* else HAS_MKSTEMP */
4918 #endif /* else WIN32 */
4925 #endif /* USE_SFIO */
4926 #endif /* PERLIO_IS_STDIO */
4928 /*======================================================================================*/
4930 * Now some functions in terms of above which may be needed even if we are
4931 * not in true PerlIO mode
4935 #undef PerlIO_setpos
4937 PerlIO_setpos(PerlIO *f, SV *pos)
4942 Off_t *posn = (Off_t *) SvPV(pos, len);
4943 if (f && len == sizeof(Off_t))
4944 return PerlIO_seek(f, *posn, SEEK_SET);
4946 SETERRNO(EINVAL, SS_IVCHAN);
4950 #undef PerlIO_setpos
4952 PerlIO_setpos(PerlIO *f, SV *pos)
4957 Fpos_t *fpos = (Fpos_t *) SvPV(pos, len);
4958 if (f && len == sizeof(Fpos_t)) {
4959 #if defined(USE_64_BIT_STDIO) && defined(USE_FSETPOS64)
4960 return fsetpos64(f, fpos);
4962 return fsetpos(f, fpos);
4966 SETERRNO(EINVAL, SS_IVCHAN);
4972 #undef PerlIO_getpos
4974 PerlIO_getpos(PerlIO *f, SV *pos)
4977 Off_t posn = PerlIO_tell(f);
4978 sv_setpvn(pos, (char *) &posn, sizeof(posn));
4979 return (posn == (Off_t) - 1) ? -1 : 0;
4982 #undef PerlIO_getpos
4984 PerlIO_getpos(PerlIO *f, SV *pos)
4989 #if defined(USE_64_BIT_STDIO) && defined(USE_FSETPOS64)
4990 code = fgetpos64(f, &fpos);
4992 code = fgetpos(f, &fpos);
4994 sv_setpvn(pos, (char *) &fpos, sizeof(fpos));
4999 #if (defined(PERLIO_IS_STDIO) || !defined(USE_SFIO)) && !defined(HAS_VPRINTF)
5002 vprintf(char *pat, char *args)
5004 _doprnt(pat, args, stdout);
5005 return 0; /* wrong, but perl doesn't use the return
5010 vfprintf(FILE *fd, char *pat, char *args)
5012 _doprnt(pat, args, fd);
5013 return 0; /* wrong, but perl doesn't use the return
5019 #ifndef PerlIO_vsprintf
5021 PerlIO_vsprintf(char *s, int n, const char *fmt, va_list ap)
5024 const int val = vsprintf(s, fmt, ap);
5026 if (strlen(s) >= (STRLEN) n) {
5028 (void) PerlIO_puts(Perl_error_log,
5029 "panic: sprintf overflow - memory corrupted!\n");
5037 #ifndef PerlIO_sprintf
5039 PerlIO_sprintf(char *s, int n, const char *fmt, ...)
5044 result = PerlIO_vsprintf(s, n, fmt, ap);
5052 * c-indentation-style: bsd
5054 * indent-tabs-mode: t
5057 * ex: set ts=8 sts=4 sw=4 noet: