2 * perlio.c Copyright (c) 1996-2002, Nick Ing-Simmons You may distribute
3 * under the terms of either the GNU General Public License or the
4 * Artistic License, as specified in the README file.
8 * Hour after hour for nearly three weary days he had jogged up and down,
9 * over passes, and through long dales, and across many streams.
13 * If we have ActivePerl-like PERL_IMPLICIT_SYS then we need a dTHX to get
14 * at the dispatch tables, even when we do not need it for other reasons.
15 * Invent a dSYS macro to abstract this out
17 #ifdef PERL_IMPLICIT_SYS
30 #define PERLIO_NOT_STDIO 0
31 #if !defined(PERLIO_IS_STDIO) && !defined(USE_SFIO)
37 * This file provides those parts of PerlIO abstraction
38 * which are not #defined in perlio.h.
39 * Which these are depends on various Configure #ifdef's
43 #define PERL_IN_PERLIO_C
46 #ifdef PERL_IMPLICIT_CONTEXT
54 perlsio_binmode(FILE *fp, int iotype, int mode)
57 * This used to be contents of do_binmode in doio.c
60 # if defined(atarist) || defined(__MINT__)
63 ((FILE *) fp)->_flag |= _IOBIN;
65 ((FILE *) fp)->_flag &= ~_IOBIN;
72 if (PerlLIO_setmode(fp, mode) != -1) {
74 if (PerlLIO_setmode(fileno(fp), mode) != -1) {
76 # if defined(WIN32) && defined(__BORLANDC__)
78 * The translation mode of the stream is maintained independent of
79 * the translation mode of the fd in the Borland RTL (heavy
80 * digging through their runtime sources reveal). User has to set
81 * the mode explicitly for the stream (though they don't document
82 * this anywhere). GSAR 97-5-24
96 # if defined(USEMYBINMODE)
98 if (my_binmode(fp, iotype, mode) != FALSE)
109 #define O_ACCMODE 3 /* Assume traditional implementation */
113 PerlIO_intmode2str(int rawmode, char *mode, int *writing)
115 int result = rawmode & O_ACCMODE;
120 ptype = IoTYPE_RDONLY;
123 ptype = IoTYPE_WRONLY;
131 *writing = (result != O_RDONLY);
133 if (result == O_RDONLY) {
137 else if (rawmode & O_APPEND) {
139 if (result != O_WRONLY)
144 if (result == O_WRONLY)
151 if (rawmode & O_BINARY)
157 #ifndef PERLIO_LAYERS
159 PerlIO_apply_layers(pTHX_ PerlIO *f, const char *mode, const char *names)
161 if (!names || !*names
162 || strEQ(names, ":crlf")
163 || strEQ(names, ":raw")
164 || strEQ(names, ":bytes")
168 Perl_croak(aTHX_ "Cannot apply \"%s\" in non-PerlIO perl", names);
176 PerlIO_destruct(pTHX)
181 PerlIO_binmode(pTHX_ PerlIO *fp, int iotype, int mode, const char *names)
186 return perlsio_binmode(fp, iotype, mode);
191 PerlIO_fdupopen(pTHX_ PerlIO *f, CLONE_PARAMS *param, int flags)
196 #ifdef PERL_IMPLICIT_SYS
197 return PerlSIO_fdupopen(f);
200 return win32_fdupopen(f);
203 int fd = PerlLIO_dup(PerlIO_fileno(f));
206 int omode = fcntl(fd, F_GETFL);
208 omode = djgpp_get_stream_mode(f);
210 PerlIO_intmode2str(omode,mode,NULL);
211 /* the r+ is a hack */
212 return PerlIO_fdopen(fd, mode);
217 SETERRNO(EBADF, SS_IVCHAN);
227 * De-mux PerlIO_openn() into fdopen, freopen and fopen type entries
231 PerlIO_openn(pTHX_ const char *layers, const char *mode, int fd,
232 int imode, int perm, PerlIO *old, int narg, SV **args)
236 Perl_croak(aTHX_ "More than one argument to open");
238 if (*args == &PL_sv_undef)
239 return PerlIO_tmpfile();
241 char *name = SvPV_nolen(*args);
243 fd = PerlLIO_open3(name, imode, perm);
245 return PerlIO_fdopen(fd, (char *) mode + 1);
248 return PerlIO_reopen(name, mode, old);
251 return PerlIO_open(name, mode);
256 return PerlIO_fdopen(fd, (char *) mode);
261 XS(XS_PerlIO__Layer__find)
265 Perl_croak(aTHX_ "Usage class->find(name[,load])");
267 char *name = SvPV_nolen(ST(1));
268 ST(0) = (strEQ(name, "crlf")
269 || strEQ(name, "raw")) ? &PL_sv_yes : &PL_sv_undef;
276 Perl_boot_core_PerlIO(pTHX)
278 newXS("PerlIO::Layer::find", XS_PerlIO__Layer__find, __FILE__);
284 #ifdef PERLIO_IS_STDIO
290 * Does nothing (yet) except force this file to be included in perl
291 * binary. That allows this file to force inclusion of other functions
292 * that may be required by loadable extensions e.g. for
293 * FileHandle::tmpfile
297 #undef PerlIO_tmpfile
304 #else /* PERLIO_IS_STDIO */
312 * This section is just to make sure these functions get pulled in from
316 #undef PerlIO_tmpfile
327 * Force this file to be included in perl binary. Which allows this
328 * file to force inclusion of other functions that may be required by
329 * loadable extensions e.g. for FileHandle::tmpfile
333 * Hack sfio does its own 'autoflush' on stdout in common cases. Flush
334 * results in a lot of lseek()s to regular files and lot of small
337 sfset(sfstdout, SF_SHARE, 0);
340 /* This is not the reverse of PerlIO_exportFILE(), PerlIO_releaseFILE() is. */
342 PerlIO_importFILE(FILE *stdio, const char *mode)
344 int fd = fileno(stdio);
345 if (!mode || !*mode) {
348 return PerlIO_fdopen(fd, mode);
352 PerlIO_findFILE(PerlIO *pio)
354 int fd = PerlIO_fileno(pio);
355 FILE *f = fdopen(fd, "r+");
357 if (!f && errno == EINVAL)
359 if (!f && errno == EINVAL)
366 /*======================================================================================*/
368 * Implement all the PerlIO interface ourselves.
374 * We _MUST_ have <unistd.h> if we are using lseek() and may have large
381 #include <sys/mman.h>
385 void PerlIO_debug(const char *fmt, ...)
386 __attribute__ ((format(__printf__, 1, 2)));
389 PerlIO_debug(const char *fmt, ...)
396 char *s = PerlEnv_getenv("PERLIO_DEBUG");
398 dbg = PerlLIO_open3(s, O_WRONLY | O_CREAT | O_APPEND, 0666);
405 /* Use fixed buffer as sv_catpvf etc. needs SVs */
409 s = CopFILE(PL_curcop);
412 sprintf(buffer, "%s:%" IVdf " ", s, (IV) CopLINE(PL_curcop));
413 len = strlen(buffer);
414 vsprintf(buffer+len, fmt, ap);
415 PerlLIO_write(dbg, buffer, strlen(buffer));
417 SV *sv = newSVpvn("", 0);
420 s = CopFILE(PL_curcop);
423 Perl_sv_catpvf(aTHX_ sv, "%s:%" IVdf " ", s,
424 (IV) CopLINE(PL_curcop));
425 Perl_sv_vcatpvf(aTHX_ sv, fmt, &ap);
428 PerlLIO_write(dbg, s, len);
435 /*--------------------------------------------------------------------------------------*/
438 * Inner level routines
442 * Table of pointers to the PerlIO structs (malloc'ed)
444 #define PERLIO_TABLE_SIZE 64
447 PerlIO_allocate(pTHX)
450 * Find a free slot in the table, allocating new table as necessary
455 while ((f = *last)) {
457 last = (PerlIO **) (f);
458 for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
464 Newz('I',f,PERLIO_TABLE_SIZE,PerlIO);
472 #undef PerlIO_fdupopen
474 PerlIO_fdupopen(pTHX_ PerlIO *f, CLONE_PARAMS *param, int flags)
476 if (PerlIOValid(f)) {
477 PerlIO_funcs *tab = PerlIOBase(f)->tab;
479 PerlIO_debug("fdupopen f=%p param=%p\n",(void*)f,(void*)param);
480 new = (*tab->Dup)(aTHX_ PerlIO_allocate(aTHX),f,param, flags);
484 SETERRNO(EBADF, SS_IVCHAN);
490 PerlIO_cleantable(pTHX_ PerlIO **tablep)
492 PerlIO *table = *tablep;
495 PerlIO_cleantable(aTHX_(PerlIO **) & (table[0]));
496 for (i = PERLIO_TABLE_SIZE - 1; i > 0; i--) {
497 PerlIO *f = table + i;
509 PerlIO_list_alloc(pTHX)
512 Newz('L', list, 1, PerlIO_list_t);
518 PerlIO_list_free(pTHX_ PerlIO_list_t *list)
521 if (--list->refcnt == 0) {
524 for (i = 0; i < list->cur; i++) {
525 if (list->array[i].arg)
526 SvREFCNT_dec(list->array[i].arg);
528 Safefree(list->array);
536 PerlIO_list_push(pTHX_ PerlIO_list_t *list, PerlIO_funcs *funcs, SV *arg)
539 if (list->cur >= list->len) {
542 Renew(list->array, list->len, PerlIO_pair_t);
544 New('l', list->array, list->len, PerlIO_pair_t);
546 p = &(list->array[list->cur++]);
548 if ((p->arg = arg)) {
554 PerlIO_clone_list(pTHX_ PerlIO_list_t *proto, CLONE_PARAMS *param)
556 PerlIO_list_t *list = (PerlIO_list_t *) NULL;
559 list = PerlIO_list_alloc(aTHX);
560 for (i=0; i < proto->cur; i++) {
562 if (proto->array[i].arg)
563 arg = PerlIO_sv_dup(aTHX_ proto->array[i].arg,param);
564 PerlIO_list_push(aTHX_ list, proto->array[i].funcs, arg);
571 PerlIO_clone(pTHX_ PerlInterpreter *proto, CLONE_PARAMS *param)
574 PerlIO **table = &proto->Iperlio;
577 PL_known_layers = PerlIO_clone_list(aTHX_ proto->Iknown_layers, param);
578 PL_def_layerlist = PerlIO_clone_list(aTHX_ proto->Idef_layerlist, param);
579 PerlIO_allocate(aTHX); /* root slot is never used */
580 PerlIO_debug("Clone %p from %p\n",aTHX,proto);
581 while ((f = *table)) {
583 table = (PerlIO **) (f++);
584 for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
586 (void) fp_dup(f, 0, param);
595 PerlIO_destruct(pTHX)
597 PerlIO **table = &PL_perlio;
600 PerlIO_debug("Destruct %p\n",aTHX);
602 while ((f = *table)) {
604 table = (PerlIO **) (f++);
605 for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
609 if (l->tab->kind & PERLIO_K_DESTRUCT) {
610 PerlIO_debug("Destruct popping %s\n", l->tab->name);
624 PerlIO_pop(pTHX_ PerlIO *f)
628 PerlIO_debug("PerlIO_pop f=%p %s\n", (void*)f, l->tab->name);
629 if (l->tab->Popped) {
631 * If popped returns non-zero do not free its layer structure
632 * it has either done so itself, or it is shared and still in
635 if ((*l->tab->Popped) (aTHX_ f) != 0)
643 /* Return as an array the stack of layers on a filehandle. Note that
644 * the stack is returned top-first in the array, and there are three
645 * times as many array elements as there are layers in the stack: the
646 * first element of a layer triplet is the name, the second one is the
647 * arguments, and the third one is the flags. */
650 PerlIO_get_layers(pTHX_ PerlIO *f)
654 if (PerlIOValid(f)) {
656 PerlIOl *l = PerlIOBase(f);
659 SV *name = l->tab && l->tab->name ?
660 newSVpv(l->tab->name, 0) : &PL_sv_undef;
661 SV *arg = l->tab && l->tab->Getarg ?
662 (*l->tab->Getarg)(aTHX_ &l, 0, 0) : &PL_sv_undef;
665 av_push(av, newSViv((IV)l->flags));
673 /*--------------------------------------------------------------------------------------*/
675 * XS Interface for perl code
679 PerlIO_find_layer(pTHX_ const char *name, STRLEN len, int load)
682 if ((SSize_t) len <= 0)
684 for (i = 0; i < PL_known_layers->cur; i++) {
685 PerlIO_funcs *f = PL_known_layers->array[i].funcs;
686 if (memEQ(f->name, name, len)) {
687 PerlIO_debug("%.*s => %p\n", (int) len, name, (void*)f);
691 if (load && PL_subname && PL_def_layerlist
692 && PL_def_layerlist->cur >= 2) {
693 if (PL_in_load_module) {
694 Perl_croak(aTHX_ "Recursive call to Perl_load_module in PerlIO_find_layer");
697 SV *pkgsv = newSVpvn("PerlIO", 6);
698 SV *layer = newSVpvn(name, len);
699 CV *cv = get_cv("PerlIO::Layer::NoWarnings", FALSE);
701 SAVEINT(PL_in_load_module);
703 SAVESPTR(PL_warnhook);
704 PL_warnhook = (SV *) cv;
708 * The two SVs are magically freed by load_module
710 Perl_load_module(aTHX_ 0, pkgsv, Nullsv, layer, Nullsv);
713 return PerlIO_find_layer(aTHX_ name, len, 0);
716 PerlIO_debug("Cannot find %.*s\n", (int) len, name);
720 #ifdef USE_ATTRIBUTES_FOR_PERLIO
723 perlio_mg_set(pTHX_ SV *sv, MAGIC *mg)
726 IO *io = GvIOn((GV *) SvRV(sv));
727 PerlIO *ifp = IoIFP(io);
728 PerlIO *ofp = IoOFP(io);
729 Perl_warn(aTHX_ "set %" SVf " %p %p %p", sv, io, ifp, ofp);
735 perlio_mg_get(pTHX_ SV *sv, MAGIC *mg)
738 IO *io = GvIOn((GV *) SvRV(sv));
739 PerlIO *ifp = IoIFP(io);
740 PerlIO *ofp = IoOFP(io);
741 Perl_warn(aTHX_ "get %" SVf " %p %p %p", sv, io, ifp, ofp);
747 perlio_mg_clear(pTHX_ SV *sv, MAGIC *mg)
749 Perl_warn(aTHX_ "clear %" SVf, sv);
754 perlio_mg_free(pTHX_ SV *sv, MAGIC *mg)
756 Perl_warn(aTHX_ "free %" SVf, sv);
760 MGVTBL perlio_vtab = {
768 XS(XS_io_MODIFY_SCALAR_ATTRIBUTES)
771 SV *sv = SvRV(ST(1));
776 sv_magic(sv, (SV *) av, PERL_MAGIC_ext, NULL, 0);
778 mg = mg_find(sv, PERL_MAGIC_ext);
779 mg->mg_virtual = &perlio_vtab;
781 Perl_warn(aTHX_ "attrib %" SVf, sv);
782 for (i = 2; i < items; i++) {
784 const char *name = SvPV(ST(i), len);
785 SV *layer = PerlIO_find_layer(aTHX_ name, len, 1);
787 av_push(av, SvREFCNT_inc(layer));
798 #endif /* USE_ATTIBUTES_FOR_PERLIO */
801 PerlIO_tab_sv(pTHX_ PerlIO_funcs *tab)
803 HV *stash = gv_stashpv("PerlIO::Layer", TRUE);
804 SV *sv = sv_bless(newRV_noinc(newSViv(PTR2IV(tab))), stash);
808 XS(XS_PerlIO__Layer__NoWarnings)
810 /* This is used as a %SIG{__WARN__} handler to supress warnings
811 during loading of layers.
815 PerlIO_debug("warning:%s\n",SvPV_nolen(ST(0)));
819 XS(XS_PerlIO__Layer__find)
823 Perl_croak(aTHX_ "Usage class->find(name[,load])");
826 char *name = SvPV(ST(1), len);
827 bool load = (items > 2) ? SvTRUE(ST(2)) : 0;
828 PerlIO_funcs *layer = PerlIO_find_layer(aTHX_ name, len, load);
830 (layer) ? sv_2mortal(PerlIO_tab_sv(aTHX_ layer)) :
837 PerlIO_define_layer(pTHX_ PerlIO_funcs *tab)
839 if (!PL_known_layers)
840 PL_known_layers = PerlIO_list_alloc(aTHX);
841 PerlIO_list_push(aTHX_ PL_known_layers, tab, Nullsv);
842 PerlIO_debug("define %s %p\n", tab->name, (void*)tab);
846 PerlIO_parse_layers(pTHX_ PerlIO_list_t *av, const char *names)
849 const char *s = names;
851 while (isSPACE(*s) || *s == ':')
856 const char *as = Nullch;
858 if (!isIDFIRST(*s)) {
860 * Message is consistent with how attribute lists are
861 * passed. Even though this means "foo : : bar" is
862 * seen as an invalid separator character.
864 char q = ((*s == '\'') ? '"' : '\'');
865 if (ckWARN(WARN_LAYER))
866 Perl_warner(aTHX_ packWARN(WARN_LAYER),
867 "perlio: invalid separator character %c%c%c in layer specification list %s",
869 SETERRNO(EINVAL, LIB_INVARG);
874 } while (isALNUM(*e));
890 * It's a nul terminated string, not allowed
891 * to \ the terminating null. Anything other
892 * character is passed over.
902 if (ckWARN(WARN_LAYER))
903 Perl_warner(aTHX_ packWARN(WARN_LAYER),
904 "perlio: argument list not closed for layer \"%.*s\"",
916 bool warn_layer = ckWARN(WARN_LAYER);
917 PerlIO_funcs *layer =
918 PerlIO_find_layer(aTHX_ s, llen, 1);
920 PerlIO_list_push(aTHX_ av, layer,
927 Perl_warner(aTHX_ packWARN(WARN_LAYER), "perlio: unknown layer \"%.*s\"",
940 PerlIO_default_buffer(pTHX_ PerlIO_list_t *av)
942 PerlIO_funcs *tab = &PerlIO_perlio;
943 #ifdef PERLIO_USING_CRLF
946 if (PerlIO_stdio.Set_ptrcnt)
949 PerlIO_debug("Pushing %s\n", tab->name);
950 PerlIO_list_push(aTHX_ av, PerlIO_find_layer(aTHX_ tab->name, 0, 0),
955 PerlIO_arg_fetch(PerlIO_list_t *av, IV n)
957 return av->array[n].arg;
961 PerlIO_layer_fetch(pTHX_ PerlIO_list_t *av, IV n, PerlIO_funcs *def)
963 if (n >= 0 && n < av->cur) {
964 PerlIO_debug("Layer %" IVdf " is %s\n", n,
965 av->array[n].funcs->name);
966 return av->array[n].funcs;
969 Perl_croak(aTHX_ "panic: PerlIO layer array corrupt");
974 PerlIOPop_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
976 if (PerlIOValid(f)) {
984 PerlIO_funcs PerlIO_remove = {
985 sizeof(PerlIO_funcs),
988 PERLIO_K_DUMMY | PERLIO_K_UTF8,
1006 NULL, /* get_base */
1007 NULL, /* get_bufsiz */
1010 NULL, /* set_ptrcnt */
1014 PerlIO_default_layers(pTHX)
1016 if (!PL_def_layerlist) {
1017 const char *s = (PL_tainting) ? Nullch : PerlEnv_getenv("PERLIO");
1018 PerlIO_funcs *osLayer = &PerlIO_unix;
1019 PL_def_layerlist = PerlIO_list_alloc(aTHX);
1020 PerlIO_define_layer(aTHX_ & PerlIO_unix);
1021 #if defined(WIN32) && !defined(UNDER_CE)
1022 PerlIO_define_layer(aTHX_ & PerlIO_win32);
1024 osLayer = &PerlIO_win32;
1027 PerlIO_define_layer(aTHX_ & PerlIO_raw);
1028 PerlIO_define_layer(aTHX_ & PerlIO_perlio);
1029 PerlIO_define_layer(aTHX_ & PerlIO_stdio);
1030 PerlIO_define_layer(aTHX_ & PerlIO_crlf);
1032 PerlIO_define_layer(aTHX_ & PerlIO_mmap);
1034 PerlIO_define_layer(aTHX_ & PerlIO_utf8);
1035 PerlIO_define_layer(aTHX_ & PerlIO_remove);
1036 PerlIO_define_layer(aTHX_ & PerlIO_byte);
1037 PerlIO_list_push(aTHX_ PL_def_layerlist,
1038 PerlIO_find_layer(aTHX_ osLayer->name, 0, 0),
1041 PerlIO_parse_layers(aTHX_ PL_def_layerlist, s);
1044 PerlIO_default_buffer(aTHX_ PL_def_layerlist);
1047 if (PL_def_layerlist->cur < 2) {
1048 PerlIO_default_buffer(aTHX_ PL_def_layerlist);
1050 return PL_def_layerlist;
1054 Perl_boot_core_PerlIO(pTHX)
1056 #ifdef USE_ATTRIBUTES_FOR_PERLIO
1057 newXS("io::MODIFY_SCALAR_ATTRIBUTES", XS_io_MODIFY_SCALAR_ATTRIBUTES,
1060 newXS("PerlIO::Layer::find", XS_PerlIO__Layer__find, __FILE__);
1061 newXS("PerlIO::Layer::NoWarnings", XS_PerlIO__Layer__NoWarnings, __FILE__);
1065 PerlIO_default_layer(pTHX_ I32 n)
1067 PerlIO_list_t *av = PerlIO_default_layers(aTHX);
1070 return PerlIO_layer_fetch(aTHX_ av, n, &PerlIO_stdio);
1073 #define PerlIO_default_top() PerlIO_default_layer(aTHX_ -1)
1074 #define PerlIO_default_btm() PerlIO_default_layer(aTHX_ 0)
1077 PerlIO_stdstreams(pTHX)
1080 PerlIO_allocate(aTHX);
1081 PerlIO_fdopen(0, "Ir" PERLIO_STDTEXT);
1082 PerlIO_fdopen(1, "Iw" PERLIO_STDTEXT);
1083 PerlIO_fdopen(2, "Iw" PERLIO_STDTEXT);
1088 PerlIO_push(pTHX_ PerlIO *f, PerlIO_funcs *tab, const char *mode, SV *arg)
1090 if (tab->fsize != sizeof(PerlIO_funcs)) {
1092 Perl_croak(aTHX_ "Layer does not match this perl");
1096 if (tab->size < sizeof(PerlIOl)) {
1099 /* Real layer with a data area */
1100 Newc('L',l,tab->size,char,PerlIOl);
1102 Zero(l, tab->size, char);
1106 PerlIO_debug("PerlIO_push f=%p %s %s %p\n", (void*)f, tab->name,
1107 (mode) ? mode : "(Null)", (void*)arg);
1108 if ((*l->tab->Pushed) (aTHX_ f, mode, arg, tab) != 0) {
1109 PerlIO_pop(aTHX_ f);
1115 /* Pseudo-layer where push does its own stack adjust */
1116 PerlIO_debug("PerlIO_push f=%p %s %s %p\n", (void*)f, tab->name,
1117 (mode) ? mode : "(Null)", (void*)arg);
1118 if ((*tab->Pushed) (aTHX_ f, mode, arg, tab) != 0) {
1126 PerlIOBase_binmode(pTHX_ PerlIO *f)
1128 if (PerlIOValid(f)) {
1129 /* Is layer suitable for raw stream ? */
1130 if (PerlIOBase(f)->tab->kind & PERLIO_K_RAW) {
1131 /* Yes - turn off UTF-8-ness, to undo UTF-8 locale effects */
1132 PerlIOBase(f)->flags &= ~PERLIO_F_UTF8;
1135 /* Not suitable - pop it */
1136 PerlIO_pop(aTHX_ f);
1144 PerlIORaw_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
1147 if (PerlIOValid(f)) {
1152 * Strip all layers that are not suitable for a raw stream
1155 while (t && (l = *t)) {
1156 if (l->tab->Binmode) {
1157 /* Has a handler - normal case */
1158 if ((*l->tab->Binmode)(aTHX_ f) == 0) {
1160 /* Layer still there - move down a layer */
1169 /* No handler - pop it */
1170 PerlIO_pop(aTHX_ t);
1173 if (PerlIOValid(f)) {
1174 PerlIO_debug(":raw f=%p :%s\n", (void*)f, PerlIOBase(f)->tab->name);
1182 PerlIO_apply_layera(pTHX_ PerlIO *f, const char *mode,
1183 PerlIO_list_t *layers, IV n, IV max)
1187 PerlIO_funcs *tab = PerlIO_layer_fetch(aTHX_ layers, n, NULL);
1189 if (!PerlIO_push(aTHX_ f, tab, mode, PerlIOArg)) {
1200 PerlIO_apply_layers(pTHX_ PerlIO *f, const char *mode, const char *names)
1204 PerlIO_list_t *layers = PerlIO_list_alloc(aTHX);
1205 code = PerlIO_parse_layers(aTHX_ layers, names);
1207 code = PerlIO_apply_layera(aTHX_ f, mode, layers, 0, layers->cur);
1209 PerlIO_list_free(aTHX_ layers);
1215 /*--------------------------------------------------------------------------------------*/
1217 * Given the abstraction above the public API functions
1221 PerlIO_binmode(pTHX_ PerlIO *f, int iotype, int mode, const char *names)
1223 PerlIO_debug("PerlIO_binmode f=%p %s %c %x %s\n",
1224 (void*)f, PerlIOBase(f)->tab->name, iotype, mode,
1225 (names) ? names : "(Null)");
1227 /* Do not flush etc. if (e.g.) switching encodings.
1228 if a pushed layer knows it needs to flush lower layers
1229 (for example :unix which is never going to call them)
1230 it can do the flush when it is pushed.
1232 return PerlIO_apply_layers(aTHX_ f, NULL, names) == 0 ? TRUE : FALSE;
1235 /* Fake 5.6 legacy of using this call to turn ON O_TEXT */
1236 #ifdef PERLIO_USING_CRLF
1237 /* Legacy binmode only has meaning if O_TEXT has a value distinct from
1238 O_BINARY so we can look for it in mode.
1240 if (!(mode & O_BINARY)) {
1242 /* FIXME?: Looking down the layer stack seems wrong,
1243 but is a way of reaching past (say) an encoding layer
1244 to flip CRLF-ness of the layer(s) below
1247 /* Perhaps we should turn on bottom-most aware layer
1248 e.g. Ilya's idea that UNIX TTY could serve
1250 if (PerlIOBase(f)->tab->kind & PERLIO_K_CANCRLF) {
1251 if (!(PerlIOBase(f)->flags & PERLIO_F_CRLF)) {
1252 /* Not in text mode - flush any pending stuff and flip it */
1254 PerlIOBase(f)->flags |= PERLIO_F_CRLF;
1256 /* Only need to turn it on in one layer so we are done */
1261 /* Not finding a CRLF aware layer presumably means we are binary
1262 which is not what was requested - so we failed
1263 We _could_ push :crlf layer but so could caller
1268 /* Legacy binmode is now _defined_ as being equivalent to pushing :raw
1269 So code that used to be here is now in PerlIORaw_pushed().
1271 return PerlIO_push(aTHX_ f, &PerlIO_raw, Nullch, Nullsv) ? TRUE : FALSE;
1276 PerlIO__close(pTHX_ PerlIO *f)
1279 return (*PerlIOBase(f)->tab->Close) (aTHX_ f);
1281 SETERRNO(EBADF, SS_IVCHAN);
1287 Perl_PerlIO_close(pTHX_ PerlIO *f)
1290 if (PerlIOValid(f)) {
1291 code = (*PerlIOBase(f)->tab->Close) (aTHX_ f);
1293 PerlIO_pop(aTHX_ f);
1300 Perl_PerlIO_fileno(pTHX_ PerlIO *f)
1303 return (*PerlIOBase(f)->tab->Fileno) (aTHX_ f);
1305 SETERRNO(EBADF, SS_IVCHAN);
1311 PerlIO_context_layers(pTHX_ const char *mode)
1313 const char *type = NULL;
1315 * Need to supply default layer info from open.pm
1318 SV *layers = PL_curcop->cop_io;
1321 type = SvPV(layers, len);
1322 if (type && mode[0] != 'r') {
1324 * Skip to write part
1326 const char *s = strchr(type, 0);
1327 if (s && (STRLEN)(s - type) < len) {
1336 static PerlIO_funcs *
1337 PerlIO_layer_from_ref(pTHX_ SV *sv)
1340 * For any scalar type load the handler which is bundled with perl
1342 if (SvTYPE(sv) < SVt_PVAV)
1343 return PerlIO_find_layer(aTHX_ "scalar", 6, 1);
1346 * For other types allow if layer is known but don't try and load it
1348 switch (SvTYPE(sv)) {
1350 return PerlIO_find_layer(aTHX_ "Array", 5, 0);
1352 return PerlIO_find_layer(aTHX_ "Hash", 4, 0);
1354 return PerlIO_find_layer(aTHX_ "Code", 4, 0);
1356 return PerlIO_find_layer(aTHX_ "Glob", 4, 0);
1362 PerlIO_resolve_layers(pTHX_ const char *layers,
1363 const char *mode, int narg, SV **args)
1365 PerlIO_list_t *def = PerlIO_default_layers(aTHX);
1368 PerlIO_stdstreams(aTHX);
1372 * If it is a reference but not an object see if we have a handler
1375 if (SvROK(arg) && !sv_isobject(arg)) {
1376 PerlIO_funcs *handler = PerlIO_layer_from_ref(aTHX_ SvRV(arg));
1378 def = PerlIO_list_alloc(aTHX);
1379 PerlIO_list_push(aTHX_ def, handler, &PL_sv_undef);
1383 * Don't fail if handler cannot be found :via(...) etc. may do
1384 * something sensible else we will just stringfy and open
1390 layers = PerlIO_context_layers(aTHX_ mode);
1391 if (layers && *layers) {
1395 av = PerlIO_list_alloc(aTHX);
1396 for (i = 0; i < def->cur; i++) {
1397 PerlIO_list_push(aTHX_ av, def->array[i].funcs,
1404 if (PerlIO_parse_layers(aTHX_ av, layers) == 0) {
1408 PerlIO_list_free(aTHX_ av);
1409 return (PerlIO_list_t *) NULL;
1420 PerlIO_openn(pTHX_ const char *layers, const char *mode, int fd,
1421 int imode, int perm, PerlIO *f, int narg, SV **args)
1423 if (!f && narg == 1 && *args == &PL_sv_undef) {
1424 if ((f = PerlIO_tmpfile())) {
1426 layers = PerlIO_context_layers(aTHX_ mode);
1427 if (layers && *layers)
1428 PerlIO_apply_layers(aTHX_ f, mode, layers);
1432 PerlIO_list_t *layera = NULL;
1434 PerlIO_funcs *tab = NULL;
1435 if (PerlIOValid(f)) {
1437 * This is "reopen" - it is not tested as perl does not use it
1441 layera = PerlIO_list_alloc(aTHX);
1443 SV *arg = (l->tab->Getarg)
1444 ? (*l->tab->Getarg) (aTHX_ &l, NULL, 0)
1446 PerlIO_list_push(aTHX_ layera, l->tab, arg);
1447 l = *PerlIONext(&l);
1451 layera = PerlIO_resolve_layers(aTHX_ layers, mode, narg, args);
1457 * Start at "top" of layer stack
1459 n = layera->cur - 1;
1461 PerlIO_funcs *t = PerlIO_layer_fetch(aTHX_ layera, n, NULL);
1470 * Found that layer 'n' can do opens - call it
1472 if (narg > 1 && !(tab->kind & PERLIO_K_MULTIARG)) {
1473 Perl_croak(aTHX_ "More than one argument to open(,':%s')",tab->name);
1475 PerlIO_debug("openn(%s,'%s','%s',%d,%x,%o,%p,%d,%p)\n",
1476 tab->name, layers, mode, fd, imode, perm,
1477 (void*)f, narg, (void*)args);
1478 f = (*tab->Open) (aTHX_ tab, layera, n, mode, fd, imode, perm,
1481 if (n + 1 < layera->cur) {
1483 * More layers above the one that we used to open -
1486 if (PerlIO_apply_layera(aTHX_ f, mode, layera, n + 1, layera->cur) != 0) {
1487 /* If pushing layers fails close the file */
1494 PerlIO_list_free(aTHX_ layera);
1501 Perl_PerlIO_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
1504 return (*PerlIOBase(f)->tab->Read) (aTHX_ f, vbuf, count);
1506 SETERRNO(EBADF, SS_IVCHAN);
1512 Perl_PerlIO_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
1515 return (*PerlIOBase(f)->tab->Unread) (aTHX_ f, vbuf, count);
1517 SETERRNO(EBADF, SS_IVCHAN);
1523 Perl_PerlIO_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
1526 return (*PerlIOBase(f)->tab->Write) (aTHX_ f, vbuf, count);
1528 SETERRNO(EBADF, SS_IVCHAN);
1534 Perl_PerlIO_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
1537 return (*PerlIOBase(f)->tab->Seek) (aTHX_ f, offset, whence);
1539 SETERRNO(EBADF, SS_IVCHAN);
1545 Perl_PerlIO_tell(pTHX_ PerlIO *f)
1548 return (*PerlIOBase(f)->tab->Tell) (aTHX_ f);
1550 SETERRNO(EBADF, SS_IVCHAN);
1556 Perl_PerlIO_flush(pTHX_ PerlIO *f)
1560 PerlIO_funcs *tab = PerlIOBase(f)->tab;
1561 if (tab && tab->Flush) {
1562 return (*tab->Flush) (aTHX_ f);
1565 PerlIO_debug("Cannot flush f=%p :%s\n", (void*)f, tab->name);
1566 SETERRNO(EBADF, SS_IVCHAN);
1571 PerlIO_debug("Cannot flush f=%p\n", (void*)f);
1572 SETERRNO(EBADF, SS_IVCHAN);
1578 * Is it good API design to do flush-all on NULL, a potentially
1579 * errorneous input? Maybe some magical value (PerlIO*
1580 * PERLIO_FLUSH_ALL = (PerlIO*)-1;)? Yes, stdio does similar
1581 * things on fflush(NULL), but should we be bound by their design
1584 PerlIO **table = &PL_perlio;
1586 while ((f = *table)) {
1588 table = (PerlIO **) (f++);
1589 for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
1590 if (*f && PerlIO_flush(f) != 0)
1600 PerlIOBase_flush_linebuf(pTHX)
1602 PerlIO **table = &PL_perlio;
1604 while ((f = *table)) {
1606 table = (PerlIO **) (f++);
1607 for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
1610 flags & (PERLIO_F_LINEBUF | PERLIO_F_CANWRITE))
1611 == (PERLIO_F_LINEBUF | PERLIO_F_CANWRITE))
1619 Perl_PerlIO_fill(pTHX_ PerlIO *f)
1622 return (*PerlIOBase(f)->tab->Fill) (aTHX_ f);
1624 SETERRNO(EBADF, SS_IVCHAN);
1630 PerlIO_isutf8(PerlIO *f)
1633 return (PerlIOBase(f)->flags & PERLIO_F_UTF8) != 0;
1635 SETERRNO(EBADF, SS_IVCHAN);
1641 Perl_PerlIO_eof(pTHX_ PerlIO *f)
1644 return (*PerlIOBase(f)->tab->Eof) (aTHX_ f);
1646 SETERRNO(EBADF, SS_IVCHAN);
1652 Perl_PerlIO_error(pTHX_ PerlIO *f)
1655 return (*PerlIOBase(f)->tab->Error) (aTHX_ f);
1657 SETERRNO(EBADF, SS_IVCHAN);
1663 Perl_PerlIO_clearerr(pTHX_ PerlIO *f)
1666 (*PerlIOBase(f)->tab->Clearerr) (aTHX_ f);
1668 SETERRNO(EBADF, SS_IVCHAN);
1672 Perl_PerlIO_setlinebuf(pTHX_ PerlIO *f)
1675 (*PerlIOBase(f)->tab->Setlinebuf) (aTHX_ f);
1677 SETERRNO(EBADF, SS_IVCHAN);
1681 PerlIO_has_base(PerlIO *f)
1683 if (PerlIOValid(f)) {
1684 return (PerlIOBase(f)->tab->Get_base != NULL);
1690 PerlIO_fast_gets(PerlIO *f)
1692 if (PerlIOValid(f) && (PerlIOBase(f)->flags & PERLIO_F_FASTGETS)) {
1693 PerlIO_funcs *tab = PerlIOBase(f)->tab;
1694 return (tab->Set_ptrcnt != NULL);
1700 PerlIO_has_cntptr(PerlIO *f)
1702 if (PerlIOValid(f)) {
1703 PerlIO_funcs *tab = PerlIOBase(f)->tab;
1704 return (tab->Get_ptr != NULL && tab->Get_cnt != NULL);
1710 PerlIO_canset_cnt(PerlIO *f)
1712 if (PerlIOValid(f)) {
1713 PerlIOl *l = PerlIOBase(f);
1714 return (l->tab->Set_ptrcnt != NULL);
1720 Perl_PerlIO_get_base(pTHX_ PerlIO *f)
1723 return (*PerlIOBase(f)->tab->Get_base) (aTHX_ f);
1728 Perl_PerlIO_get_bufsiz(pTHX_ PerlIO *f)
1731 return (*PerlIOBase(f)->tab->Get_bufsiz) (aTHX_ f);
1736 Perl_PerlIO_get_ptr(pTHX_ PerlIO *f)
1738 if (PerlIOValid(f)) {
1739 PerlIO_funcs *tab = PerlIOBase(f)->tab;
1740 if (tab->Get_ptr == NULL)
1742 return (*tab->Get_ptr) (aTHX_ f);
1748 Perl_PerlIO_get_cnt(pTHX_ PerlIO *f)
1750 if (PerlIOValid(f)) {
1751 PerlIO_funcs *tab = PerlIOBase(f)->tab;
1752 if (tab->Get_cnt == NULL)
1754 return (*tab->Get_cnt) (aTHX_ f);
1760 Perl_PerlIO_set_cnt(pTHX_ PerlIO *f, int cnt)
1762 if (PerlIOValid(f)) {
1763 (*PerlIOBase(f)->tab->Set_ptrcnt) (aTHX_ f, NULL, cnt);
1768 Perl_PerlIO_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, int cnt)
1770 if (PerlIOValid(f)) {
1771 PerlIO_funcs *tab = PerlIOBase(f)->tab;
1772 if (tab->Set_ptrcnt == NULL) {
1773 Perl_croak(aTHX_ "PerlIO buffer snooping abuse");
1775 (*PerlIOBase(f)->tab->Set_ptrcnt) (aTHX_ f, ptr, cnt);
1780 /*--------------------------------------------------------------------------------------*/
1782 * utf8 and raw dummy layers
1786 PerlIOUtf8_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
1788 if (PerlIOValid(f)) {
1789 if (tab->kind & PERLIO_K_UTF8)
1790 PerlIOBase(f)->flags |= PERLIO_F_UTF8;
1792 PerlIOBase(f)->flags &= ~PERLIO_F_UTF8;
1798 PerlIO_funcs PerlIO_utf8 = {
1799 sizeof(PerlIO_funcs),
1802 PERLIO_K_DUMMY | PERLIO_K_UTF8,
1820 NULL, /* get_base */
1821 NULL, /* get_bufsiz */
1824 NULL, /* set_ptrcnt */
1827 PerlIO_funcs PerlIO_byte = {
1828 sizeof(PerlIO_funcs),
1849 NULL, /* get_base */
1850 NULL, /* get_bufsiz */
1853 NULL, /* set_ptrcnt */
1857 PerlIORaw_open(pTHX_ PerlIO_funcs *self, PerlIO_list_t *layers,
1858 IV n, const char *mode, int fd, int imode, int perm,
1859 PerlIO *old, int narg, SV **args)
1861 PerlIO_funcs *tab = PerlIO_default_btm();
1862 return (*tab->Open) (aTHX_ tab, layers, n - 1, mode, fd, imode, perm,
1866 PerlIO_funcs PerlIO_raw = {
1867 sizeof(PerlIO_funcs),
1888 NULL, /* get_base */
1889 NULL, /* get_bufsiz */
1892 NULL, /* set_ptrcnt */
1894 /*--------------------------------------------------------------------------------------*/
1895 /*--------------------------------------------------------------------------------------*/
1897 * "Methods" of the "base class"
1901 PerlIOBase_fileno(pTHX_ PerlIO *f)
1903 return PerlIOValid(f) ? PerlIO_fileno(PerlIONext(f)) : -1;
1907 PerlIO_modestr(PerlIO * f, char *buf)
1910 if (PerlIOValid(f)) {
1911 IV flags = PerlIOBase(f)->flags;
1912 if (flags & PERLIO_F_APPEND) {
1914 if (flags & PERLIO_F_CANREAD) {
1918 else if (flags & PERLIO_F_CANREAD) {
1920 if (flags & PERLIO_F_CANWRITE)
1923 else if (flags & PERLIO_F_CANWRITE) {
1925 if (flags & PERLIO_F_CANREAD) {
1929 #ifdef PERLIO_USING_CRLF
1930 if (!(flags & PERLIO_F_CRLF))
1940 PerlIOBase_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
1942 PerlIOl *l = PerlIOBase(f);
1944 const char *omode = mode;
1947 l->flags &= ~(PERLIO_F_CANREAD | PERLIO_F_CANWRITE |
1948 PERLIO_F_TRUNCATE | PERLIO_F_APPEND);
1949 if (tab->Set_ptrcnt != NULL)
1950 l->flags |= PERLIO_F_FASTGETS;
1952 if (*mode == '#' || *mode == 'I')
1956 l->flags |= PERLIO_F_CANREAD;
1959 l->flags |= PERLIO_F_APPEND | PERLIO_F_CANWRITE;
1962 l->flags |= PERLIO_F_TRUNCATE | PERLIO_F_CANWRITE;
1965 SETERRNO(EINVAL, LIB_INVARG);
1971 l->flags |= PERLIO_F_CANREAD | PERLIO_F_CANWRITE;
1974 l->flags &= ~PERLIO_F_CRLF;
1977 l->flags |= PERLIO_F_CRLF;
1980 SETERRNO(EINVAL, LIB_INVARG);
1987 l->flags |= l->next->flags &
1988 (PERLIO_F_CANREAD | PERLIO_F_CANWRITE | PERLIO_F_TRUNCATE |
1993 PerlIO_debug("PerlIOBase_pushed f=%p %s %s fl=%08" UVxf " (%s)\n",
1994 f, PerlIOBase(f)->tab->name, (omode) ? omode : "(Null)",
1995 l->flags, PerlIO_modestr(f, temp));
2001 PerlIOBase_popped(pTHX_ PerlIO *f)
2007 PerlIOBase_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
2010 * Save the position as current head considers it
2012 Off_t old = PerlIO_tell(f);
2014 PerlIO_push(aTHX_ f, &PerlIO_pending, "r", Nullsv);
2015 PerlIOSelf(f, PerlIOBuf)->posn = old;
2016 done = PerlIOBuf_unread(aTHX_ f, vbuf, count);
2021 PerlIOBase_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
2023 STDCHAR *buf = (STDCHAR *) vbuf;
2025 if (!(PerlIOBase(f)->flags & PERLIO_F_CANREAD))
2028 SSize_t avail = PerlIO_get_cnt(f);
2031 take = ((SSize_t)count < avail) ? count : avail;
2033 STDCHAR *ptr = PerlIO_get_ptr(f);
2034 Copy(ptr, buf, take, STDCHAR);
2035 PerlIO_set_ptrcnt(f, ptr + take, (avail -= take));
2039 if (count > 0 && avail <= 0) {
2040 if (PerlIO_fill(f) != 0)
2044 return (buf - (STDCHAR *) vbuf);
2050 PerlIOBase_noop_ok(pTHX_ PerlIO *f)
2056 PerlIOBase_noop_fail(pTHX_ PerlIO *f)
2062 PerlIOBase_close(pTHX_ PerlIO *f)
2065 PerlIO *n = PerlIONext(f);
2066 if (PerlIO_flush(f) != 0)
2068 if (PerlIOValid(n) && (*PerlIOBase(n)->tab->Close)(aTHX_ n) != 0)
2070 PerlIOBase(f)->flags &=
2071 ~(PERLIO_F_CANREAD | PERLIO_F_CANWRITE | PERLIO_F_OPEN);
2076 PerlIOBase_eof(pTHX_ PerlIO *f)
2078 if (PerlIOValid(f)) {
2079 return (PerlIOBase(f)->flags & PERLIO_F_EOF) != 0;
2085 PerlIOBase_error(pTHX_ PerlIO *f)
2087 if (PerlIOValid(f)) {
2088 return (PerlIOBase(f)->flags & PERLIO_F_ERROR) != 0;
2094 PerlIOBase_clearerr(pTHX_ PerlIO *f)
2096 if (PerlIOValid(f)) {
2097 PerlIO *n = PerlIONext(f);
2098 PerlIOBase(f)->flags &= ~(PERLIO_F_ERROR | PERLIO_F_EOF);
2105 PerlIOBase_setlinebuf(pTHX_ PerlIO *f)
2107 if (PerlIOValid(f)) {
2108 PerlIOBase(f)->flags |= PERLIO_F_LINEBUF;
2113 PerlIO_sv_dup(pTHX_ SV *arg, CLONE_PARAMS *param)
2119 return sv_dup(arg, param);
2122 return newSVsv(arg);
2125 return newSVsv(arg);
2130 PerlIOBase_dup(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags)
2132 PerlIO *nexto = PerlIONext(o);
2133 if (PerlIOValid(nexto)) {
2134 PerlIO_funcs *tab = PerlIOBase(nexto)->tab;
2135 f = (*tab->Dup)(aTHX_ f, nexto, param, flags);
2138 PerlIO_funcs *self = PerlIOBase(o)->tab;
2141 PerlIO_debug("PerlIOBase_dup %s f=%p o=%p param=%p\n",
2142 self->name, (void*)f, (void*)o, (void*)param);
2144 arg = (*self->Getarg)(aTHX_ o,param,flags);
2146 f = PerlIO_push(aTHX_ f, self, PerlIO_modestr(o,buf), arg);
2154 #define PERLIO_MAX_REFCOUNTABLE_FD 2048
2156 perl_mutex PerlIO_mutex;
2158 int PerlIO_fd_refcnt[PERLIO_MAX_REFCOUNTABLE_FD];
2163 /* Place holder for stdstreams call ??? */
2165 MUTEX_INIT(&PerlIO_mutex);
2170 PerlIOUnix_refcnt_inc(int fd)
2172 if (fd >= 0 && fd < PERLIO_MAX_REFCOUNTABLE_FD) {
2174 MUTEX_LOCK(&PerlIO_mutex);
2176 PerlIO_fd_refcnt[fd]++;
2177 PerlIO_debug("fd %d refcnt=%d\n",fd,PerlIO_fd_refcnt[fd]);
2179 MUTEX_UNLOCK(&PerlIO_mutex);
2185 PerlIOUnix_refcnt_dec(int fd)
2188 if (fd >= 0 && fd < PERLIO_MAX_REFCOUNTABLE_FD) {
2190 MUTEX_LOCK(&PerlIO_mutex);
2192 cnt = --PerlIO_fd_refcnt[fd];
2193 PerlIO_debug("fd %d refcnt=%d\n",fd,cnt);
2195 MUTEX_UNLOCK(&PerlIO_mutex);
2202 PerlIO_cleanup(pTHX)
2206 PerlIO_debug("Cleanup layers for %p\n",aTHX);
2208 PerlIO_debug("Cleanup layers\n");
2210 /* Raise STDIN..STDERR refcount so we don't close them */
2211 for (i=0; i < 3; i++)
2212 PerlIOUnix_refcnt_inc(i);
2213 PerlIO_cleantable(aTHX_ &PL_perlio);
2214 /* Restore STDIN..STDERR refcount */
2215 for (i=0; i < 3; i++)
2216 PerlIOUnix_refcnt_dec(i);
2218 if (PL_known_layers) {
2219 PerlIO_list_free(aTHX_ PL_known_layers);
2220 PL_known_layers = NULL;
2222 if(PL_def_layerlist) {
2223 PerlIO_list_free(aTHX_ PL_def_layerlist);
2224 PL_def_layerlist = NULL;
2230 /*--------------------------------------------------------------------------------------*/
2232 * Bottom-most level for UNIX-like case
2236 struct _PerlIO base; /* The generic part */
2237 int fd; /* UNIX like file descriptor */
2238 int oflags; /* open/fcntl flags */
2242 PerlIOUnix_oflags(const char *mode)
2245 if (*mode == 'I' || *mode == '#')
2250 if (*++mode == '+') {
2257 oflags = O_CREAT | O_TRUNC;
2258 if (*++mode == '+') {
2267 oflags = O_CREAT | O_APPEND;
2268 if (*++mode == '+') {
2281 else if (*mode == 't') {
2283 oflags &= ~O_BINARY;
2287 * Always open in binary mode
2290 if (*mode || oflags == -1) {
2291 SETERRNO(EINVAL, LIB_INVARG);
2298 PerlIOUnix_fileno(pTHX_ PerlIO *f)
2300 return PerlIOSelf(f, PerlIOUnix)->fd;
2304 PerlIOUnix_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
2306 IV code = PerlIOBase_pushed(aTHX_ f, mode, arg, tab);
2307 PerlIOUnix *s = PerlIOSelf(f, PerlIOUnix);
2308 if (*PerlIONext(f)) {
2309 /* We never call down so do any pending stuff now */
2310 PerlIO_flush(PerlIONext(f));
2311 s->fd = PerlIO_fileno(PerlIONext(f));
2313 * XXX could (or should) we retrieve the oflags from the open file
2314 * handle rather than believing the "mode" we are passed in? XXX
2315 * Should the value on NULL mode be 0 or -1?
2317 s->oflags = mode ? PerlIOUnix_oflags(mode) : -1;
2319 PerlIOBase(f)->flags |= PERLIO_F_OPEN;
2324 PerlIOUnix_open(pTHX_ PerlIO_funcs *self, PerlIO_list_t *layers,
2325 IV n, const char *mode, int fd, int imode,
2326 int perm, PerlIO *f, int narg, SV **args)
2328 if (PerlIOValid(f)) {
2329 if (PerlIOBase(f)->flags & PERLIO_F_OPEN)
2330 (*PerlIOBase(f)->tab->Close)(aTHX_ f);
2333 char *path = SvPV_nolen(*args);
2337 imode = PerlIOUnix_oflags(mode);
2341 fd = PerlLIO_open3(path, imode, perm);
2349 f = PerlIO_allocate(aTHX);
2351 if (!PerlIOValid(f)) {
2352 if (!(f = PerlIO_push(aTHX_ f, self, mode, PerlIOArg))) {
2356 s = PerlIOSelf(f, PerlIOUnix);
2359 PerlIOBase(f)->flags |= PERLIO_F_OPEN;
2360 PerlIOUnix_refcnt_inc(fd);
2366 * FIXME: pop layers ???
2374 PerlIOUnix_dup(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags)
2376 PerlIOUnix *os = PerlIOSelf(o, PerlIOUnix);
2378 if (flags & PERLIO_DUP_FD) {
2379 fd = PerlLIO_dup(fd);
2381 if (fd >= 0 && fd < PERLIO_MAX_REFCOUNTABLE_FD) {
2382 f = PerlIOBase_dup(aTHX_ f, o, param, flags);
2384 /* If all went well overwrite fd in dup'ed lay with the dup()'ed fd */
2385 PerlIOUnix *s = PerlIOSelf(f, PerlIOUnix);
2387 PerlIOUnix_refcnt_inc(fd);
2396 PerlIOUnix_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
2398 int fd = PerlIOSelf(f, PerlIOUnix)->fd;
2399 if (!(PerlIOBase(f)->flags & PERLIO_F_CANREAD) ||
2400 PerlIOBase(f)->flags & (PERLIO_F_EOF|PERLIO_F_ERROR)) {
2404 SSize_t len = PerlLIO_read(fd, vbuf, count);
2405 if (len >= 0 || errno != EINTR) {
2407 PerlIOBase(f)->flags |= PERLIO_F_ERROR;
2408 else if (len == 0 && count != 0)
2409 PerlIOBase(f)->flags |= PERLIO_F_EOF;
2417 PerlIOUnix_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
2419 int fd = PerlIOSelf(f, PerlIOUnix)->fd;
2421 SSize_t len = PerlLIO_write(fd, vbuf, count);
2422 if (len >= 0 || errno != EINTR) {
2424 PerlIOBase(f)->flags |= PERLIO_F_ERROR;
2432 PerlIOUnix_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
2435 PerlLIO_lseek(PerlIOSelf(f, PerlIOUnix)->fd, offset, whence);
2436 PerlIOBase(f)->flags &= ~PERLIO_F_EOF;
2437 return (new == (Off_t) - 1) ? -1 : 0;
2441 PerlIOUnix_tell(pTHX_ PerlIO *f)
2443 return PerlLIO_lseek(PerlIOSelf(f, PerlIOUnix)->fd, 0, SEEK_CUR);
2448 PerlIOUnix_close(pTHX_ PerlIO *f)
2450 int fd = PerlIOSelf(f, PerlIOUnix)->fd;
2452 if (PerlIOBase(f)->flags & PERLIO_F_OPEN) {
2453 if (PerlIOUnix_refcnt_dec(fd) > 0) {
2454 PerlIOBase(f)->flags &= ~PERLIO_F_OPEN;
2459 SETERRNO(EBADF,SS_IVCHAN);
2462 while (PerlLIO_close(fd) != 0) {
2463 if (errno != EINTR) {
2470 PerlIOBase(f)->flags &= ~PERLIO_F_OPEN;
2475 PerlIO_funcs PerlIO_unix = {
2476 sizeof(PerlIO_funcs),
2483 PerlIOBase_binmode, /* binmode */
2493 PerlIOBase_noop_ok, /* flush */
2494 PerlIOBase_noop_fail, /* fill */
2497 PerlIOBase_clearerr,
2498 PerlIOBase_setlinebuf,
2499 NULL, /* get_base */
2500 NULL, /* get_bufsiz */
2503 NULL, /* set_ptrcnt */
2506 /*--------------------------------------------------------------------------------------*/
2511 #if defined(VMS) && !defined(STDIO_BUFFER_WRITABLE)
2512 /* perl5.8 - This ensures the last minute VMS ungetc fix is not
2513 broken by the last second glibc 2.3 fix
2515 #define STDIO_BUFFER_WRITABLE
2520 struct _PerlIO base;
2521 FILE *stdio; /* The stream */
2525 PerlIOStdio_fileno(pTHX_ PerlIO *f)
2528 if (PerlIOValid(f) && (s = PerlIOSelf(f, PerlIOStdio)->stdio)) {
2529 return PerlSIO_fileno(s);
2536 PerlIOStdio_mode(const char *mode, char *tmode)
2542 #ifdef PERLIO_USING_CRLF
2550 PerlIOStdio_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
2553 if (PerlIOValid(f) && PerlIOValid(n = PerlIONext(f))) {
2554 PerlIO_funcs *toptab = PerlIOBase(n)->tab;
2555 if (toptab == tab) {
2556 /* Top is already stdio - pop self (duplicate) and use original */
2557 PerlIO_pop(aTHX_ f);
2560 int fd = PerlIO_fileno(n);
2563 if (fd >= 0 && (stdio = PerlSIO_fdopen(fd,
2564 mode = PerlIOStdio_mode(mode, tmode)))) {
2565 PerlIOSelf(f, PerlIOStdio)->stdio = stdio;
2566 /* We never call down so do any pending stuff now */
2567 PerlIO_flush(PerlIONext(f));
2574 return PerlIOBase_pushed(aTHX_ f, mode, arg, tab);
2579 PerlIO_importFILE(FILE *stdio, const char *mode)
2585 if (!mode || !*mode) {
2586 /* We need to probe to see how we can open the stream
2587 so start with read/write and then try write and read
2588 we dup() so that we can fclose without loosing the fd.
2590 Note that the errno value set by a failing fdopen
2591 varies between stdio implementations.
2593 int fd = PerlLIO_dup(fileno(stdio));
2594 FILE *f2 = PerlSIO_fdopen(fd, (mode = "r+"));
2596 f2 = PerlSIO_fdopen(fd, (mode = "w"));
2599 f2 = PerlSIO_fdopen(fd, (mode = "r"));
2602 /* Don't seem to be able to open */
2608 if ((f = PerlIO_push(aTHX_(f = PerlIO_allocate(aTHX)), &PerlIO_stdio, mode, Nullsv))) {
2609 s = PerlIOSelf(f, PerlIOStdio);
2617 PerlIOStdio_open(pTHX_ PerlIO_funcs *self, PerlIO_list_t *layers,
2618 IV n, const char *mode, int fd, int imode,
2619 int perm, PerlIO *f, int narg, SV **args)
2622 if (PerlIOValid(f)) {
2623 char *path = SvPV_nolen(*args);
2624 PerlIOStdio *s = PerlIOSelf(f, PerlIOStdio);
2626 PerlIOUnix_refcnt_dec(fileno(s->stdio));
2627 stdio = PerlSIO_freopen(path, (mode = PerlIOStdio_mode(mode, tmode)),
2632 PerlIOUnix_refcnt_inc(fileno(s->stdio));
2637 char *path = SvPV_nolen(*args);
2640 fd = PerlLIO_open3(path, imode, perm);
2643 FILE *stdio = PerlSIO_fopen(path, mode);
2647 f = PerlIO_allocate(aTHX);
2649 if ((f = PerlIO_push(aTHX_ f, self,
2650 (mode = PerlIOStdio_mode(mode, tmode)),
2652 s = PerlIOSelf(f, PerlIOStdio);
2654 PerlIOUnix_refcnt_inc(fileno(s->stdio));
2673 stdio = PerlSIO_stdin;
2676 stdio = PerlSIO_stdout;
2679 stdio = PerlSIO_stderr;
2684 stdio = PerlSIO_fdopen(fd, mode =
2685 PerlIOStdio_mode(mode, tmode));
2690 f = PerlIO_allocate(aTHX);
2692 if ((f = PerlIO_push(aTHX_ f, self, mode, PerlIOArg))) {
2693 s = PerlIOSelf(f, PerlIOStdio);
2695 PerlIOUnix_refcnt_inc(fileno(s->stdio));
2705 PerlIOStdio_dup(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags)
2707 /* This assumes no layers underneath - which is what
2708 happens, but is not how I remember it. NI-S 2001/10/16
2710 if ((f = PerlIOBase_dup(aTHX_ f, o, param, flags))) {
2711 FILE *stdio = PerlIOSelf(o, PerlIOStdio)->stdio;
2712 int fd = fileno(stdio);
2714 if (flags & PERLIO_DUP_FD) {
2715 int dfd = PerlLIO_dup(fileno(stdio));
2717 stdio = PerlSIO_fdopen(dfd, PerlIO_modestr(o,mode));
2721 /* FIXME: To avoid messy error recovery if dup fails
2722 re-use the existing stdio as though flag was not set
2726 stdio = PerlSIO_fdopen(fd, PerlIO_modestr(o,mode));
2728 PerlIOSelf(f, PerlIOStdio)->stdio = stdio;
2729 PerlIOUnix_refcnt_inc(fileno(stdio));
2735 PerlIOStdio_invalidate_fileno(pTHX_ FILE *f)
2737 /* XXX this could use PerlIO_canset_fileno() and
2738 * PerlIO_set_fileno() support from Configure
2740 # if defined(__GLIBC__)
2741 /* There may be a better way for GLIBC:
2742 - libio.h defines a flag to not close() on cleanup
2746 # elif defined(__sun__)
2748 /* On solaris, if _LP64 is defined, the FILE structure is this:
2754 * It turns out that the fd is stored in the top 32 bits of
2755 * file->__pad[4]. The lower 32 bits contain flags. file->pad[5] appears
2756 * to contain a pointer or offset into another structure. All the
2757 * remaining fields are zero.
2759 * We set the top bits to -1 (0xFFFFFFFF).
2761 f->__pad[4] |= 0xffffffff00000000L;
2762 assert(fileno(f) == 0xffffffff);
2763 # else /* !defined(_LP64) */
2764 /* _file is just a unsigned char :-(
2765 Not clear why we dup() rather than using -1
2766 even if that would be treated as 0xFF - so will
2769 f->_file = PerlLIO_dup(fileno(f));
2770 # endif /* defined(_LP64) */
2772 # elif defined(__hpux)
2776 /* Next one ->_file seems to be a reasonable fallback, i.e. if
2777 your platform does not have special entry try this one.
2778 [For OSF only have confirmation for Tru64 (alpha)
2779 but assume other OSFs will be similar.]
2781 # elif defined(_AIX) || defined(__osf__) || defined(__irix__)
2784 # elif defined(__FreeBSD__)
2785 /* There may be a better way on FreeBSD:
2786 - we could insert a dummy func in the _close function entry
2787 f->_close = (int (*)(void *)) dummy_close;
2791 # elif defined(__CYGWIN__)
2792 /* There may be a better way on CYGWIN:
2793 - we could insert a dummy func in the _close function entry
2794 f->_close = (int (*)(void *)) dummy_close;
2798 # elif defined(WIN32)
2799 # if defined(__BORLANDC__)
2800 f->fd = PerlLIO_dup(fileno(f));
2801 # elif defined(UNDER_CE)
2802 /* WIN_CE does not have access to FILE internals, it hardly has FILE
2811 /* Sarathy's code did this - we fall back to a dup/dup2 hack
2812 (which isn't thread safe) instead
2814 # error "Don't know how to set FILE.fileno on your platform"
2821 PerlIOStdio_close(pTHX_ PerlIO *f)
2823 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
2829 int fd = fileno(stdio);
2835 #ifdef SOCKS5_VERSION_NAME
2836 /* Socks lib overrides close() but stdio isn't linked to
2837 that library (though we are) - so we must call close()
2838 on sockets on stdio's behalf.
2841 Sock_size_t optlen = sizeof(int);
2842 if (getsockopt(fd, SOL_SOCKET, SO_TYPE, (void *) &optval, &optlen) == 0) {
2847 if (PerlIOUnix_refcnt_dec(fd) > 0) {
2848 /* File descriptor still in use */
2853 /* For STD* handles don't close the stdio at all
2854 this is because we have shared the FILE * too
2856 if (stdio == stdin) {
2857 /* Some stdios are buggy fflush-ing inputs */
2860 else if (stdio == stdout || stdio == stderr) {
2861 return PerlIO_flush(f);
2863 /* Tricky - must fclose(stdio) to free memory but not close(fd)
2864 Use Sarathy's trick from maint-5.6 to invalidate the
2865 fileno slot of the FILE *
2867 result = PerlIO_flush(f);
2869 if (!(invalidate = PerlIOStdio_invalidate_fileno(aTHX_ stdio))) {
2870 dupfd = PerlLIO_dup(fd);
2873 result = PerlSIO_fclose(stdio);
2874 /* We treat error from stdio as success if we invalidated
2875 errno may NOT be expected EBADF
2877 if (invalidate && result != 0) {
2882 /* in SOCKS case let close() determine return value */
2886 PerlLIO_dup2(dupfd,fd);
2894 PerlIOStdio_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
2896 FILE *s = PerlIOSelf(f, PerlIOStdio)->stdio;
2900 STDCHAR *buf = (STDCHAR *) vbuf;
2902 * Perl is expecting PerlIO_getc() to fill the buffer Linux's
2903 * stdio does not do that for fread()
2905 int ch = PerlSIO_fgetc(s);
2912 got = PerlSIO_fread(vbuf, 1, count, s);
2913 if (got || errno != EINTR)
2916 errno = 0; /* just in case */
2922 PerlIOStdio_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
2925 FILE *s = PerlIOSelf(f, PerlIOStdio)->stdio;
2927 #ifdef STDIO_BUFFER_WRITABLE
2928 if (PerlIO_fast_gets(f) && PerlIO_has_base(f)) {
2929 STDCHAR *buf = ((STDCHAR *) vbuf) + count;
2930 STDCHAR *base = PerlIO_get_base(f);
2931 SSize_t cnt = PerlIO_get_cnt(f);
2932 STDCHAR *ptr = PerlIO_get_ptr(f);
2933 SSize_t avail = ptr - base;
2935 if (avail > count) {
2939 Move(buf-avail,ptr,avail,STDCHAR);
2942 PerlIO_set_ptrcnt(f,ptr,cnt+avail);
2943 if (PerlSIO_feof(s) && unread >= 0)
2944 PerlSIO_clearerr(s);
2949 if (PerlIO_has_cntptr(f)) {
2950 /* We can get pointer to buffer but not its base
2951 Do ungetc() but check chars are ending up in the
2954 STDCHAR *eptr = (STDCHAR*)PerlSIO_get_ptr(s);
2955 STDCHAR *buf = ((STDCHAR *) vbuf) + count;
2957 int ch = *--buf & 0xFF;
2958 if (ungetc(ch,s) != ch) {
2959 /* ungetc did not work */
2962 if ((STDCHAR*)PerlSIO_get_ptr(s) != --eptr || ((*eptr & 0xFF) != ch)) {
2963 /* Did not change pointer as expected */
2964 fgetc(s); /* get char back again */
2974 unread += PerlIOBase_unread(aTHX_ f, vbuf, count);
2980 PerlIOStdio_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
2984 got = PerlSIO_fwrite(vbuf, 1, count,
2985 PerlIOSelf(f, PerlIOStdio)->stdio);
2986 if (got || errno != EINTR)
2989 errno = 0; /* just in case */
2995 PerlIOStdio_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
2997 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
2998 return PerlSIO_fseek(stdio, offset, whence);
3002 PerlIOStdio_tell(pTHX_ PerlIO *f)
3004 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3005 return PerlSIO_ftell(stdio);
3009 PerlIOStdio_flush(pTHX_ PerlIO *f)
3011 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3012 if (PerlIOBase(f)->flags & PERLIO_F_CANWRITE) {
3013 return PerlSIO_fflush(stdio);
3018 * FIXME: This discards ungetc() and pre-read stuff which is not
3019 * right if this is just a "sync" from a layer above Suspect right
3020 * design is to do _this_ but not have layer above flush this
3021 * layer read-to-read
3024 * Not writeable - sync by attempting a seek
3027 if (PerlSIO_fseek(stdio, (Off_t) 0, SEEK_CUR) != 0)
3035 PerlIOStdio_eof(pTHX_ PerlIO *f)
3037 return PerlSIO_feof(PerlIOSelf(f, PerlIOStdio)->stdio);
3041 PerlIOStdio_error(pTHX_ PerlIO *f)
3043 return PerlSIO_ferror(PerlIOSelf(f, PerlIOStdio)->stdio);
3047 PerlIOStdio_clearerr(pTHX_ PerlIO *f)
3049 PerlSIO_clearerr(PerlIOSelf(f, PerlIOStdio)->stdio);
3053 PerlIOStdio_setlinebuf(pTHX_ PerlIO *f)
3055 #ifdef HAS_SETLINEBUF
3056 PerlSIO_setlinebuf(PerlIOSelf(f, PerlIOStdio)->stdio);
3058 PerlSIO_setvbuf(PerlIOSelf(f, PerlIOStdio)->stdio, Nullch, _IOLBF, 0);
3064 PerlIOStdio_get_base(pTHX_ PerlIO *f)
3066 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3067 return (STDCHAR*)PerlSIO_get_base(stdio);
3071 PerlIOStdio_get_bufsiz(pTHX_ PerlIO *f)
3073 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3074 return PerlSIO_get_bufsiz(stdio);
3078 #ifdef USE_STDIO_PTR
3080 PerlIOStdio_get_ptr(pTHX_ PerlIO *f)
3082 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3083 return (STDCHAR*)PerlSIO_get_ptr(stdio);
3087 PerlIOStdio_get_cnt(pTHX_ PerlIO *f)
3089 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3090 return PerlSIO_get_cnt(stdio);
3094 PerlIOStdio_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, SSize_t cnt)
3096 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3098 #ifdef STDIO_PTR_LVALUE
3099 PerlSIO_set_ptr(stdio, (void*)ptr); /* LHS STDCHAR* cast non-portable */
3100 #ifdef STDIO_PTR_LVAL_SETS_CNT
3101 if (PerlSIO_get_cnt(stdio) != (cnt)) {
3102 assert(PerlSIO_get_cnt(stdio) == (cnt));
3105 #if (!defined(STDIO_PTR_LVAL_NOCHANGE_CNT))
3107 * Setting ptr _does_ change cnt - we are done
3111 #else /* STDIO_PTR_LVALUE */
3113 #endif /* STDIO_PTR_LVALUE */
3116 * Now (or only) set cnt
3118 #ifdef STDIO_CNT_LVALUE
3119 PerlSIO_set_cnt(stdio, cnt);
3120 #else /* STDIO_CNT_LVALUE */
3121 #if (defined(STDIO_PTR_LVALUE) && defined(STDIO_PTR_LVAL_SETS_CNT))
3122 PerlSIO_set_ptr(stdio,
3123 PerlSIO_get_ptr(stdio) + (PerlSIO_get_cnt(stdio) -
3125 #else /* STDIO_PTR_LVAL_SETS_CNT */
3127 #endif /* STDIO_PTR_LVAL_SETS_CNT */
3128 #endif /* STDIO_CNT_LVALUE */
3135 PerlIOStdio_fill(pTHX_ PerlIO *f)
3137 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3140 * fflush()ing read-only streams can cause trouble on some stdio-s
3142 if ((PerlIOBase(f)->flags & PERLIO_F_CANWRITE)) {
3143 if (PerlSIO_fflush(stdio) != 0)
3146 c = PerlSIO_fgetc(stdio);
3150 #if (defined(STDIO_PTR_LVALUE) && (defined(STDIO_CNT_LVALUE) || defined(STDIO_PTR_LVAL_SETS_CNT)))
3152 #ifdef STDIO_BUFFER_WRITABLE
3153 if (PerlIO_fast_gets(f) && PerlIO_has_base(f)) {
3154 /* Fake ungetc() to the real buffer in case system's ungetc
3157 STDCHAR *base = (STDCHAR*)PerlSIO_get_base(stdio);
3158 SSize_t cnt = PerlSIO_get_cnt(stdio);
3159 STDCHAR *ptr = (STDCHAR*)PerlSIO_get_ptr(stdio);
3160 if (ptr == base+1) {
3161 *--ptr = (STDCHAR) c;
3162 PerlIOStdio_set_ptrcnt(aTHX_ f,ptr,cnt+1);
3163 if (PerlSIO_feof(stdio))
3164 PerlSIO_clearerr(stdio);
3170 if (PerlIO_has_cntptr(f)) {
3172 if (PerlIOStdio_unread(aTHX_ f,&ch,1) == 1) {
3179 /* An ungetc()d char is handled separately from the regular
3180 * buffer, so we stuff it in the buffer ourselves.
3181 * Should never get called as should hit code above
3183 *(--((*stdio)->_ptr)) = (unsigned char) c;
3186 /* If buffer snoop scheme above fails fall back to
3189 if (PerlSIO_ungetc(c, stdio) != c)
3197 PerlIO_funcs PerlIO_stdio = {
3198 sizeof(PerlIO_funcs),
3200 sizeof(PerlIOStdio),
3201 PERLIO_K_BUFFERED|PERLIO_K_RAW,
3205 PerlIOBase_binmode, /* binmode */
3219 PerlIOStdio_clearerr,
3220 PerlIOStdio_setlinebuf,
3222 PerlIOStdio_get_base,
3223 PerlIOStdio_get_bufsiz,
3228 #ifdef USE_STDIO_PTR
3229 PerlIOStdio_get_ptr,
3230 PerlIOStdio_get_cnt,
3231 #if (defined(STDIO_PTR_LVALUE) && (defined(STDIO_CNT_LVALUE) || defined(STDIO_PTR_LVAL_SETS_CNT)))
3232 PerlIOStdio_set_ptrcnt
3233 #else /* STDIO_PTR_LVALUE */
3235 #endif /* STDIO_PTR_LVALUE */
3236 #else /* USE_STDIO_PTR */
3240 #endif /* USE_STDIO_PTR */
3243 /* Note that calls to PerlIO_exportFILE() are reversed using
3244 * PerlIO_releaseFILE(), not importFILE. */
3246 PerlIO_exportFILE(PerlIO * f, const char *mode)
3250 if (PerlIOValid(f)) {
3253 if (!mode || !*mode) {
3254 mode = PerlIO_modestr(f, buf);
3256 stdio = PerlSIO_fdopen(PerlIO_fileno(f), mode);
3259 /* De-link any lower layers so new :stdio sticks */
3261 if ((f = PerlIO_push(aTHX_ f, &PerlIO_stdio, buf, Nullsv))) {
3262 PerlIOStdio *s = PerlIOSelf(f, PerlIOStdio);
3264 /* Link previous lower layers under new one */
3268 /* restore layers list */
3278 PerlIO_findFILE(PerlIO *f)
3282 if (l->tab == &PerlIO_stdio) {
3283 PerlIOStdio *s = PerlIOSelf(&l, PerlIOStdio);
3286 l = *PerlIONext(&l);
3288 /* Uses fallback "mode" via PerlIO_modestr() in PerlIO_exportFILE */
3289 return PerlIO_exportFILE(f, Nullch);
3292 /* Use this to reverse PerlIO_exportFILE calls. */
3294 PerlIO_releaseFILE(PerlIO *p, FILE *f)
3298 if (l->tab == &PerlIO_stdio) {
3299 PerlIOStdio *s = PerlIOSelf(&l, PerlIOStdio);
3300 if (s->stdio == f) {
3302 PerlIO_pop(aTHX_ p);
3311 /*--------------------------------------------------------------------------------------*/
3313 * perlio buffer layer
3317 PerlIOBuf_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
3319 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3320 int fd = PerlIO_fileno(f);
3321 if (fd >= 0 && PerlLIO_isatty(fd)) {
3322 PerlIOBase(f)->flags |= PERLIO_F_LINEBUF | PERLIO_F_TTY;
3324 if (*PerlIONext(f)) {
3325 Off_t posn = PerlIO_tell(PerlIONext(f));
3326 if (posn != (Off_t) - 1) {
3330 return PerlIOBase_pushed(aTHX_ f, mode, arg, tab);
3334 PerlIOBuf_open(pTHX_ PerlIO_funcs *self, PerlIO_list_t *layers,
3335 IV n, const char *mode, int fd, int imode, int perm,
3336 PerlIO *f, int narg, SV **args)
3338 if (PerlIOValid(f)) {
3339 PerlIO *next = PerlIONext(f);
3340 PerlIO_funcs *tab = PerlIO_layer_fetch(aTHX_ layers, n - 1, PerlIOBase(next)->tab);
3341 next = (*tab->Open) (aTHX_ tab, layers, n - 1, mode, fd, imode, perm,
3343 if (!next || (*PerlIOBase(f)->tab->Pushed) (aTHX_ f, mode, PerlIOArg, self) != 0) {
3348 PerlIO_funcs *tab = PerlIO_layer_fetch(aTHX_ layers, n - 1, PerlIO_default_btm());
3356 f = (*tab->Open) (aTHX_ tab, layers, n - 1, mode, fd, imode, perm,
3359 if (PerlIO_push(aTHX_ f, self, mode, PerlIOArg) == 0) {
3361 * if push fails during open, open fails. close will pop us.
3366 fd = PerlIO_fileno(f);
3367 if (init && fd == 2) {
3369 * Initial stderr is unbuffered
3371 PerlIOBase(f)->flags |= PERLIO_F_UNBUF;
3373 #ifdef PERLIO_USING_CRLF
3374 # ifdef PERLIO_IS_BINMODE_FD
3375 if (PERLIO_IS_BINMODE_FD(fd))
3376 PerlIO_binmode(aTHX_ f, '<'/*not used*/, O_BINARY, Nullch);
3380 * do something about failing setmode()? --jhi
3382 PerlLIO_setmode(fd, O_BINARY);
3391 * This "flush" is akin to sfio's sync in that it handles files in either
3392 * read or write state
3395 PerlIOBuf_flush(pTHX_ PerlIO *f)
3397 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3399 PerlIO *n = PerlIONext(f);
3400 if (PerlIOBase(f)->flags & PERLIO_F_WRBUF) {
3402 * write() the buffer
3404 STDCHAR *buf = b->buf;
3406 while (p < b->ptr) {
3407 SSize_t count = PerlIO_write(n, p, b->ptr - p);
3411 else if (count < 0 || PerlIO_error(n)) {
3412 PerlIOBase(f)->flags |= PERLIO_F_ERROR;
3417 b->posn += (p - buf);
3419 else if (PerlIOBase(f)->flags & PERLIO_F_RDBUF) {
3420 STDCHAR *buf = PerlIO_get_base(f);
3422 * Note position change
3424 b->posn += (b->ptr - buf);
3425 if (b->ptr < b->end) {
3426 /* We did not consume all of it - try and seek downstream to
3427 our logical position
3429 if (PerlIOValid(n) && PerlIO_seek(n, b->posn, SEEK_SET) == 0) {
3430 /* Reload n as some layers may pop themselves on seek */
3431 b->posn = PerlIO_tell(n = PerlIONext(f));
3434 /* Seek failed (e.g. pipe or tty). Do NOT clear buffer or pre-read
3435 data is lost for good - so return saying "ok" having undone
3438 b->posn -= (b->ptr - buf);
3443 b->ptr = b->end = b->buf;
3444 PerlIOBase(f)->flags &= ~(PERLIO_F_RDBUF | PERLIO_F_WRBUF);
3445 /* We check for Valid because of dubious decision to make PerlIO_flush(NULL) flush all */
3446 if (PerlIOValid(n) && PerlIO_flush(n) != 0)
3452 PerlIOBuf_fill(pTHX_ PerlIO *f)
3454 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3455 PerlIO *n = PerlIONext(f);
3458 * Down-stream flush is defined not to loose read data so is harmless.
3459 * we would not normally be fill'ing if there was data left in anycase.
3461 if (PerlIO_flush(f) != 0)
3463 if (PerlIOBase(f)->flags & PERLIO_F_TTY)
3464 PerlIOBase_flush_linebuf(aTHX);
3467 PerlIO_get_base(f); /* allocate via vtable */
3469 b->ptr = b->end = b->buf;
3471 if (!PerlIOValid(n)) {
3472 PerlIOBase(f)->flags |= PERLIO_F_EOF;
3476 if (PerlIO_fast_gets(n)) {
3478 * Layer below is also buffered. We do _NOT_ want to call its
3479 * ->Read() because that will loop till it gets what we asked for
3480 * which may hang on a pipe etc. Instead take anything it has to
3481 * hand, or ask it to fill _once_.
3483 avail = PerlIO_get_cnt(n);
3485 avail = PerlIO_fill(n);
3487 avail = PerlIO_get_cnt(n);
3489 if (!PerlIO_error(n) && PerlIO_eof(n))
3494 STDCHAR *ptr = PerlIO_get_ptr(n);
3495 SSize_t cnt = avail;
3496 if (avail > (SSize_t)b->bufsiz)
3498 Copy(ptr, b->buf, avail, STDCHAR);
3499 PerlIO_set_ptrcnt(n, ptr + avail, cnt - avail);
3503 avail = PerlIO_read(n, b->ptr, b->bufsiz);
3507 PerlIOBase(f)->flags |= PERLIO_F_EOF;
3509 PerlIOBase(f)->flags |= PERLIO_F_ERROR;
3512 b->end = b->buf + avail;
3513 PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
3518 PerlIOBuf_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
3520 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3521 if (PerlIOValid(f)) {
3524 return PerlIOBase_read(aTHX_ f, vbuf, count);
3530 PerlIOBuf_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
3532 const STDCHAR *buf = (const STDCHAR *) vbuf + count;
3533 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3536 if (PerlIOBase(f)->flags & PERLIO_F_WRBUF)
3541 if (PerlIOBase(f)->flags & PERLIO_F_RDBUF) {
3543 * Buffer is already a read buffer, we can overwrite any chars
3544 * which have been read back to buffer start
3546 avail = (b->ptr - b->buf);
3550 * Buffer is idle, set it up so whole buffer is available for
3554 b->end = b->buf + avail;
3556 PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
3558 * Buffer extends _back_ from where we are now
3560 b->posn -= b->bufsiz;
3562 if (avail > (SSize_t) count) {
3564 * If we have space for more than count, just move count
3572 * In simple stdio-like ungetc() case chars will be already
3575 if (buf != b->ptr) {
3576 Copy(buf, b->ptr, avail, STDCHAR);
3580 PerlIOBase(f)->flags &= ~PERLIO_F_EOF;
3584 unread += PerlIOBase_unread(aTHX_ f, vbuf, count);
3590 PerlIOBuf_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
3592 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3593 const STDCHAR *buf = (const STDCHAR *) vbuf;
3597 if (!(PerlIOBase(f)->flags & PERLIO_F_CANWRITE))
3599 if (PerlIOBase(f)->flags & PERLIO_F_RDBUF) {
3600 if (PerlIO_flush(f) != 0) {
3605 SSize_t avail = b->bufsiz - (b->ptr - b->buf);
3606 if ((SSize_t) count < avail)
3608 PerlIOBase(f)->flags |= PERLIO_F_WRBUF;
3609 if (PerlIOBase(f)->flags & PERLIO_F_LINEBUF) {
3624 Copy(buf, b->ptr, avail, STDCHAR);
3631 if (b->ptr >= (b->buf + b->bufsiz))
3634 if (PerlIOBase(f)->flags & PERLIO_F_UNBUF)
3640 PerlIOBuf_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
3643 if ((code = PerlIO_flush(f)) == 0) {
3644 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3645 PerlIOBase(f)->flags &= ~PERLIO_F_EOF;
3646 code = PerlIO_seek(PerlIONext(f), offset, whence);
3648 b->posn = PerlIO_tell(PerlIONext(f));
3655 PerlIOBuf_tell(pTHX_ PerlIO *f)
3657 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3659 * b->posn is file position where b->buf was read, or will be written
3661 Off_t posn = b->posn;
3662 if ((PerlIOBase(f)->flags & PERLIO_F_APPEND) &&
3663 (PerlIOBase(f)->flags & PERLIO_F_WRBUF)) {
3665 /* As O_APPEND files are normally shared in some sense it is better
3670 /* when file is NOT shared then this is sufficient */
3671 PerlIO_seek(PerlIONext(f),0, SEEK_END);
3673 posn = b->posn = PerlIO_tell(PerlIONext(f));
3677 * If buffer is valid adjust position by amount in buffer
3679 posn += (b->ptr - b->buf);
3685 PerlIOBuf_popped(pTHX_ PerlIO *f)
3687 IV code = PerlIOBase_popped(aTHX_ f);
3688 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3689 if (b->buf && b->buf != (STDCHAR *) & b->oneword) {
3693 b->ptr = b->end = b->buf;
3694 PerlIOBase(f)->flags &= ~(PERLIO_F_RDBUF | PERLIO_F_WRBUF);
3699 PerlIOBuf_close(pTHX_ PerlIO *f)
3701 IV code = PerlIOBase_close(aTHX_ f);
3702 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3703 if (b->buf && b->buf != (STDCHAR *) & b->oneword) {
3707 b->ptr = b->end = b->buf;
3708 PerlIOBase(f)->flags &= ~(PERLIO_F_RDBUF | PERLIO_F_WRBUF);
3713 PerlIOBuf_get_ptr(pTHX_ PerlIO *f)
3715 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3722 PerlIOBuf_get_cnt(pTHX_ PerlIO *f)
3724 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3727 if (PerlIOBase(f)->flags & PERLIO_F_RDBUF)
3728 return (b->end - b->ptr);
3733 PerlIOBuf_get_base(pTHX_ PerlIO *f)
3735 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3740 Newz('B',b->buf,b->bufsiz, STDCHAR);
3742 b->buf = (STDCHAR *) & b->oneword;
3743 b->bufsiz = sizeof(b->oneword);
3752 PerlIOBuf_bufsiz(pTHX_ PerlIO *f)
3754 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3757 return (b->end - b->buf);
3761 PerlIOBuf_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, SSize_t cnt)
3763 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3767 if (PerlIO_get_cnt(f) != cnt || b->ptr < b->buf) {
3768 assert(PerlIO_get_cnt(f) == cnt);
3769 assert(b->ptr >= b->buf);
3771 PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
3775 PerlIOBuf_dup(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags)
3777 return PerlIOBase_dup(aTHX_ f, o, param, flags);
3782 PerlIO_funcs PerlIO_perlio = {
3783 sizeof(PerlIO_funcs),
3786 PERLIO_K_BUFFERED|PERLIO_K_RAW,
3790 PerlIOBase_binmode, /* binmode */
3804 PerlIOBase_clearerr,
3805 PerlIOBase_setlinebuf,
3810 PerlIOBuf_set_ptrcnt,
3813 /*--------------------------------------------------------------------------------------*/
3815 * Temp layer to hold unread chars when cannot do it any other way
3819 PerlIOPending_fill(pTHX_ PerlIO *f)
3822 * Should never happen
3829 PerlIOPending_close(pTHX_ PerlIO *f)
3832 * A tad tricky - flush pops us, then we close new top
3835 return PerlIO_close(f);
3839 PerlIOPending_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
3842 * A tad tricky - flush pops us, then we seek new top
3845 return PerlIO_seek(f, offset, whence);
3850 PerlIOPending_flush(pTHX_ PerlIO *f)
3852 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3853 if (b->buf && b->buf != (STDCHAR *) & b->oneword) {
3857 PerlIO_pop(aTHX_ f);
3862 PerlIOPending_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, SSize_t cnt)
3868 PerlIOBuf_set_ptrcnt(aTHX_ f, ptr, cnt);
3873 PerlIOPending_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
3875 IV code = PerlIOBase_pushed(aTHX_ f, mode, arg, tab);
3876 PerlIOl *l = PerlIOBase(f);
3878 * Our PerlIO_fast_gets must match what we are pushed on, or sv_gets()
3879 * etc. get muddled when it changes mid-string when we auto-pop.
3881 l->flags = (l->flags & ~(PERLIO_F_FASTGETS | PERLIO_F_UTF8)) |
3882 (PerlIOBase(PerlIONext(f))->
3883 flags & (PERLIO_F_FASTGETS | PERLIO_F_UTF8));
3888 PerlIOPending_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
3890 SSize_t avail = PerlIO_get_cnt(f);
3892 if ((SSize_t)count < avail)
3895 got = PerlIOBuf_read(aTHX_ f, vbuf, avail);
3896 if (got >= 0 && got < (SSize_t)count) {
3898 PerlIO_read(f, ((STDCHAR *) vbuf) + got, count - got);
3899 if (more >= 0 || got == 0)
3905 PerlIO_funcs PerlIO_pending = {
3906 sizeof(PerlIO_funcs),
3909 PERLIO_K_BUFFERED|PERLIO_K_RAW, /* not sure about RAW here */
3910 PerlIOPending_pushed,
3913 PerlIOBase_binmode, /* binmode */
3922 PerlIOPending_close,
3923 PerlIOPending_flush,
3927 PerlIOBase_clearerr,
3928 PerlIOBase_setlinebuf,
3933 PerlIOPending_set_ptrcnt,
3938 /*--------------------------------------------------------------------------------------*/
3940 * crlf - translation On read translate CR,LF to "\n" we do this by
3941 * overriding ptr/cnt entries to hand back a line at a time and keeping a
3942 * record of which nl we "lied" about. On write translate "\n" to CR,LF
3946 PerlIOBuf base; /* PerlIOBuf stuff */
3947 STDCHAR *nl; /* Position of crlf we "lied" about in the
3952 PerlIOCrlf_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
3955 PerlIOBase(f)->flags |= PERLIO_F_CRLF;
3956 code = PerlIOBuf_pushed(aTHX_ f, mode, arg, tab);
3958 PerlIO_debug("PerlIOCrlf_pushed f=%p %s %s fl=%08" UVxf "\n",
3959 f, PerlIOBase(f)->tab->name, (mode) ? mode : "(Null)",
3960 PerlIOBase(f)->flags);
3967 PerlIOCrlf_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
3969 PerlIOCrlf *c = PerlIOSelf(f, PerlIOCrlf);
3974 if (!(PerlIOBase(f)->flags & PERLIO_F_CRLF))
3975 return PerlIOBuf_unread(aTHX_ f, vbuf, count);
3977 const STDCHAR *buf = (const STDCHAR *) vbuf + count;
3978 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3980 if (PerlIOBase(f)->flags & PERLIO_F_WRBUF)
3985 if (!(PerlIOBase(f)->flags & PERLIO_F_RDBUF)) {
3986 b->end = b->ptr = b->buf + b->bufsiz;
3987 PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
3988 b->posn -= b->bufsiz;
3990 while (count > 0 && b->ptr > b->buf) {
3993 if (b->ptr - 2 >= b->buf) {
4016 PerlIOCrlf_get_cnt(pTHX_ PerlIO *f)
4018 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
4021 if (PerlIOBase(f)->flags & PERLIO_F_RDBUF) {
4022 PerlIOCrlf *c = PerlIOSelf(f, PerlIOCrlf);
4023 if ((PerlIOBase(f)->flags & PERLIO_F_CRLF) && (!c->nl || *c->nl == 0xd)) {
4024 STDCHAR *nl = (c->nl) ? c->nl : b->ptr;
4026 while (nl < b->end && *nl != 0xd)
4028 if (nl < b->end && *nl == 0xd) {
4030 if (nl + 1 < b->end) {
4037 * Not CR,LF but just CR
4045 * Blast - found CR as last char in buffer
4050 * They may not care, defer work as long as
4054 return (nl - b->ptr);
4058 b->ptr++; /* say we have read it as far as
4059 * flush() is concerned */
4060 b->buf++; /* Leave space in front of buffer */
4061 /* Note as we have moved buf up flush's
4063 will naturally make posn point at CR
4065 b->bufsiz--; /* Buffer is thus smaller */
4066 code = PerlIO_fill(f); /* Fetch some more */
4067 b->bufsiz++; /* Restore size for next time */
4068 b->buf--; /* Point at space */
4069 b->ptr = nl = b->buf; /* Which is what we hand
4071 *nl = 0xd; /* Fill in the CR */
4073 goto test; /* fill() call worked */
4075 * CR at EOF - just fall through
4077 /* Should we clear EOF though ??? */
4082 return (((c->nl) ? (c->nl + 1) : b->end) - b->ptr);
4088 PerlIOCrlf_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, SSize_t cnt)
4090 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
4091 PerlIOCrlf *c = PerlIOSelf(f, PerlIOCrlf);
4097 if (ptr == b->end && *c->nl == 0xd) {
4098 /* Defered CR at end of buffer case - we lied about count */
4110 * Test code - delete when it works ...
4112 IV flags = PerlIOBase(f)->flags;
4113 STDCHAR *chk = (c->nl) ? (c->nl+1) : b->end;
4114 if (ptr+cnt == c->nl && c->nl+1 == b->end && *c->nl == 0xd) {
4115 /* Defered CR at end of buffer case - we lied about count */
4121 Perl_croak(aTHX_ "ptr wrong %p != %p fl=%08" UVxf
4122 " nl=%p e=%p for %d", ptr, chk, flags, c->nl,
4130 * They have taken what we lied about
4138 PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
4142 PerlIOCrlf_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
4144 if (!(PerlIOBase(f)->flags & PERLIO_F_CRLF))
4145 return PerlIOBuf_write(aTHX_ f, vbuf, count);
4147 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
4148 const STDCHAR *buf = (const STDCHAR *) vbuf;
4149 const STDCHAR *ebuf = buf + count;
4152 if (!(PerlIOBase(f)->flags & PERLIO_F_CANWRITE))
4154 while (buf < ebuf) {
4155 STDCHAR *eptr = b->buf + b->bufsiz;
4156 PerlIOBase(f)->flags |= PERLIO_F_WRBUF;
4157 while (buf < ebuf && b->ptr < eptr) {
4159 if ((b->ptr + 2) > eptr) {
4167 *(b->ptr)++ = 0xd; /* CR */
4168 *(b->ptr)++ = 0xa; /* LF */
4170 if (PerlIOBase(f)->flags & PERLIO_F_LINEBUF) {
4180 if (b->ptr >= eptr) {
4186 if (PerlIOBase(f)->flags & PERLIO_F_UNBUF)
4188 return (buf - (STDCHAR *) vbuf);
4193 PerlIOCrlf_flush(pTHX_ PerlIO *f)
4195 PerlIOCrlf *c = PerlIOSelf(f, PerlIOCrlf);
4200 return PerlIOBuf_flush(aTHX_ f);
4204 PerlIOCrlf_binmode(pTHX_ PerlIO *f)
4206 if ((PerlIOBase(f)->flags & PERLIO_F_CRLF)) {
4207 /* In text mode - flush any pending stuff and flip it */
4208 PerlIOBase(f)->flags &= ~PERLIO_F_CRLF;
4209 #ifndef PERLIO_USING_CRLF
4210 /* CRLF is unusual case - if this is just the :crlf layer pop it */
4211 if (PerlIOBase(f)->tab == &PerlIO_crlf) {
4212 PerlIO_pop(aTHX_ f);
4219 PerlIO_funcs PerlIO_crlf = {
4220 sizeof(PerlIO_funcs),
4223 PERLIO_K_BUFFERED | PERLIO_K_CANCRLF | PERLIO_K_RAW,
4225 PerlIOBuf_popped, /* popped */
4227 PerlIOCrlf_binmode, /* binmode */
4231 PerlIOBuf_read, /* generic read works with ptr/cnt lies
4233 PerlIOCrlf_unread, /* Put CR,LF in buffer for each '\n' */
4234 PerlIOCrlf_write, /* Put CR,LF in buffer for each '\n' */
4242 PerlIOBase_clearerr,
4243 PerlIOBase_setlinebuf,
4248 PerlIOCrlf_set_ptrcnt,
4252 /*--------------------------------------------------------------------------------------*/
4254 * mmap as "buffer" layer
4258 PerlIOBuf base; /* PerlIOBuf stuff */
4259 Mmap_t mptr; /* Mapped address */
4260 Size_t len; /* mapped length */
4261 STDCHAR *bbuf; /* malloced buffer if map fails */
4264 static size_t page_size = 0;
4267 PerlIOMmap_map(pTHX_ PerlIO *f)
4269 PerlIOMmap *m = PerlIOSelf(f, PerlIOMmap);
4270 IV flags = PerlIOBase(f)->flags;
4274 if (flags & PERLIO_F_CANREAD) {
4275 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
4276 int fd = PerlIO_fileno(f);
4278 code = Fstat(fd, &st);
4279 if (code == 0 && S_ISREG(st.st_mode)) {
4280 SSize_t len = st.st_size - b->posn;
4284 #if defined(HAS_SYSCONF) && (defined(_SC_PAGESIZE) || defined(_SC_PAGE_SIZE))
4286 SETERRNO(0, SS_NORMAL);
4287 # ifdef _SC_PAGESIZE
4288 page_size = sysconf(_SC_PAGESIZE);
4290 page_size = sysconf(_SC_PAGE_SIZE);
4292 if ((long) page_size < 0) {
4297 (void) SvUPGRADE(error, SVt_PV);
4298 msg = SvPVx(error, n_a);
4299 Perl_croak(aTHX_ "panic: sysconf: %s",
4304 "panic: sysconf: pagesize unknown");
4308 # ifdef HAS_GETPAGESIZE
4309 page_size = getpagesize();
4311 # if defined(I_SYS_PARAM) && defined(PAGESIZE)
4312 page_size = PAGESIZE; /* compiletime, bad */
4316 if ((IV) page_size <= 0)
4317 Perl_croak(aTHX_ "panic: bad pagesize %" IVdf,
4322 * This is a hack - should never happen - open should
4325 b->posn = PerlIO_tell(PerlIONext(f));
4327 posn = (b->posn / page_size) * page_size;
4328 len = st.st_size - posn;
4329 m->mptr = mmap(NULL, len, PROT_READ, MAP_SHARED, fd, posn);
4330 if (m->mptr && m->mptr != (Mmap_t) - 1) {
4331 #if 0 && defined(HAS_MADVISE) && defined(MADV_SEQUENTIAL)
4332 madvise(m->mptr, len, MADV_SEQUENTIAL);
4334 #if 0 && defined(HAS_MADVISE) && defined(MADV_WILLNEED)
4335 madvise(m->mptr, len, MADV_WILLNEED);
4337 PerlIOBase(f)->flags =
4338 (flags & ~PERLIO_F_EOF) | PERLIO_F_RDBUF;
4339 b->end = ((STDCHAR *) m->mptr) + len;
4340 b->buf = ((STDCHAR *) m->mptr) + (b->posn - posn);
4349 PerlIOBase(f)->flags =
4350 flags | PERLIO_F_EOF | PERLIO_F_RDBUF;
4352 b->ptr = b->end = b->ptr;
4361 PerlIOMmap_unmap(pTHX_ PerlIO *f)
4363 PerlIOMmap *m = PerlIOSelf(f, PerlIOMmap);
4364 PerlIOBuf *b = &m->base;
4368 code = munmap(m->mptr, m->len);
4372 if (PerlIO_seek(PerlIONext(f), b->posn, SEEK_SET) != 0)
4375 b->ptr = b->end = b->buf;
4376 PerlIOBase(f)->flags &= ~(PERLIO_F_RDBUF | PERLIO_F_WRBUF);
4382 PerlIOMmap_get_base(pTHX_ PerlIO *f)
4384 PerlIOMmap *m = PerlIOSelf(f, PerlIOMmap);
4385 PerlIOBuf *b = &m->base;
4386 if (b->buf && (PerlIOBase(f)->flags & PERLIO_F_RDBUF)) {
4388 * Already have a readbuffer in progress
4394 * We have a write buffer or flushed PerlIOBuf read buffer
4396 m->bbuf = b->buf; /* save it in case we need it again */
4397 b->buf = NULL; /* Clear to trigger below */
4400 PerlIOMmap_map(aTHX_ f); /* Try and map it */
4403 * Map did not work - recover PerlIOBuf buffer if we have one
4408 b->ptr = b->end = b->buf;
4411 return PerlIOBuf_get_base(aTHX_ f);
4415 PerlIOMmap_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
4417 PerlIOMmap *m = PerlIOSelf(f, PerlIOMmap);
4418 PerlIOBuf *b = &m->base;
4419 if (PerlIOBase(f)->flags & PERLIO_F_WRBUF)
4421 if (b->ptr && (b->ptr - count) >= b->buf
4422 && memEQ(b->ptr - count, vbuf, count)) {
4424 PerlIOBase(f)->flags &= ~PERLIO_F_EOF;
4429 * Loose the unwritable mapped buffer
4433 * If flush took the "buffer" see if we have one from before
4435 if (!b->buf && m->bbuf)
4438 PerlIOBuf_get_base(aTHX_ f);
4442 return PerlIOBuf_unread(aTHX_ f, vbuf, count);
4446 PerlIOMmap_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
4448 PerlIOMmap *m = PerlIOSelf(f, PerlIOMmap);
4449 PerlIOBuf *b = &m->base;
4450 if (!b->buf || !(PerlIOBase(f)->flags & PERLIO_F_WRBUF)) {
4452 * No, or wrong sort of, buffer
4455 if (PerlIOMmap_unmap(aTHX_ f) != 0)
4459 * If unmap took the "buffer" see if we have one from before
4461 if (!b->buf && m->bbuf)
4464 PerlIOBuf_get_base(aTHX_ f);
4468 return PerlIOBuf_write(aTHX_ f, vbuf, count);
4472 PerlIOMmap_flush(pTHX_ PerlIO *f)
4474 PerlIOMmap *m = PerlIOSelf(f, PerlIOMmap);
4475 PerlIOBuf *b = &m->base;
4476 IV code = PerlIOBuf_flush(aTHX_ f);
4478 * Now we are "synced" at PerlIOBuf level
4485 if (PerlIOMmap_unmap(aTHX_ f) != 0)
4490 * We seem to have a PerlIOBuf buffer which was not mapped
4491 * remember it in case we need one later
4500 PerlIOMmap_fill(pTHX_ PerlIO *f)
4502 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
4503 IV code = PerlIO_flush(f);
4504 if (code == 0 && !b->buf) {
4505 code = PerlIOMmap_map(aTHX_ f);
4507 if (code == 0 && !(PerlIOBase(f)->flags & PERLIO_F_RDBUF)) {
4508 code = PerlIOBuf_fill(aTHX_ f);
4514 PerlIOMmap_close(pTHX_ PerlIO *f)
4516 PerlIOMmap *m = PerlIOSelf(f, PerlIOMmap);
4517 PerlIOBuf *b = &m->base;
4518 IV code = PerlIO_flush(f);
4522 b->ptr = b->end = b->buf;
4524 if (PerlIOBuf_close(aTHX_ f) != 0)
4530 PerlIOMmap_dup(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags)
4532 return PerlIOBase_dup(aTHX_ f, o, param, flags);
4536 PerlIO_funcs PerlIO_mmap = {
4537 sizeof(PerlIO_funcs),
4540 PERLIO_K_BUFFERED|PERLIO_K_RAW,
4544 PerlIOBase_binmode, /* binmode */
4558 PerlIOBase_clearerr,
4559 PerlIOBase_setlinebuf,
4560 PerlIOMmap_get_base,
4564 PerlIOBuf_set_ptrcnt,
4567 #endif /* HAS_MMAP */
4570 Perl_PerlIO_stdin(pTHX)
4573 PerlIO_stdstreams(aTHX);
4575 return &PL_perlio[1];
4579 Perl_PerlIO_stdout(pTHX)
4582 PerlIO_stdstreams(aTHX);
4584 return &PL_perlio[2];
4588 Perl_PerlIO_stderr(pTHX)
4591 PerlIO_stdstreams(aTHX);
4593 return &PL_perlio[3];
4596 /*--------------------------------------------------------------------------------------*/
4599 PerlIO_getname(PerlIO *f, char *buf)
4604 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
4606 name = fgetname(stdio, buf);
4608 Perl_croak(aTHX_ "Don't know how to get file name");
4614 /*--------------------------------------------------------------------------------------*/
4616 * Functions which can be called on any kind of PerlIO implemented in
4620 #undef PerlIO_fdopen
4622 PerlIO_fdopen(int fd, const char *mode)
4625 return PerlIO_openn(aTHX_ Nullch, mode, fd, 0, 0, NULL, 0, NULL);
4630 PerlIO_open(const char *path, const char *mode)
4633 SV *name = sv_2mortal(newSVpvn(path, strlen(path)));
4634 return PerlIO_openn(aTHX_ Nullch, mode, -1, 0, 0, NULL, 1, &name);
4637 #undef Perlio_reopen
4639 PerlIO_reopen(const char *path, const char *mode, PerlIO *f)
4642 SV *name = sv_2mortal(newSVpvn(path, strlen(path)));
4643 return PerlIO_openn(aTHX_ Nullch, mode, -1, 0, 0, f, 1, &name);
4648 PerlIO_getc(PerlIO *f)
4652 SSize_t count = PerlIO_read(f, buf, 1);
4654 return (unsigned char) buf[0];
4659 #undef PerlIO_ungetc
4661 PerlIO_ungetc(PerlIO *f, int ch)
4666 if (PerlIO_unread(f, &buf, 1) == 1)
4674 PerlIO_putc(PerlIO *f, int ch)
4678 return PerlIO_write(f, &buf, 1);
4683 PerlIO_puts(PerlIO *f, const char *s)
4686 STRLEN len = strlen(s);
4687 return PerlIO_write(f, s, len);
4690 #undef PerlIO_rewind
4692 PerlIO_rewind(PerlIO *f)
4695 PerlIO_seek(f, (Off_t) 0, SEEK_SET);
4699 #undef PerlIO_vprintf
4701 PerlIO_vprintf(PerlIO *f, const char *fmt, va_list ap)
4704 SV *sv = newSVpvn("", 0);
4710 Perl_va_copy(ap, apc);
4711 sv_vcatpvf(sv, fmt, &apc);
4713 sv_vcatpvf(sv, fmt, &ap);
4716 wrote = PerlIO_write(f, s, len);
4721 #undef PerlIO_printf
4723 PerlIO_printf(PerlIO *f, const char *fmt, ...)
4728 result = PerlIO_vprintf(f, fmt, ap);
4733 #undef PerlIO_stdoutf
4735 PerlIO_stdoutf(const char *fmt, ...)
4741 result = PerlIO_vprintf(PerlIO_stdout(), fmt, ap);
4746 #undef PerlIO_tmpfile
4748 PerlIO_tmpfile(void)
4751 * I have no idea how portable mkstemp() is ...
4753 #if defined(WIN32) || !defined(HAVE_MKSTEMP)
4756 FILE *stdio = PerlSIO_tmpfile();
4758 if ((f = PerlIO_push(aTHX_(PerlIO_allocate(aTHX)), &PerlIO_stdio, "w+", Nullsv))) {
4759 PerlIOStdio *s = PerlIOSelf(f, PerlIOStdio);
4766 SV *sv = newSVpv("/tmp/PerlIO_XXXXXX", 0);
4767 int fd = mkstemp(SvPVX(sv));
4770 f = PerlIO_fdopen(fd, "w+");
4772 PerlIOBase(f)->flags |= PERLIO_F_TEMP;
4774 PerlLIO_unlink(SvPVX(sv));
4784 #endif /* USE_SFIO */
4785 #endif /* PERLIO_IS_STDIO */
4787 /*======================================================================================*/
4789 * Now some functions in terms of above which may be needed even if we are
4790 * not in true PerlIO mode
4794 #undef PerlIO_setpos
4796 PerlIO_setpos(PerlIO *f, SV *pos)
4801 Off_t *posn = (Off_t *) SvPV(pos, len);
4802 if (f && len == sizeof(Off_t))
4803 return PerlIO_seek(f, *posn, SEEK_SET);
4805 SETERRNO(EINVAL, SS_IVCHAN);
4809 #undef PerlIO_setpos
4811 PerlIO_setpos(PerlIO *f, SV *pos)
4816 Fpos_t *fpos = (Fpos_t *) SvPV(pos, len);
4817 if (f && len == sizeof(Fpos_t)) {
4818 #if defined(USE_64_BIT_STDIO) && defined(USE_FSETPOS64)
4819 return fsetpos64(f, fpos);
4821 return fsetpos(f, fpos);
4825 SETERRNO(EINVAL, SS_IVCHAN);
4831 #undef PerlIO_getpos
4833 PerlIO_getpos(PerlIO *f, SV *pos)
4836 Off_t posn = PerlIO_tell(f);
4837 sv_setpvn(pos, (char *) &posn, sizeof(posn));
4838 return (posn == (Off_t) - 1) ? -1 : 0;
4841 #undef PerlIO_getpos
4843 PerlIO_getpos(PerlIO *f, SV *pos)
4848 #if defined(USE_64_BIT_STDIO) && defined(USE_FSETPOS64)
4849 code = fgetpos64(f, &fpos);
4851 code = fgetpos(f, &fpos);
4853 sv_setpvn(pos, (char *) &fpos, sizeof(fpos));
4858 #if (defined(PERLIO_IS_STDIO) || !defined(USE_SFIO)) && !defined(HAS_VPRINTF)
4861 vprintf(char *pat, char *args)
4863 _doprnt(pat, args, stdout);
4864 return 0; /* wrong, but perl doesn't use the return
4869 vfprintf(FILE *fd, char *pat, char *args)
4871 _doprnt(pat, args, fd);
4872 return 0; /* wrong, but perl doesn't use the return
4878 #ifndef PerlIO_vsprintf
4880 PerlIO_vsprintf(char *s, int n, const char *fmt, va_list ap)
4882 int val = vsprintf(s, fmt, ap);
4884 if (strlen(s) >= (STRLEN) n) {
4886 (void) PerlIO_puts(Perl_error_log,
4887 "panic: sprintf overflow - memory corrupted!\n");
4895 #ifndef PerlIO_sprintf
4897 PerlIO_sprintf(char *s, int n, const char *fmt, ...)
4902 result = PerlIO_vsprintf(s, n, fmt, ap);