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
143 * the translation mode of the fd in the Borland RTL (heavy
144 * digging through their runtime sources reveal). User has to
146 * the mode explicitly for the stream (though they don't
148 * this anywhere). GSAR 97-5-24
154 fp->flags &= ~_F_BIN;
162 # if defined(USEMYBINMODE)
164 if (my_binmode(fp, iotype, mode) != FALSE)
170 PERL_UNUSED_ARG(iotype);
171 PERL_UNUSED_ARG(mode);
179 #define O_ACCMODE 3 /* Assume traditional implementation */
183 PerlIO_intmode2str(int rawmode, char *mode, int *writing)
185 const int result = rawmode & O_ACCMODE;
190 ptype = IoTYPE_RDONLY;
193 ptype = IoTYPE_WRONLY;
201 *writing = (result != O_RDONLY);
203 if (result == O_RDONLY) {
207 else if (rawmode & O_APPEND) {
209 if (result != O_WRONLY)
214 if (result == O_WRONLY)
221 if (rawmode & O_BINARY)
227 #ifndef PERLIO_LAYERS
229 PerlIO_apply_layers(pTHX_ PerlIO *f, const char *mode, const char *names)
231 if (!names || !*names
232 || strEQ(names, ":crlf")
233 || strEQ(names, ":raw")
234 || strEQ(names, ":bytes")
238 Perl_croak(aTHX_ "Cannot apply \"%s\" in non-PerlIO perl", names);
246 PerlIO_destruct(pTHX)
251 PerlIO_binmode(pTHX_ PerlIO *fp, int iotype, int mode, const char *names)
254 PERL_UNUSED_ARG(iotype);
255 PERL_UNUSED_ARG(mode);
256 PERL_UNUSED_ARG(names);
259 return perlsio_binmode(fp, iotype, mode);
264 PerlIO_fdupopen(pTHX_ PerlIO *f, CLONE_PARAMS *param, int flags)
266 #if defined(PERL_MICRO) || defined(__SYMBIAN32__)
269 #ifdef PERL_IMPLICIT_SYS
270 return PerlSIO_fdupopen(f);
273 return win32_fdupopen(f);
276 const int fd = PerlLIO_dup(PerlIO_fileno(f));
280 const int omode = djgpp_get_stream_mode(f);
282 const int omode = fcntl(fd, F_GETFL);
284 PerlIO_intmode2str(omode,mode,NULL);
285 /* the r+ is a hack */
286 return PerlIO_fdopen(fd, mode);
291 SETERRNO(EBADF, SS_IVCHAN);
301 * De-mux PerlIO_openn() into fdopen, freopen and fopen type entries
305 PerlIO_openn(pTHX_ const char *layers, const char *mode, int fd,
306 int imode, int perm, PerlIO *old, int narg, SV **args)
310 Perl_croak(aTHX_ "More than one argument to open");
312 if (*args == &PL_sv_undef)
313 return PerlIO_tmpfile();
315 const char *name = SvPV_nolen_const(*args);
316 if (*mode == IoTYPE_NUMERIC) {
317 fd = PerlLIO_open3(name, imode, perm);
319 return PerlIO_fdopen(fd, mode + 1);
322 return PerlIO_reopen(name, mode, old);
325 return PerlIO_open(name, mode);
330 return PerlIO_fdopen(fd, (char *) mode);
335 XS(XS_PerlIO__Layer__find)
339 Perl_croak(aTHX_ "Usage class->find(name[,load])");
341 const char * const name = SvPV_nolen_const(ST(1));
342 ST(0) = (strEQ(name, "crlf")
343 || strEQ(name, "raw")) ? &PL_sv_yes : &PL_sv_undef;
350 Perl_boot_core_PerlIO(pTHX)
352 newXS("PerlIO::Layer::find", XS_PerlIO__Layer__find, __FILE__);
358 #ifdef PERLIO_IS_STDIO
364 * Does nothing (yet) except force this file to be included in perl
365 * binary. That allows this file to force inclusion of other functions
366 * that may be required by loadable extensions e.g. for
367 * FileHandle::tmpfile
371 #undef PerlIO_tmpfile
378 #else /* PERLIO_IS_STDIO */
386 * This section is just to make sure these functions get pulled in from
390 #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 const STRLEN len2 = vsprintf(buffer+len, fmt, ap);
479 PerlLIO_write(PL_perlio_debug_fd, buffer, len + len2);
481 const char *s = CopFILE(PL_curcop);
483 SV * const sv = newSVpvn("", 0);
484 Perl_sv_catpvf(aTHX_ sv, "%s:%" IVdf " ", s ? s : "(none)",
485 (IV) CopLINE(PL_curcop));
486 Perl_sv_vcatpvf(aTHX_ sv, fmt, &ap);
488 s = SvPV_const(sv, len);
489 PerlLIO_write(PL_perlio_debug_fd, s, len);
496 /*--------------------------------------------------------------------------------------*/
499 * Inner level routines
503 * Table of pointers to the PerlIO structs (malloc'ed)
505 #define PERLIO_TABLE_SIZE 64
508 PerlIO_allocate(pTHX)
511 * Find a free slot in the table, allocating new table as necessary
516 while ((f = *last)) {
518 last = (PerlIO **) (f);
519 for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
525 Newxz(f,PERLIO_TABLE_SIZE,PerlIO);
533 #undef PerlIO_fdupopen
535 PerlIO_fdupopen(pTHX_ PerlIO *f, CLONE_PARAMS *param, int flags)
537 if (PerlIOValid(f)) {
538 const PerlIO_funcs * const tab = PerlIOBase(f)->tab;
539 PerlIO_debug("fdupopen f=%p param=%p\n",(void*)f,(void*)param);
541 return (*tab->Dup)(aTHX_ PerlIO_allocate(aTHX), f, param, flags);
543 return PerlIOBase_dup(aTHX_ PerlIO_allocate(aTHX), f, param, flags);
547 SETERRNO(EBADF, SS_IVCHAN);
553 PerlIO_cleantable(pTHX_ PerlIO **tablep)
555 PerlIO * const table = *tablep;
558 PerlIO_cleantable(aTHX_(PerlIO **) & (table[0]));
559 for (i = PERLIO_TABLE_SIZE - 1; i > 0; i--) {
560 PerlIO * const f = table + i;
572 PerlIO_list_alloc(pTHX)
575 Newxz(list, 1, PerlIO_list_t);
581 PerlIO_list_free(pTHX_ PerlIO_list_t *list)
584 if (--list->refcnt == 0) {
587 for (i = 0; i < list->cur; i++) {
588 if (list->array[i].arg)
589 SvREFCNT_dec(list->array[i].arg);
591 Safefree(list->array);
599 PerlIO_list_push(pTHX_ PerlIO_list_t *list, PerlIO_funcs *funcs, SV *arg)
602 if (list->cur >= list->len) {
605 Renew(list->array, list->len, PerlIO_pair_t);
607 Newx(list->array, list->len, PerlIO_pair_t);
609 p = &(list->array[list->cur++]);
611 if ((p->arg = arg)) {
612 (void)SvREFCNT_inc(arg);
617 PerlIO_clone_list(pTHX_ PerlIO_list_t *proto, CLONE_PARAMS *param)
619 PerlIO_list_t *list = (PerlIO_list_t *) NULL;
622 list = PerlIO_list_alloc(aTHX);
623 for (i=0; i < proto->cur; i++) {
625 if (proto->array[i].arg)
626 arg = PerlIO_sv_dup(aTHX_ proto->array[i].arg,param);
627 PerlIO_list_push(aTHX_ list, proto->array[i].funcs, arg);
634 PerlIO_clone(pTHX_ PerlInterpreter *proto, CLONE_PARAMS *param)
637 PerlIO **table = &proto->Iperlio;
640 PL_known_layers = PerlIO_clone_list(aTHX_ proto->Iknown_layers, param);
641 PL_def_layerlist = PerlIO_clone_list(aTHX_ proto->Idef_layerlist, param);
642 PerlIO_allocate(aTHX); /* root slot is never used */
643 PerlIO_debug("Clone %p from %p\n",aTHX,proto);
644 while ((f = *table)) {
646 table = (PerlIO **) (f++);
647 for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
649 (void) fp_dup(f, 0, param);
655 PERL_UNUSED_ARG(proto);
656 PERL_UNUSED_ARG(param);
661 PerlIO_destruct(pTHX)
663 PerlIO **table = &PL_perlio;
666 PerlIO_debug("Destruct %p\n",aTHX);
668 while ((f = *table)) {
670 table = (PerlIO **) (f++);
671 for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
675 if (l->tab->kind & PERLIO_K_DESTRUCT) {
676 PerlIO_debug("Destruct popping %s\n", l->tab->name);
690 PerlIO_pop(pTHX_ PerlIO *f)
692 const PerlIOl *l = *f;
694 PerlIO_debug("PerlIO_pop f=%p %s\n", (void*)f, l->tab->name);
695 if (l->tab->Popped) {
697 * If popped returns non-zero do not free its layer structure
698 * it has either done so itself, or it is shared and still in
701 if ((*l->tab->Popped) (aTHX_ f) != 0)
709 /* Return as an array the stack of layers on a filehandle. Note that
710 * the stack is returned top-first in the array, and there are three
711 * times as many array elements as there are layers in the stack: the
712 * first element of a layer triplet is the name, the second one is the
713 * arguments, and the third one is the flags. */
716 PerlIO_get_layers(pTHX_ PerlIO *f)
718 AV * const av = newAV();
720 if (PerlIOValid(f)) {
721 PerlIOl *l = PerlIOBase(f);
724 SV * const name = l->tab && l->tab->name ?
725 newSVpv(l->tab->name, 0) : &PL_sv_undef;
726 SV * const arg = l->tab && l->tab->Getarg ?
727 (*l->tab->Getarg)(aTHX_ &l, 0, 0) : &PL_sv_undef;
730 av_push(av, newSViv((IV)l->flags));
738 /*--------------------------------------------------------------------------------------*/
740 * XS Interface for perl code
744 PerlIO_find_layer(pTHX_ const char *name, STRLEN len, int load)
748 if ((SSize_t) len <= 0)
750 for (i = 0; i < PL_known_layers->cur; i++) {
751 PerlIO_funcs * const f = PL_known_layers->array[i].funcs;
752 if (memEQ(f->name, name, len) && f->name[len] == 0) {
753 PerlIO_debug("%.*s => %p\n", (int) len, name, (void*)f);
757 if (load && PL_subname && PL_def_layerlist
758 && PL_def_layerlist->cur >= 2) {
759 if (PL_in_load_module) {
760 Perl_croak(aTHX_ "Recursive call to Perl_load_module in PerlIO_find_layer");
763 SV * const pkgsv = newSVpvn("PerlIO", 6);
764 SV * const layer = newSVpvn(name, len);
765 CV * const cv = get_cv("PerlIO::Layer::NoWarnings", FALSE);
767 SAVEINT(PL_in_load_module);
769 SAVEGENERICSV(PL_warnhook);
770 (void)SvREFCNT_inc(cv);
771 PL_warnhook = (SV *) cv;
775 * The two SVs are magically freed by load_module
777 Perl_load_module(aTHX_ 0, pkgsv, Nullsv, layer, Nullsv);
780 return PerlIO_find_layer(aTHX_ name, len, 0);
783 PerlIO_debug("Cannot find %.*s\n", (int) len, name);
787 #ifdef USE_ATTRIBUTES_FOR_PERLIO
790 perlio_mg_set(pTHX_ SV *sv, MAGIC *mg)
793 IO * const io = GvIOn((GV *) SvRV(sv));
794 PerlIO * const ifp = IoIFP(io);
795 PerlIO * const ofp = IoOFP(io);
796 Perl_warn(aTHX_ "set %" SVf " %p %p %p", sv, io, ifp, ofp);
802 perlio_mg_get(pTHX_ SV *sv, MAGIC *mg)
805 IO * const io = GvIOn((GV *) SvRV(sv));
806 PerlIO * const ifp = IoIFP(io);
807 PerlIO * const ofp = IoOFP(io);
808 Perl_warn(aTHX_ "get %" SVf " %p %p %p", sv, io, ifp, ofp);
814 perlio_mg_clear(pTHX_ SV *sv, MAGIC *mg)
816 Perl_warn(aTHX_ "clear %" SVf, sv);
821 perlio_mg_free(pTHX_ SV *sv, MAGIC *mg)
823 Perl_warn(aTHX_ "free %" SVf, sv);
827 MGVTBL perlio_vtab = {
835 XS(XS_io_MODIFY_SCALAR_ATTRIBUTES)
838 SV * const sv = SvRV(ST(1));
839 AV * const av = newAV();
843 sv_magic(sv, (SV *) av, PERL_MAGIC_ext, NULL, 0);
845 mg = mg_find(sv, PERL_MAGIC_ext);
846 mg->mg_virtual = &perlio_vtab;
848 Perl_warn(aTHX_ "attrib %" SVf, sv);
849 for (i = 2; i < items; i++) {
851 const char * const name = SvPV_const(ST(i), len);
852 SV * const layer = PerlIO_find_layer(aTHX_ name, len, 1);
854 av_push(av, SvREFCNT_inc(layer));
865 #endif /* USE_ATTIBUTES_FOR_PERLIO */
868 PerlIO_tab_sv(pTHX_ PerlIO_funcs *tab)
870 HV * const stash = gv_stashpv("PerlIO::Layer", TRUE);
871 SV * const sv = sv_bless(newRV_noinc(newSViv(PTR2IV(tab))), stash);
875 XS(XS_PerlIO__Layer__NoWarnings)
877 /* This is used as a %SIG{__WARN__} handler to supress warnings
878 during loading of layers.
882 PerlIO_debug("warning:%s\n",SvPV_nolen_const(ST(0)));
886 XS(XS_PerlIO__Layer__find)
890 Perl_croak(aTHX_ "Usage class->find(name[,load])");
893 const char * const name = SvPV_const(ST(1), len);
894 const bool load = (items > 2) ? SvTRUE(ST(2)) : 0;
895 PerlIO_funcs * const layer = PerlIO_find_layer(aTHX_ name, len, load);
897 (layer) ? sv_2mortal(PerlIO_tab_sv(aTHX_ layer)) :
904 PerlIO_define_layer(pTHX_ PerlIO_funcs *tab)
906 if (!PL_known_layers)
907 PL_known_layers = PerlIO_list_alloc(aTHX);
908 PerlIO_list_push(aTHX_ PL_known_layers, tab, Nullsv);
909 PerlIO_debug("define %s %p\n", tab->name, (void*)tab);
913 PerlIO_parse_layers(pTHX_ PerlIO_list_t *av, const char *names)
916 const char *s = names;
918 while (isSPACE(*s) || *s == ':')
923 const char *as = Nullch;
925 if (!isIDFIRST(*s)) {
927 * Message is consistent with how attribute lists are
928 * passed. Even though this means "foo : : bar" is
929 * seen as an invalid separator character.
931 const char q = ((*s == '\'') ? '"' : '\'');
932 if (ckWARN(WARN_LAYER))
933 Perl_warner(aTHX_ packWARN(WARN_LAYER),
934 "Invalid separator character %c%c%c in PerlIO layer specification %s",
936 SETERRNO(EINVAL, LIB_INVARG);
941 } while (isALNUM(*e));
957 * It's a nul terminated string, not allowed
958 * to \ the terminating null. Anything other
959 * character is passed over.
969 if (ckWARN(WARN_LAYER))
970 Perl_warner(aTHX_ packWARN(WARN_LAYER),
971 "Argument list not closed for PerlIO layer \"%.*s\"",
983 PerlIO_funcs * const layer =
984 PerlIO_find_layer(aTHX_ s, llen, 1);
986 PerlIO_list_push(aTHX_ av, layer,
992 if (ckWARN(WARN_LAYER))
993 Perl_warner(aTHX_ packWARN(WARN_LAYER), "Unknown PerlIO layer \"%.*s\"",
1006 PerlIO_default_buffer(pTHX_ PerlIO_list_t *av)
1008 PERLIO_FUNCS_DECL(*tab) = &PerlIO_perlio;
1009 #ifdef PERLIO_USING_CRLF
1012 if (PerlIO_stdio.Set_ptrcnt)
1013 tab = &PerlIO_stdio;
1015 PerlIO_debug("Pushing %s\n", tab->name);
1016 PerlIO_list_push(aTHX_ av, PerlIO_find_layer(aTHX_ tab->name, 0, 0),
1021 PerlIO_arg_fetch(PerlIO_list_t *av, IV n)
1023 return av->array[n].arg;
1027 PerlIO_layer_fetch(pTHX_ PerlIO_list_t *av, IV n, PerlIO_funcs *def)
1029 if (n >= 0 && n < av->cur) {
1030 PerlIO_debug("Layer %" IVdf " is %s\n", n,
1031 av->array[n].funcs->name);
1032 return av->array[n].funcs;
1035 Perl_croak(aTHX_ "panic: PerlIO layer array corrupt");
1040 PerlIOPop_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
1042 PERL_UNUSED_ARG(mode);
1043 PERL_UNUSED_ARG(arg);
1044 PERL_UNUSED_ARG(tab);
1045 if (PerlIOValid(f)) {
1047 PerlIO_pop(aTHX_ f);
1053 PERLIO_FUNCS_DECL(PerlIO_remove) = {
1054 sizeof(PerlIO_funcs),
1057 PERLIO_K_DUMMY | PERLIO_K_UTF8,
1077 NULL, /* get_base */
1078 NULL, /* get_bufsiz */
1081 NULL, /* set_ptrcnt */
1085 PerlIO_default_layers(pTHX)
1087 if (!PL_def_layerlist) {
1088 const char * const s = (PL_tainting) ? Nullch : PerlEnv_getenv("PERLIO");
1089 PERLIO_FUNCS_DECL(*osLayer) = &PerlIO_unix;
1090 PL_def_layerlist = PerlIO_list_alloc(aTHX);
1091 PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_unix));
1093 PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_win32));
1095 osLayer = &PerlIO_win32;
1098 PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_raw));
1099 PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_perlio));
1100 PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_stdio));
1101 PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_crlf));
1103 PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_mmap));
1105 PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_utf8));
1106 PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_remove));
1107 PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_byte));
1108 PerlIO_list_push(aTHX_ PL_def_layerlist,
1109 PerlIO_find_layer(aTHX_ osLayer->name, 0, 0),
1112 PerlIO_parse_layers(aTHX_ PL_def_layerlist, s);
1115 PerlIO_default_buffer(aTHX_ PL_def_layerlist);
1118 if (PL_def_layerlist->cur < 2) {
1119 PerlIO_default_buffer(aTHX_ PL_def_layerlist);
1121 return PL_def_layerlist;
1125 Perl_boot_core_PerlIO(pTHX)
1127 #ifdef USE_ATTRIBUTES_FOR_PERLIO
1128 newXS("io::MODIFY_SCALAR_ATTRIBUTES", XS_io_MODIFY_SCALAR_ATTRIBUTES,
1131 newXS("PerlIO::Layer::find", XS_PerlIO__Layer__find, __FILE__);
1132 newXS("PerlIO::Layer::NoWarnings", XS_PerlIO__Layer__NoWarnings, __FILE__);
1136 PerlIO_default_layer(pTHX_ I32 n)
1138 PerlIO_list_t * const av = PerlIO_default_layers(aTHX);
1141 return PerlIO_layer_fetch(aTHX_ av, n, PERLIO_FUNCS_CAST(&PerlIO_stdio));
1144 #define PerlIO_default_top() PerlIO_default_layer(aTHX_ -1)
1145 #define PerlIO_default_btm() PerlIO_default_layer(aTHX_ 0)
1148 PerlIO_stdstreams(pTHX)
1151 PerlIO_allocate(aTHX);
1152 PerlIO_fdopen(0, "Ir" PERLIO_STDTEXT);
1153 PerlIO_fdopen(1, "Iw" PERLIO_STDTEXT);
1154 PerlIO_fdopen(2, "Iw" PERLIO_STDTEXT);
1159 PerlIO_push(pTHX_ PerlIO *f, PERLIO_FUNCS_DECL(*tab), const char *mode, SV *arg)
1161 if (tab->fsize != sizeof(PerlIO_funcs)) {
1163 Perl_croak(aTHX_ "Layer does not match this perl");
1167 if (tab->size < sizeof(PerlIOl)) {
1170 /* Real layer with a data area */
1171 Newxc(l,tab->size,char,PerlIOl);
1173 Zero(l, tab->size, char);
1175 l->tab = (PerlIO_funcs*) tab;
1177 PerlIO_debug("PerlIO_push f=%p %s %s %p\n", (void*)f, tab->name,
1178 (mode) ? mode : "(Null)", (void*)arg);
1179 if (*l->tab->Pushed &&
1180 (*l->tab->Pushed) (aTHX_ f, mode, arg, (PerlIO_funcs*) tab) != 0) {
1181 PerlIO_pop(aTHX_ f);
1187 /* Pseudo-layer where push does its own stack adjust */
1188 PerlIO_debug("PerlIO_push f=%p %s %s %p\n", (void*)f, tab->name,
1189 (mode) ? mode : "(Null)", (void*)arg);
1191 (*tab->Pushed) (aTHX_ f, mode, arg, (PerlIO_funcs*) tab) != 0) {
1199 PerlIOBase_binmode(pTHX_ PerlIO *f)
1201 if (PerlIOValid(f)) {
1202 /* Is layer suitable for raw stream ? */
1203 if (PerlIOBase(f)->tab->kind & PERLIO_K_RAW) {
1204 /* Yes - turn off UTF-8-ness, to undo UTF-8 locale effects */
1205 PerlIOBase(f)->flags &= ~PERLIO_F_UTF8;
1208 /* Not suitable - pop it */
1209 PerlIO_pop(aTHX_ f);
1217 PerlIORaw_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
1219 PERL_UNUSED_ARG(mode);
1220 PERL_UNUSED_ARG(arg);
1221 PERL_UNUSED_ARG(tab);
1223 if (PerlIOValid(f)) {
1228 * Strip all layers that are not suitable for a raw stream
1231 while (t && (l = *t)) {
1232 if (l->tab->Binmode) {
1233 /* Has a handler - normal case */
1234 if ((*l->tab->Binmode)(aTHX_ f) == 0) {
1236 /* Layer still there - move down a layer */
1245 /* No handler - pop it */
1246 PerlIO_pop(aTHX_ t);
1249 if (PerlIOValid(f)) {
1250 PerlIO_debug(":raw f=%p :%s\n", (void*)f, PerlIOBase(f)->tab->name);
1258 PerlIO_apply_layera(pTHX_ PerlIO *f, const char *mode,
1259 PerlIO_list_t *layers, IV n, IV max)
1263 PerlIO_funcs * const tab = PerlIO_layer_fetch(aTHX_ layers, n, NULL);
1265 if (!PerlIO_push(aTHX_ f, tab, mode, PerlIOArg)) {
1276 PerlIO_apply_layers(pTHX_ PerlIO *f, const char *mode, const char *names)
1280 PerlIO_list_t * const layers = PerlIO_list_alloc(aTHX);
1281 code = PerlIO_parse_layers(aTHX_ layers, names);
1283 code = PerlIO_apply_layera(aTHX_ f, mode, layers, 0, layers->cur);
1285 PerlIO_list_free(aTHX_ layers);
1291 /*--------------------------------------------------------------------------------------*/
1293 * Given the abstraction above the public API functions
1297 PerlIO_binmode(pTHX_ PerlIO *f, int iotype, int mode, const char *names)
1299 PerlIO_debug("PerlIO_binmode f=%p %s %c %x %s\n", (void*)f,
1300 (PerlIOBase(f)) ? PerlIOBase(f)->tab->name : "(Null)",
1301 iotype, mode, (names) ? names : "(Null)");
1304 /* Do not flush etc. if (e.g.) switching encodings.
1305 if a pushed layer knows it needs to flush lower layers
1306 (for example :unix which is never going to call them)
1307 it can do the flush when it is pushed.
1309 return PerlIO_apply_layers(aTHX_ f, NULL, names) == 0 ? TRUE : FALSE;
1312 /* Fake 5.6 legacy of using this call to turn ON O_TEXT */
1313 #ifdef PERLIO_USING_CRLF
1314 /* Legacy binmode only has meaning if O_TEXT has a value distinct from
1315 O_BINARY so we can look for it in mode.
1317 if (!(mode & O_BINARY)) {
1319 /* FIXME?: Looking down the layer stack seems wrong,
1320 but is a way of reaching past (say) an encoding layer
1321 to flip CRLF-ness of the layer(s) below
1324 /* Perhaps we should turn on bottom-most aware layer
1325 e.g. Ilya's idea that UNIX TTY could serve
1327 if (PerlIOBase(f)->tab->kind & PERLIO_K_CANCRLF) {
1328 if (!(PerlIOBase(f)->flags & PERLIO_F_CRLF)) {
1329 /* Not in text mode - flush any pending stuff and flip it */
1331 PerlIOBase(f)->flags |= PERLIO_F_CRLF;
1333 /* Only need to turn it on in one layer so we are done */
1338 /* Not finding a CRLF aware layer presumably means we are binary
1339 which is not what was requested - so we failed
1340 We _could_ push :crlf layer but so could caller
1345 /* Legacy binmode is now _defined_ as being equivalent to pushing :raw
1346 So code that used to be here is now in PerlIORaw_pushed().
1348 return PerlIO_push(aTHX_ f, PERLIO_FUNCS_CAST(&PerlIO_raw), Nullch, Nullsv) ? TRUE : FALSE;
1353 PerlIO__close(pTHX_ PerlIO *f)
1355 if (PerlIOValid(f)) {
1356 PerlIO_funcs * const tab = PerlIOBase(f)->tab;
1357 if (tab && tab->Close)
1358 return (*tab->Close)(aTHX_ f);
1360 return PerlIOBase_close(aTHX_ f);
1363 SETERRNO(EBADF, SS_IVCHAN);
1369 Perl_PerlIO_close(pTHX_ PerlIO *f)
1371 const int code = PerlIO__close(aTHX_ f);
1372 while (PerlIOValid(f)) {
1373 PerlIO_pop(aTHX_ f);
1379 Perl_PerlIO_fileno(pTHX_ PerlIO *f)
1381 Perl_PerlIO_or_Base(f, Fileno, fileno, -1, (aTHX_ f));
1385 PerlIO_context_layers(pTHX_ const char *mode)
1387 const char *type = NULL;
1389 * Need to supply default layer info from open.pm
1392 SV * const layers = PL_curcop->cop_io;
1395 type = SvPV_const(layers, len);
1396 if (type && mode[0] != 'r') {
1398 * Skip to write part
1400 const char * const s = strchr(type, 0);
1401 if (s && (STRLEN)(s - type) < len) {
1410 static PerlIO_funcs *
1411 PerlIO_layer_from_ref(pTHX_ SV *sv)
1414 * For any scalar type load the handler which is bundled with perl
1416 if (SvTYPE(sv) < SVt_PVAV)
1417 return PerlIO_find_layer(aTHX_ "scalar", 6, 1);
1420 * For other types allow if layer is known but don't try and load it
1422 switch (SvTYPE(sv)) {
1424 return PerlIO_find_layer(aTHX_ "Array", 5, 0);
1426 return PerlIO_find_layer(aTHX_ "Hash", 4, 0);
1428 return PerlIO_find_layer(aTHX_ "Code", 4, 0);
1430 return PerlIO_find_layer(aTHX_ "Glob", 4, 0);
1436 PerlIO_resolve_layers(pTHX_ const char *layers,
1437 const char *mode, int narg, SV **args)
1439 PerlIO_list_t *def = PerlIO_default_layers(aTHX);
1442 PerlIO_stdstreams(aTHX);
1444 SV * const arg = *args;
1446 * If it is a reference but not an object see if we have a handler
1449 if (SvROK(arg) && !sv_isobject(arg)) {
1450 PerlIO_funcs * const handler = PerlIO_layer_from_ref(aTHX_ SvRV(arg));
1452 def = PerlIO_list_alloc(aTHX);
1453 PerlIO_list_push(aTHX_ def, handler, &PL_sv_undef);
1457 * Don't fail if handler cannot be found :via(...) etc. may do
1458 * something sensible else we will just stringfy and open
1463 if (!layers || !*layers)
1464 layers = PerlIO_context_layers(aTHX_ mode);
1465 if (layers && *layers) {
1469 av = PerlIO_list_alloc(aTHX);
1470 for (i = 0; i < def->cur; i++) {
1471 PerlIO_list_push(aTHX_ av, def->array[i].funcs,
1478 if (PerlIO_parse_layers(aTHX_ av, layers) == 0) {
1482 PerlIO_list_free(aTHX_ av);
1483 return (PerlIO_list_t *) NULL;
1494 PerlIO_openn(pTHX_ const char *layers, const char *mode, int fd,
1495 int imode, int perm, PerlIO *f, int narg, SV **args)
1497 if (!f && narg == 1 && *args == &PL_sv_undef) {
1498 if ((f = PerlIO_tmpfile())) {
1499 if (!layers || !*layers)
1500 layers = PerlIO_context_layers(aTHX_ mode);
1501 if (layers && *layers)
1502 PerlIO_apply_layers(aTHX_ f, mode, layers);
1506 PerlIO_list_t *layera;
1508 PerlIO_funcs *tab = NULL;
1509 if (PerlIOValid(f)) {
1511 * This is "reopen" - it is not tested as perl does not use it
1515 layera = PerlIO_list_alloc(aTHX);
1517 SV * const arg = (l->tab->Getarg)
1518 ? (*l->tab->Getarg) (aTHX_ &l, NULL, 0)
1520 PerlIO_list_push(aTHX_ layera, l->tab, arg);
1521 l = *PerlIONext(&l);
1525 layera = PerlIO_resolve_layers(aTHX_ layers, mode, narg, args);
1531 * Start at "top" of layer stack
1533 n = layera->cur - 1;
1535 PerlIO_funcs * const t = PerlIO_layer_fetch(aTHX_ layera, n, NULL);
1544 * Found that layer 'n' can do opens - call it
1546 if (narg > 1 && !(tab->kind & PERLIO_K_MULTIARG)) {
1547 Perl_croak(aTHX_ "More than one argument to open(,':%s')",tab->name);
1549 PerlIO_debug("openn(%s,'%s','%s',%d,%x,%o,%p,%d,%p)\n",
1550 tab->name, layers ? layers : "(Null)", mode, fd,
1551 imode, perm, (void*)f, narg, (void*)args);
1553 f = (*tab->Open) (aTHX_ tab, layera, n, mode, fd, imode, perm,
1556 SETERRNO(EINVAL, LIB_INVARG);
1560 if (n + 1 < layera->cur) {
1562 * More layers above the one that we used to open -
1565 if (PerlIO_apply_layera(aTHX_ f, mode, layera, n + 1, layera->cur) != 0) {
1566 /* If pushing layers fails close the file */
1573 PerlIO_list_free(aTHX_ layera);
1580 Perl_PerlIO_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
1582 Perl_PerlIO_or_Base(f, Read, read, -1, (aTHX_ f, vbuf, count));
1586 Perl_PerlIO_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
1588 Perl_PerlIO_or_Base(f, Unread, unread, -1, (aTHX_ f, vbuf, count));
1592 Perl_PerlIO_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
1594 Perl_PerlIO_or_fail(f, Write, -1, (aTHX_ f, vbuf, count));
1598 Perl_PerlIO_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
1600 Perl_PerlIO_or_fail(f, Seek, -1, (aTHX_ f, offset, whence));
1604 Perl_PerlIO_tell(pTHX_ PerlIO *f)
1606 Perl_PerlIO_or_fail(f, Tell, -1, (aTHX_ f));
1610 Perl_PerlIO_flush(pTHX_ PerlIO *f)
1614 const PerlIO_funcs *tab = PerlIOBase(f)->tab;
1616 if (tab && tab->Flush)
1617 return (*tab->Flush) (aTHX_ f);
1619 return 0; /* If no Flush defined, silently succeed. */
1622 PerlIO_debug("Cannot flush f=%p\n", (void*)f);
1623 SETERRNO(EBADF, SS_IVCHAN);
1629 * Is it good API design to do flush-all on NULL, a potentially
1630 * errorneous input? Maybe some magical value (PerlIO*
1631 * PERLIO_FLUSH_ALL = (PerlIO*)-1;)? Yes, stdio does similar
1632 * things on fflush(NULL), but should we be bound by their design
1635 PerlIO **table = &PL_perlio;
1637 while ((f = *table)) {
1639 table = (PerlIO **) (f++);
1640 for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
1641 if (*f && PerlIO_flush(f) != 0)
1651 PerlIOBase_flush_linebuf(pTHX)
1653 PerlIO **table = &PL_perlio;
1655 while ((f = *table)) {
1657 table = (PerlIO **) (f++);
1658 for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
1661 flags & (PERLIO_F_LINEBUF | PERLIO_F_CANWRITE))
1662 == (PERLIO_F_LINEBUF | PERLIO_F_CANWRITE))
1670 Perl_PerlIO_fill(pTHX_ PerlIO *f)
1672 Perl_PerlIO_or_fail(f, Fill, -1, (aTHX_ f));
1676 PerlIO_isutf8(PerlIO *f)
1679 return (PerlIOBase(f)->flags & PERLIO_F_UTF8) != 0;
1681 SETERRNO(EBADF, SS_IVCHAN);
1687 Perl_PerlIO_eof(pTHX_ PerlIO *f)
1689 Perl_PerlIO_or_Base(f, Eof, eof, -1, (aTHX_ f));
1693 Perl_PerlIO_error(pTHX_ PerlIO *f)
1695 Perl_PerlIO_or_Base(f, Error, error, -1, (aTHX_ f));
1699 Perl_PerlIO_clearerr(pTHX_ PerlIO *f)
1701 Perl_PerlIO_or_Base_void(f, Clearerr, clearerr, (aTHX_ f));
1705 Perl_PerlIO_setlinebuf(pTHX_ PerlIO *f)
1707 Perl_PerlIO_or_Base_void(f, Setlinebuf, setlinebuf, (aTHX_ f));
1711 PerlIO_has_base(PerlIO *f)
1713 if (PerlIOValid(f)) {
1714 const PerlIO_funcs * const tab = PerlIOBase(f)->tab;
1717 return (tab->Get_base != NULL);
1718 SETERRNO(EINVAL, LIB_INVARG);
1721 SETERRNO(EBADF, SS_IVCHAN);
1727 PerlIO_fast_gets(PerlIO *f)
1729 if (PerlIOValid(f) && (PerlIOBase(f)->flags & PERLIO_F_FASTGETS)) {
1730 const PerlIO_funcs * const tab = PerlIOBase(f)->tab;
1733 return (tab->Set_ptrcnt != NULL);
1734 SETERRNO(EINVAL, LIB_INVARG);
1737 SETERRNO(EBADF, SS_IVCHAN);
1743 PerlIO_has_cntptr(PerlIO *f)
1745 if (PerlIOValid(f)) {
1746 const PerlIO_funcs * const tab = PerlIOBase(f)->tab;
1749 return (tab->Get_ptr != NULL && tab->Get_cnt != NULL);
1750 SETERRNO(EINVAL, LIB_INVARG);
1753 SETERRNO(EBADF, SS_IVCHAN);
1759 PerlIO_canset_cnt(PerlIO *f)
1761 if (PerlIOValid(f)) {
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 Perl_PerlIO_get_base(pTHX_ PerlIO *f)
1777 Perl_PerlIO_or_fail(f, Get_base, NULL, (aTHX_ f));
1781 Perl_PerlIO_get_bufsiz(pTHX_ PerlIO *f)
1783 Perl_PerlIO_or_fail(f, Get_bufsiz, -1, (aTHX_ f));
1787 Perl_PerlIO_get_ptr(pTHX_ PerlIO *f)
1789 Perl_PerlIO_or_fail(f, Get_ptr, NULL, (aTHX_ f));
1793 Perl_PerlIO_get_cnt(pTHX_ PerlIO *f)
1795 Perl_PerlIO_or_fail(f, Get_cnt, -1, (aTHX_ f));
1799 Perl_PerlIO_set_cnt(pTHX_ PerlIO *f, int cnt)
1801 Perl_PerlIO_or_fail_void(f, Set_ptrcnt, (aTHX_ f, NULL, cnt));
1805 Perl_PerlIO_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, int cnt)
1807 Perl_PerlIO_or_fail_void(f, Set_ptrcnt, (aTHX_ f, ptr, cnt));
1811 /*--------------------------------------------------------------------------------------*/
1813 * utf8 and raw dummy layers
1817 PerlIOUtf8_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
1819 PERL_UNUSED_ARG(mode);
1820 PERL_UNUSED_ARG(arg);
1821 if (PerlIOValid(f)) {
1822 if (tab->kind & PERLIO_K_UTF8)
1823 PerlIOBase(f)->flags |= PERLIO_F_UTF8;
1825 PerlIOBase(f)->flags &= ~PERLIO_F_UTF8;
1831 PERLIO_FUNCS_DECL(PerlIO_utf8) = {
1832 sizeof(PerlIO_funcs),
1835 PERLIO_K_DUMMY | PERLIO_K_UTF8,
1855 NULL, /* get_base */
1856 NULL, /* get_bufsiz */
1859 NULL, /* set_ptrcnt */
1862 PERLIO_FUNCS_DECL(PerlIO_byte) = {
1863 sizeof(PerlIO_funcs),
1886 NULL, /* get_base */
1887 NULL, /* get_bufsiz */
1890 NULL, /* set_ptrcnt */
1894 PerlIORaw_open(pTHX_ PerlIO_funcs *self, PerlIO_list_t *layers,
1895 IV n, const char *mode, int fd, int imode, int perm,
1896 PerlIO *old, int narg, SV **args)
1898 PerlIO_funcs * const tab = PerlIO_default_btm();
1899 PERL_UNUSED_ARG(self);
1900 if (tab && tab->Open)
1901 return (*tab->Open) (aTHX_ tab, layers, n - 1, mode, fd, imode, perm,
1903 SETERRNO(EINVAL, LIB_INVARG);
1907 PERLIO_FUNCS_DECL(PerlIO_raw) = {
1908 sizeof(PerlIO_funcs),
1931 NULL, /* get_base */
1932 NULL, /* get_bufsiz */
1935 NULL, /* set_ptrcnt */
1937 /*--------------------------------------------------------------------------------------*/
1938 /*--------------------------------------------------------------------------------------*/
1940 * "Methods" of the "base class"
1944 PerlIOBase_fileno(pTHX_ PerlIO *f)
1946 return PerlIOValid(f) ? PerlIO_fileno(PerlIONext(f)) : -1;
1950 PerlIO_modestr(PerlIO * f, char *buf)
1953 if (PerlIOValid(f)) {
1954 const IV flags = PerlIOBase(f)->flags;
1955 if (flags & PERLIO_F_APPEND) {
1957 if (flags & PERLIO_F_CANREAD) {
1961 else if (flags & PERLIO_F_CANREAD) {
1963 if (flags & PERLIO_F_CANWRITE)
1966 else if (flags & PERLIO_F_CANWRITE) {
1968 if (flags & PERLIO_F_CANREAD) {
1972 #ifdef PERLIO_USING_CRLF
1973 if (!(flags & PERLIO_F_CRLF))
1983 PerlIOBase_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
1985 PerlIOl * const l = PerlIOBase(f);
1986 PERL_UNUSED_ARG(arg);
1988 l->flags &= ~(PERLIO_F_CANREAD | PERLIO_F_CANWRITE |
1989 PERLIO_F_TRUNCATE | PERLIO_F_APPEND);
1990 if (tab->Set_ptrcnt != NULL)
1991 l->flags |= PERLIO_F_FASTGETS;
1993 if (*mode == IoTYPE_NUMERIC || *mode == IoTYPE_IMPLICIT)
1997 l->flags |= PERLIO_F_CANREAD;
2000 l->flags |= PERLIO_F_APPEND | PERLIO_F_CANWRITE;
2003 l->flags |= PERLIO_F_TRUNCATE | PERLIO_F_CANWRITE;
2006 SETERRNO(EINVAL, LIB_INVARG);
2012 l->flags |= PERLIO_F_CANREAD | PERLIO_F_CANWRITE;
2015 l->flags &= ~PERLIO_F_CRLF;
2018 l->flags |= PERLIO_F_CRLF;
2021 SETERRNO(EINVAL, LIB_INVARG);
2028 l->flags |= l->next->flags &
2029 (PERLIO_F_CANREAD | PERLIO_F_CANWRITE | PERLIO_F_TRUNCATE |
2034 PerlIO_debug("PerlIOBase_pushed f=%p %s %s fl=%08" UVxf " (%s)\n",
2035 f, PerlIOBase(f)->tab->name, (omode) ? omode : "(Null)",
2036 l->flags, PerlIO_modestr(f, temp));
2042 PerlIOBase_popped(pTHX_ PerlIO *f)
2049 PerlIOBase_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
2052 * Save the position as current head considers it
2054 const Off_t old = PerlIO_tell(f);
2055 PerlIO_push(aTHX_ f, PERLIO_FUNCS_CAST(&PerlIO_pending), "r", Nullsv);
2056 PerlIOSelf(f, PerlIOBuf)->posn = old;
2057 return PerlIOBuf_unread(aTHX_ f, vbuf, count);
2061 PerlIOBase_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
2063 STDCHAR *buf = (STDCHAR *) vbuf;
2065 if (!(PerlIOBase(f)->flags & PERLIO_F_CANREAD)) {
2066 PerlIOBase(f)->flags |= PERLIO_F_ERROR;
2067 SETERRNO(EBADF, SS_IVCHAN);
2073 SSize_t avail = PerlIO_get_cnt(f);
2076 take = ((SSize_t)count < avail) ? count : avail;
2078 STDCHAR *ptr = PerlIO_get_ptr(f);
2079 Copy(ptr, buf, take, STDCHAR);
2080 PerlIO_set_ptrcnt(f, ptr + take, (avail -= take));
2083 if (avail == 0) /* set_ptrcnt could have reset avail */
2086 if (count > 0 && avail <= 0) {
2087 if (PerlIO_fill(f) != 0)
2092 return (buf - (STDCHAR *) vbuf);
2098 PerlIOBase_noop_ok(pTHX_ PerlIO *f)
2105 PerlIOBase_noop_fail(pTHX_ PerlIO *f)
2112 PerlIOBase_close(pTHX_ PerlIO *f)
2115 if (PerlIOValid(f)) {
2116 PerlIO *n = PerlIONext(f);
2117 code = PerlIO_flush(f);
2118 PerlIOBase(f)->flags &=
2119 ~(PERLIO_F_CANREAD | PERLIO_F_CANWRITE | PERLIO_F_OPEN);
2120 while (PerlIOValid(n)) {
2121 const PerlIO_funcs * const tab = PerlIOBase(n)->tab;
2122 if (tab && tab->Close) {
2123 if ((*tab->Close)(aTHX_ n) != 0)
2128 PerlIOBase(n)->flags &=
2129 ~(PERLIO_F_CANREAD | PERLIO_F_CANWRITE | PERLIO_F_OPEN);
2135 SETERRNO(EBADF, SS_IVCHAN);
2141 PerlIOBase_eof(pTHX_ PerlIO *f)
2143 if (PerlIOValid(f)) {
2144 return (PerlIOBase(f)->flags & PERLIO_F_EOF) != 0;
2150 PerlIOBase_error(pTHX_ PerlIO *f)
2152 if (PerlIOValid(f)) {
2153 return (PerlIOBase(f)->flags & PERLIO_F_ERROR) != 0;
2159 PerlIOBase_clearerr(pTHX_ PerlIO *f)
2161 if (PerlIOValid(f)) {
2162 PerlIO * const n = PerlIONext(f);
2163 PerlIOBase(f)->flags &= ~(PERLIO_F_ERROR | PERLIO_F_EOF);
2170 PerlIOBase_setlinebuf(pTHX_ PerlIO *f)
2172 if (PerlIOValid(f)) {
2173 PerlIOBase(f)->flags |= PERLIO_F_LINEBUF;
2178 PerlIO_sv_dup(pTHX_ SV *arg, CLONE_PARAMS *param)
2184 return sv_dup(arg, param);
2187 return newSVsv(arg);
2190 PERL_UNUSED_ARG(param);
2191 return newSVsv(arg);
2196 PerlIOBase_dup(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags)
2198 PerlIO * const nexto = PerlIONext(o);
2199 if (PerlIOValid(nexto)) {
2200 const PerlIO_funcs * const tab = PerlIOBase(nexto)->tab;
2201 if (tab && tab->Dup)
2202 f = (*tab->Dup)(aTHX_ f, nexto, param, flags);
2204 f = PerlIOBase_dup(aTHX_ f, nexto, param, flags);
2207 PerlIO_funcs * const self = PerlIOBase(o)->tab;
2210 PerlIO_debug("PerlIOBase_dup %s f=%p o=%p param=%p\n",
2211 self->name, (void*)f, (void*)o, (void*)param);
2213 arg = (*self->Getarg)(aTHX_ o, param, flags);
2217 f = PerlIO_push(aTHX_ f, self, PerlIO_modestr(o,buf), arg);
2226 perl_mutex PerlIO_mutex;
2229 /* PL_perlio_fd_refcnt[] is in intrpvar.h */
2234 /* Place holder for stdstreams call ??? */
2236 MUTEX_INIT(&PerlIO_mutex);
2241 PerlIOUnix_refcnt_inc(int fd)
2244 if (fd >= 0 && fd < PERLIO_MAX_REFCOUNTABLE_FD) {
2246 MUTEX_LOCK(&PerlIO_mutex);
2248 PL_perlio_fd_refcnt[fd]++;
2249 PerlIO_debug("fd %d refcnt=%d\n",fd,PL_perlio_fd_refcnt[fd]);
2251 MUTEX_UNLOCK(&PerlIO_mutex);
2257 PerlIOUnix_refcnt_dec(int fd)
2261 if (fd >= 0 && fd < PERLIO_MAX_REFCOUNTABLE_FD) {
2263 MUTEX_LOCK(&PerlIO_mutex);
2265 cnt = --PL_perlio_fd_refcnt[fd];
2266 PerlIO_debug("fd %d refcnt=%d\n",fd,cnt);
2268 MUTEX_UNLOCK(&PerlIO_mutex);
2275 PerlIO_cleanup(pTHX)
2279 PerlIO_debug("Cleanup layers for %p\n",aTHX);
2281 PerlIO_debug("Cleanup layers\n");
2283 /* Raise STDIN..STDERR refcount so we don't close them */
2284 for (i=0; i < 3; i++)
2285 PerlIOUnix_refcnt_inc(i);
2286 PerlIO_cleantable(aTHX_ &PL_perlio);
2287 /* Restore STDIN..STDERR refcount */
2288 for (i=0; i < 3; i++)
2289 PerlIOUnix_refcnt_dec(i);
2291 if (PL_known_layers) {
2292 PerlIO_list_free(aTHX_ PL_known_layers);
2293 PL_known_layers = NULL;
2295 if (PL_def_layerlist) {
2296 PerlIO_list_free(aTHX_ PL_def_layerlist);
2297 PL_def_layerlist = NULL;
2303 /*--------------------------------------------------------------------------------------*/
2305 * Bottom-most level for UNIX-like case
2309 struct _PerlIO base; /* The generic part */
2310 int fd; /* UNIX like file descriptor */
2311 int oflags; /* open/fcntl flags */
2315 PerlIOUnix_oflags(const char *mode)
2318 if (*mode == IoTYPE_IMPLICIT || *mode == IoTYPE_NUMERIC)
2323 if (*++mode == '+') {
2330 oflags = O_CREAT | O_TRUNC;
2331 if (*++mode == '+') {
2340 oflags = O_CREAT | O_APPEND;
2341 if (*++mode == '+') {
2354 else if (*mode == 't') {
2356 oflags &= ~O_BINARY;
2360 * Always open in binary mode
2363 if (*mode || oflags == -1) {
2364 SETERRNO(EINVAL, LIB_INVARG);
2371 PerlIOUnix_fileno(pTHX_ PerlIO *f)
2373 return PerlIOSelf(f, PerlIOUnix)->fd;
2377 PerlIOUnix_setfd(pTHX_ PerlIO *f, int fd, int imode)
2379 PerlIOUnix * const s = PerlIOSelf(f, PerlIOUnix);
2382 if (PerlLIO_fstat(fd, &st) == 0) {
2383 if (!S_ISREG(st.st_mode)) {
2384 PerlIO_debug("%d is not regular file\n",fd);
2385 PerlIOBase(f)->flags |= PERLIO_F_NOTREG;
2388 PerlIO_debug("%d _is_ a regular file\n",fd);
2394 PerlIOUnix_refcnt_inc(fd);
2398 PerlIOUnix_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
2400 IV code = PerlIOBase_pushed(aTHX_ f, mode, arg, tab);
2401 if (*PerlIONext(f)) {
2402 /* We never call down so do any pending stuff now */
2403 PerlIO_flush(PerlIONext(f));
2405 * XXX could (or should) we retrieve the oflags from the open file
2406 * handle rather than believing the "mode" we are passed in? XXX
2407 * Should the value on NULL mode be 0 or -1?
2409 PerlIOUnix_setfd(aTHX_ f, PerlIO_fileno(PerlIONext(f)),
2410 mode ? PerlIOUnix_oflags(mode) : -1);
2412 PerlIOBase(f)->flags |= PERLIO_F_OPEN;
2418 PerlIOUnix_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
2420 const int fd = PerlIOSelf(f, PerlIOUnix)->fd;
2422 if (PerlIOBase(f)->flags & PERLIO_F_NOTREG) {
2424 SETERRNO(ESPIPE, LIB_INVARG);
2426 SETERRNO(EINVAL, LIB_INVARG);
2430 new_loc = PerlLIO_lseek(fd, offset, whence);
2431 if (new_loc == (Off_t) - 1)
2433 PerlIOBase(f)->flags &= ~PERLIO_F_EOF;
2438 PerlIOUnix_open(pTHX_ PerlIO_funcs *self, PerlIO_list_t *layers,
2439 IV n, const char *mode, int fd, int imode,
2440 int perm, PerlIO *f, int narg, SV **args)
2442 if (PerlIOValid(f)) {
2443 if (PerlIOBase(f)->flags & PERLIO_F_OPEN)
2444 (*PerlIOBase(f)->tab->Close)(aTHX_ f);
2447 if (*mode == IoTYPE_NUMERIC)
2450 imode = PerlIOUnix_oflags(mode);
2454 const char *path = SvPV_nolen_const(*args);
2455 fd = PerlLIO_open3(path, imode, perm);
2459 if (*mode == IoTYPE_IMPLICIT)
2462 f = PerlIO_allocate(aTHX);
2464 if (!PerlIOValid(f)) {
2465 if (!(f = PerlIO_push(aTHX_ f, self, mode, PerlIOArg))) {
2469 PerlIOUnix_setfd(aTHX_ f, fd, imode);
2470 PerlIOBase(f)->flags |= PERLIO_F_OPEN;
2471 if (*mode == IoTYPE_APPEND)
2472 PerlIOUnix_seek(aTHX_ f, 0, SEEK_END);
2478 * FIXME: pop layers ???
2486 PerlIOUnix_dup(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags)
2488 const PerlIOUnix * const os = PerlIOSelf(o, PerlIOUnix);
2490 if (flags & PERLIO_DUP_FD) {
2491 fd = PerlLIO_dup(fd);
2493 if (fd >= 0 && fd < PERLIO_MAX_REFCOUNTABLE_FD) {
2494 f = PerlIOBase_dup(aTHX_ f, o, param, flags);
2496 /* If all went well overwrite fd in dup'ed lay with the dup()'ed fd */
2497 PerlIOUnix_setfd(aTHX_ f, fd, os->oflags);
2506 PerlIOUnix_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
2508 const int fd = PerlIOSelf(f, PerlIOUnix)->fd;
2509 #ifdef PERLIO_STD_SPECIAL
2511 return PERLIO_STD_IN(fd, vbuf, count);
2513 if (!(PerlIOBase(f)->flags & PERLIO_F_CANREAD) ||
2514 PerlIOBase(f)->flags & (PERLIO_F_EOF|PERLIO_F_ERROR)) {
2518 const SSize_t len = PerlLIO_read(fd, vbuf, count);
2519 if (len >= 0 || errno != EINTR) {
2521 if (errno != EAGAIN) {
2522 PerlIOBase(f)->flags |= PERLIO_F_ERROR;
2525 else if (len == 0 && count != 0) {
2526 PerlIOBase(f)->flags |= PERLIO_F_EOF;
2537 PerlIOUnix_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
2539 const int fd = PerlIOSelf(f, PerlIOUnix)->fd;
2540 #ifdef PERLIO_STD_SPECIAL
2541 if (fd == 1 || fd == 2)
2542 return PERLIO_STD_OUT(fd, vbuf, count);
2545 const SSize_t len = PerlLIO_write(fd, vbuf, count);
2546 if (len >= 0 || errno != EINTR) {
2548 if (errno != EAGAIN) {
2549 PerlIOBase(f)->flags |= PERLIO_F_ERROR;
2560 PerlIOUnix_tell(pTHX_ PerlIO *f)
2562 return PerlLIO_lseek(PerlIOSelf(f, PerlIOUnix)->fd, 0, SEEK_CUR);
2567 PerlIOUnix_close(pTHX_ PerlIO *f)
2569 const int fd = PerlIOSelf(f, PerlIOUnix)->fd;
2571 if (PerlIOBase(f)->flags & PERLIO_F_OPEN) {
2572 if (PerlIOUnix_refcnt_dec(fd) > 0) {
2573 PerlIOBase(f)->flags &= ~PERLIO_F_OPEN;
2578 SETERRNO(EBADF,SS_IVCHAN);
2581 while (PerlLIO_close(fd) != 0) {
2582 if (errno != EINTR) {
2589 PerlIOBase(f)->flags &= ~PERLIO_F_OPEN;
2594 PERLIO_FUNCS_DECL(PerlIO_unix) = {
2595 sizeof(PerlIO_funcs),
2602 PerlIOBase_binmode, /* binmode */
2612 PerlIOBase_noop_ok, /* flush */
2613 PerlIOBase_noop_fail, /* fill */
2616 PerlIOBase_clearerr,
2617 PerlIOBase_setlinebuf,
2618 NULL, /* get_base */
2619 NULL, /* get_bufsiz */
2622 NULL, /* set_ptrcnt */
2625 /*--------------------------------------------------------------------------------------*/
2630 #if defined(VMS) && !defined(STDIO_BUFFER_WRITABLE)
2631 /* perl5.8 - This ensures the last minute VMS ungetc fix is not
2632 broken by the last second glibc 2.3 fix
2634 #define STDIO_BUFFER_WRITABLE
2639 struct _PerlIO base;
2640 FILE *stdio; /* The stream */
2644 PerlIOStdio_fileno(pTHX_ PerlIO *f)
2646 if (PerlIOValid(f)) {
2647 FILE * const s = PerlIOSelf(f, PerlIOStdio)->stdio;
2649 return PerlSIO_fileno(s);
2656 PerlIOStdio_mode(const char *mode, char *tmode)
2658 char * const ret = tmode;
2664 #if defined(PERLIO_USING_CRLF) || defined(__CYGWIN__)
2672 PerlIOStdio_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
2675 if (PerlIOValid(f) && PerlIOValid(n = PerlIONext(f))) {
2676 PerlIO_funcs * const toptab = PerlIOBase(n)->tab;
2677 if (toptab == tab) {
2678 /* Top is already stdio - pop self (duplicate) and use original */
2679 PerlIO_pop(aTHX_ f);
2682 const int fd = PerlIO_fileno(n);
2685 if (fd >= 0 && (stdio = PerlSIO_fdopen(fd,
2686 mode = PerlIOStdio_mode(mode, tmode)))) {
2687 PerlIOSelf(f, PerlIOStdio)->stdio = stdio;
2688 /* We never call down so do any pending stuff now */
2689 PerlIO_flush(PerlIONext(f));
2696 return PerlIOBase_pushed(aTHX_ f, mode, arg, tab);
2701 PerlIO_importFILE(FILE *stdio, const char *mode)
2707 if (!mode || !*mode) {
2708 /* We need to probe to see how we can open the stream
2709 so start with read/write and then try write and read
2710 we dup() so that we can fclose without loosing the fd.
2712 Note that the errno value set by a failing fdopen
2713 varies between stdio implementations.
2715 const int fd = PerlLIO_dup(fileno(stdio));
2716 FILE *f2 = PerlSIO_fdopen(fd, (mode = "r+"));
2718 f2 = PerlSIO_fdopen(fd, (mode = "w"));
2721 f2 = PerlSIO_fdopen(fd, (mode = "r"));
2724 /* Don't seem to be able to open */
2730 if ((f = PerlIO_push(aTHX_(f = PerlIO_allocate(aTHX)), PERLIO_FUNCS_CAST(&PerlIO_stdio), mode, Nullsv))) {
2731 s = PerlIOSelf(f, PerlIOStdio);
2739 PerlIOStdio_open(pTHX_ PerlIO_funcs *self, PerlIO_list_t *layers,
2740 IV n, const char *mode, int fd, int imode,
2741 int perm, PerlIO *f, int narg, SV **args)
2744 if (PerlIOValid(f)) {
2745 const char * const path = SvPV_nolen_const(*args);
2746 PerlIOStdio * const s = PerlIOSelf(f, PerlIOStdio);
2748 PerlIOUnix_refcnt_dec(fileno(s->stdio));
2749 stdio = PerlSIO_freopen(path, (mode = PerlIOStdio_mode(mode, tmode)),
2754 PerlIOUnix_refcnt_inc(fileno(s->stdio));
2759 const char * const path = SvPV_nolen_const(*args);
2760 if (*mode == IoTYPE_NUMERIC) {
2762 fd = PerlLIO_open3(path, imode, perm);
2766 bool appended = FALSE;
2768 /* Cygwin wants its 'b' early. */
2770 mode = PerlIOStdio_mode(mode, tmode);
2772 stdio = PerlSIO_fopen(path, mode);
2776 f = PerlIO_allocate(aTHX);
2779 mode = PerlIOStdio_mode(mode, tmode);
2780 f = PerlIO_push(aTHX_ f, self, mode, PerlIOArg);
2782 s = PerlIOSelf(f, PerlIOStdio);
2784 PerlIOUnix_refcnt_inc(fileno(s->stdio));
2796 if (*mode == IoTYPE_IMPLICIT) {
2803 stdio = PerlSIO_stdin;
2806 stdio = PerlSIO_stdout;
2809 stdio = PerlSIO_stderr;
2814 stdio = PerlSIO_fdopen(fd, mode =
2815 PerlIOStdio_mode(mode, tmode));
2819 f = PerlIO_allocate(aTHX);
2821 if ((f = PerlIO_push(aTHX_ f, self, mode, PerlIOArg))) {
2822 PerlIOStdio * const s = PerlIOSelf(f, PerlIOStdio);
2824 PerlIOUnix_refcnt_inc(fileno(s->stdio));
2834 PerlIOStdio_dup(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags)
2836 /* This assumes no layers underneath - which is what
2837 happens, but is not how I remember it. NI-S 2001/10/16
2839 if ((f = PerlIOBase_dup(aTHX_ f, o, param, flags))) {
2840 FILE *stdio = PerlIOSelf(o, PerlIOStdio)->stdio;
2841 const int fd = fileno(stdio);
2843 if (flags & PERLIO_DUP_FD) {
2844 const int dfd = PerlLIO_dup(fileno(stdio));
2846 stdio = PerlSIO_fdopen(dfd, PerlIO_modestr(o,mode));
2850 /* FIXME: To avoid messy error recovery if dup fails
2851 re-use the existing stdio as though flag was not set
2855 stdio = PerlSIO_fdopen(fd, PerlIO_modestr(o,mode));
2857 PerlIOSelf(f, PerlIOStdio)->stdio = stdio;
2858 PerlIOUnix_refcnt_inc(fileno(stdio));
2864 PerlIOStdio_invalidate_fileno(pTHX_ FILE *f)
2866 /* XXX this could use PerlIO_canset_fileno() and
2867 * PerlIO_set_fileno() support from Configure
2869 # if defined(__UCLIBC__)
2870 /* uClibc must come before glibc because it defines __GLIBC__ as well. */
2873 # elif defined(__GLIBC__)
2874 /* There may be a better way for GLIBC:
2875 - libio.h defines a flag to not close() on cleanup
2879 # elif defined(__sun__)
2881 /* On solaris, if _LP64 is defined, the FILE structure is this:
2887 * It turns out that the fd is stored in the top 32 bits of
2888 * file->__pad[4]. The lower 32 bits contain flags. file->pad[5] appears
2889 * to contain a pointer or offset into another structure. All the
2890 * remaining fields are zero.
2892 * We set the top bits to -1 (0xFFFFFFFF).
2894 f->__pad[4] |= 0xffffffff00000000L;
2895 assert(fileno(f) == 0xffffffff);
2896 # else /* !defined(_LP64) */
2897 /* _file is just a unsigned char :-(
2898 Not clear why we dup() rather than using -1
2899 even if that would be treated as 0xFF - so will
2902 f->_file = PerlLIO_dup(fileno(f));
2903 # endif /* defined(_LP64) */
2905 # elif defined(__hpux)
2909 /* Next one ->_file seems to be a reasonable fallback, i.e. if
2910 your platform does not have special entry try this one.
2911 [For OSF only have confirmation for Tru64 (alpha)
2912 but assume other OSFs will be similar.]
2914 # elif defined(_AIX) || defined(__osf__) || defined(__irix__)
2917 # elif defined(__FreeBSD__)
2918 /* There may be a better way on FreeBSD:
2919 - we could insert a dummy func in the _close function entry
2920 f->_close = (int (*)(void *)) dummy_close;
2924 # elif defined(__OpenBSD__)
2925 /* There may be a better way on OpenBSD:
2926 - we could insert a dummy func in the _close function entry
2927 f->_close = (int (*)(void *)) dummy_close;
2931 # elif defined(__EMX__)
2932 /* f->_flags &= ~_IOOPEN; */ /* Will leak stream->_buffer */
2935 # elif defined(__CYGWIN__)
2936 /* There may be a better way on CYGWIN:
2937 - we could insert a dummy func in the _close function entry
2938 f->_close = (int (*)(void *)) dummy_close;
2942 # elif defined(WIN32)
2943 # if defined(__BORLANDC__)
2944 f->fd = PerlLIO_dup(fileno(f));
2945 # elif defined(UNDER_CE)
2946 /* WIN_CE does not have access to FILE internals, it hardly has FILE
2955 /* Sarathy's code did this - we fall back to a dup/dup2 hack
2956 (which isn't thread safe) instead
2958 # error "Don't know how to set FILE.fileno on your platform"
2966 PerlIOStdio_close(pTHX_ PerlIO *f)
2968 FILE * const stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
2974 const int fd = fileno(stdio);
2980 #ifdef SOCKS5_VERSION_NAME
2981 /* Socks lib overrides close() but stdio isn't linked to
2982 that library (though we are) - so we must call close()
2983 on sockets on stdio's behalf.
2986 Sock_size_t optlen = sizeof(int);
2987 if (getsockopt(fd, SOL_SOCKET, SO_TYPE, (void *) &optval, &optlen) == 0) {
2992 if (PerlIOUnix_refcnt_dec(fd) > 0) {
2993 /* File descriptor still in use */
2998 /* For STD* handles don't close the stdio at all
2999 this is because we have shared the FILE * too
3001 if (stdio == stdin) {
3002 /* Some stdios are buggy fflush-ing inputs */
3005 else if (stdio == stdout || stdio == stderr) {
3006 return PerlIO_flush(f);
3008 /* Tricky - must fclose(stdio) to free memory but not close(fd)
3009 Use Sarathy's trick from maint-5.6 to invalidate the
3010 fileno slot of the FILE *
3012 result = PerlIO_flush(f);
3014 if (!(invalidate = PerlIOStdio_invalidate_fileno(aTHX_ stdio))) {
3015 dupfd = PerlLIO_dup(fd);
3018 result = PerlSIO_fclose(stdio);
3019 /* We treat error from stdio as success if we invalidated
3020 errno may NOT be expected EBADF
3022 if (invalidate && result != 0) {
3027 /* in SOCKS case let close() determine return value */
3031 PerlLIO_dup2(dupfd,fd);
3032 PerlLIO_close(dupfd);
3039 PerlIOStdio_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
3041 FILE * const s = PerlIOSelf(f, PerlIOStdio)->stdio;
3045 STDCHAR *buf = (STDCHAR *) vbuf;
3047 * Perl is expecting PerlIO_getc() to fill the buffer Linux's
3048 * stdio does not do that for fread()
3050 const int ch = PerlSIO_fgetc(s);
3057 got = PerlSIO_fread(vbuf, 1, count, s);
3058 if (got == 0 && PerlSIO_ferror(s))
3060 if (got >= 0 || errno != EINTR)
3063 SETERRNO(0,0); /* just in case */
3069 PerlIOStdio_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
3072 FILE * const s = PerlIOSelf(f, PerlIOStdio)->stdio;
3074 #ifdef STDIO_BUFFER_WRITABLE
3075 if (PerlIO_fast_gets(f) && PerlIO_has_base(f)) {
3076 STDCHAR *buf = ((STDCHAR *) vbuf) + count;
3077 STDCHAR *base = PerlIO_get_base(f);
3078 SSize_t cnt = PerlIO_get_cnt(f);
3079 STDCHAR *ptr = PerlIO_get_ptr(f);
3080 SSize_t avail = ptr - base;
3082 if (avail > count) {
3086 Move(buf-avail,ptr,avail,STDCHAR);
3089 PerlIO_set_ptrcnt(f,ptr,cnt+avail);
3090 if (PerlSIO_feof(s) && unread >= 0)
3091 PerlSIO_clearerr(s);
3096 if (PerlIO_has_cntptr(f)) {
3097 /* We can get pointer to buffer but not its base
3098 Do ungetc() but check chars are ending up in the
3101 STDCHAR *eptr = (STDCHAR*)PerlSIO_get_ptr(s);
3102 STDCHAR *buf = ((STDCHAR *) vbuf) + count;
3104 const int ch = *--buf & 0xFF;
3105 if (ungetc(ch,s) != ch) {
3106 /* ungetc did not work */
3109 if ((STDCHAR*)PerlSIO_get_ptr(s) != --eptr || ((*eptr & 0xFF) != ch)) {
3110 /* Did not change pointer as expected */
3111 fgetc(s); /* get char back again */
3121 unread += PerlIOBase_unread(aTHX_ f, vbuf, count);
3127 PerlIOStdio_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
3131 got = PerlSIO_fwrite(vbuf, 1, count,
3132 PerlIOSelf(f, PerlIOStdio)->stdio);
3133 if (got >= 0 || errno != EINTR)
3136 SETERRNO(0,0); /* just in case */
3142 PerlIOStdio_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
3144 FILE * const stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3145 return PerlSIO_fseek(stdio, offset, whence);
3149 PerlIOStdio_tell(pTHX_ PerlIO *f)
3151 FILE * const stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3152 return PerlSIO_ftell(stdio);
3156 PerlIOStdio_flush(pTHX_ PerlIO *f)
3158 FILE * const stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3159 if (PerlIOBase(f)->flags & PERLIO_F_CANWRITE) {
3160 return PerlSIO_fflush(stdio);
3165 * FIXME: This discards ungetc() and pre-read stuff which is not
3166 * right if this is just a "sync" from a layer above Suspect right
3167 * design is to do _this_ but not have layer above flush this
3168 * layer read-to-read
3171 * Not writeable - sync by attempting a seek
3173 const int err = errno;
3174 if (PerlSIO_fseek(stdio, (Off_t) 0, SEEK_CUR) != 0)
3182 PerlIOStdio_eof(pTHX_ PerlIO *f)
3184 return PerlSIO_feof(PerlIOSelf(f, PerlIOStdio)->stdio);
3188 PerlIOStdio_error(pTHX_ PerlIO *f)
3190 return PerlSIO_ferror(PerlIOSelf(f, PerlIOStdio)->stdio);
3194 PerlIOStdio_clearerr(pTHX_ PerlIO *f)
3196 PerlSIO_clearerr(PerlIOSelf(f, PerlIOStdio)->stdio);
3200 PerlIOStdio_setlinebuf(pTHX_ PerlIO *f)
3202 #ifdef HAS_SETLINEBUF
3203 PerlSIO_setlinebuf(PerlIOSelf(f, PerlIOStdio)->stdio);
3205 PerlSIO_setvbuf(PerlIOSelf(f, PerlIOStdio)->stdio, Nullch, _IOLBF, 0);
3211 PerlIOStdio_get_base(pTHX_ PerlIO *f)
3213 FILE * const stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3214 return (STDCHAR*)PerlSIO_get_base(stdio);
3218 PerlIOStdio_get_bufsiz(pTHX_ PerlIO *f)
3220 FILE * const stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3221 return PerlSIO_get_bufsiz(stdio);
3225 #ifdef USE_STDIO_PTR
3227 PerlIOStdio_get_ptr(pTHX_ PerlIO *f)
3229 FILE * const stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3230 return (STDCHAR*)PerlSIO_get_ptr(stdio);
3234 PerlIOStdio_get_cnt(pTHX_ PerlIO *f)
3236 FILE * const stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3237 return PerlSIO_get_cnt(stdio);
3241 PerlIOStdio_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, SSize_t cnt)
3243 FILE * const stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3245 #ifdef STDIO_PTR_LVALUE
3246 PerlSIO_set_ptr(stdio, (void*)ptr); /* LHS STDCHAR* cast non-portable */
3247 #ifdef STDIO_PTR_LVAL_SETS_CNT
3248 if (PerlSIO_get_cnt(stdio) != (cnt)) {
3249 assert(PerlSIO_get_cnt(stdio) == (cnt));
3252 #if (!defined(STDIO_PTR_LVAL_NOCHANGE_CNT))
3254 * Setting ptr _does_ change cnt - we are done
3258 #else /* STDIO_PTR_LVALUE */
3260 #endif /* STDIO_PTR_LVALUE */
3263 * Now (or only) set cnt
3265 #ifdef STDIO_CNT_LVALUE
3266 PerlSIO_set_cnt(stdio, cnt);
3267 #else /* STDIO_CNT_LVALUE */
3268 #if (defined(STDIO_PTR_LVALUE) && defined(STDIO_PTR_LVAL_SETS_CNT))
3269 PerlSIO_set_ptr(stdio,
3270 PerlSIO_get_ptr(stdio) + (PerlSIO_get_cnt(stdio) -
3272 #else /* STDIO_PTR_LVAL_SETS_CNT */
3274 #endif /* STDIO_PTR_LVAL_SETS_CNT */
3275 #endif /* STDIO_CNT_LVALUE */
3282 PerlIOStdio_fill(pTHX_ PerlIO *f)
3284 FILE * const stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3287 * fflush()ing read-only streams can cause trouble on some stdio-s
3289 if ((PerlIOBase(f)->flags & PERLIO_F_CANWRITE)) {
3290 if (PerlSIO_fflush(stdio) != 0)
3293 c = PerlSIO_fgetc(stdio);
3297 #if (defined(STDIO_PTR_LVALUE) && (defined(STDIO_CNT_LVALUE) || defined(STDIO_PTR_LVAL_SETS_CNT)))
3299 #ifdef STDIO_BUFFER_WRITABLE
3300 if (PerlIO_fast_gets(f) && PerlIO_has_base(f)) {
3301 /* Fake ungetc() to the real buffer in case system's ungetc
3304 STDCHAR *base = (STDCHAR*)PerlSIO_get_base(stdio);
3305 SSize_t cnt = PerlSIO_get_cnt(stdio);
3306 STDCHAR *ptr = (STDCHAR*)PerlSIO_get_ptr(stdio);
3307 if (ptr == base+1) {
3308 *--ptr = (STDCHAR) c;
3309 PerlIOStdio_set_ptrcnt(aTHX_ f,ptr,cnt+1);
3310 if (PerlSIO_feof(stdio))
3311 PerlSIO_clearerr(stdio);
3317 if (PerlIO_has_cntptr(f)) {
3319 if (PerlIOStdio_unread(aTHX_ f,&ch,1) == 1) {
3326 /* An ungetc()d char is handled separately from the regular
3327 * buffer, so we stuff it in the buffer ourselves.
3328 * Should never get called as should hit code above
3330 *(--((*stdio)->_ptr)) = (unsigned char) c;
3333 /* If buffer snoop scheme above fails fall back to
3336 if (PerlSIO_ungetc(c, stdio) != c)
3344 PERLIO_FUNCS_DECL(PerlIO_stdio) = {
3345 sizeof(PerlIO_funcs),
3347 sizeof(PerlIOStdio),
3348 PERLIO_K_BUFFERED|PERLIO_K_RAW,
3352 PerlIOBase_binmode, /* binmode */
3366 PerlIOStdio_clearerr,
3367 PerlIOStdio_setlinebuf,
3369 PerlIOStdio_get_base,
3370 PerlIOStdio_get_bufsiz,
3375 #ifdef USE_STDIO_PTR
3376 PerlIOStdio_get_ptr,
3377 PerlIOStdio_get_cnt,
3378 # if defined(HAS_FAST_STDIO) && defined(USE_FAST_STDIO)
3379 PerlIOStdio_set_ptrcnt,
3382 # endif /* HAS_FAST_STDIO && USE_FAST_STDIO */
3387 #endif /* USE_STDIO_PTR */
3390 /* Note that calls to PerlIO_exportFILE() are reversed using
3391 * PerlIO_releaseFILE(), not importFILE. */
3393 PerlIO_exportFILE(PerlIO * f, const char *mode)
3397 if (PerlIOValid(f)) {
3400 if (!mode || !*mode) {
3401 mode = PerlIO_modestr(f, buf);
3403 stdio = PerlSIO_fdopen(PerlIO_fileno(f), mode);
3407 /* De-link any lower layers so new :stdio sticks */
3409 if ((f2 = PerlIO_push(aTHX_ f, PERLIO_FUNCS_CAST(&PerlIO_stdio), buf, Nullsv))) {
3410 PerlIOStdio *s = PerlIOSelf((f = f2), PerlIOStdio);
3412 /* Link previous lower layers under new one */
3416 /* restore layers list */
3426 PerlIO_findFILE(PerlIO *f)
3430 if (l->tab == &PerlIO_stdio) {
3431 PerlIOStdio *s = PerlIOSelf(&l, PerlIOStdio);
3434 l = *PerlIONext(&l);
3436 /* Uses fallback "mode" via PerlIO_modestr() in PerlIO_exportFILE */
3437 return PerlIO_exportFILE(f, Nullch);
3440 /* Use this to reverse PerlIO_exportFILE calls. */
3442 PerlIO_releaseFILE(PerlIO *p, FILE *f)
3447 if (l->tab == &PerlIO_stdio) {
3448 PerlIOStdio *s = PerlIOSelf(&l, PerlIOStdio);
3449 if (s->stdio == f) {
3451 PerlIO_pop(aTHX_ p);
3460 /*--------------------------------------------------------------------------------------*/
3462 * perlio buffer layer
3466 PerlIOBuf_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
3468 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3469 const int fd = PerlIO_fileno(f);
3470 if (fd >= 0 && PerlLIO_isatty(fd)) {
3471 PerlIOBase(f)->flags |= PERLIO_F_LINEBUF | PERLIO_F_TTY;
3473 if (*PerlIONext(f)) {
3474 const Off_t posn = PerlIO_tell(PerlIONext(f));
3475 if (posn != (Off_t) - 1) {
3479 return PerlIOBase_pushed(aTHX_ f, mode, arg, tab);
3483 PerlIOBuf_open(pTHX_ PerlIO_funcs *self, PerlIO_list_t *layers,
3484 IV n, const char *mode, int fd, int imode, int perm,
3485 PerlIO *f, int narg, SV **args)
3487 if (PerlIOValid(f)) {
3488 PerlIO *next = PerlIONext(f);
3490 PerlIO_layer_fetch(aTHX_ layers, n - 1, PerlIOBase(next)->tab);
3491 if (tab && tab->Open)
3493 (*tab->Open)(aTHX_ tab, layers, n - 1, mode, fd, imode, perm,
3495 if (!next || (*PerlIOBase(f)->tab->Pushed) (aTHX_ f, mode, PerlIOArg, self) != 0) {
3500 PerlIO_funcs *tab = PerlIO_layer_fetch(aTHX_ layers, n - 1, PerlIO_default_btm());
3502 if (*mode == IoTYPE_IMPLICIT) {
3508 if (tab && tab->Open)
3509 f = (*tab->Open)(aTHX_ tab, layers, n - 1, mode, fd, imode, perm,
3512 SETERRNO(EINVAL, LIB_INVARG);
3514 if (PerlIO_push(aTHX_ f, self, mode, PerlIOArg) == 0) {
3516 * if push fails during open, open fails. close will pop us.
3521 fd = PerlIO_fileno(f);
3522 if (init && fd == 2) {
3524 * Initial stderr is unbuffered
3526 PerlIOBase(f)->flags |= PERLIO_F_UNBUF;
3528 #ifdef PERLIO_USING_CRLF
3529 # ifdef PERLIO_IS_BINMODE_FD
3530 if (PERLIO_IS_BINMODE_FD(fd))
3531 PerlIO_binmode(aTHX_ f, '<'/*not used*/, O_BINARY, Nullch);
3535 * do something about failing setmode()? --jhi
3537 PerlLIO_setmode(fd, O_BINARY);
3546 * This "flush" is akin to sfio's sync in that it handles files in either
3547 * read or write state. For write state, we put the postponed data through
3548 * the next layers. For read state, we seek() the next layers to the
3549 * offset given by current position in the buffer, and discard the buffer
3550 * state (XXXX supposed to be for seek()able buffers only, but now it is done
3551 * in any case?). Then the pass the stick further in chain.
3554 PerlIOBuf_flush(pTHX_ PerlIO *f)
3556 PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
3558 PerlIO *n = PerlIONext(f);
3559 if (PerlIOBase(f)->flags & PERLIO_F_WRBUF) {
3561 * write() the buffer
3563 const STDCHAR *buf = b->buf;
3564 const STDCHAR *p = buf;
3565 while (p < b->ptr) {
3566 SSize_t count = PerlIO_write(n, p, b->ptr - p);
3570 else if (count < 0 || PerlIO_error(n)) {
3571 PerlIOBase(f)->flags |= PERLIO_F_ERROR;
3576 b->posn += (p - buf);
3578 else if (PerlIOBase(f)->flags & PERLIO_F_RDBUF) {
3579 STDCHAR *buf = PerlIO_get_base(f);
3581 * Note position change
3583 b->posn += (b->ptr - buf);
3584 if (b->ptr < b->end) {
3585 /* We did not consume all of it - try and seek downstream to
3586 our logical position
3588 if (PerlIOValid(n) && PerlIO_seek(n, b->posn, SEEK_SET) == 0) {
3589 /* Reload n as some layers may pop themselves on seek */
3590 b->posn = PerlIO_tell(n = PerlIONext(f));
3593 /* Seek failed (e.g. pipe or tty). Do NOT clear buffer or pre-read
3594 data is lost for good - so return saying "ok" having undone
3597 b->posn -= (b->ptr - buf);
3602 b->ptr = b->end = b->buf;
3603 PerlIOBase(f)->flags &= ~(PERLIO_F_RDBUF | PERLIO_F_WRBUF);
3604 /* We check for Valid because of dubious decision to make PerlIO_flush(NULL) flush all */
3605 if (PerlIOValid(n) && PerlIO_flush(n) != 0)
3610 /* This discards the content of the buffer after b->ptr, and rereads
3611 * the buffer from the position off in the layer downstream; here off
3612 * is at offset corresponding to b->ptr - b->buf.
3615 PerlIOBuf_fill(pTHX_ PerlIO *f)
3617 PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
3618 PerlIO *n = PerlIONext(f);
3621 * Down-stream flush is defined not to loose read data so is harmless.
3622 * we would not normally be fill'ing if there was data left in anycase.
3624 if (PerlIO_flush(f) != 0) /* XXXX Check that its seek() succeeded?! */
3626 if (PerlIOBase(f)->flags & PERLIO_F_TTY)
3627 PerlIOBase_flush_linebuf(aTHX);
3630 PerlIO_get_base(f); /* allocate via vtable */
3632 b->ptr = b->end = b->buf;
3634 if (!PerlIOValid(n)) {
3635 PerlIOBase(f)->flags |= PERLIO_F_EOF;
3639 if (PerlIO_fast_gets(n)) {
3641 * Layer below is also buffered. We do _NOT_ want to call its
3642 * ->Read() because that will loop till it gets what we asked for
3643 * which may hang on a pipe etc. Instead take anything it has to
3644 * hand, or ask it to fill _once_.
3646 avail = PerlIO_get_cnt(n);
3648 avail = PerlIO_fill(n);
3650 avail = PerlIO_get_cnt(n);
3652 if (!PerlIO_error(n) && PerlIO_eof(n))
3657 STDCHAR *ptr = PerlIO_get_ptr(n);
3658 const SSize_t cnt = avail;
3659 if (avail > (SSize_t)b->bufsiz)
3661 Copy(ptr, b->buf, avail, STDCHAR);
3662 PerlIO_set_ptrcnt(n, ptr + avail, cnt - avail);
3666 avail = PerlIO_read(n, b->ptr, b->bufsiz);
3670 PerlIOBase(f)->flags |= PERLIO_F_EOF;
3672 PerlIOBase(f)->flags |= PERLIO_F_ERROR;
3675 b->end = b->buf + avail;
3676 PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
3681 PerlIOBuf_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
3683 if (PerlIOValid(f)) {
3684 const PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
3687 return PerlIOBase_read(aTHX_ f, vbuf, count);
3693 PerlIOBuf_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
3695 const STDCHAR *buf = (const STDCHAR *) vbuf + count;
3696 PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
3699 if (PerlIOBase(f)->flags & PERLIO_F_WRBUF)
3704 if (PerlIOBase(f)->flags & PERLIO_F_RDBUF) {
3706 * Buffer is already a read buffer, we can overwrite any chars
3707 * which have been read back to buffer start
3709 avail = (b->ptr - b->buf);
3713 * Buffer is idle, set it up so whole buffer is available for
3717 b->end = b->buf + avail;
3719 PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
3721 * Buffer extends _back_ from where we are now
3723 b->posn -= b->bufsiz;
3725 if (avail > (SSize_t) count) {
3727 * If we have space for more than count, just move count
3735 * In simple stdio-like ungetc() case chars will be already
3738 if (buf != b->ptr) {
3739 Copy(buf, b->ptr, avail, STDCHAR);
3743 PerlIOBase(f)->flags &= ~PERLIO_F_EOF;
3747 unread += PerlIOBase_unread(aTHX_ f, vbuf, count);
3753 PerlIOBuf_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
3755 PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
3756 const STDCHAR *buf = (const STDCHAR *) vbuf;
3757 const STDCHAR *flushptr = buf;
3761 if (!(PerlIOBase(f)->flags & PERLIO_F_CANWRITE))
3763 if (PerlIOBase(f)->flags & PERLIO_F_RDBUF) {
3764 if (PerlIO_flush(f) != 0) {
3768 if (PerlIOBase(f)->flags & PERLIO_F_LINEBUF) {
3769 flushptr = buf + count;
3770 while (flushptr > buf && *(flushptr - 1) != '\n')
3774 SSize_t avail = b->bufsiz - (b->ptr - b->buf);
3775 if ((SSize_t) count < avail)
3777 if (flushptr > buf && flushptr <= buf + avail)
3778 avail = flushptr - buf;
3779 PerlIOBase(f)->flags |= PERLIO_F_WRBUF;
3781 Copy(buf, b->ptr, avail, STDCHAR);
3786 if (buf == flushptr)
3789 if (b->ptr >= (b->buf + b->bufsiz))
3792 if (PerlIOBase(f)->flags & PERLIO_F_UNBUF)
3798 PerlIOBuf_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
3801 if ((code = PerlIO_flush(f)) == 0) {
3802 PerlIOBase(f)->flags &= ~PERLIO_F_EOF;
3803 code = PerlIO_seek(PerlIONext(f), offset, whence);
3805 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3806 b->posn = PerlIO_tell(PerlIONext(f));
3813 PerlIOBuf_tell(pTHX_ PerlIO *f)
3815 PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
3817 * b->posn is file position where b->buf was read, or will be written
3819 Off_t posn = b->posn;
3820 if ((PerlIOBase(f)->flags & PERLIO_F_APPEND) &&
3821 (PerlIOBase(f)->flags & PERLIO_F_WRBUF)) {
3823 /* As O_APPEND files are normally shared in some sense it is better
3828 /* when file is NOT shared then this is sufficient */
3829 PerlIO_seek(PerlIONext(f),0, SEEK_END);
3831 posn = b->posn = PerlIO_tell(PerlIONext(f));
3835 * If buffer is valid adjust position by amount in buffer
3837 posn += (b->ptr - b->buf);
3843 PerlIOBuf_popped(pTHX_ PerlIO *f)
3845 const IV code = PerlIOBase_popped(aTHX_ f);
3846 PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
3847 if (b->buf && b->buf != (STDCHAR *) & b->oneword) {
3850 b->ptr = b->end = b->buf = NULL;
3851 PerlIOBase(f)->flags &= ~(PERLIO_F_RDBUF | PERLIO_F_WRBUF);
3856 PerlIOBuf_close(pTHX_ PerlIO *f)
3858 const IV code = PerlIOBase_close(aTHX_ f);
3859 PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
3860 if (b->buf && b->buf != (STDCHAR *) & b->oneword) {
3863 b->ptr = b->end = b->buf = NULL;
3864 PerlIOBase(f)->flags &= ~(PERLIO_F_RDBUF | PERLIO_F_WRBUF);
3869 PerlIOBuf_get_ptr(pTHX_ PerlIO *f)
3871 const PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
3878 PerlIOBuf_get_cnt(pTHX_ PerlIO *f)
3880 const PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
3883 if (PerlIOBase(f)->flags & PERLIO_F_RDBUF)
3884 return (b->end - b->ptr);
3889 PerlIOBuf_get_base(pTHX_ PerlIO *f)
3891 PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
3895 b->buf = Newxz(b->buf,b->bufsiz, STDCHAR);
3897 b->buf = (STDCHAR *) & b->oneword;
3898 b->bufsiz = sizeof(b->oneword);
3900 b->end = b->ptr = b->buf;
3906 PerlIOBuf_bufsiz(pTHX_ PerlIO *f)
3908 const PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
3911 return (b->end - b->buf);
3915 PerlIOBuf_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, SSize_t cnt)
3917 PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
3921 if (PerlIO_get_cnt(f) != cnt || b->ptr < b->buf) {
3922 assert(PerlIO_get_cnt(f) == cnt);
3923 assert(b->ptr >= b->buf);
3925 PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
3929 PerlIOBuf_dup(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags)
3931 return PerlIOBase_dup(aTHX_ f, o, param, flags);
3936 PERLIO_FUNCS_DECL(PerlIO_perlio) = {
3937 sizeof(PerlIO_funcs),
3940 PERLIO_K_BUFFERED|PERLIO_K_RAW,
3944 PerlIOBase_binmode, /* binmode */
3958 PerlIOBase_clearerr,
3959 PerlIOBase_setlinebuf,
3964 PerlIOBuf_set_ptrcnt,
3967 /*--------------------------------------------------------------------------------------*/
3969 * Temp layer to hold unread chars when cannot do it any other way
3973 PerlIOPending_fill(pTHX_ PerlIO *f)
3976 * Should never happen
3983 PerlIOPending_close(pTHX_ PerlIO *f)
3986 * A tad tricky - flush pops us, then we close new top
3989 return PerlIO_close(f);
3993 PerlIOPending_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
3996 * A tad tricky - flush pops us, then we seek new top
3999 return PerlIO_seek(f, offset, whence);
4004 PerlIOPending_flush(pTHX_ PerlIO *f)
4006 PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
4007 if (b->buf && b->buf != (STDCHAR *) & b->oneword) {
4011 PerlIO_pop(aTHX_ f);
4016 PerlIOPending_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, SSize_t cnt)
4022 PerlIOBuf_set_ptrcnt(aTHX_ f, ptr, cnt);
4027 PerlIOPending_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
4029 const IV code = PerlIOBase_pushed(aTHX_ f, mode, arg, tab);
4030 PerlIOl * const l = PerlIOBase(f);
4032 * Our PerlIO_fast_gets must match what we are pushed on, or sv_gets()
4033 * etc. get muddled when it changes mid-string when we auto-pop.
4035 l->flags = (l->flags & ~(PERLIO_F_FASTGETS | PERLIO_F_UTF8)) |
4036 (PerlIOBase(PerlIONext(f))->
4037 flags & (PERLIO_F_FASTGETS | PERLIO_F_UTF8));
4042 PerlIOPending_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
4044 SSize_t avail = PerlIO_get_cnt(f);
4046 if ((SSize_t)count < avail)
4049 got = PerlIOBuf_read(aTHX_ f, vbuf, avail);
4050 if (got >= 0 && got < (SSize_t)count) {
4051 const SSize_t more =
4052 PerlIO_read(f, ((STDCHAR *) vbuf) + got, count - got);
4053 if (more >= 0 || got == 0)
4059 PERLIO_FUNCS_DECL(PerlIO_pending) = {
4060 sizeof(PerlIO_funcs),
4063 PERLIO_K_BUFFERED|PERLIO_K_RAW, /* not sure about RAW here */
4064 PerlIOPending_pushed,
4067 PerlIOBase_binmode, /* binmode */
4076 PerlIOPending_close,
4077 PerlIOPending_flush,
4081 PerlIOBase_clearerr,
4082 PerlIOBase_setlinebuf,
4087 PerlIOPending_set_ptrcnt,
4092 /*--------------------------------------------------------------------------------------*/
4094 * crlf - translation On read translate CR,LF to "\n" we do this by
4095 * overriding ptr/cnt entries to hand back a line at a time and keeping a
4096 * record of which nl we "lied" about. On write translate "\n" to CR,LF
4098 * c->nl points on the first byte of CR LF pair when it is temporarily
4099 * replaced by LF, or to the last CR of the buffer. In the former case
4100 * the caller thinks that the buffer ends at c->nl + 1, in the latter
4101 * that it ends at c->nl; these two cases can be distinguished by
4102 * *c->nl. c->nl is set during _getcnt() call, and unset during
4103 * _unread() and _flush() calls.
4104 * It only matters for read operations.
4108 PerlIOBuf base; /* PerlIOBuf stuff */
4109 STDCHAR *nl; /* Position of crlf we "lied" about in the
4114 PerlIOCrlf_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
4117 PerlIOBase(f)->flags |= PERLIO_F_CRLF;
4118 code = PerlIOBuf_pushed(aTHX_ f, mode, arg, tab);
4120 PerlIO_debug("PerlIOCrlf_pushed f=%p %s %s fl=%08" UVxf "\n",
4121 f, PerlIOBase(f)->tab->name, (mode) ? mode : "(Null)",
4122 PerlIOBase(f)->flags);
4125 /* Enable the first CRLF capable layer you can find, but if none
4126 * found, the one we just pushed is fine. This results in at
4127 * any given moment at most one CRLF-capable layer being enabled
4128 * in the whole layer stack. */
4129 PerlIO *g = PerlIONext(f);
4131 PerlIOl *b = PerlIOBase(g);
4132 if (b && b->tab == &PerlIO_crlf) {
4133 if (!(b->flags & PERLIO_F_CRLF))
4134 b->flags |= PERLIO_F_CRLF;
4135 PerlIO_pop(aTHX_ f);
4146 PerlIOCrlf_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
4148 PerlIOCrlf * const c = PerlIOSelf(f, PerlIOCrlf);
4149 if (c->nl) { /* XXXX Shouldn't it be done only if b->ptr > c->nl? */
4153 if (!(PerlIOBase(f)->flags & PERLIO_F_CRLF))
4154 return PerlIOBuf_unread(aTHX_ f, vbuf, count);
4156 const STDCHAR *buf = (const STDCHAR *) vbuf + count;
4157 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
4159 if (PerlIOBase(f)->flags & PERLIO_F_WRBUF)
4164 if (!(PerlIOBase(f)->flags & PERLIO_F_RDBUF)) {
4165 b->end = b->ptr = b->buf + b->bufsiz;
4166 PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
4167 b->posn -= b->bufsiz;
4169 while (count > 0 && b->ptr > b->buf) {
4170 const int ch = *--buf;
4172 if (b->ptr - 2 >= b->buf) {
4179 /* If b->ptr - 1 == b->buf, we are undoing reading 0xa */
4180 *--(b->ptr) = 0xa; /* Works even if 0xa == '\r' */
4196 /* XXXX This code assumes that buffer size >=2, but does not check it... */
4198 PerlIOCrlf_get_cnt(pTHX_ PerlIO *f)
4200 PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
4203 if (PerlIOBase(f)->flags & PERLIO_F_RDBUF) {
4204 PerlIOCrlf * const c = PerlIOSelf(f, PerlIOCrlf);
4205 if ((PerlIOBase(f)->flags & PERLIO_F_CRLF) && (!c->nl || *c->nl == 0xd)) {
4206 STDCHAR *nl = (c->nl) ? c->nl : b->ptr;
4208 while (nl < b->end && *nl != 0xd)
4210 if (nl < b->end && *nl == 0xd) {
4212 if (nl + 1 < b->end) {
4219 * Not CR,LF but just CR
4227 * Blast - found CR as last char in buffer
4232 * They may not care, defer work as long as
4236 return (nl - b->ptr);
4240 b->ptr++; /* say we have read it as far as
4241 * flush() is concerned */
4242 b->buf++; /* Leave space in front of buffer */
4243 /* Note as we have moved buf up flush's
4245 will naturally make posn point at CR
4247 b->bufsiz--; /* Buffer is thus smaller */
4248 code = PerlIO_fill(f); /* Fetch some more */
4249 b->bufsiz++; /* Restore size for next time */
4250 b->buf--; /* Point at space */
4251 b->ptr = nl = b->buf; /* Which is what we hand
4253 *nl = 0xd; /* Fill in the CR */
4255 goto test; /* fill() call worked */
4257 * CR at EOF - just fall through
4259 /* Should we clear EOF though ??? */
4264 return (((c->nl) ? (c->nl + 1) : b->end) - b->ptr);
4270 PerlIOCrlf_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, SSize_t cnt)
4272 PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
4273 PerlIOCrlf * const c = PerlIOSelf(f, PerlIOCrlf);
4279 if (ptr == b->end && *c->nl == 0xd) {
4280 /* Defered CR at end of buffer case - we lied about count */
4292 * Test code - delete when it works ...
4294 IV flags = PerlIOBase(f)->flags;
4295 STDCHAR *chk = (c->nl) ? (c->nl+1) : b->end;
4296 if (ptr+cnt == c->nl && c->nl+1 == b->end && *c->nl == 0xd) {
4297 /* Defered CR at end of buffer case - we lied about count */
4303 Perl_croak(aTHX_ "ptr wrong %p != %p fl=%08" UVxf
4304 " nl=%p e=%p for %d", ptr, chk, flags, c->nl,
4312 * They have taken what we lied about
4320 PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
4324 PerlIOCrlf_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
4326 if (!(PerlIOBase(f)->flags & PERLIO_F_CRLF))
4327 return PerlIOBuf_write(aTHX_ f, vbuf, count);
4329 PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
4330 const STDCHAR *buf = (const STDCHAR *) vbuf;
4331 const STDCHAR * const ebuf = buf + count;
4334 if (!(PerlIOBase(f)->flags & PERLIO_F_CANWRITE))
4336 while (buf < ebuf) {
4337 const STDCHAR * const eptr = b->buf + b->bufsiz;
4338 PerlIOBase(f)->flags |= PERLIO_F_WRBUF;
4339 while (buf < ebuf && b->ptr < eptr) {
4341 if ((b->ptr + 2) > eptr) {
4349 *(b->ptr)++ = 0xd; /* CR */
4350 *(b->ptr)++ = 0xa; /* LF */
4352 if (PerlIOBase(f)->flags & PERLIO_F_LINEBUF) {
4359 *(b->ptr)++ = *buf++;
4361 if (b->ptr >= eptr) {
4367 if (PerlIOBase(f)->flags & PERLIO_F_UNBUF)
4369 return (buf - (STDCHAR *) vbuf);
4374 PerlIOCrlf_flush(pTHX_ PerlIO *f)
4376 PerlIOCrlf * const c = PerlIOSelf(f, PerlIOCrlf);
4381 return PerlIOBuf_flush(aTHX_ f);
4385 PerlIOCrlf_binmode(pTHX_ PerlIO *f)
4387 if ((PerlIOBase(f)->flags & PERLIO_F_CRLF)) {
4388 /* In text mode - flush any pending stuff and flip it */
4389 PerlIOBase(f)->flags &= ~PERLIO_F_CRLF;
4390 #ifndef PERLIO_USING_CRLF
4391 /* CRLF is unusual case - if this is just the :crlf layer pop it */
4392 if (PerlIOBase(f)->tab == &PerlIO_crlf) {
4393 PerlIO_pop(aTHX_ f);
4400 PERLIO_FUNCS_DECL(PerlIO_crlf) = {
4401 sizeof(PerlIO_funcs),
4404 PERLIO_K_BUFFERED | PERLIO_K_CANCRLF | PERLIO_K_RAW,
4406 PerlIOBuf_popped, /* popped */
4408 PerlIOCrlf_binmode, /* binmode */
4412 PerlIOBuf_read, /* generic read works with ptr/cnt lies */
4413 PerlIOCrlf_unread, /* Put CR,LF in buffer for each '\n' */
4414 PerlIOCrlf_write, /* Put CR,LF in buffer for each '\n' */
4422 PerlIOBase_clearerr,
4423 PerlIOBase_setlinebuf,
4428 PerlIOCrlf_set_ptrcnt,
4432 /*--------------------------------------------------------------------------------------*/
4434 * mmap as "buffer" layer
4438 PerlIOBuf base; /* PerlIOBuf stuff */
4439 Mmap_t mptr; /* Mapped address */
4440 Size_t len; /* mapped length */
4441 STDCHAR *bbuf; /* malloced buffer if map fails */
4445 PerlIOMmap_map(pTHX_ PerlIO *f)
4448 PerlIOMmap * const m = PerlIOSelf(f, PerlIOMmap);
4449 const IV flags = PerlIOBase(f)->flags;
4453 if (flags & PERLIO_F_CANREAD) {
4454 PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
4455 const int fd = PerlIO_fileno(f);
4457 code = Fstat(fd, &st);
4458 if (code == 0 && S_ISREG(st.st_mode)) {
4459 SSize_t len = st.st_size - b->posn;
4462 if (PL_mmap_page_size <= 0)
4463 Perl_croak(aTHX_ "panic: bad pagesize %" IVdf,
4467 * This is a hack - should never happen - open should
4470 b->posn = PerlIO_tell(PerlIONext(f));
4472 posn = (b->posn / PL_mmap_page_size) * PL_mmap_page_size;
4473 len = st.st_size - posn;
4474 m->mptr = mmap(NULL, len, PROT_READ, MAP_SHARED, fd, posn);
4475 if (m->mptr && m->mptr != (Mmap_t) - 1) {
4476 #if 0 && defined(HAS_MADVISE) && defined(MADV_SEQUENTIAL)
4477 madvise(m->mptr, len, MADV_SEQUENTIAL);
4479 #if 0 && defined(HAS_MADVISE) && defined(MADV_WILLNEED)
4480 madvise(m->mptr, len, MADV_WILLNEED);
4482 PerlIOBase(f)->flags =
4483 (flags & ~PERLIO_F_EOF) | PERLIO_F_RDBUF;
4484 b->end = ((STDCHAR *) m->mptr) + len;
4485 b->buf = ((STDCHAR *) m->mptr) + (b->posn - posn);
4494 PerlIOBase(f)->flags =
4495 flags | PERLIO_F_EOF | PERLIO_F_RDBUF;
4497 b->ptr = b->end = b->ptr;
4506 PerlIOMmap_unmap(pTHX_ PerlIO *f)
4508 PerlIOMmap * const m = PerlIOSelf(f, PerlIOMmap);
4511 PerlIOBuf * const b = &m->base;
4513 code = munmap(m->mptr, m->len);
4517 if (PerlIO_seek(PerlIONext(f), b->posn, SEEK_SET) != 0)
4520 b->ptr = b->end = b->buf;
4521 PerlIOBase(f)->flags &= ~(PERLIO_F_RDBUF | PERLIO_F_WRBUF);
4527 PerlIOMmap_get_base(pTHX_ PerlIO *f)
4529 PerlIOMmap * const m = PerlIOSelf(f, PerlIOMmap);
4530 PerlIOBuf * const b = &m->base;
4531 if (b->buf && (PerlIOBase(f)->flags & PERLIO_F_RDBUF)) {
4533 * Already have a readbuffer in progress
4539 * We have a write buffer or flushed PerlIOBuf read buffer
4541 m->bbuf = b->buf; /* save it in case we need it again */
4542 b->buf = NULL; /* Clear to trigger below */
4545 PerlIOMmap_map(aTHX_ f); /* Try and map it */
4548 * Map did not work - recover PerlIOBuf buffer if we have one
4553 b->ptr = b->end = b->buf;
4556 return PerlIOBuf_get_base(aTHX_ f);
4560 PerlIOMmap_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
4562 PerlIOMmap * const m = PerlIOSelf(f, PerlIOMmap);
4563 PerlIOBuf * const b = &m->base;
4564 if (PerlIOBase(f)->flags & PERLIO_F_WRBUF)
4566 if (b->ptr && (b->ptr - count) >= b->buf
4567 && memEQ(b->ptr - count, vbuf, count)) {
4569 PerlIOBase(f)->flags &= ~PERLIO_F_EOF;
4574 * Loose the unwritable mapped buffer
4578 * If flush took the "buffer" see if we have one from before
4580 if (!b->buf && m->bbuf)
4583 PerlIOBuf_get_base(aTHX_ f);
4587 return PerlIOBuf_unread(aTHX_ f, vbuf, count);
4591 PerlIOMmap_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
4593 PerlIOMmap * const m = PerlIOSelf(f, PerlIOMmap);
4594 PerlIOBuf * const b = &m->base;
4596 if (!b->buf || !(PerlIOBase(f)->flags & PERLIO_F_WRBUF)) {
4598 * No, or wrong sort of, buffer
4601 if (PerlIOMmap_unmap(aTHX_ f) != 0)
4605 * If unmap took the "buffer" see if we have one from before
4607 if (!b->buf && m->bbuf)
4610 PerlIOBuf_get_base(aTHX_ f);
4614 return PerlIOBuf_write(aTHX_ f, vbuf, count);
4618 PerlIOMmap_flush(pTHX_ PerlIO *f)
4620 PerlIOMmap * const m = PerlIOSelf(f, PerlIOMmap);
4621 PerlIOBuf * const b = &m->base;
4622 IV code = PerlIOBuf_flush(aTHX_ f);
4624 * Now we are "synced" at PerlIOBuf level
4631 if (PerlIOMmap_unmap(aTHX_ f) != 0)
4636 * We seem to have a PerlIOBuf buffer which was not mapped
4637 * remember it in case we need one later
4646 PerlIOMmap_fill(pTHX_ PerlIO *f)
4648 PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
4649 IV code = PerlIO_flush(f);
4650 if (code == 0 && !b->buf) {
4651 code = PerlIOMmap_map(aTHX_ f);
4653 if (code == 0 && !(PerlIOBase(f)->flags & PERLIO_F_RDBUF)) {
4654 code = PerlIOBuf_fill(aTHX_ f);
4660 PerlIOMmap_close(pTHX_ PerlIO *f)
4662 PerlIOMmap * const m = PerlIOSelf(f, PerlIOMmap);
4663 PerlIOBuf * const b = &m->base;
4664 IV code = PerlIO_flush(f);
4668 b->ptr = b->end = b->buf;
4670 if (PerlIOBuf_close(aTHX_ f) != 0)
4676 PerlIOMmap_dup(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags)
4678 return PerlIOBase_dup(aTHX_ f, o, param, flags);
4682 PERLIO_FUNCS_DECL(PerlIO_mmap) = {
4683 sizeof(PerlIO_funcs),
4686 PERLIO_K_BUFFERED|PERLIO_K_RAW,
4690 PerlIOBase_binmode, /* binmode */
4704 PerlIOBase_clearerr,
4705 PerlIOBase_setlinebuf,
4706 PerlIOMmap_get_base,
4710 PerlIOBuf_set_ptrcnt,
4713 #endif /* HAS_MMAP */
4716 Perl_PerlIO_stdin(pTHX)
4719 PerlIO_stdstreams(aTHX);
4721 return &PL_perlio[1];
4725 Perl_PerlIO_stdout(pTHX)
4728 PerlIO_stdstreams(aTHX);
4730 return &PL_perlio[2];
4734 Perl_PerlIO_stderr(pTHX)
4737 PerlIO_stdstreams(aTHX);
4739 return &PL_perlio[3];
4742 /*--------------------------------------------------------------------------------------*/
4745 PerlIO_getname(PerlIO *f, char *buf)
4750 bool exported = FALSE;
4751 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
4753 stdio = PerlIO_exportFILE(f,0);
4757 name = fgetname(stdio, buf);
4758 if (exported) PerlIO_releaseFILE(f,stdio);
4763 PERL_UNUSED_ARG(buf);
4764 Perl_croak(aTHX_ "Don't know how to get file name");
4770 /*--------------------------------------------------------------------------------------*/
4772 * Functions which can be called on any kind of PerlIO implemented in
4776 #undef PerlIO_fdopen
4778 PerlIO_fdopen(int fd, const char *mode)
4781 return PerlIO_openn(aTHX_ Nullch, mode, fd, 0, 0, NULL, 0, NULL);
4786 PerlIO_open(const char *path, const char *mode)
4789 SV *name = sv_2mortal(newSVpv(path, 0));
4790 return PerlIO_openn(aTHX_ Nullch, mode, -1, 0, 0, NULL, 1, &name);
4793 #undef Perlio_reopen
4795 PerlIO_reopen(const char *path, const char *mode, PerlIO *f)
4798 SV *name = sv_2mortal(newSVpv(path,0));
4799 return PerlIO_openn(aTHX_ Nullch, mode, -1, 0, 0, f, 1, &name);
4804 PerlIO_getc(PerlIO *f)
4808 if ( 1 == PerlIO_read(f, buf, 1) ) {
4809 return (unsigned char) buf[0];
4814 #undef PerlIO_ungetc
4816 PerlIO_ungetc(PerlIO *f, int ch)
4821 if (PerlIO_unread(f, &buf, 1) == 1)
4829 PerlIO_putc(PerlIO *f, int ch)
4833 return PerlIO_write(f, &buf, 1);
4838 PerlIO_puts(PerlIO *f, const char *s)
4841 return PerlIO_write(f, s, strlen(s));
4844 #undef PerlIO_rewind
4846 PerlIO_rewind(PerlIO *f)
4849 PerlIO_seek(f, (Off_t) 0, SEEK_SET);
4853 #undef PerlIO_vprintf
4855 PerlIO_vprintf(PerlIO *f, const char *fmt, va_list ap)
4858 SV * const sv = newSVpvn("", 0);
4864 Perl_va_copy(ap, apc);
4865 sv_vcatpvf(sv, fmt, &apc);
4867 sv_vcatpvf(sv, fmt, &ap);
4869 s = SvPV_const(sv, len);
4870 wrote = PerlIO_write(f, s, len);
4875 #undef PerlIO_printf
4877 PerlIO_printf(PerlIO *f, const char *fmt, ...)
4882 result = PerlIO_vprintf(f, fmt, ap);
4887 #undef PerlIO_stdoutf
4889 PerlIO_stdoutf(const char *fmt, ...)
4895 result = PerlIO_vprintf(PerlIO_stdout(), fmt, ap);
4900 #undef PerlIO_tmpfile
4902 PerlIO_tmpfile(void)
4907 const int fd = win32_tmpfd();
4909 f = PerlIO_fdopen(fd, "w+b");
4911 # if defined(HAS_MKSTEMP) && ! defined(VMS) && ! defined(OS2)
4912 SV * const sv = newSVpv("/tmp/PerlIO_XXXXXX", 0);
4914 * I have no idea how portable mkstemp() is ...