3 * Copyright (c) 1996-2006, Nick Ing-Simmons
4 * Copyright (c) 2006, 2007, 2008, 2009, 2010, 2011 Larry Wall and others
6 * You may distribute under the terms of either the GNU General Public License
7 * or the Artistic License, as specified in the README file.
11 * Hour after hour for nearly three weary days he had jogged up and down,
12 * over passes, and through long dales, and across many streams.
14 * [pp.791-792 of _The Lord of the Rings_, V/iii: "The Muster of Rohan"]
17 /* This file contains the functions needed to implement PerlIO, which
18 * is Perl's private replacement for the C stdio library. This is used
19 * by default unless you compile with -Uuseperlio or run with
20 * PERLIO=:stdio (but don't do this unless you know what you're doing)
24 * If we have ActivePerl-like PERL_IMPLICIT_SYS then we need a dTHX to get
25 * at the dispatch tables, even when we do not need it for other reasons.
26 * Invent a dSYS macro to abstract this out
28 #ifdef PERL_IMPLICIT_SYS
34 #define PERLIO_NOT_STDIO 0
36 * This file provides those parts of PerlIO abstraction
37 * which are not #defined in perlio.h.
38 * Which these are depends on various Configure #ifdef's
42 #define PERL_IN_PERLIO_C
45 #ifdef PERL_IMPLICIT_CONTEXT
53 /* Missing proto on LynxOS */
61 #define PerlIO_lockcnt(f) (((PerlIOl*)(f))->head->flags)
63 /* Call the callback or PerlIOBase, and return failure. */
64 #define Perl_PerlIO_or_Base(f, callback, base, failure, args) \
65 if (PerlIOValid(f)) { \
66 const PerlIO_funcs * const tab = PerlIOBase(f)->tab;\
67 if (tab && tab->callback) \
68 return (*tab->callback) args; \
70 return PerlIOBase_ ## base args; \
73 SETERRNO(EBADF, SS_IVCHAN); \
76 /* Call the callback or fail, and return failure. */
77 #define Perl_PerlIO_or_fail(f, callback, failure, args) \
78 if (PerlIOValid(f)) { \
79 const PerlIO_funcs * const tab = PerlIOBase(f)->tab;\
80 if (tab && tab->callback) \
81 return (*tab->callback) args; \
82 SETERRNO(EINVAL, LIB_INVARG); \
85 SETERRNO(EBADF, SS_IVCHAN); \
88 /* Call the callback or PerlIOBase, and be void. */
89 #define Perl_PerlIO_or_Base_void(f, callback, base, args) \
90 if (PerlIOValid(f)) { \
91 const PerlIO_funcs * const tab = PerlIOBase(f)->tab;\
92 if (tab && tab->callback) \
93 (*tab->callback) args; \
95 PerlIOBase_ ## base args; \
98 SETERRNO(EBADF, SS_IVCHAN)
100 /* Call the callback or fail, and be void. */
101 #define Perl_PerlIO_or_fail_void(f, callback, args) \
102 if (PerlIOValid(f)) { \
103 const PerlIO_funcs * const tab = PerlIOBase(f)->tab;\
104 if (tab && tab->callback) \
105 (*tab->callback) args; \
107 SETERRNO(EINVAL, LIB_INVARG); \
110 SETERRNO(EBADF, SS_IVCHAN)
112 #if defined(__osf__) && _XOPEN_SOURCE < 500
113 extern int fseeko(FILE *, off_t, int);
114 extern off_t ftello(FILE *);
117 #define NATIVE_0xd CR_NATIVE
118 #define NATIVE_0xa LF_NATIVE
122 EXTERN_C int perlsio_binmode(FILE *fp, int iotype, int mode);
125 perlsio_binmode(FILE *fp, int iotype, int mode)
128 * This used to be contents of do_binmode in doio.c
132 PERL_UNUSED_ARG(iotype);
134 if (PerlLIO_setmode(fp, mode) != -1) {
136 if (PerlLIO_setmode(fileno(fp), mode) != -1) {
143 # if defined(USEMYBINMODE)
145 # if defined(__CYGWIN__)
146 PERL_UNUSED_ARG(iotype);
148 if (my_binmode(fp, iotype, mode) != FALSE)
154 PERL_UNUSED_ARG(iotype);
155 PERL_UNUSED_ARG(mode);
163 #define O_ACCMODE 3 /* Assume traditional implementation */
167 PerlIO_intmode2str(int rawmode, char *mode, int *writing)
169 const int result = rawmode & O_ACCMODE;
174 ptype = IoTYPE_RDONLY;
177 ptype = IoTYPE_WRONLY;
185 *writing = (result != O_RDONLY);
187 if (result == O_RDONLY) {
191 else if (rawmode & O_APPEND) {
193 if (result != O_WRONLY)
198 if (result == O_WRONLY)
205 if (rawmode & O_BINARY)
211 #ifndef PERLIO_LAYERS
213 PerlIO_apply_layers(pTHX_ PerlIO *f, const char *mode, const char *names)
215 if (!names || !*names
216 || strEQ(names, ":crlf")
217 || strEQ(names, ":raw")
218 || strEQ(names, ":bytes")
222 Perl_croak(aTHX_ "Cannot apply \"%s\" in non-PerlIO perl", names);
230 PerlIO_destruct(pTHX)
235 PerlIO_binmode(pTHX_ PerlIO *fp, int iotype, int mode, const char *names)
238 PERL_UNUSED_ARG(iotype);
239 PERL_UNUSED_ARG(mode);
240 PERL_UNUSED_ARG(names);
243 return perlsio_binmode(fp, iotype, mode);
248 PerlIO_fdupopen(pTHX_ PerlIO *f, CLONE_PARAMS *param, int flags)
250 #if defined(PERL_MICRO) || defined(__SYMBIAN32__)
253 #ifdef PERL_IMPLICIT_SYS
254 return PerlSIO_fdupopen(f);
257 return win32_fdupopen(f);
260 const int fd = PerlLIO_dup(PerlIO_fileno(f));
264 const int omode = djgpp_get_stream_mode(f);
266 const int omode = fcntl(fd, F_GETFL);
268 PerlIO_intmode2str(omode,mode,NULL);
269 /* the r+ is a hack */
270 return PerlIO_fdopen(fd, mode);
275 SETERRNO(EBADF, SS_IVCHAN);
285 * De-mux PerlIO_openn() into fdopen, freopen and fopen type entries
289 PerlIO_openn(pTHX_ const char *layers, const char *mode, int fd,
290 int imode, int perm, PerlIO *old, int narg, SV **args)
294 Perl_croak(aTHX_ "More than one argument to open");
296 if (*args == &PL_sv_undef)
297 return PerlIO_tmpfile();
300 const char *name = SvPV_const(*args, len);
301 if (!IS_SAFE_PATHNAME(name, len, "open"))
304 if (*mode == IoTYPE_NUMERIC) {
305 fd = PerlLIO_open3(name, imode, perm);
307 return PerlIO_fdopen(fd, mode + 1);
310 return PerlIO_reopen(name, mode, old);
313 return PerlIO_open(name, mode);
318 return PerlIO_fdopen(fd, (char *) mode);
323 XS(XS_PerlIO__Layer__find)
327 Perl_croak(aTHX_ "Usage class->find(name[,load])");
329 const char * const name = SvPV_nolen_const(ST(1));
330 ST(0) = (strEQ(name, "crlf")
331 || strEQ(name, "raw")) ? &PL_sv_yes : &PL_sv_undef;
338 Perl_boot_core_PerlIO(pTHX)
340 newXS("PerlIO::Layer::find", XS_PerlIO__Layer__find, __FILE__);
346 #ifdef PERLIO_IS_STDIO
353 * Does nothing (yet) except force this file to be included in perl
354 * binary. That allows this file to force inclusion of other functions
355 * that may be required by loadable extensions e.g. for
356 * FileHandle::tmpfile
360 #undef PerlIO_tmpfile
367 #else /* PERLIO_IS_STDIO */
375 * This section is just to make sure these functions get pulled in from
379 #undef PerlIO_tmpfile
391 * Force this file to be included in perl binary. Which allows this
392 * file to force inclusion of other functions that may be required by
393 * loadable extensions e.g. for FileHandle::tmpfile
397 * Hack sfio does its own 'autoflush' on stdout in common cases. Flush
398 * results in a lot of lseek()s to regular files and lot of small
401 sfset(sfstdout, SF_SHARE, 0);
404 /* This is not the reverse of PerlIO_exportFILE(), PerlIO_releaseFILE() is. */
406 PerlIO_importFILE(FILE *stdio, const char *mode)
408 const int fd = fileno(stdio);
409 if (!mode || !*mode) {
412 return PerlIO_fdopen(fd, mode);
416 PerlIO_findFILE(PerlIO *pio)
418 const int fd = PerlIO_fileno(pio);
419 FILE * const f = fdopen(fd, "r+");
421 if (!f && errno == EINVAL)
423 if (!f && errno == EINVAL)
430 /*======================================================================================*/
432 * Implement all the PerlIO interface ourselves.
438 PerlIO_debug(const char *fmt, ...)
443 if (!PL_perlio_debug_fd) {
445 PerlProc_getuid() == PerlProc_geteuid() &&
446 PerlProc_getgid() == PerlProc_getegid()) {
447 const char * const s = PerlEnv_getenv("PERLIO_DEBUG");
450 = PerlLIO_open3(s, O_WRONLY | O_CREAT | O_APPEND, 0666);
452 PL_perlio_debug_fd = -1;
454 /* tainting or set*id, so ignore the environment, and ensure we
455 skip these tests next time through. */
456 PL_perlio_debug_fd = -1;
459 if (PL_perlio_debug_fd > 0) {
461 const char * const s = CopFILE(PL_curcop);
462 /* Use fixed buffer as sv_catpvf etc. needs SVs */
464 const STRLEN len1 = my_snprintf(buffer, sizeof(buffer), "%.40s:%" IVdf " ", s ? s : "(none)", (IV) CopLINE(PL_curcop));
465 const STRLEN len2 = my_vsnprintf(buffer + len1, sizeof(buffer) - len1, fmt, ap);
466 PerlLIO_write(PL_perlio_debug_fd, buffer, len1 + len2);
468 const char *s = CopFILE(PL_curcop);
470 SV * const sv = Perl_newSVpvf(aTHX_ "%s:%" IVdf " ", s ? s : "(none)",
471 (IV) CopLINE(PL_curcop));
472 Perl_sv_vcatpvf(aTHX_ sv, fmt, &ap);
474 s = SvPV_const(sv, len);
475 PerlLIO_write(PL_perlio_debug_fd, s, len);
482 /*--------------------------------------------------------------------------------------*/
485 * Inner level routines
488 /* check that the head field of each layer points back to the head */
491 # define VERIFY_HEAD(f) PerlIO_verify_head(aTHX_ f)
493 PerlIO_verify_head(pTHX_ PerlIO *f)
499 p = head = PerlIOBase(f)->head;
502 assert(p->head == head);
503 if (p == (PerlIOl*)f)
510 # define VERIFY_HEAD(f)
515 * Table of pointers to the PerlIO structs (malloc'ed)
517 #define PERLIO_TABLE_SIZE 64
520 PerlIO_init_table(pTHX)
524 Newxz(PL_perlio, PERLIO_TABLE_SIZE, PerlIOl);
530 PerlIO_allocate(pTHX)
534 * Find a free slot in the table, allocating new table as necessary
539 while ((f = *last)) {
541 last = (PerlIOl **) (f);
542 for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
543 if (!((++f)->next)) {
544 f->flags = 0; /* lockcnt */
551 Newxz(f,PERLIO_TABLE_SIZE,PerlIOl);
555 *last = (PerlIOl*) f++;
556 f->flags = 0; /* lockcnt */
562 #undef PerlIO_fdupopen
564 PerlIO_fdupopen(pTHX_ PerlIO *f, CLONE_PARAMS *param, int flags)
566 if (PerlIOValid(f)) {
567 const PerlIO_funcs * const tab = PerlIOBase(f)->tab;
568 PerlIO_debug("fdupopen f=%p param=%p\n",(void*)f,(void*)param);
570 return (*tab->Dup)(aTHX_ PerlIO_allocate(aTHX), f, param, flags);
572 return PerlIOBase_dup(aTHX_ PerlIO_allocate(aTHX), f, param, flags);
576 SETERRNO(EBADF, SS_IVCHAN);
582 PerlIO_cleantable(pTHX_ PerlIOl **tablep)
584 PerlIOl * const table = *tablep;
587 PerlIO_cleantable(aTHX_(PerlIOl **) & (table[0]));
588 for (i = PERLIO_TABLE_SIZE - 1; i > 0; i--) {
589 PerlIOl * const f = table + i;
591 PerlIO_close(&(f->next));
601 PerlIO_list_alloc(pTHX)
605 Newxz(list, 1, PerlIO_list_t);
611 PerlIO_list_free(pTHX_ PerlIO_list_t *list)
614 if (--list->refcnt == 0) {
617 for (i = 0; i < list->cur; i++)
618 SvREFCNT_dec(list->array[i].arg);
619 Safefree(list->array);
627 PerlIO_list_push(pTHX_ PerlIO_list_t *list, PerlIO_funcs *funcs, SV *arg)
633 if (list->cur >= list->len) {
636 Renew(list->array, list->len, PerlIO_pair_t);
638 Newx(list->array, list->len, PerlIO_pair_t);
640 p = &(list->array[list->cur++]);
642 if ((p->arg = arg)) {
643 SvREFCNT_inc_simple_void_NN(arg);
648 PerlIO_clone_list(pTHX_ PerlIO_list_t *proto, CLONE_PARAMS *param)
650 PerlIO_list_t *list = NULL;
653 list = PerlIO_list_alloc(aTHX);
654 for (i=0; i < proto->cur; i++) {
655 SV *arg = proto->array[i].arg;
658 arg = sv_dup(arg, param);
660 PERL_UNUSED_ARG(param);
662 PerlIO_list_push(aTHX_ list, proto->array[i].funcs, arg);
669 PerlIO_clone(pTHX_ PerlInterpreter *proto, CLONE_PARAMS *param)
672 PerlIOl **table = &proto->Iperlio;
675 PL_known_layers = PerlIO_clone_list(aTHX_ proto->Iknown_layers, param);
676 PL_def_layerlist = PerlIO_clone_list(aTHX_ proto->Idef_layerlist, param);
677 PerlIO_init_table(aTHX);
678 PerlIO_debug("Clone %p from %p\n",(void*)aTHX,(void*)proto);
679 while ((f = *table)) {
681 table = (PerlIOl **) (f++);
682 for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
684 (void) fp_dup(&(f->next), 0, param);
691 PERL_UNUSED_ARG(proto);
692 PERL_UNUSED_ARG(param);
697 PerlIO_destruct(pTHX)
700 PerlIOl **table = &PL_perlio;
703 PerlIO_debug("Destruct %p\n",(void*)aTHX);
705 while ((f = *table)) {
707 table = (PerlIOl **) (f++);
708 for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
709 PerlIO *x = &(f->next);
712 if (l->tab && l->tab->kind & PERLIO_K_DESTRUCT) {
713 PerlIO_debug("Destruct popping %s\n", l->tab->name);
727 PerlIO_pop(pTHX_ PerlIO *f)
729 const PerlIOl *l = *f;
732 PerlIO_debug("PerlIO_pop f=%p %s\n", (void*)f,
733 l->tab ? l->tab->name : "(Null)");
734 if (l->tab && l->tab->Popped) {
736 * If popped returns non-zero do not free its layer structure
737 * it has either done so itself, or it is shared and still in
740 if ((*l->tab->Popped) (aTHX_ f) != 0)
743 if (PerlIO_lockcnt(f)) {
744 /* we're in use; defer freeing the structure */
745 PerlIOBase(f)->flags = PERLIO_F_CLEARED;
746 PerlIOBase(f)->tab = NULL;
756 /* Return as an array the stack of layers on a filehandle. Note that
757 * the stack is returned top-first in the array, and there are three
758 * times as many array elements as there are layers in the stack: the
759 * first element of a layer triplet is the name, the second one is the
760 * arguments, and the third one is the flags. */
763 PerlIO_get_layers(pTHX_ PerlIO *f)
766 AV * const av = newAV();
768 if (PerlIOValid(f)) {
769 PerlIOl *l = PerlIOBase(f);
772 /* There is some collusion in the implementation of
773 XS_PerlIO_get_layers - it knows that name and flags are
774 generated as fresh SVs here, and takes advantage of that to
775 "copy" them by taking a reference. If it changes here, it needs
776 to change there too. */
777 SV * const name = l->tab && l->tab->name ?
778 newSVpv(l->tab->name, 0) : &PL_sv_undef;
779 SV * const arg = l->tab && l->tab->Getarg ?
780 (*l->tab->Getarg)(aTHX_ &l, 0, 0) : &PL_sv_undef;
783 av_push(av, newSViv((IV)l->flags));
791 /*--------------------------------------------------------------------------------------*/
793 * XS Interface for perl code
797 PerlIO_find_layer(pTHX_ const char *name, STRLEN len, int load)
801 if ((SSize_t) len <= 0)
803 for (i = 0; i < PL_known_layers->cur; i++) {
804 PerlIO_funcs * const f = PL_known_layers->array[i].funcs;
805 const STRLEN this_len = strlen(f->name);
806 if (this_len == len && memEQ(f->name, name, len)) {
807 PerlIO_debug("%.*s => %p\n", (int) len, name, (void*)f);
811 if (load && PL_subname && PL_def_layerlist
812 && PL_def_layerlist->cur >= 2) {
813 if (PL_in_load_module) {
814 Perl_croak(aTHX_ "Recursive call to Perl_load_module in PerlIO_find_layer");
817 SV * const pkgsv = newSVpvs("PerlIO");
818 SV * const layer = newSVpvn(name, len);
819 CV * const cv = get_cvs("PerlIO::Layer::NoWarnings", 0);
821 SAVEBOOL(PL_in_load_module);
823 SAVEGENERICSV(PL_warnhook);
824 PL_warnhook = MUTABLE_SV((SvREFCNT_inc_simple_NN(cv)));
826 PL_in_load_module = TRUE;
828 * The two SVs are magically freed by load_module
830 Perl_load_module(aTHX_ 0, pkgsv, NULL, layer, NULL);
832 return PerlIO_find_layer(aTHX_ name, len, 0);
835 PerlIO_debug("Cannot find %.*s\n", (int) len, name);
839 #ifdef USE_ATTRIBUTES_FOR_PERLIO
842 perlio_mg_set(pTHX_ SV *sv, MAGIC *mg)
845 IO * const io = GvIOn(MUTABLE_GV(SvRV(sv)));
846 PerlIO * const ifp = IoIFP(io);
847 PerlIO * const ofp = IoOFP(io);
848 Perl_warn(aTHX_ "set %" SVf " %p %p %p",
849 SVfARG(sv), (void*)io, (void*)ifp, (void*)ofp);
855 perlio_mg_get(pTHX_ SV *sv, MAGIC *mg)
858 IO * const io = GvIOn(MUTABLE_GV(SvRV(sv)));
859 PerlIO * const ifp = IoIFP(io);
860 PerlIO * const ofp = IoOFP(io);
861 Perl_warn(aTHX_ "get %" SVf " %p %p %p",
862 SVfARG(sv), (void*)io, (void*)ifp, (void*)ofp);
868 perlio_mg_clear(pTHX_ SV *sv, MAGIC *mg)
870 Perl_warn(aTHX_ "clear %" SVf, SVfARG(sv));
875 perlio_mg_free(pTHX_ SV *sv, MAGIC *mg)
877 Perl_warn(aTHX_ "free %" SVf, SVfARG(sv));
881 MGVTBL perlio_vtab = {
889 XS(XS_io_MODIFY_SCALAR_ATTRIBUTES)
892 SV * const sv = SvRV(ST(1));
893 AV * const av = newAV();
897 sv_magic(sv, MUTABLE_SV(av), PERL_MAGIC_ext, NULL, 0);
899 mg = mg_find(sv, PERL_MAGIC_ext);
900 mg->mg_virtual = &perlio_vtab;
902 Perl_warn(aTHX_ "attrib %" SVf, SVfARG(sv));
903 for (i = 2; i < items; i++) {
905 const char * const name = SvPV_const(ST(i), len);
906 SV * const layer = PerlIO_find_layer(aTHX_ name, len, 1);
908 av_push(av, SvREFCNT_inc_simple_NN(layer));
919 #endif /* USE_ATTIBUTES_FOR_PERLIO */
922 PerlIO_tab_sv(pTHX_ PerlIO_funcs *tab)
924 HV * const stash = gv_stashpvs("PerlIO::Layer", GV_ADD);
925 SV * const sv = sv_bless(newRV_noinc(newSViv(PTR2IV(tab))), stash);
929 XS(XS_PerlIO__Layer__NoWarnings)
931 /* This is used as a %SIG{__WARN__} handler to suppress warnings
932 during loading of layers.
938 PerlIO_debug("warning:%s\n",SvPV_nolen_const(ST(0)));
942 XS(XS_PerlIO__Layer__find)
948 Perl_croak(aTHX_ "Usage class->find(name[,load])");
951 const char * const name = SvPV_const(ST(1), len);
952 const bool load = (items > 2) ? SvTRUE(ST(2)) : 0;
953 PerlIO_funcs * const layer = PerlIO_find_layer(aTHX_ name, len, load);
955 (layer) ? sv_2mortal(PerlIO_tab_sv(aTHX_ layer)) :
962 PerlIO_define_layer(pTHX_ PerlIO_funcs *tab)
965 if (!PL_known_layers)
966 PL_known_layers = PerlIO_list_alloc(aTHX);
967 PerlIO_list_push(aTHX_ PL_known_layers, tab, NULL);
968 PerlIO_debug("define %s %p\n", tab->name, (void*)tab);
972 PerlIO_parse_layers(pTHX_ PerlIO_list_t *av, const char *names)
976 const char *s = names;
978 while (isSPACE(*s) || *s == ':')
983 const char *as = NULL;
985 if (!isIDFIRST(*s)) {
987 * Message is consistent with how attribute lists are
988 * passed. Even though this means "foo : : bar" is
989 * seen as an invalid separator character.
991 const char q = ((*s == '\'') ? '"' : '\'');
992 Perl_ck_warner(aTHX_ packWARN(WARN_LAYER),
993 "Invalid separator character %c%c%c in PerlIO layer specification %s",
995 SETERRNO(EINVAL, LIB_INVARG);
1000 } while (isWORDCHAR(*e));
1009 alen = (e - 1) - as;
1016 * It's a nul terminated string, not allowed
1017 * to \ the terminating null. Anything other
1018 * character is passed over.
1028 Perl_ck_warner(aTHX_ packWARN(WARN_LAYER),
1029 "Argument list not closed for PerlIO layer \"%.*s\"",
1041 PerlIO_funcs * const layer =
1042 PerlIO_find_layer(aTHX_ s, llen, 1);
1046 arg = newSVpvn(as, alen);
1047 PerlIO_list_push(aTHX_ av, layer,
1048 (arg) ? arg : &PL_sv_undef);
1052 Perl_ck_warner(aTHX_ packWARN(WARN_LAYER), "Unknown PerlIO layer \"%.*s\"",
1065 PerlIO_default_buffer(pTHX_ PerlIO_list_t *av)
1068 PERLIO_FUNCS_DECL(*tab) = &PerlIO_perlio;
1069 #ifdef PERLIO_USING_CRLF
1072 if (PerlIO_stdio.Set_ptrcnt)
1073 tab = &PerlIO_stdio;
1075 PerlIO_debug("Pushing %s\n", tab->name);
1076 PerlIO_list_push(aTHX_ av, PerlIO_find_layer(aTHX_ tab->name, 0, 0),
1081 PerlIO_arg_fetch(PerlIO_list_t *av, IV n)
1083 return av->array[n].arg;
1087 PerlIO_layer_fetch(pTHX_ PerlIO_list_t *av, IV n, PerlIO_funcs *def)
1089 if (n >= 0 && n < av->cur) {
1090 PerlIO_debug("Layer %" IVdf " is %s\n", n,
1091 av->array[n].funcs->name);
1092 return av->array[n].funcs;
1095 Perl_croak(aTHX_ "panic: PerlIO layer array corrupt");
1100 PerlIOPop_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
1102 PERL_UNUSED_ARG(mode);
1103 PERL_UNUSED_ARG(arg);
1104 PERL_UNUSED_ARG(tab);
1105 if (PerlIOValid(f)) {
1107 PerlIO_pop(aTHX_ f);
1113 PERLIO_FUNCS_DECL(PerlIO_remove) = {
1114 sizeof(PerlIO_funcs),
1117 PERLIO_K_DUMMY | PERLIO_K_UTF8,
1137 NULL, /* get_base */
1138 NULL, /* get_bufsiz */
1141 NULL, /* set_ptrcnt */
1145 PerlIO_default_layers(pTHX)
1148 if (!PL_def_layerlist) {
1149 const char * const s = TAINTING_get ? NULL : PerlEnv_getenv("PERLIO");
1150 PERLIO_FUNCS_DECL(*osLayer) = &PerlIO_unix;
1151 PL_def_layerlist = PerlIO_list_alloc(aTHX);
1152 PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_unix));
1154 PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_win32));
1156 osLayer = &PerlIO_win32;
1159 PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_raw));
1160 PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_perlio));
1161 PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_stdio));
1162 PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_crlf));
1163 PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_utf8));
1164 PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_remove));
1165 PerlIO_define_layer(aTHX_ PERLIO_FUNCS_CAST(&PerlIO_byte));
1166 PerlIO_list_push(aTHX_ PL_def_layerlist,
1167 PerlIO_find_layer(aTHX_ osLayer->name, 0, 0),
1170 PerlIO_parse_layers(aTHX_ PL_def_layerlist, s);
1173 PerlIO_default_buffer(aTHX_ PL_def_layerlist);
1176 if (PL_def_layerlist->cur < 2) {
1177 PerlIO_default_buffer(aTHX_ PL_def_layerlist);
1179 return PL_def_layerlist;
1183 Perl_boot_core_PerlIO(pTHX)
1185 #ifdef USE_ATTRIBUTES_FOR_PERLIO
1186 newXS("io::MODIFY_SCALAR_ATTRIBUTES", XS_io_MODIFY_SCALAR_ATTRIBUTES,
1189 newXS("PerlIO::Layer::find", XS_PerlIO__Layer__find, __FILE__);
1190 newXS("PerlIO::Layer::NoWarnings", XS_PerlIO__Layer__NoWarnings, __FILE__);
1194 PerlIO_default_layer(pTHX_ I32 n)
1197 PerlIO_list_t * const av = PerlIO_default_layers(aTHX);
1200 return PerlIO_layer_fetch(aTHX_ av, n, PERLIO_FUNCS_CAST(&PerlIO_stdio));
1203 #define PerlIO_default_top() PerlIO_default_layer(aTHX_ -1)
1204 #define PerlIO_default_btm() PerlIO_default_layer(aTHX_ 0)
1207 PerlIO_stdstreams(pTHX)
1211 PerlIO_init_table(aTHX);
1212 PerlIO_fdopen(0, "Ir" PERLIO_STDTEXT);
1213 PerlIO_fdopen(1, "Iw" PERLIO_STDTEXT);
1214 PerlIO_fdopen(2, "Iw" PERLIO_STDTEXT);
1219 PerlIO_push(pTHX_ PerlIO *f, PERLIO_FUNCS_DECL(*tab), const char *mode, SV *arg)
1222 if (tab->fsize != sizeof(PerlIO_funcs)) {
1224 "%s (%"UVuf") does not match %s (%"UVuf")",
1225 "PerlIO layer function table size", (UV)tab->fsize,
1226 "size expected by this perl", (UV)sizeof(PerlIO_funcs) );
1230 if (tab->size < sizeof(PerlIOl)) {
1232 "%s (%"UVuf") smaller than %s (%"UVuf")",
1233 "PerlIO layer instance size", (UV)tab->size,
1234 "size expected by this perl", (UV)sizeof(PerlIOl) );
1236 /* Real layer with a data area */
1239 Newxz(temp, tab->size, char);
1243 l->tab = (PerlIO_funcs*) tab;
1244 l->head = ((PerlIOl*)f)->head;
1246 PerlIO_debug("PerlIO_push f=%p %s %s %p\n",
1247 (void*)f, tab->name,
1248 (mode) ? mode : "(Null)", (void*)arg);
1249 if (*l->tab->Pushed &&
1251 (aTHX_ f, mode, arg, (PerlIO_funcs*) tab) != 0) {
1252 PerlIO_pop(aTHX_ f);
1261 /* Pseudo-layer where push does its own stack adjust */
1262 PerlIO_debug("PerlIO_push f=%p %s %s %p\n", (void*)f, tab->name,
1263 (mode) ? mode : "(Null)", (void*)arg);
1265 (*tab->Pushed) (aTHX_ f, mode, arg, (PerlIO_funcs*) tab) != 0) {
1273 PerlIOBase_open(pTHX_ PerlIO_funcs *self, PerlIO_list_t *layers,
1274 IV n, const char *mode, int fd, int imode, int perm,
1275 PerlIO *old, int narg, SV **args)
1277 PerlIO_funcs * const tab = PerlIO_layer_fetch(aTHX_ layers, n - 1, PerlIO_default_layer(aTHX_ 0));
1278 if (tab && tab->Open) {
1279 PerlIO* ret = (*tab->Open)(aTHX_ tab, layers, n - 1, mode, fd, imode, perm, old, narg, args);
1280 if (ret && PerlIO_push(aTHX_ ret, self, mode, PerlIOArg) == NULL) {
1286 SETERRNO(EINVAL, LIB_INVARG);
1291 PerlIOBase_binmode(pTHX_ PerlIO *f)
1293 if (PerlIOValid(f)) {
1294 /* Is layer suitable for raw stream ? */
1295 if (PerlIOBase(f)->tab && PerlIOBase(f)->tab->kind & PERLIO_K_RAW) {
1296 /* Yes - turn off UTF-8-ness, to undo UTF-8 locale effects */
1297 PerlIOBase(f)->flags &= ~PERLIO_F_UTF8;
1300 /* Not suitable - pop it */
1301 PerlIO_pop(aTHX_ f);
1309 PerlIORaw_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
1311 PERL_UNUSED_ARG(mode);
1312 PERL_UNUSED_ARG(arg);
1313 PERL_UNUSED_ARG(tab);
1315 if (PerlIOValid(f)) {
1320 * Strip all layers that are not suitable for a raw stream
1323 while (t && (l = *t)) {
1324 if (l->tab && l->tab->Binmode) {
1325 /* Has a handler - normal case */
1326 if ((*l->tab->Binmode)(aTHX_ t) == 0) {
1328 /* Layer still there - move down a layer */
1337 /* No handler - pop it */
1338 PerlIO_pop(aTHX_ t);
1341 if (PerlIOValid(f)) {
1342 PerlIO_debug(":raw f=%p :%s\n", (void*)f,
1343 PerlIOBase(f)->tab ? PerlIOBase(f)->tab->name : "(Null)");
1351 PerlIO_apply_layera(pTHX_ PerlIO *f, const char *mode,
1352 PerlIO_list_t *layers, IV n, IV max)
1356 PerlIO_funcs * const tab = PerlIO_layer_fetch(aTHX_ layers, n, NULL);
1358 if (!PerlIO_push(aTHX_ f, tab, mode, PerlIOArg)) {
1369 PerlIO_apply_layers(pTHX_ PerlIO *f, const char *mode, const char *names)
1373 save_scalar(PL_errgv);
1375 PerlIO_list_t * const layers = PerlIO_list_alloc(aTHX);
1376 code = PerlIO_parse_layers(aTHX_ layers, names);
1378 code = PerlIO_apply_layera(aTHX_ f, mode, layers, 0, layers->cur);
1380 PerlIO_list_free(aTHX_ layers);
1387 /*--------------------------------------------------------------------------------------*/
1389 * Given the abstraction above the public API functions
1393 PerlIO_binmode(pTHX_ PerlIO *f, int iotype, int mode, const char *names)
1395 PerlIO_debug("PerlIO_binmode f=%p %s %c %x %s\n", (void*)f,
1396 (PerlIOBase(f) && PerlIOBase(f)->tab) ?
1397 PerlIOBase(f)->tab->name : "(Null)",
1398 iotype, mode, (names) ? names : "(Null)");
1401 /* Do not flush etc. if (e.g.) switching encodings.
1402 if a pushed layer knows it needs to flush lower layers
1403 (for example :unix which is never going to call them)
1404 it can do the flush when it is pushed.
1406 return PerlIO_apply_layers(aTHX_ f, NULL, names) == 0 ? TRUE : FALSE;
1409 /* Fake 5.6 legacy of using this call to turn ON O_TEXT */
1410 #ifdef PERLIO_USING_CRLF
1411 /* Legacy binmode only has meaning if O_TEXT has a value distinct from
1412 O_BINARY so we can look for it in mode.
1414 if (!(mode & O_BINARY)) {
1416 /* FIXME?: Looking down the layer stack seems wrong,
1417 but is a way of reaching past (say) an encoding layer
1418 to flip CRLF-ness of the layer(s) below
1421 /* Perhaps we should turn on bottom-most aware layer
1422 e.g. Ilya's idea that UNIX TTY could serve
1424 if (PerlIOBase(f)->tab &&
1425 PerlIOBase(f)->tab->kind & PERLIO_K_CANCRLF)
1427 if (!(PerlIOBase(f)->flags & PERLIO_F_CRLF)) {
1428 /* Not in text mode - flush any pending stuff and flip it */
1430 PerlIOBase(f)->flags |= PERLIO_F_CRLF;
1432 /* Only need to turn it on in one layer so we are done */
1437 /* Not finding a CRLF aware layer presumably means we are binary
1438 which is not what was requested - so we failed
1439 We _could_ push :crlf layer but so could caller
1444 /* Legacy binmode is now _defined_ as being equivalent to pushing :raw
1445 So code that used to be here is now in PerlIORaw_pushed().
1447 return PerlIO_push(aTHX_ f, PERLIO_FUNCS_CAST(&PerlIO_raw), NULL, NULL) ? TRUE : FALSE;
1452 PerlIO__close(pTHX_ PerlIO *f)
1454 if (PerlIOValid(f)) {
1455 PerlIO_funcs * const tab = PerlIOBase(f)->tab;
1456 if (tab && tab->Close)
1457 return (*tab->Close)(aTHX_ f);
1459 return PerlIOBase_close(aTHX_ f);
1462 SETERRNO(EBADF, SS_IVCHAN);
1468 Perl_PerlIO_close(pTHX_ PerlIO *f)
1470 const int code = PerlIO__close(aTHX_ f);
1471 while (PerlIOValid(f)) {
1472 PerlIO_pop(aTHX_ f);
1473 if (PerlIO_lockcnt(f))
1474 /* we're in use; the 'pop' deferred freeing the structure */
1481 Perl_PerlIO_fileno(pTHX_ PerlIO *f)
1484 Perl_PerlIO_or_Base(f, Fileno, fileno, -1, (aTHX_ f));
1488 static PerlIO_funcs *
1489 PerlIO_layer_from_ref(pTHX_ SV *sv)
1493 * For any scalar type load the handler which is bundled with perl
1495 if (SvTYPE(sv) < SVt_PVAV && (!isGV_with_GP(sv) || SvFAKE(sv))) {
1496 PerlIO_funcs *f = PerlIO_find_layer(aTHX_ STR_WITH_LEN("scalar"), 1);
1497 /* This isn't supposed to happen, since PerlIO::scalar is core,
1498 * but could happen anyway in smaller installs or with PAR */
1500 /* diag_listed_as: Unknown PerlIO layer "%s" */
1501 Perl_ck_warner(aTHX_ packWARN(WARN_LAYER), "Unknown PerlIO layer \"scalar\"");
1506 * For other types allow if layer is known but don't try and load it
1508 switch (SvTYPE(sv)) {
1510 return PerlIO_find_layer(aTHX_ STR_WITH_LEN("Array"), 0);
1512 return PerlIO_find_layer(aTHX_ STR_WITH_LEN("Hash"), 0);
1514 return PerlIO_find_layer(aTHX_ STR_WITH_LEN("Code"), 0);
1516 return PerlIO_find_layer(aTHX_ STR_WITH_LEN("Glob"), 0);
1523 PerlIO_resolve_layers(pTHX_ const char *layers,
1524 const char *mode, int narg, SV **args)
1527 PerlIO_list_t *def = PerlIO_default_layers(aTHX);
1530 PerlIO_stdstreams(aTHX);
1532 SV * const arg = *args;
1534 * If it is a reference but not an object see if we have a handler
1537 if (SvROK(arg) && !sv_isobject(arg)) {
1538 PerlIO_funcs * const handler = PerlIO_layer_from_ref(aTHX_ SvRV(arg));
1540 def = PerlIO_list_alloc(aTHX);
1541 PerlIO_list_push(aTHX_ def, handler, &PL_sv_undef);
1545 * Don't fail if handler cannot be found :via(...) etc. may do
1546 * something sensible else we will just stringfy and open
1551 if (!layers || !*layers)
1552 layers = Perl_PerlIO_context_layers(aTHX_ mode);
1553 if (layers && *layers) {
1556 av = PerlIO_clone_list(aTHX_ def, NULL);
1561 if (PerlIO_parse_layers(aTHX_ av, layers) == 0) {
1565 PerlIO_list_free(aTHX_ av);
1577 PerlIO_openn(pTHX_ const char *layers, const char *mode, int fd,
1578 int imode, int perm, PerlIO *f, int narg, SV **args)
1581 if (!f && narg == 1 && *args == &PL_sv_undef) {
1582 if ((f = PerlIO_tmpfile())) {
1583 if (!layers || !*layers)
1584 layers = Perl_PerlIO_context_layers(aTHX_ mode);
1585 if (layers && *layers)
1586 PerlIO_apply_layers(aTHX_ f, mode, layers);
1590 PerlIO_list_t *layera;
1592 PerlIO_funcs *tab = NULL;
1593 if (PerlIOValid(f)) {
1595 * This is "reopen" - it is not tested as perl does not use it
1599 layera = PerlIO_list_alloc(aTHX);
1602 if (l->tab && l->tab->Getarg)
1603 arg = (*l->tab->Getarg) (aTHX_ &l, NULL, 0);
1604 PerlIO_list_push(aTHX_ layera, l->tab,
1605 (arg) ? arg : &PL_sv_undef);
1607 l = *PerlIONext(&l);
1611 layera = PerlIO_resolve_layers(aTHX_ layers, mode, narg, args);
1617 * Start at "top" of layer stack
1619 n = layera->cur - 1;
1621 PerlIO_funcs * const t = PerlIO_layer_fetch(aTHX_ layera, n, NULL);
1630 * Found that layer 'n' can do opens - call it
1632 if (narg > 1 && !(tab->kind & PERLIO_K_MULTIARG)) {
1633 Perl_croak(aTHX_ "More than one argument to open(,':%s')",tab->name);
1635 PerlIO_debug("openn(%s,'%s','%s',%d,%x,%o,%p,%d,%p)\n",
1636 tab->name, layers ? layers : "(Null)", mode, fd,
1637 imode, perm, (void*)f, narg, (void*)args);
1639 f = (*tab->Open) (aTHX_ tab, layera, n, mode, fd, imode, perm,
1642 SETERRNO(EINVAL, LIB_INVARG);
1646 if (n + 1 < layera->cur) {
1648 * More layers above the one that we used to open -
1651 if (PerlIO_apply_layera(aTHX_ f, mode, layera, n + 1, layera->cur) != 0) {
1652 /* If pushing layers fails close the file */
1659 PerlIO_list_free(aTHX_ layera);
1666 Perl_PerlIO_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
1668 PERL_ARGS_ASSERT_PERLIO_READ;
1670 Perl_PerlIO_or_Base(f, Read, read, -1, (aTHX_ f, vbuf, count));
1674 Perl_PerlIO_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
1676 PERL_ARGS_ASSERT_PERLIO_UNREAD;
1678 Perl_PerlIO_or_Base(f, Unread, unread, -1, (aTHX_ f, vbuf, count));
1682 Perl_PerlIO_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
1684 PERL_ARGS_ASSERT_PERLIO_WRITE;
1686 Perl_PerlIO_or_fail(f, Write, -1, (aTHX_ f, vbuf, count));
1690 Perl_PerlIO_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
1692 Perl_PerlIO_or_fail(f, Seek, -1, (aTHX_ f, offset, whence));
1696 Perl_PerlIO_tell(pTHX_ PerlIO *f)
1698 Perl_PerlIO_or_fail(f, Tell, -1, (aTHX_ f));
1702 Perl_PerlIO_flush(pTHX_ PerlIO *f)
1707 const PerlIO_funcs *tab = PerlIOBase(f)->tab;
1709 if (tab && tab->Flush)
1710 return (*tab->Flush) (aTHX_ f);
1712 return 0; /* If no Flush defined, silently succeed. */
1715 PerlIO_debug("Cannot flush f=%p\n", (void*)f);
1716 SETERRNO(EBADF, SS_IVCHAN);
1722 * Is it good API design to do flush-all on NULL, a potentially
1723 * erroneous input? Maybe some magical value (PerlIO*
1724 * PERLIO_FLUSH_ALL = (PerlIO*)-1;)? Yes, stdio does similar
1725 * things on fflush(NULL), but should we be bound by their design
1728 PerlIOl **table = &PL_perlio;
1731 while ((ff = *table)) {
1733 table = (PerlIOl **) (ff++);
1734 for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
1735 if (ff->next && PerlIO_flush(&(ff->next)) != 0)
1745 PerlIOBase_flush_linebuf(pTHX)
1748 PerlIOl **table = &PL_perlio;
1750 while ((f = *table)) {
1752 table = (PerlIOl **) (f++);
1753 for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
1755 && (PerlIOBase(&(f->next))->
1756 flags & (PERLIO_F_LINEBUF | PERLIO_F_CANWRITE))
1757 == (PERLIO_F_LINEBUF | PERLIO_F_CANWRITE))
1758 PerlIO_flush(&(f->next));
1765 Perl_PerlIO_fill(pTHX_ PerlIO *f)
1767 Perl_PerlIO_or_fail(f, Fill, -1, (aTHX_ f));
1771 PerlIO_isutf8(PerlIO *f)
1774 return (PerlIOBase(f)->flags & PERLIO_F_UTF8) != 0;
1776 SETERRNO(EBADF, SS_IVCHAN);
1782 Perl_PerlIO_eof(pTHX_ PerlIO *f)
1784 Perl_PerlIO_or_Base(f, Eof, eof, -1, (aTHX_ f));
1788 Perl_PerlIO_error(pTHX_ PerlIO *f)
1790 Perl_PerlIO_or_Base(f, Error, error, -1, (aTHX_ f));
1794 Perl_PerlIO_clearerr(pTHX_ PerlIO *f)
1796 Perl_PerlIO_or_Base_void(f, Clearerr, clearerr, (aTHX_ f));
1800 Perl_PerlIO_setlinebuf(pTHX_ PerlIO *f)
1802 Perl_PerlIO_or_Base_void(f, Setlinebuf, setlinebuf, (aTHX_ f));
1806 PerlIO_has_base(PerlIO *f)
1808 if (PerlIOValid(f)) {
1809 const PerlIO_funcs * const tab = PerlIOBase(f)->tab;
1812 return (tab->Get_base != NULL);
1819 PerlIO_fast_gets(PerlIO *f)
1821 if (PerlIOValid(f)) {
1822 if (PerlIOBase(f)->flags & PERLIO_F_FASTGETS) {
1823 const PerlIO_funcs * const tab = PerlIOBase(f)->tab;
1826 return (tab->Set_ptrcnt != NULL);
1834 PerlIO_has_cntptr(PerlIO *f)
1836 if (PerlIOValid(f)) {
1837 const PerlIO_funcs * const tab = PerlIOBase(f)->tab;
1840 return (tab->Get_ptr != NULL && tab->Get_cnt != NULL);
1847 PerlIO_canset_cnt(PerlIO *f)
1849 if (PerlIOValid(f)) {
1850 const PerlIO_funcs * const tab = PerlIOBase(f)->tab;
1853 return (tab->Set_ptrcnt != NULL);
1860 Perl_PerlIO_get_base(pTHX_ PerlIO *f)
1862 Perl_PerlIO_or_fail(f, Get_base, NULL, (aTHX_ f));
1866 Perl_PerlIO_get_bufsiz(pTHX_ PerlIO *f)
1868 /* Note that Get_bufsiz returns a Size_t */
1869 Perl_PerlIO_or_fail(f, Get_bufsiz, -1, (aTHX_ f));
1873 Perl_PerlIO_get_ptr(pTHX_ PerlIO *f)
1875 Perl_PerlIO_or_fail(f, Get_ptr, NULL, (aTHX_ f));
1879 Perl_PerlIO_get_cnt(pTHX_ PerlIO *f)
1881 Perl_PerlIO_or_fail(f, Get_cnt, -1, (aTHX_ f));
1885 Perl_PerlIO_set_cnt(pTHX_ PerlIO *f, SSize_t cnt)
1887 Perl_PerlIO_or_fail_void(f, Set_ptrcnt, (aTHX_ f, NULL, cnt));
1891 Perl_PerlIO_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, SSize_t cnt)
1893 Perl_PerlIO_or_fail_void(f, Set_ptrcnt, (aTHX_ f, ptr, cnt));
1897 /*--------------------------------------------------------------------------------------*/
1899 * utf8 and raw dummy layers
1903 PerlIOUtf8_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
1905 PERL_UNUSED_CONTEXT;
1906 PERL_UNUSED_ARG(mode);
1907 PERL_UNUSED_ARG(arg);
1908 if (PerlIOValid(f)) {
1909 if (tab && tab->kind & PERLIO_K_UTF8)
1910 PerlIOBase(f)->flags |= PERLIO_F_UTF8;
1912 PerlIOBase(f)->flags &= ~PERLIO_F_UTF8;
1918 PERLIO_FUNCS_DECL(PerlIO_utf8) = {
1919 sizeof(PerlIO_funcs),
1922 PERLIO_K_DUMMY | PERLIO_K_UTF8 | PERLIO_K_MULTIARG,
1942 NULL, /* get_base */
1943 NULL, /* get_bufsiz */
1946 NULL, /* set_ptrcnt */
1949 PERLIO_FUNCS_DECL(PerlIO_byte) = {
1950 sizeof(PerlIO_funcs),
1953 PERLIO_K_DUMMY | PERLIO_K_MULTIARG,
1973 NULL, /* get_base */
1974 NULL, /* get_bufsiz */
1977 NULL, /* set_ptrcnt */
1980 PERLIO_FUNCS_DECL(PerlIO_raw) = {
1981 sizeof(PerlIO_funcs),
2004 NULL, /* get_base */
2005 NULL, /* get_bufsiz */
2008 NULL, /* set_ptrcnt */
2010 /*--------------------------------------------------------------------------------------*/
2011 /*--------------------------------------------------------------------------------------*/
2013 * "Methods" of the "base class"
2017 PerlIOBase_fileno(pTHX_ PerlIO *f)
2019 return PerlIOValid(f) ? PerlIO_fileno(PerlIONext(f)) : -1;
2023 PerlIO_modestr(PerlIO * f, char *buf)
2026 if (PerlIOValid(f)) {
2027 const IV flags = PerlIOBase(f)->flags;
2028 if (flags & PERLIO_F_APPEND) {
2030 if (flags & PERLIO_F_CANREAD) {
2034 else if (flags & PERLIO_F_CANREAD) {
2036 if (flags & PERLIO_F_CANWRITE)
2039 else if (flags & PERLIO_F_CANWRITE) {
2041 if (flags & PERLIO_F_CANREAD) {
2045 #ifdef PERLIO_USING_CRLF
2046 if (!(flags & PERLIO_F_CRLF))
2056 PerlIOBase_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
2058 PerlIOl * const l = PerlIOBase(f);
2059 PERL_UNUSED_CONTEXT;
2060 PERL_UNUSED_ARG(arg);
2062 l->flags &= ~(PERLIO_F_CANREAD | PERLIO_F_CANWRITE |
2063 PERLIO_F_TRUNCATE | PERLIO_F_APPEND);
2064 if (tab && tab->Set_ptrcnt != NULL)
2065 l->flags |= PERLIO_F_FASTGETS;
2067 if (*mode == IoTYPE_NUMERIC || *mode == IoTYPE_IMPLICIT)
2071 l->flags |= PERLIO_F_CANREAD;
2074 l->flags |= PERLIO_F_APPEND | PERLIO_F_CANWRITE;
2077 l->flags |= PERLIO_F_TRUNCATE | PERLIO_F_CANWRITE;
2080 SETERRNO(EINVAL, LIB_INVARG);
2086 l->flags |= PERLIO_F_CANREAD | PERLIO_F_CANWRITE;
2089 l->flags &= ~PERLIO_F_CRLF;
2092 l->flags |= PERLIO_F_CRLF;
2095 SETERRNO(EINVAL, LIB_INVARG);
2102 l->flags |= l->next->flags &
2103 (PERLIO_F_CANREAD | PERLIO_F_CANWRITE | PERLIO_F_TRUNCATE |
2108 PerlIO_debug("PerlIOBase_pushed f=%p %s %s fl=%08" UVxf " (%s)\n",
2109 (void*)f, PerlIOBase(f)->tab->name, (omode) ? omode : "(Null)",
2110 l->flags, PerlIO_modestr(f, temp));
2116 PerlIOBase_popped(pTHX_ PerlIO *f)
2118 PERL_UNUSED_CONTEXT;
2124 PerlIOBase_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
2127 * Save the position as current head considers it
2129 const Off_t old = PerlIO_tell(f);
2130 PerlIO_push(aTHX_ f, PERLIO_FUNCS_CAST(&PerlIO_pending), "r", NULL);
2131 PerlIOSelf(f, PerlIOBuf)->posn = old;
2132 return PerlIOBuf_unread(aTHX_ f, vbuf, count);
2136 PerlIOBase_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
2138 STDCHAR *buf = (STDCHAR *) vbuf;
2140 if (!(PerlIOBase(f)->flags & PERLIO_F_CANREAD)) {
2141 PerlIOBase(f)->flags |= PERLIO_F_ERROR;
2142 SETERRNO(EBADF, SS_IVCHAN);
2148 SSize_t avail = PerlIO_get_cnt(f);
2151 take = (((SSize_t) count >= 0) && ((SSize_t)count < avail)) ? (SSize_t)count : avail;
2153 STDCHAR *ptr = PerlIO_get_ptr(f);
2154 Copy(ptr, buf, take, STDCHAR);
2155 PerlIO_set_ptrcnt(f, ptr + take, (avail -= take));
2158 if (avail == 0) /* set_ptrcnt could have reset avail */
2161 if (count > 0 && avail <= 0) {
2162 if (PerlIO_fill(f) != 0)
2167 return (buf - (STDCHAR *) vbuf);
2173 PerlIOBase_noop_ok(pTHX_ PerlIO *f)
2175 PERL_UNUSED_CONTEXT;
2181 PerlIOBase_noop_fail(pTHX_ PerlIO *f)
2183 PERL_UNUSED_CONTEXT;
2189 PerlIOBase_close(pTHX_ PerlIO *f)
2192 if (PerlIOValid(f)) {
2193 PerlIO *n = PerlIONext(f);
2194 code = PerlIO_flush(f);
2195 PerlIOBase(f)->flags &=
2196 ~(PERLIO_F_CANREAD | PERLIO_F_CANWRITE | PERLIO_F_OPEN);
2197 while (PerlIOValid(n)) {
2198 const PerlIO_funcs * const tab = PerlIOBase(n)->tab;
2199 if (tab && tab->Close) {
2200 if ((*tab->Close)(aTHX_ n) != 0)
2205 PerlIOBase(n)->flags &=
2206 ~(PERLIO_F_CANREAD | PERLIO_F_CANWRITE | PERLIO_F_OPEN);
2212 SETERRNO(EBADF, SS_IVCHAN);
2218 PerlIOBase_eof(pTHX_ PerlIO *f)
2220 PERL_UNUSED_CONTEXT;
2221 if (PerlIOValid(f)) {
2222 return (PerlIOBase(f)->flags & PERLIO_F_EOF) != 0;
2228 PerlIOBase_error(pTHX_ PerlIO *f)
2230 PERL_UNUSED_CONTEXT;
2231 if (PerlIOValid(f)) {
2232 return (PerlIOBase(f)->flags & PERLIO_F_ERROR) != 0;
2238 PerlIOBase_clearerr(pTHX_ PerlIO *f)
2240 if (PerlIOValid(f)) {
2241 PerlIO * const n = PerlIONext(f);
2242 PerlIOBase(f)->flags &= ~(PERLIO_F_ERROR | PERLIO_F_EOF);
2249 PerlIOBase_setlinebuf(pTHX_ PerlIO *f)
2251 PERL_UNUSED_CONTEXT;
2252 if (PerlIOValid(f)) {
2253 PerlIOBase(f)->flags |= PERLIO_F_LINEBUF;
2258 PerlIO_sv_dup(pTHX_ SV *arg, CLONE_PARAMS *param)
2264 arg = sv_dup(arg, param);
2265 SvREFCNT_inc_simple_void_NN(arg);
2269 return newSVsv(arg);
2272 PERL_UNUSED_ARG(param);
2273 return newSVsv(arg);
2278 PerlIOBase_dup(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags)
2280 PerlIO * const nexto = PerlIONext(o);
2281 if (PerlIOValid(nexto)) {
2282 const PerlIO_funcs * const tab = PerlIOBase(nexto)->tab;
2283 if (tab && tab->Dup)
2284 f = (*tab->Dup)(aTHX_ f, nexto, param, flags);
2286 f = PerlIOBase_dup(aTHX_ f, nexto, param, flags);
2289 PerlIO_funcs * const self = PerlIOBase(o)->tab;
2292 PerlIO_debug("PerlIOBase_dup %s f=%p o=%p param=%p\n",
2293 self ? self->name : "(Null)",
2294 (void*)f, (void*)o, (void*)param);
2295 if (self && self->Getarg)
2296 arg = (*self->Getarg)(aTHX_ o, param, flags);
2297 f = PerlIO_push(aTHX_ f, self, PerlIO_modestr(o,buf), arg);
2298 if (f && PerlIOBase(o)->flags & PERLIO_F_UTF8)
2299 PerlIOBase(f)->flags |= PERLIO_F_UTF8;
2305 /* PL_perlio_fd_refcnt[] is in intrpvar.h */
2307 /* Must be called with PL_perlio_mutex locked. */
2309 S_more_refcounted_fds(pTHX_ const int new_fd) {
2311 const int old_max = PL_perlio_fd_refcnt_size;
2312 const int new_max = 16 + (new_fd & ~15);
2315 PerlIO_debug("More fds - old=%d, need %d, new=%d\n",
2316 old_max, new_fd, new_max);
2318 if (new_fd < old_max) {
2322 assert (new_max > new_fd);
2324 /* Use plain realloc() since we need this memory to be really
2325 * global and visible to all the interpreters and/or threads. */
2326 new_array = (int*) realloc(PL_perlio_fd_refcnt, new_max * sizeof(int));
2330 MUTEX_UNLOCK(&PL_perlio_mutex);
2335 PL_perlio_fd_refcnt_size = new_max;
2336 PL_perlio_fd_refcnt = new_array;
2338 PerlIO_debug("Zeroing %p, %d\n",
2339 (void*)(new_array + old_max),
2342 Zero(new_array + old_max, new_max - old_max, int);
2349 /* MUTEX_INIT(&PL_perlio_mutex) is done in PERL_SYS_INIT3(). */
2350 PERL_UNUSED_CONTEXT;
2354 PerlIOUnix_refcnt_inc(int fd)
2361 MUTEX_LOCK(&PL_perlio_mutex);
2363 if (fd >= PL_perlio_fd_refcnt_size)
2364 S_more_refcounted_fds(aTHX_ fd);
2366 PL_perlio_fd_refcnt[fd]++;
2367 if (PL_perlio_fd_refcnt[fd] <= 0) {
2368 /* diag_listed_as: refcnt_inc: fd %d%s */
2369 Perl_croak(aTHX_ "refcnt_inc: fd %d: %d <= 0\n",
2370 fd, PL_perlio_fd_refcnt[fd]);
2372 PerlIO_debug("refcnt_inc: fd %d refcnt=%d\n",
2373 fd, PL_perlio_fd_refcnt[fd]);
2376 MUTEX_UNLOCK(&PL_perlio_mutex);
2379 /* diag_listed_as: refcnt_inc: fd %d%s */
2380 Perl_croak(aTHX_ "refcnt_inc: fd %d < 0\n", fd);
2385 PerlIOUnix_refcnt_dec(int fd)
2391 MUTEX_LOCK(&PL_perlio_mutex);
2393 if (fd >= PL_perlio_fd_refcnt_size) {
2394 /* diag_listed_as: refcnt_dec: fd %d%s */
2395 Perl_croak_nocontext("refcnt_dec: fd %d >= refcnt_size %d\n",
2396 fd, PL_perlio_fd_refcnt_size);
2398 if (PL_perlio_fd_refcnt[fd] <= 0) {
2399 /* diag_listed_as: refcnt_dec: fd %d%s */
2400 Perl_croak_nocontext("refcnt_dec: fd %d: %d <= 0\n",
2401 fd, PL_perlio_fd_refcnt[fd]);
2403 cnt = --PL_perlio_fd_refcnt[fd];
2404 PerlIO_debug("refcnt_dec: fd %d refcnt=%d\n", fd, cnt);
2406 MUTEX_UNLOCK(&PL_perlio_mutex);
2409 /* diag_listed_as: refcnt_dec: fd %d%s */
2410 Perl_croak_nocontext("refcnt_dec: fd %d < 0\n", fd);
2416 PerlIOUnix_refcnt(int fd)
2423 MUTEX_LOCK(&PL_perlio_mutex);
2425 if (fd >= PL_perlio_fd_refcnt_size) {
2426 /* diag_listed_as: refcnt: fd %d%s */
2427 Perl_croak(aTHX_ "refcnt: fd %d >= refcnt_size %d\n",
2428 fd, PL_perlio_fd_refcnt_size);
2430 if (PL_perlio_fd_refcnt[fd] <= 0) {
2431 /* diag_listed_as: refcnt: fd %d%s */
2432 Perl_croak(aTHX_ "refcnt: fd %d: %d <= 0\n",
2433 fd, PL_perlio_fd_refcnt[fd]);
2435 cnt = PL_perlio_fd_refcnt[fd];
2437 MUTEX_UNLOCK(&PL_perlio_mutex);
2440 /* diag_listed_as: refcnt: fd %d%s */
2441 Perl_croak(aTHX_ "refcnt: fd %d < 0\n", fd);
2447 PerlIO_cleanup(pTHX)
2452 PerlIO_debug("Cleanup layers for %p\n",(void*)aTHX);
2454 PerlIO_debug("Cleanup layers\n");
2457 /* Raise STDIN..STDERR refcount so we don't close them */
2458 for (i=0; i < 3; i++)
2459 PerlIOUnix_refcnt_inc(i);
2460 PerlIO_cleantable(aTHX_ &PL_perlio);
2461 /* Restore STDIN..STDERR refcount */
2462 for (i=0; i < 3; i++)
2463 PerlIOUnix_refcnt_dec(i);
2465 if (PL_known_layers) {
2466 PerlIO_list_free(aTHX_ PL_known_layers);
2467 PL_known_layers = NULL;
2469 if (PL_def_layerlist) {
2470 PerlIO_list_free(aTHX_ PL_def_layerlist);
2471 PL_def_layerlist = NULL;
2475 void PerlIO_teardown(void) /* Call only from PERL_SYS_TERM(). */
2479 /* XXX we can't rely on an interpreter being present at this late stage,
2480 XXX so we can't use a function like PerlLIO_write that relies on one
2481 being present (at least in win32) :-(.
2486 /* By now all filehandles should have been closed, so any
2487 * stray (non-STD-)filehandles indicate *possible* (PerlIO)
2489 #define PERLIO_TEARDOWN_MESSAGE_BUF_SIZE 64
2490 #define PERLIO_TEARDOWN_MESSAGE_FD 2
2491 char buf[PERLIO_TEARDOWN_MESSAGE_BUF_SIZE];
2493 for (i = 3; i < PL_perlio_fd_refcnt_size; i++) {
2494 if (PL_perlio_fd_refcnt[i]) {
2496 my_snprintf(buf, sizeof(buf),
2497 "PerlIO_teardown: fd %d refcnt=%d\n",
2498 i, PL_perlio_fd_refcnt[i]);
2499 PerlLIO_write(PERLIO_TEARDOWN_MESSAGE_FD, buf, len);
2505 /* Not bothering with PL_perlio_mutex since by now
2506 * all the interpreters are gone. */
2507 if (PL_perlio_fd_refcnt_size /* Assuming initial size of zero. */
2508 && PL_perlio_fd_refcnt) {
2509 free(PL_perlio_fd_refcnt); /* To match realloc() in S_more_refcounted_fds(). */
2510 PL_perlio_fd_refcnt = NULL;
2511 PL_perlio_fd_refcnt_size = 0;
2515 /*--------------------------------------------------------------------------------------*/
2517 * Bottom-most level for UNIX-like case
2521 struct _PerlIO base; /* The generic part */
2522 int fd; /* UNIX like file descriptor */
2523 int oflags; /* open/fcntl flags */
2527 S_lockcnt_dec(pTHX_ const void* f)
2529 PerlIO_lockcnt((PerlIO*)f)--;
2533 /* call the signal handler, and if that handler happens to clear
2534 * this handle, free what we can and return true */
2537 S_perlio_async_run(pTHX_ PerlIO* f) {
2539 SAVEDESTRUCTOR_X(S_lockcnt_dec, (void*)f);
2540 PerlIO_lockcnt(f)++;
2542 if ( !(PerlIOBase(f)->flags & PERLIO_F_CLEARED) ) {
2546 /* we've just run some perl-level code that could have done
2547 * anything, including closing the file or clearing this layer.
2548 * If so, free any lower layers that have already been
2549 * cleared, then return an error. */
2550 while (PerlIOValid(f) &&
2551 (PerlIOBase(f)->flags & PERLIO_F_CLEARED))
2553 const PerlIOl *l = *f;
2562 PerlIOUnix_oflags(const char *mode)
2565 if (*mode == IoTYPE_IMPLICIT || *mode == IoTYPE_NUMERIC)
2570 if (*++mode == '+') {
2577 oflags = O_CREAT | O_TRUNC;
2578 if (*++mode == '+') {
2587 oflags = O_CREAT | O_APPEND;
2588 if (*++mode == '+') {
2601 else if (*mode == 't') {
2603 oflags &= ~O_BINARY;
2607 #ifdef PERLIO_USING_CRLF
2609 * If neither "t" nor "b" was specified, open the file
2615 if (*mode || oflags == -1) {
2616 SETERRNO(EINVAL, LIB_INVARG);
2623 PerlIOUnix_fileno(pTHX_ PerlIO *f)
2625 PERL_UNUSED_CONTEXT;
2626 return PerlIOSelf(f, PerlIOUnix)->fd;
2630 PerlIOUnix_setfd(pTHX_ PerlIO *f, int fd, int imode)
2632 PerlIOUnix * const s = PerlIOSelf(f, PerlIOUnix);
2635 if (PerlLIO_fstat(fd, &st) == 0) {
2636 if (!S_ISREG(st.st_mode)) {
2637 PerlIO_debug("%d is not regular file\n",fd);
2638 PerlIOBase(f)->flags |= PERLIO_F_NOTREG;
2641 PerlIO_debug("%d _is_ a regular file\n",fd);
2647 PerlIOUnix_refcnt_inc(fd);
2648 PERL_UNUSED_CONTEXT;
2652 PerlIOUnix_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
2654 IV code = PerlIOBase_pushed(aTHX_ f, mode, arg, tab);
2655 if (*PerlIONext(f)) {
2656 /* We never call down so do any pending stuff now */
2657 PerlIO_flush(PerlIONext(f));
2659 * XXX could (or should) we retrieve the oflags from the open file
2660 * handle rather than believing the "mode" we are passed in? XXX
2661 * Should the value on NULL mode be 0 or -1?
2663 PerlIOUnix_setfd(aTHX_ f, PerlIO_fileno(PerlIONext(f)),
2664 mode ? PerlIOUnix_oflags(mode) : -1);
2666 PerlIOBase(f)->flags |= PERLIO_F_OPEN;
2672 PerlIOUnix_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
2674 const int fd = PerlIOSelf(f, PerlIOUnix)->fd;
2676 PERL_UNUSED_CONTEXT;
2677 if (PerlIOBase(f)->flags & PERLIO_F_NOTREG) {
2679 SETERRNO(ESPIPE, LIB_INVARG);
2681 SETERRNO(EINVAL, LIB_INVARG);
2685 new_loc = PerlLIO_lseek(fd, offset, whence);
2686 if (new_loc == (Off_t) - 1)
2688 PerlIOBase(f)->flags &= ~PERLIO_F_EOF;
2693 PerlIOUnix_open(pTHX_ PerlIO_funcs *self, PerlIO_list_t *layers,
2694 IV n, const char *mode, int fd, int imode,
2695 int perm, PerlIO *f, int narg, SV **args)
2697 if (PerlIOValid(f)) {
2698 if (PerlIOBase(f)->tab && PerlIOBase(f)->flags & PERLIO_F_OPEN)
2699 (*PerlIOBase(f)->tab->Close)(aTHX_ f);
2702 if (*mode == IoTYPE_NUMERIC)
2705 imode = PerlIOUnix_oflags(mode);
2707 perm = 0777; /* preserve RMS defaults, ACL inheritance, etc. */
2714 const char *path = SvPV_const(*args, len);
2715 if (!IS_SAFE_PATHNAME(path, len, "open"))
2717 fd = PerlLIO_open3(path, imode, perm);
2721 if (*mode == IoTYPE_IMPLICIT)
2724 f = PerlIO_allocate(aTHX);
2726 if (!PerlIOValid(f)) {
2727 if (!(f = PerlIO_push(aTHX_ f, self, mode, PerlIOArg))) {
2731 PerlIOUnix_setfd(aTHX_ f, fd, imode);
2732 PerlIOBase(f)->flags |= PERLIO_F_OPEN;
2733 if (*mode == IoTYPE_APPEND)
2734 PerlIOUnix_seek(aTHX_ f, 0, SEEK_END);
2741 * FIXME: pop layers ???
2749 PerlIOUnix_dup(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags)
2751 const PerlIOUnix * const os = PerlIOSelf(o, PerlIOUnix);
2753 if (flags & PERLIO_DUP_FD) {
2754 fd = PerlLIO_dup(fd);
2757 f = PerlIOBase_dup(aTHX_ f, o, param, flags);
2759 /* If all went well overwrite fd in dup'ed lay with the dup()'ed fd */
2760 PerlIOUnix_setfd(aTHX_ f, fd, os->oflags);
2769 PerlIOUnix_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
2773 if (PerlIO_lockcnt(f)) /* in use: abort ungracefully */
2775 fd = PerlIOSelf(f, PerlIOUnix)->fd;
2776 #ifdef PERLIO_STD_SPECIAL
2778 return PERLIO_STD_IN(fd, vbuf, count);
2780 if (!(PerlIOBase(f)->flags & PERLIO_F_CANREAD) ||
2781 PerlIOBase(f)->flags & (PERLIO_F_EOF|PERLIO_F_ERROR)) {
2785 const SSize_t len = PerlLIO_read(fd, vbuf, count);
2786 if (len >= 0 || errno != EINTR) {
2788 if (errno != EAGAIN) {
2789 PerlIOBase(f)->flags |= PERLIO_F_ERROR;
2792 else if (len == 0 && count != 0) {
2793 PerlIOBase(f)->flags |= PERLIO_F_EOF;
2799 if (PL_sig_pending && S_perlio_async_run(aTHX_ f))
2806 PerlIOUnix_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
2810 if (PerlIO_lockcnt(f)) /* in use: abort ungracefully */
2812 fd = PerlIOSelf(f, PerlIOUnix)->fd;
2813 #ifdef PERLIO_STD_SPECIAL
2814 if (fd == 1 || fd == 2)
2815 return PERLIO_STD_OUT(fd, vbuf, count);
2818 const SSize_t len = PerlLIO_write(fd, vbuf, count);
2819 if (len >= 0 || errno != EINTR) {
2821 if (errno != EAGAIN) {
2822 PerlIOBase(f)->flags |= PERLIO_F_ERROR;
2828 if (PL_sig_pending && S_perlio_async_run(aTHX_ f))
2835 PerlIOUnix_tell(pTHX_ PerlIO *f)
2837 PERL_UNUSED_CONTEXT;
2839 return PerlLIO_lseek(PerlIOSelf(f, PerlIOUnix)->fd, 0, SEEK_CUR);
2844 PerlIOUnix_close(pTHX_ PerlIO *f)
2847 const int fd = PerlIOSelf(f, PerlIOUnix)->fd;
2849 if (PerlIOBase(f)->flags & PERLIO_F_OPEN) {
2850 if (PerlIOUnix_refcnt_dec(fd) > 0) {
2851 PerlIOBase(f)->flags &= ~PERLIO_F_OPEN;
2856 SETERRNO(EBADF,SS_IVCHAN);
2859 while (PerlLIO_close(fd) != 0) {
2860 if (errno != EINTR) {
2865 if (PL_sig_pending && S_perlio_async_run(aTHX_ f))
2869 PerlIOBase(f)->flags &= ~PERLIO_F_OPEN;
2874 PERLIO_FUNCS_DECL(PerlIO_unix) = {
2875 sizeof(PerlIO_funcs),
2882 PerlIOBase_binmode, /* binmode */
2892 PerlIOBase_noop_ok, /* flush */
2893 PerlIOBase_noop_fail, /* fill */
2896 PerlIOBase_clearerr,
2897 PerlIOBase_setlinebuf,
2898 NULL, /* get_base */
2899 NULL, /* get_bufsiz */
2902 NULL, /* set_ptrcnt */
2905 /*--------------------------------------------------------------------------------------*/
2910 #if defined(VMS) && !defined(STDIO_BUFFER_WRITABLE)
2911 /* perl5.8 - This ensures the last minute VMS ungetc fix is not
2912 broken by the last second glibc 2.3 fix
2914 #define STDIO_BUFFER_WRITABLE
2919 struct _PerlIO base;
2920 FILE *stdio; /* The stream */
2924 PerlIOStdio_fileno(pTHX_ PerlIO *f)
2926 PERL_UNUSED_CONTEXT;
2928 if (PerlIOValid(f)) {
2929 FILE * const s = PerlIOSelf(f, PerlIOStdio)->stdio;
2931 return PerlSIO_fileno(s);
2938 PerlIOStdio_mode(const char *mode, char *tmode)
2940 char * const ret = tmode;
2946 #if defined(PERLIO_USING_CRLF) || defined(__CYGWIN__)
2954 PerlIOStdio_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
2957 if (PerlIOValid(f) && PerlIOValid(n = PerlIONext(f))) {
2958 PerlIO_funcs * const toptab = PerlIOBase(n)->tab;
2959 if (toptab == tab) {
2960 /* Top is already stdio - pop self (duplicate) and use original */
2961 PerlIO_pop(aTHX_ f);
2964 const int fd = PerlIO_fileno(n);
2967 if (fd >= 0 && (stdio = PerlSIO_fdopen(fd,
2968 mode = PerlIOStdio_mode(mode, tmode)))) {
2969 PerlIOSelf(f, PerlIOStdio)->stdio = stdio;
2970 /* We never call down so do any pending stuff now */
2971 PerlIO_flush(PerlIONext(f));
2978 return PerlIOBase_pushed(aTHX_ f, mode, arg, tab);
2983 PerlIO_importFILE(FILE *stdio, const char *mode)
2989 if (!mode || !*mode) {
2990 /* We need to probe to see how we can open the stream
2991 so start with read/write and then try write and read
2992 we dup() so that we can fclose without loosing the fd.
2994 Note that the errno value set by a failing fdopen
2995 varies between stdio implementations.
2997 const int fd = PerlLIO_dup(fileno(stdio));
2998 FILE *f2 = PerlSIO_fdopen(fd, (mode = "r+"));
3000 f2 = PerlSIO_fdopen(fd, (mode = "w"));
3003 f2 = PerlSIO_fdopen(fd, (mode = "r"));
3006 /* Don't seem to be able to open */
3012 if ((f = PerlIO_push(aTHX_(f = PerlIO_allocate(aTHX)), PERLIO_FUNCS_CAST(&PerlIO_stdio), mode, NULL))) {
3013 s = PerlIOSelf(f, PerlIOStdio);
3015 PerlIOUnix_refcnt_inc(fileno(stdio));
3022 PerlIOStdio_open(pTHX_ PerlIO_funcs *self, PerlIO_list_t *layers,
3023 IV n, const char *mode, int fd, int imode,
3024 int perm, PerlIO *f, int narg, SV **args)
3027 if (PerlIOValid(f)) {
3029 const char * const path = SvPV_const(*args, len);
3030 PerlIOStdio * const s = PerlIOSelf(f, PerlIOStdio);
3032 if (!IS_SAFE_PATHNAME(path, len, "open"))
3034 PerlIOUnix_refcnt_dec(fileno(s->stdio));
3035 stdio = PerlSIO_freopen(path, (mode = PerlIOStdio_mode(mode, tmode)),
3040 PerlIOUnix_refcnt_inc(fileno(s->stdio));
3046 const char * const path = SvPV_const(*args, len);
3047 if (!IS_SAFE_PATHNAME(path, len, "open"))
3049 if (*mode == IoTYPE_NUMERIC) {
3051 fd = PerlLIO_open3(path, imode, perm);
3055 bool appended = FALSE;
3057 /* Cygwin wants its 'b' early. */
3059 mode = PerlIOStdio_mode(mode, tmode);
3061 stdio = PerlSIO_fopen(path, mode);
3064 f = PerlIO_allocate(aTHX);
3067 mode = PerlIOStdio_mode(mode, tmode);
3068 f = PerlIO_push(aTHX_ f, self, mode, PerlIOArg);
3070 PerlIOSelf(f, PerlIOStdio)->stdio = stdio;
3071 PerlIOUnix_refcnt_inc(fileno(stdio));
3073 PerlSIO_fclose(stdio);
3085 if (*mode == IoTYPE_IMPLICIT) {
3092 stdio = PerlSIO_stdin;
3095 stdio = PerlSIO_stdout;
3098 stdio = PerlSIO_stderr;
3103 stdio = PerlSIO_fdopen(fd, mode =
3104 PerlIOStdio_mode(mode, tmode));
3108 f = PerlIO_allocate(aTHX);
3110 if ((f = PerlIO_push(aTHX_ f, self, mode, PerlIOArg))) {
3111 PerlIOSelf(f, PerlIOStdio)->stdio = stdio;
3112 PerlIOUnix_refcnt_inc(fileno(stdio));
3122 PerlIOStdio_dup(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags)
3124 /* This assumes no layers underneath - which is what
3125 happens, but is not how I remember it. NI-S 2001/10/16
3127 if ((f = PerlIOBase_dup(aTHX_ f, o, param, flags))) {
3128 FILE *stdio = PerlIOSelf(o, PerlIOStdio)->stdio;
3129 const int fd = fileno(stdio);
3131 if (flags & PERLIO_DUP_FD) {
3132 const int dfd = PerlLIO_dup(fileno(stdio));
3134 stdio = PerlSIO_fdopen(dfd, PerlIO_modestr(o,mode));
3139 /* FIXME: To avoid messy error recovery if dup fails
3140 re-use the existing stdio as though flag was not set
3144 stdio = PerlSIO_fdopen(fd, PerlIO_modestr(o,mode));
3146 PerlIOSelf(f, PerlIOStdio)->stdio = stdio;
3148 PerlIOUnix_refcnt_inc(fileno(stdio));
3155 PerlIOStdio_invalidate_fileno(pTHX_ FILE *f)
3157 PERL_UNUSED_CONTEXT;
3159 /* XXX this could use PerlIO_canset_fileno() and
3160 * PerlIO_set_fileno() support from Configure
3162 # if defined(__UCLIBC__)
3163 /* uClibc must come before glibc because it defines __GLIBC__ as well. */
3166 # elif defined(__GLIBC__)
3167 /* There may be a better way for GLIBC:
3168 - libio.h defines a flag to not close() on cleanup
3172 # elif defined(__sun__)
3175 # elif defined(__hpux)
3179 /* Next one ->_file seems to be a reasonable fallback, i.e. if
3180 your platform does not have special entry try this one.
3181 [For OSF only have confirmation for Tru64 (alpha)
3182 but assume other OSFs will be similar.]
3184 # elif defined(_AIX) || defined(__osf__) || defined(__irix__)
3187 # elif defined(__FreeBSD__)
3188 /* There may be a better way on FreeBSD:
3189 - we could insert a dummy func in the _close function entry
3190 f->_close = (int (*)(void *)) dummy_close;
3194 # elif defined(__OpenBSD__)
3195 /* There may be a better way on OpenBSD:
3196 - we could insert a dummy func in the _close function entry
3197 f->_close = (int (*)(void *)) dummy_close;
3201 # elif defined(__EMX__)
3202 /* f->_flags &= ~_IOOPEN; */ /* Will leak stream->_buffer */
3205 # elif defined(__CYGWIN__)
3206 /* There may be a better way on CYGWIN:
3207 - we could insert a dummy func in the _close function entry
3208 f->_close = (int (*)(void *)) dummy_close;
3212 # elif defined(WIN32)
3213 # if defined(UNDER_CE)
3214 /* WIN_CE does not have access to FILE internals, it hardly has FILE
3223 /* Sarathy's code did this - we fall back to a dup/dup2 hack
3224 (which isn't thread safe) instead
3226 # error "Don't know how to set FILE.fileno on your platform"
3234 PerlIOStdio_close(pTHX_ PerlIO *f)
3236 FILE * const stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3242 const int fd = fileno(stdio);
3250 #ifdef SOCKS5_VERSION_NAME
3251 /* Socks lib overrides close() but stdio isn't linked to
3252 that library (though we are) - so we must call close()
3253 on sockets on stdio's behalf.
3256 Sock_size_t optlen = sizeof(int);
3257 if (getsockopt(fd, SOL_SOCKET, SO_TYPE, (void *) &optval, &optlen) == 0)
3260 /* Test for -1, as *BSD stdio (at least) on fclose sets the FILE* such
3261 that a subsequent fileno() on it returns -1. Don't want to croak()
3262 from within PerlIOUnix_refcnt_dec() if some buggy caller code is
3263 trying to close an already closed handle which somehow it still has
3264 a reference to. (via.xs, I'm looking at you). */
3265 if (fd != -1 && PerlIOUnix_refcnt_dec(fd) > 0) {
3266 /* File descriptor still in use */
3270 /* For STD* handles, don't close stdio, since we shared the FILE *, too. */
3271 if (stdio == stdin) /* Some stdios are buggy fflush-ing inputs */
3273 if (stdio == stdout || stdio == stderr)
3274 return PerlIO_flush(f);
3275 /* Tricky - must fclose(stdio) to free memory but not close(fd)
3276 Use Sarathy's trick from maint-5.6 to invalidate the
3277 fileno slot of the FILE *
3279 result = PerlIO_flush(f);
3281 invalidate = PerlIOStdio_invalidate_fileno(aTHX_ stdio);
3284 MUTEX_LOCK(&PL_perlio_mutex);
3285 /* Right. We need a mutex here because for a brief while we
3286 will have the situation that fd is actually closed. Hence if
3287 a second thread were to get into this block, its dup() would
3288 likely return our fd as its dupfd. (after all, it is closed)
3289 Then if we get to the dup2() first, we blat the fd back
3290 (messing up its temporary as a side effect) only for it to
3291 then close its dupfd (== our fd) in its close(dupfd) */
3293 /* There is, of course, a race condition, that any other thread
3294 trying to input/output/whatever on this fd will be stuffed
3295 for the duration of this little manoeuvrer. Perhaps we
3296 should hold an IO mutex for the duration of every IO
3297 operation if we know that invalidate doesn't work on this
3298 platform, but that would suck, and could kill performance.
3300 Except that correctness trumps speed.
3301 Advice from klortho #11912. */
3303 dupfd = PerlLIO_dup(fd);
3306 MUTEX_UNLOCK(&PL_perlio_mutex);
3307 /* Oh cXap. This isn't going to go well. Not sure if we can
3308 recover from here, or if closing this particular FILE *
3309 is a good idea now. */
3314 SAVE_ERRNO; /* This is here only to silence compiler warnings */
3316 result = PerlSIO_fclose(stdio);
3317 /* We treat error from stdio as success if we invalidated
3318 errno may NOT be expected EBADF
3320 if (invalidate && result != 0) {
3324 #ifdef SOCKS5_VERSION_NAME
3325 /* in SOCKS' case, let close() determine return value */
3329 PerlLIO_dup2(dupfd,fd);
3330 PerlLIO_close(dupfd);
3332 MUTEX_UNLOCK(&PL_perlio_mutex);
3340 PerlIOStdio_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
3345 if (PerlIO_lockcnt(f)) /* in use: abort ungracefully */
3347 s = PerlIOSelf(f, PerlIOStdio)->stdio;
3350 STDCHAR *buf = (STDCHAR *) vbuf;
3352 * Perl is expecting PerlIO_getc() to fill the buffer Linux's
3353 * stdio does not do that for fread()
3355 const int ch = PerlSIO_fgetc(s);
3362 got = PerlSIO_fread(vbuf, 1, count, s);
3363 if (got == 0 && PerlSIO_ferror(s))
3365 if (got >= 0 || errno != EINTR)
3367 if (PL_sig_pending && S_perlio_async_run(aTHX_ f))
3369 SETERRNO(0,0); /* just in case */
3375 PerlIOStdio_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
3378 FILE * const s = PerlIOSelf(f, PerlIOStdio)->stdio;
3380 #ifdef STDIO_BUFFER_WRITABLE
3381 if (PerlIO_fast_gets(f) && PerlIO_has_base(f)) {
3382 STDCHAR *buf = ((STDCHAR *) vbuf) + count;
3383 STDCHAR *base = PerlIO_get_base(f);
3384 SSize_t cnt = PerlIO_get_cnt(f);
3385 STDCHAR *ptr = PerlIO_get_ptr(f);
3386 SSize_t avail = ptr - base;
3388 if (avail > count) {
3392 Move(buf-avail,ptr,avail,STDCHAR);
3395 PerlIO_set_ptrcnt(f,ptr,cnt+avail);
3396 if (PerlSIO_feof(s) && unread >= 0)
3397 PerlSIO_clearerr(s);
3402 if (PerlIO_has_cntptr(f)) {
3403 /* We can get pointer to buffer but not its base
3404 Do ungetc() but check chars are ending up in the
3407 STDCHAR *eptr = (STDCHAR*)PerlSIO_get_ptr(s);
3408 STDCHAR *buf = ((STDCHAR *) vbuf) + count;
3410 const int ch = *--buf & 0xFF;
3411 if (ungetc(ch,s) != ch) {
3412 /* ungetc did not work */
3415 if ((STDCHAR*)PerlSIO_get_ptr(s) != --eptr || ((*eptr & 0xFF) != ch)) {
3416 /* Did not change pointer as expected */
3417 fgetc(s); /* get char back again */
3427 unread += PerlIOBase_unread(aTHX_ f, vbuf, count);
3433 PerlIOStdio_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
3437 if (PerlIO_lockcnt(f)) /* in use: abort ungracefully */
3440 got = PerlSIO_fwrite(vbuf, 1, count,
3441 PerlIOSelf(f, PerlIOStdio)->stdio);
3442 if (got >= 0 || errno != EINTR)
3444 if (PL_sig_pending && S_perlio_async_run(aTHX_ f))
3446 SETERRNO(0,0); /* just in case */
3452 PerlIOStdio_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
3454 FILE * const stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3455 PERL_UNUSED_CONTEXT;
3457 return PerlSIO_fseek(stdio, offset, whence);
3461 PerlIOStdio_tell(pTHX_ PerlIO *f)
3463 FILE * const stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3464 PERL_UNUSED_CONTEXT;
3466 return PerlSIO_ftell(stdio);
3470 PerlIOStdio_flush(pTHX_ PerlIO *f)
3472 FILE * const stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3473 PERL_UNUSED_CONTEXT;
3475 if (PerlIOBase(f)->flags & PERLIO_F_CANWRITE) {
3476 return PerlSIO_fflush(stdio);
3482 * FIXME: This discards ungetc() and pre-read stuff which is not
3483 * right if this is just a "sync" from a layer above Suspect right
3484 * design is to do _this_ but not have layer above flush this
3485 * layer read-to-read
3488 * Not writeable - sync by attempting a seek
3491 if (PerlSIO_fseek(stdio, (Off_t) 0, SEEK_CUR) != 0)
3499 PerlIOStdio_eof(pTHX_ PerlIO *f)
3501 PERL_UNUSED_CONTEXT;
3503 return PerlSIO_feof(PerlIOSelf(f, PerlIOStdio)->stdio);
3507 PerlIOStdio_error(pTHX_ PerlIO *f)
3509 PERL_UNUSED_CONTEXT;
3511 return PerlSIO_ferror(PerlIOSelf(f, PerlIOStdio)->stdio);
3515 PerlIOStdio_clearerr(pTHX_ PerlIO *f)
3517 PERL_UNUSED_CONTEXT;
3519 PerlSIO_clearerr(PerlIOSelf(f, PerlIOStdio)->stdio);
3523 PerlIOStdio_setlinebuf(pTHX_ PerlIO *f)
3525 PERL_UNUSED_CONTEXT;
3527 #ifdef HAS_SETLINEBUF
3528 PerlSIO_setlinebuf(PerlIOSelf(f, PerlIOStdio)->stdio);
3530 PerlSIO_setvbuf(PerlIOSelf(f, PerlIOStdio)->stdio, NULL, _IOLBF, 0);
3536 PerlIOStdio_get_base(pTHX_ PerlIO *f)
3538 FILE * const stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3539 return (STDCHAR*)PerlSIO_get_base(stdio);
3543 PerlIOStdio_get_bufsiz(pTHX_ PerlIO *f)
3545 FILE * const stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3546 return PerlSIO_get_bufsiz(stdio);
3550 #ifdef USE_STDIO_PTR
3552 PerlIOStdio_get_ptr(pTHX_ PerlIO *f)
3554 FILE * const stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3555 return (STDCHAR*)PerlSIO_get_ptr(stdio);
3559 PerlIOStdio_get_cnt(pTHX_ PerlIO *f)
3561 FILE * const stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3562 return PerlSIO_get_cnt(stdio);
3566 PerlIOStdio_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, SSize_t cnt)
3568 FILE * const stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3570 #ifdef STDIO_PTR_LVALUE
3571 PerlSIO_set_ptr(stdio, ptr); /* LHS STDCHAR* cast non-portable */
3572 #ifdef STDIO_PTR_LVAL_SETS_CNT
3573 assert(PerlSIO_get_cnt(stdio) == (cnt));
3575 #if (!defined(STDIO_PTR_LVAL_NOCHANGE_CNT))
3577 * Setting ptr _does_ change cnt - we are done
3581 #else /* STDIO_PTR_LVALUE */
3583 #endif /* STDIO_PTR_LVALUE */
3586 * Now (or only) set cnt
3588 #ifdef STDIO_CNT_LVALUE
3589 PerlSIO_set_cnt(stdio, cnt);
3590 #else /* STDIO_CNT_LVALUE */
3591 #if (defined(STDIO_PTR_LVALUE) && defined(STDIO_PTR_LVAL_SETS_CNT))
3592 PerlSIO_set_ptr(stdio,
3593 PerlSIO_get_ptr(stdio) + (PerlSIO_get_cnt(stdio) -
3595 #else /* STDIO_PTR_LVAL_SETS_CNT */
3597 #endif /* STDIO_PTR_LVAL_SETS_CNT */
3598 #endif /* STDIO_CNT_LVALUE */
3605 PerlIOStdio_fill(pTHX_ PerlIO *f)
3609 PERL_UNUSED_CONTEXT;
3610 if (PerlIO_lockcnt(f)) /* in use: abort ungracefully */
3612 stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3615 * fflush()ing read-only streams can cause trouble on some stdio-s
3617 if ((PerlIOBase(f)->flags & PERLIO_F_CANWRITE)) {
3618 if (PerlSIO_fflush(stdio) != 0)
3622 c = PerlSIO_fgetc(stdio);
3625 if (! PerlSIO_ferror(stdio) || errno != EINTR)
3627 if (PL_sig_pending && S_perlio_async_run(aTHX_ f))
3632 #if (defined(STDIO_PTR_LVALUE) && (defined(STDIO_CNT_LVALUE) || defined(STDIO_PTR_LVAL_SETS_CNT)))
3634 #ifdef STDIO_BUFFER_WRITABLE
3635 if (PerlIO_fast_gets(f) && PerlIO_has_base(f)) {
3636 /* Fake ungetc() to the real buffer in case system's ungetc
3639 STDCHAR *base = (STDCHAR*)PerlSIO_get_base(stdio);
3640 SSize_t cnt = PerlSIO_get_cnt(stdio);
3641 STDCHAR *ptr = (STDCHAR*)PerlSIO_get_ptr(stdio);
3642 if (ptr == base+1) {
3643 *--ptr = (STDCHAR) c;
3644 PerlIOStdio_set_ptrcnt(aTHX_ f,ptr,cnt+1);
3645 if (PerlSIO_feof(stdio))
3646 PerlSIO_clearerr(stdio);
3652 if (PerlIO_has_cntptr(f)) {
3654 if (PerlIOStdio_unread(aTHX_ f,&ch,1) == 1) {
3661 /* An ungetc()d char is handled separately from the regular
3662 * buffer, so we stuff it in the buffer ourselves.
3663 * Should never get called as should hit code above
3665 *(--((*stdio)->_ptr)) = (unsigned char) c;
3668 /* If buffer snoop scheme above fails fall back to
3671 if (PerlSIO_ungetc(c, stdio) != c)
3679 PERLIO_FUNCS_DECL(PerlIO_stdio) = {
3680 sizeof(PerlIO_funcs),
3682 sizeof(PerlIOStdio),
3683 PERLIO_K_BUFFERED|PERLIO_K_RAW,
3687 PerlIOBase_binmode, /* binmode */
3701 PerlIOStdio_clearerr,
3702 PerlIOStdio_setlinebuf,
3704 PerlIOStdio_get_base,
3705 PerlIOStdio_get_bufsiz,
3710 #ifdef USE_STDIO_PTR
3711 PerlIOStdio_get_ptr,
3712 PerlIOStdio_get_cnt,
3713 # if defined(HAS_FAST_STDIO) && defined(USE_FAST_STDIO)
3714 PerlIOStdio_set_ptrcnt,
3717 # endif /* HAS_FAST_STDIO && USE_FAST_STDIO */
3722 #endif /* USE_STDIO_PTR */
3725 /* Note that calls to PerlIO_exportFILE() are reversed using
3726 * PerlIO_releaseFILE(), not importFILE. */
3728 PerlIO_exportFILE(PerlIO * f, const char *mode)
3732 if (PerlIOValid(f)) {
3735 if (!mode || !*mode) {
3736 mode = PerlIO_modestr(f, buf);
3738 stdio = PerlSIO_fdopen(PerlIO_fileno(f), mode);
3742 /* De-link any lower layers so new :stdio sticks */
3744 if ((f2 = PerlIO_push(aTHX_ f, PERLIO_FUNCS_CAST(&PerlIO_stdio), buf, NULL))) {
3745 PerlIOStdio *s = PerlIOSelf((f = f2), PerlIOStdio);
3747 PerlIOUnix_refcnt_inc(fileno(stdio));
3748 /* Link previous lower layers under new one */
3752 /* restore layers list */
3762 PerlIO_findFILE(PerlIO *f)
3767 if (l->tab == &PerlIO_stdio) {
3768 PerlIOStdio *s = PerlIOSelf(&l, PerlIOStdio);
3771 l = *PerlIONext(&l);
3773 /* Uses fallback "mode" via PerlIO_modestr() in PerlIO_exportFILE */
3774 /* However, we're not really exporting a FILE * to someone else (who
3775 becomes responsible for closing it, or calling PerlIO_releaseFILE())
3776 So we need to undo its reference count increase on the underlying file
3777 descriptor. We have to do this, because if the loop above returns you
3778 the FILE *, then *it* didn't increase any reference count. So there's
3779 only one way to be consistent. */
3780 stdio = PerlIO_exportFILE(f, NULL);
3782 const int fd = fileno(stdio);
3784 PerlIOUnix_refcnt_dec(fd);
3789 /* Use this to reverse PerlIO_exportFILE calls. */
3791 PerlIO_releaseFILE(PerlIO *p, FILE *f)
3796 if (l->tab == &PerlIO_stdio) {
3797 PerlIOStdio *s = PerlIOSelf(&l, PerlIOStdio);
3798 if (s->stdio == f) { /* not in a loop */
3799 const int fd = fileno(f);
3801 PerlIOUnix_refcnt_dec(fd);
3804 PerlIO_pop(aTHX_ p);
3814 /*--------------------------------------------------------------------------------------*/
3816 * perlio buffer layer
3820 PerlIOBuf_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
3822 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3823 const int fd = PerlIO_fileno(f);
3824 if (fd >= 0 && PerlLIO_isatty(fd)) {
3825 PerlIOBase(f)->flags |= PERLIO_F_LINEBUF | PERLIO_F_TTY;
3827 if (*PerlIONext(f)) {
3828 const Off_t posn = PerlIO_tell(PerlIONext(f));
3829 if (posn != (Off_t) - 1) {
3833 return PerlIOBase_pushed(aTHX_ f, mode, arg, tab);
3837 PerlIOBuf_open(pTHX_ PerlIO_funcs *self, PerlIO_list_t *layers,
3838 IV n, const char *mode, int fd, int imode, int perm,
3839 PerlIO *f, int narg, SV **args)
3841 if (PerlIOValid(f)) {
3842 PerlIO *next = PerlIONext(f);
3844 PerlIO_layer_fetch(aTHX_ layers, n - 1, PerlIOBase(next)->tab);
3845 if (tab && tab->Open)
3847 (*tab->Open)(aTHX_ tab, layers, n - 1, mode, fd, imode, perm,
3849 if (!next || (*PerlIOBase(f)->tab->Pushed) (aTHX_ f, mode, PerlIOArg, self) != 0) {
3854 PerlIO_funcs *tab = PerlIO_layer_fetch(aTHX_ layers, n - 1, PerlIO_default_btm());
3856 if (*mode == IoTYPE_IMPLICIT) {
3862 if (tab && tab->Open)
3863 f = (*tab->Open)(aTHX_ tab, layers, n - 1, mode, fd, imode, perm,
3866 SETERRNO(EINVAL, LIB_INVARG);
3868 if (PerlIO_push(aTHX_ f, self, mode, PerlIOArg) == 0) {
3870 * if push fails during open, open fails. close will pop us.
3875 fd = PerlIO_fileno(f);
3876 if (init && fd == 2) {
3878 * Initial stderr is unbuffered
3880 PerlIOBase(f)->flags |= PERLIO_F_UNBUF;
3882 #ifdef PERLIO_USING_CRLF
3883 # ifdef PERLIO_IS_BINMODE_FD
3884 if (PERLIO_IS_BINMODE_FD(fd))
3885 PerlIO_binmode(aTHX_ f, '<'/*not used*/, O_BINARY, NULL);
3889 * do something about failing setmode()? --jhi
3891 PerlLIO_setmode(fd, O_BINARY);
3894 /* Enable line buffering with record-oriented regular files
3895 * so we don't introduce an extraneous record boundary when
3896 * the buffer fills up.
3898 if (PerlIOBase(f)->flags & PERLIO_F_CANWRITE) {
3900 if (PerlLIO_fstat(fd, &st) == 0
3901 && S_ISREG(st.st_mode)
3902 && (st.st_fab_rfm == FAB$C_VAR
3903 || st.st_fab_rfm == FAB$C_VFC)) {
3904 PerlIOBase(f)->flags |= PERLIO_F_LINEBUF;
3915 * This "flush" is akin to sfio's sync in that it handles files in either
3916 * read or write state. For write state, we put the postponed data through
3917 * the next layers. For read state, we seek() the next layers to the
3918 * offset given by current position in the buffer, and discard the buffer
3919 * state (XXXX supposed to be for seek()able buffers only, but now it is done
3920 * in any case?). Then the pass the stick further in chain.
3923 PerlIOBuf_flush(pTHX_ PerlIO *f)
3925 PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
3927 PerlIO *n = PerlIONext(f);
3928 if (PerlIOBase(f)->flags & PERLIO_F_WRBUF) {
3930 * write() the buffer
3932 const STDCHAR *buf = b->buf;
3933 const STDCHAR *p = buf;
3934 while (p < b->ptr) {
3935 SSize_t count = PerlIO_write(n, p, b->ptr - p);
3939 else if (count < 0 || PerlIO_error(n)) {
3940 PerlIOBase(f)->flags |= PERLIO_F_ERROR;
3945 b->posn += (p - buf);
3947 else if (PerlIOBase(f)->flags & PERLIO_F_RDBUF) {
3948 STDCHAR *buf = PerlIO_get_base(f);
3950 * Note position change
3952 b->posn += (b->ptr - buf);
3953 if (b->ptr < b->end) {
3954 /* We did not consume all of it - try and seek downstream to
3955 our logical position
3957 if (PerlIOValid(n) && PerlIO_seek(n, b->posn, SEEK_SET) == 0) {
3958 /* Reload n as some layers may pop themselves on seek */
3959 b->posn = PerlIO_tell(n = PerlIONext(f));
3962 /* Seek failed (e.g. pipe or tty). Do NOT clear buffer or pre-read
3963 data is lost for good - so return saying "ok" having undone
3966 b->posn -= (b->ptr - buf);
3971 b->ptr = b->end = b->buf;
3972 PerlIOBase(f)->flags &= ~(PERLIO_F_RDBUF | PERLIO_F_WRBUF);
3973 /* We check for Valid because of dubious decision to make PerlIO_flush(NULL) flush all */
3974 if (PerlIOValid(n) && PerlIO_flush(n) != 0)
3979 /* This discards the content of the buffer after b->ptr, and rereads
3980 * the buffer from the position off in the layer downstream; here off
3981 * is at offset corresponding to b->ptr - b->buf.
3984 PerlIOBuf_fill(pTHX_ PerlIO *f)
3986 PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
3987 PerlIO *n = PerlIONext(f);
3990 * Down-stream flush is defined not to loose read data so is harmless.
3991 * we would not normally be fill'ing if there was data left in anycase.
3993 if (PerlIO_flush(f) != 0) /* XXXX Check that its seek() succeeded?! */
3995 if (PerlIOBase(f)->flags & PERLIO_F_TTY)
3996 PerlIOBase_flush_linebuf(aTHX);
3999 PerlIO_get_base(f); /* allocate via vtable */
4001 assert(b->buf); /* The b->buf does get allocated via the vtable system. */
4003 b->ptr = b->end = b->buf;
4005 if (!PerlIOValid(n)) {
4006 PerlIOBase(f)->flags |= PERLIO_F_EOF;
4010 if (PerlIO_fast_gets(n)) {
4012 * Layer below is also buffered. We do _NOT_ want to call its
4013 * ->Read() because that will loop till it gets what we asked for
4014 * which may hang on a pipe etc. Instead take anything it has to
4015 * hand, or ask it to fill _once_.
4017 avail = PerlIO_get_cnt(n);
4019 avail = PerlIO_fill(n);
4021 avail = PerlIO_get_cnt(n);
4023 if (!PerlIO_error(n) && PerlIO_eof(n))
4028 STDCHAR *ptr = PerlIO_get_ptr(n);
4029 const SSize_t cnt = avail;
4030 if (avail > (SSize_t)b->bufsiz)
4032 Copy(ptr, b->buf, avail, STDCHAR);
4033 PerlIO_set_ptrcnt(n, ptr + avail, cnt - avail);
4037 avail = PerlIO_read(n, b->ptr, b->bufsiz);
4041 PerlIOBase(f)->flags |= PERLIO_F_EOF;
4043 PerlIOBase(f)->flags |= PERLIO_F_ERROR;
4046 b->end = b->buf + avail;
4047 PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
4052 PerlIOBuf_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
4054 if (PerlIOValid(f)) {
4055 const PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
4058 return PerlIOBase_read(aTHX_ f, vbuf, count);
4064 PerlIOBuf_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
4066 const STDCHAR *buf = (const STDCHAR *) vbuf + count;
4067 PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
4070 if (PerlIOBase(f)->flags & PERLIO_F_WRBUF)
4075 if (PerlIOBase(f)->flags & PERLIO_F_RDBUF) {
4077 * Buffer is already a read buffer, we can overwrite any chars
4078 * which have been read back to buffer start
4080 avail = (b->ptr - b->buf);
4084 * Buffer is idle, set it up so whole buffer is available for
4088 b->end = b->buf + avail;
4090 PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
4092 * Buffer extends _back_ from where we are now
4094 b->posn -= b->bufsiz;
4096 if ((SSize_t) count >= 0 && avail > (SSize_t) count) {
4098 * If we have space for more than count, just move count
4106 * In simple stdio-like ungetc() case chars will be already
4109 if (buf != b->ptr) {
4110 Copy(buf, b->ptr, avail, STDCHAR);
4114 PerlIOBase(f)->flags &= ~PERLIO_F_EOF;
4118 unread += PerlIOBase_unread(aTHX_ f, vbuf, count);
4124 PerlIOBuf_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
4126 PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
4127 const STDCHAR *buf = (const STDCHAR *) vbuf;
4128 const STDCHAR *flushptr = buf;
4132 if (!(PerlIOBase(f)->flags & PERLIO_F_CANWRITE))
4134 if (PerlIOBase(f)->flags & PERLIO_F_RDBUF) {
4135 if (PerlIO_flush(f) != 0) {
4139 if (PerlIOBase(f)->flags & PERLIO_F_LINEBUF) {
4140 flushptr = buf + count;
4141 while (flushptr > buf && *(flushptr - 1) != '\n')
4145 SSize_t avail = b->bufsiz - (b->ptr - b->buf);
4146 if ((SSize_t) count >= 0 && (SSize_t) count < avail)
4148 if (flushptr > buf && flushptr <= buf + avail)
4149 avail = flushptr - buf;
4150 PerlIOBase(f)->flags |= PERLIO_F_WRBUF;
4152 Copy(buf, b->ptr, avail, STDCHAR);
4157 if (buf == flushptr)
4160 if (b->ptr >= (b->buf + b->bufsiz))
4161 if (PerlIO_flush(f) == -1)
4164 if (PerlIOBase(f)->flags & PERLIO_F_UNBUF)
4170 PerlIOBuf_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
4173 if ((code = PerlIO_flush(f)) == 0) {
4174 PerlIOBase(f)->flags &= ~PERLIO_F_EOF;
4175 code = PerlIO_seek(PerlIONext(f), offset, whence);
4177 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
4178 b->posn = PerlIO_tell(PerlIONext(f));
4185 PerlIOBuf_tell(pTHX_ PerlIO *f)
4187 PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
4189 * b->posn is file position where b->buf was read, or will be written
4191 Off_t posn = b->posn;
4192 if ((PerlIOBase(f)->flags & PERLIO_F_APPEND) &&
4193 (PerlIOBase(f)->flags & PERLIO_F_WRBUF)) {
4195 /* As O_APPEND files are normally shared in some sense it is better
4200 /* when file is NOT shared then this is sufficient */
4201 PerlIO_seek(PerlIONext(f),0, SEEK_END);
4203 posn = b->posn = PerlIO_tell(PerlIONext(f));
4207 * If buffer is valid adjust position by amount in buffer
4209 posn += (b->ptr - b->buf);
4215 PerlIOBuf_popped(pTHX_ PerlIO *f)
4217 const IV code = PerlIOBase_popped(aTHX_ f);
4218 PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
4219 if (b->buf && b->buf != (STDCHAR *) & b->oneword) {
4222 b->ptr = b->end = b->buf = NULL;
4223 PerlIOBase(f)->flags &= ~(PERLIO_F_RDBUF | PERLIO_F_WRBUF);
4228 PerlIOBuf_close(pTHX_ PerlIO *f)
4230 const IV code = PerlIOBase_close(aTHX_ f);
4231 PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
4232 if (b->buf && b->buf != (STDCHAR *) & b->oneword) {
4235 b->ptr = b->end = b->buf = NULL;
4236 PerlIOBase(f)->flags &= ~(PERLIO_F_RDBUF | PERLIO_F_WRBUF);
4241 PerlIOBuf_get_ptr(pTHX_ PerlIO *f)
4243 const PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
4250 PerlIOBuf_get_cnt(pTHX_ PerlIO *f)
4252 const PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
4255 if (PerlIOBase(f)->flags & PERLIO_F_RDBUF)
4256 return (b->end - b->ptr);
4261 PerlIOBuf_get_base(pTHX_ PerlIO *f)
4263 PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
4264 PERL_UNUSED_CONTEXT;
4268 b->bufsiz = PERLIOBUF_DEFAULT_BUFSIZ;
4269 Newxz(b->buf,b->bufsiz, STDCHAR);
4271 b->buf = (STDCHAR *) & b->oneword;
4272 b->bufsiz = sizeof(b->oneword);
4274 b->end = b->ptr = b->buf;
4280 PerlIOBuf_bufsiz(pTHX_ PerlIO *f)
4282 const PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
4285 return (b->end - b->buf);
4289 PerlIOBuf_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, SSize_t cnt)
4291 PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
4293 PERL_UNUSED_ARG(cnt);
4298 assert(PerlIO_get_cnt(f) == cnt);
4299 assert(b->ptr >= b->buf);
4300 PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
4304 PerlIOBuf_dup(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags)
4306 return PerlIOBase_dup(aTHX_ f, o, param, flags);
4311 PERLIO_FUNCS_DECL(PerlIO_perlio) = {
4312 sizeof(PerlIO_funcs),
4315 PERLIO_K_BUFFERED|PERLIO_K_RAW,
4319 PerlIOBase_binmode, /* binmode */
4333 PerlIOBase_clearerr,
4334 PerlIOBase_setlinebuf,
4339 PerlIOBuf_set_ptrcnt,
4342 /*--------------------------------------------------------------------------------------*/
4344 * Temp layer to hold unread chars when cannot do it any other way
4348 PerlIOPending_fill(pTHX_ PerlIO *f)
4351 * Should never happen
4358 PerlIOPending_close(pTHX_ PerlIO *f)
4361 * A tad tricky - flush pops us, then we close new top
4364 return PerlIO_close(f);
4368 PerlIOPending_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
4371 * A tad tricky - flush pops us, then we seek new top
4374 return PerlIO_seek(f, offset, whence);
4379 PerlIOPending_flush(pTHX_ PerlIO *f)
4381 PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
4382 if (b->buf && b->buf != (STDCHAR *) & b->oneword) {
4386 PerlIO_pop(aTHX_ f);
4391 PerlIOPending_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, SSize_t cnt)
4397 PerlIOBuf_set_ptrcnt(aTHX_ f, ptr, cnt);
4402 PerlIOPending_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
4404 const IV code = PerlIOBase_pushed(aTHX_ f, mode, arg, tab);
4405 PerlIOl * const l = PerlIOBase(f);
4407 * Our PerlIO_fast_gets must match what we are pushed on, or sv_gets()
4408 * etc. get muddled when it changes mid-string when we auto-pop.
4410 l->flags = (l->flags & ~(PERLIO_F_FASTGETS | PERLIO_F_UTF8)) |
4411 (PerlIOBase(PerlIONext(f))->
4412 flags & (PERLIO_F_FASTGETS | PERLIO_F_UTF8));
4417 PerlIOPending_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
4419 SSize_t avail = PerlIO_get_cnt(f);
4421 if ((SSize_t) count >= 0 && (SSize_t)count < avail)
4424 got = PerlIOBuf_read(aTHX_ f, vbuf, avail);
4425 if (got >= 0 && got < (SSize_t)count) {
4426 const SSize_t more =
4427 PerlIO_read(f, ((STDCHAR *) vbuf) + got, count - got);
4428 if (more >= 0 || got == 0)
4434 PERLIO_FUNCS_DECL(PerlIO_pending) = {
4435 sizeof(PerlIO_funcs),
4438 PERLIO_K_BUFFERED|PERLIO_K_RAW, /* not sure about RAW here */
4439 PerlIOPending_pushed,
4442 PerlIOBase_binmode, /* binmode */
4451 PerlIOPending_close,
4452 PerlIOPending_flush,
4456 PerlIOBase_clearerr,
4457 PerlIOBase_setlinebuf,
4462 PerlIOPending_set_ptrcnt,
4467 /*--------------------------------------------------------------------------------------*/
4469 * crlf - translation On read translate CR,LF to "\n" we do this by
4470 * overriding ptr/cnt entries to hand back a line at a time and keeping a
4471 * record of which nl we "lied" about. On write translate "\n" to CR,LF
4473 * c->nl points on the first byte of CR LF pair when it is temporarily
4474 * replaced by LF, or to the last CR of the buffer. In the former case
4475 * the caller thinks that the buffer ends at c->nl + 1, in the latter
4476 * that it ends at c->nl; these two cases can be distinguished by
4477 * *c->nl. c->nl is set during _getcnt() call, and unset during
4478 * _unread() and _flush() calls.
4479 * It only matters for read operations.
4483 PerlIOBuf base; /* PerlIOBuf stuff */
4484 STDCHAR *nl; /* Position of crlf we "lied" about in the
4488 /* Inherit the PERLIO_F_UTF8 flag from previous layer.
4489 * Otherwise the :crlf layer would always revert back to
4493 S_inherit_utf8_flag(PerlIO *f)
4495 PerlIO *g = PerlIONext(f);
4496 if (PerlIOValid(g)) {
4497 if (PerlIOBase(g)->flags & PERLIO_F_UTF8) {
4498 PerlIOBase(f)->flags |= PERLIO_F_UTF8;
4504 PerlIOCrlf_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
4507 PerlIOBase(f)->flags |= PERLIO_F_CRLF;
4508 code = PerlIOBuf_pushed(aTHX_ f, mode, arg, tab);
4510 PerlIO_debug("PerlIOCrlf_pushed f=%p %s %s fl=%08" UVxf "\n",
4511 (void*)f, PerlIOBase(f)->tab->name, (mode) ? mode : "(Null)",
4512 PerlIOBase(f)->flags);
4515 /* If the old top layer is a CRLF layer, reactivate it (if
4516 * necessary) and remove this new layer from the stack */
4517 PerlIO *g = PerlIONext(f);
4518 if (PerlIOValid(g)) {
4519 PerlIOl *b = PerlIOBase(g);
4520 if (b && b->tab == &PerlIO_crlf) {
4521 if (!(b->flags & PERLIO_F_CRLF))
4522 b->flags |= PERLIO_F_CRLF;
4523 S_inherit_utf8_flag(g);
4524 PerlIO_pop(aTHX_ f);
4529 S_inherit_utf8_flag(f);
4535 PerlIOCrlf_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
4537 PerlIOCrlf * const c = PerlIOSelf(f, PerlIOCrlf);
4538 if (c->nl) { /* XXXX Shouldn't it be done only if b->ptr > c->nl? */
4539 *(c->nl) = NATIVE_0xd;
4542 if (!(PerlIOBase(f)->flags & PERLIO_F_CRLF))
4543 return PerlIOBuf_unread(aTHX_ f, vbuf, count);
4545 const STDCHAR *buf = (const STDCHAR *) vbuf + count;
4546 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
4548 if (PerlIOBase(f)->flags & PERLIO_F_WRBUF)
4553 if (!(PerlIOBase(f)->flags & PERLIO_F_RDBUF)) {
4554 b->end = b->ptr = b->buf + b->bufsiz;
4555 PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
4556 b->posn -= b->bufsiz;
4558 while (count > 0 && b->ptr > b->buf) {
4559 const int ch = *--buf;
4561 if (b->ptr - 2 >= b->buf) {
4562 *--(b->ptr) = NATIVE_0xa;
4563 *--(b->ptr) = NATIVE_0xd;
4568 /* If b->ptr - 1 == b->buf, we are undoing reading 0xa */
4569 *--(b->ptr) = NATIVE_0xa; /* Works even if 0xa ==
4583 unread += PerlIOBase_unread(aTHX_ f, (const STDCHAR *) vbuf + unread, count);
4588 /* XXXX This code assumes that buffer size >=2, but does not check it... */
4590 PerlIOCrlf_get_cnt(pTHX_ PerlIO *f)
4592 PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
4595 if (PerlIOBase(f)->flags & PERLIO_F_RDBUF) {
4596 PerlIOCrlf * const c = PerlIOSelf(f, PerlIOCrlf);
4597 if ((PerlIOBase(f)->flags & PERLIO_F_CRLF) && (!c->nl || *c->nl == NATIVE_0xd)) {
4598 STDCHAR *nl = (c->nl) ? c->nl : b->ptr;
4600 while (nl < b->end && *nl != NATIVE_0xd)
4602 if (nl < b->end && *nl == NATIVE_0xd) {
4604 if (nl + 1 < b->end) {
4605 if (nl[1] == NATIVE_0xa) {
4611 * Not CR,LF but just CR
4619 * Blast - found CR as last char in buffer
4624 * They may not care, defer work as long as
4628 return (nl - b->ptr);
4632 b->ptr++; /* say we have read it as far as
4633 * flush() is concerned */
4634 b->buf++; /* Leave space in front of buffer */
4635 /* Note as we have moved buf up flush's
4637 will naturally make posn point at CR
4639 b->bufsiz--; /* Buffer is thus smaller */
4640 code = PerlIO_fill(f); /* Fetch some more */
4641 b->bufsiz++; /* Restore size for next time */
4642 b->buf--; /* Point at space */
4643 b->ptr = nl = b->buf; /* Which is what we hand
4645 *nl = NATIVE_0xd; /* Fill in the CR */
4647 goto test; /* fill() call worked */
4649 * CR at EOF - just fall through
4651 /* Should we clear EOF though ??? */
4656 return (((c->nl) ? (c->nl + 1) : b->end) - b->ptr);
4662 PerlIOCrlf_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, SSize_t cnt)
4664 PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
4665 PerlIOCrlf * const c = PerlIOSelf(f, PerlIOCrlf);
4671 if (ptr == b->end && *c->nl == NATIVE_0xd) {
4672 /* Deferred CR at end of buffer case - we lied about count */
4685 * Test code - delete when it works ...
4687 IV flags = PerlIOBase(f)->flags;
4688 STDCHAR *chk = (c->nl) ? (c->nl+1) : b->end;
4689 if (ptr+cnt == c->nl && c->nl+1 == b->end && *c->nl == NATIVE_0xd) {
4690 /* Deferred CR at end of buffer case - we lied about count */
4696 Perl_croak(aTHX_ "ptr wrong %p != %p fl=%08" UVxf
4697 " nl=%p e=%p for %d", (void*)ptr, (void*)chk,
4698 flags, c->nl, b->end, cnt);
4705 * They have taken what we lied about
4707 *(c->nl) = NATIVE_0xd;
4713 PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
4717 PerlIOCrlf_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
4719 if (!(PerlIOBase(f)->flags & PERLIO_F_CRLF))
4720 return PerlIOBuf_write(aTHX_ f, vbuf, count);
4722 PerlIOBuf * const b = PerlIOSelf(f, PerlIOBuf);
4723 const STDCHAR *buf = (const STDCHAR *) vbuf;
4724 const STDCHAR * const ebuf = buf + count;
4727 if (!(PerlIOBase(f)->flags & PERLIO_F_CANWRITE))
4729 while (buf < ebuf) {
4730 const STDCHAR * const eptr = b->buf + b->bufsiz;
4731 PerlIOBase(f)->flags |= PERLIO_F_WRBUF;
4732 while (buf < ebuf && b->ptr < eptr) {
4734 if ((b->ptr + 2) > eptr) {
4742 *(b->ptr)++ = NATIVE_0xd; /* CR */
4743 *(b->ptr)++ = NATIVE_0xa; /* LF */
4745 if (PerlIOBase(f)->flags & PERLIO_F_LINEBUF) {
4752 *(b->ptr)++ = *buf++;
4754 if (b->ptr >= eptr) {
4760 if (PerlIOBase(f)->flags & PERLIO_F_UNBUF)
4762 return (buf - (STDCHAR *) vbuf);
4767 PerlIOCrlf_flush(pTHX_ PerlIO *f)
4769 PerlIOCrlf * const c = PerlIOSelf(f, PerlIOCrlf);
4771 *(c->nl) = NATIVE_0xd;
4774 return PerlIOBuf_flush(aTHX_ f);
4778 PerlIOCrlf_binmode(pTHX_ PerlIO *f)
4780 if ((PerlIOBase(f)->flags & PERLIO_F_CRLF)) {
4781 /* In text mode - flush any pending stuff and flip it */
4782 PerlIOBase(f)->flags &= ~PERLIO_F_CRLF;
4783 #ifndef PERLIO_USING_CRLF
4784 /* CRLF is unusual case - if this is just the :crlf layer pop it */
4785 PerlIO_pop(aTHX_ f);
4791 PERLIO_FUNCS_DECL(PerlIO_crlf) = {
4792 sizeof(PerlIO_funcs),
4795 PERLIO_K_BUFFERED | PERLIO_K_CANCRLF | PERLIO_K_RAW,
4797 PerlIOBuf_popped, /* popped */
4799 PerlIOCrlf_binmode, /* binmode */
4803 PerlIOBuf_read, /* generic read works with ptr/cnt lies */
4804 PerlIOCrlf_unread, /* Put CR,LF in buffer for each '\n' */
4805 PerlIOCrlf_write, /* Put CR,LF in buffer for each '\n' */
4813 PerlIOBase_clearerr,
4814 PerlIOBase_setlinebuf,
4819 PerlIOCrlf_set_ptrcnt,
4823 Perl_PerlIO_stdin(pTHX)
4827 PerlIO_stdstreams(aTHX);
4829 return (PerlIO*)&PL_perlio[1];
4833 Perl_PerlIO_stdout(pTHX)
4837 PerlIO_stdstreams(aTHX);
4839 return (PerlIO*)&PL_perlio[2];
4843 Perl_PerlIO_stderr(pTHX)
4847 PerlIO_stdstreams(aTHX);
4849 return (PerlIO*)&PL_perlio[3];
4852 /*--------------------------------------------------------------------------------------*/
4855 PerlIO_getname(PerlIO *f, char *buf)
4860 bool exported = FALSE;
4861 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
4863 stdio = PerlIO_exportFILE(f,0);
4867 name = fgetname(stdio, buf);
4868 if (exported) PerlIO_releaseFILE(f,stdio);
4873 PERL_UNUSED_ARG(buf);
4874 Perl_croak_nocontext("Don't know how to get file name");
4880 /*--------------------------------------------------------------------------------------*/
4882 * Functions which can be called on any kind of PerlIO implemented in
4886 #undef PerlIO_fdopen
4888 PerlIO_fdopen(int fd, const char *mode)
4891 return PerlIO_openn(aTHX_ NULL, mode, fd, 0, 0, NULL, 0, NULL);
4896 PerlIO_open(const char *path, const char *mode)
4899 SV *name = sv_2mortal(newSVpv(path, 0));
4900 return PerlIO_openn(aTHX_ NULL, mode, -1, 0, 0, NULL, 1, &name);
4903 #undef Perlio_reopen
4905 PerlIO_reopen(const char *path, const char *mode, PerlIO *f)
4908 SV *name = sv_2mortal(newSVpv(path,0));
4909 return PerlIO_openn(aTHX_ NULL, mode, -1, 0, 0, f, 1, &name);
4914 PerlIO_getc(PerlIO *f)
4918 if ( 1 == PerlIO_read(f, buf, 1) ) {
4919 return (unsigned char) buf[0];
4924 #undef PerlIO_ungetc
4926 PerlIO_ungetc(PerlIO *f, int ch)
4931 if (PerlIO_unread(f, &buf, 1) == 1)
4939 PerlIO_putc(PerlIO *f, int ch)
4943 return PerlIO_write(f, &buf, 1);
4948 PerlIO_puts(PerlIO *f, const char *s)
4951 return PerlIO_write(f, s, strlen(s));
4954 #undef PerlIO_rewind
4956 PerlIO_rewind(PerlIO *f)
4959 PerlIO_seek(f, (Off_t) 0, SEEK_SET);
4963 #undef PerlIO_vprintf
4965 PerlIO_vprintf(PerlIO *f, const char *fmt, va_list ap)
4974 Perl_va_copy(ap, apc);
4975 sv = vnewSVpvf(fmt, &apc);
4977 sv = vnewSVpvf(fmt, &ap);
4979 s = SvPV_const(sv, len);
4980 wrote = PerlIO_write(f, s, len);
4985 #undef PerlIO_printf
4987 PerlIO_printf(PerlIO *f, const char *fmt, ...)
4992 result = PerlIO_vprintf(f, fmt, ap);
4997 #undef PerlIO_stdoutf
4999 PerlIO_stdoutf(const char *fmt, ...)
5005 result = PerlIO_vprintf(PerlIO_stdout(), fmt, ap);
5010 #undef PerlIO_tmpfile
5012 PerlIO_tmpfile(void)
5019 const int fd = win32_tmpfd();
5021 f = PerlIO_fdopen(fd, "w+b");
5023 # if defined(HAS_MKSTEMP) && ! defined(VMS) && ! defined(OS2)
5025 char tempname[] = "/tmp/PerlIO_XXXXXX";
5026 const char * const tmpdir = TAINTING_get ? NULL : PerlEnv_getenv("TMPDIR");
5029 * I have no idea how portable mkstemp() is ... NI-S
5031 if (tmpdir && *tmpdir) {
5032 /* if TMPDIR is set and not empty, we try that first */
5033 sv = newSVpv(tmpdir, 0);
5034 sv_catpv(sv, tempname + 4);
5035 fd = mkstemp(SvPVX(sv));
5039 /* else we try /tmp */
5040 fd = mkstemp(tempname);
5043 f = PerlIO_fdopen(fd, "w+");
5045 PerlIOBase(f)->flags |= PERLIO_F_TEMP;
5046 PerlLIO_unlink(sv ? SvPVX_const(sv) : tempname);
5049 # else /* !HAS_MKSTEMP, fallback to stdio tmpfile(). */
5050 FILE * const stdio = PerlSIO_tmpfile();
5053 f = PerlIO_fdopen(fileno(stdio), "w+");
5055 # endif /* else HAS_MKSTEMP */
5056 #endif /* else WIN32 */
5063 #endif /* USE_SFIO */
5064 #endif /* PERLIO_IS_STDIO */
5066 /*======================================================================================*/
5068 * Now some functions in terms of above which may be needed even if we are
5069 * not in true PerlIO mode
5072 Perl_PerlIO_context_layers(pTHX_ const char *mode)
5075 const char *direction = NULL;
5078 * Need to supply default layer info from open.pm
5084 if (mode && mode[0] != 'r') {
5085 if (PL_curcop->cop_hints & HINT_LEXICAL_IO_OUT)
5086 direction = "open>";
5088 if (PL_curcop->cop_hints & HINT_LEXICAL_IO_IN)
5089 direction = "open<";
5094 layers = cop_hints_fetch_pvn(PL_curcop, direction, 5, 0, 0);
5097 return SvOK(layers) ? SvPV_nolen_const(layers) : NULL;
5102 #undef PerlIO_setpos
5104 PerlIO_setpos(PerlIO *f, SV *pos)
5109 const Off_t * const posn = (Off_t *) SvPV(pos, len);
5110 if (f && len == sizeof(Off_t))
5111 return PerlIO_seek(f, *posn, SEEK_SET);
5113 SETERRNO(EINVAL, SS_IVCHAN);
5117 #undef PerlIO_setpos
5119 PerlIO_setpos(PerlIO *f, SV *pos)
5124 Fpos_t * const fpos = (Fpos_t *) SvPV(pos, len);
5125 if (f && len == sizeof(Fpos_t)) {
5126 #if defined(USE_64_BIT_STDIO) && defined(USE_FSETPOS64)
5127 return fsetpos64(f, fpos);
5129 return fsetpos(f, fpos);
5133 SETERRNO(EINVAL, SS_IVCHAN);
5139 #undef PerlIO_getpos
5141 PerlIO_getpos(PerlIO *f, SV *pos)
5144 Off_t posn = PerlIO_tell(f);
5145 sv_setpvn(pos, (char *) &posn, sizeof(posn));
5146 return (posn == (Off_t) - 1) ? -1 : 0;
5149 #undef PerlIO_getpos
5151 PerlIO_getpos(PerlIO *f, SV *pos)
5156 #if defined(USE_64_BIT_STDIO) && defined(USE_FSETPOS64)
5157 code = fgetpos64(f, &fpos);
5159 code = fgetpos(f, &fpos);
5161 sv_setpvn(pos, (char *) &fpos, sizeof(fpos));
5166 #if (defined(PERLIO_IS_STDIO) || !defined(USE_SFIO)) && !defined(HAS_VPRINTF)
5169 vprintf(char *pat, char *args)
5171 _doprnt(pat, args, stdout);
5172 return 0; /* wrong, but perl doesn't use the return
5177 vfprintf(FILE *fd, char *pat, char *args)
5179 _doprnt(pat, args, fd);
5180 return 0; /* wrong, but perl doesn't use the return
5186 #ifndef PerlIO_vsprintf
5188 PerlIO_vsprintf(char *s, int n, const char *fmt, va_list ap)
5191 const int val = my_vsnprintf(s, n > 0 ? n : 0, fmt, ap);
5192 PERL_UNUSED_CONTEXT;
5194 #ifndef PERL_MY_VSNPRINTF_GUARDED
5195 if (val < 0 || (n > 0 ? val >= n : 0)) {
5196 Perl_croak(aTHX_ "panic: my_vsnprintf overflow in PerlIO_vsprintf\n");
5203 #ifndef PerlIO_sprintf
5205 PerlIO_sprintf(char *s, int n, const char *fmt, ...)
5210 result = PerlIO_vsprintf(s, n, fmt, ap);
5218 * c-indentation-style: bsd
5220 * indent-tabs-mode: nil
5223 * ex: set ts=8 sts=4 sw=4 et: