This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Integrate a patch from Gentoo for uclibc support.
[perl5.git] / perlio.c
CommitLineData
14a5cf38 1/*
b5f8cc5c 2 * perlio.c Copyright (c) 1996-2004, Nick Ing-Simmons You may distribute
14a5cf38 3 * under the terms of either the GNU General Public License or the
71200d45 4 * Artistic License, as specified in the README file.
760ac839
LW
5 */
6
14a5cf38 7/*
d31a8517
AT
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.
10 */
11
166f8a29
DM
12/* This file contains the functions needed to implement PerlIO, which
13 * is Perl's private replacement for the C stdio library. This is used
14 * by default unless you compile with -Uuseperlio or run with
15 * PERLIO=:stdio (but don't do this unless you know what you're doing)
16 */
17
d31a8517 18/*
71200d45 19 * If we have ActivePerl-like PERL_IMPLICIT_SYS then we need a dTHX to get
14a5cf38 20 * at the dispatch tables, even when we do not need it for other reasons.
71200d45 21 * Invent a dSYS macro to abstract this out
14a5cf38 22 */
7bcba3d4
NIS
23#ifdef PERL_IMPLICIT_SYS
24#define dSYS dTHX
25#else
26#define dSYS dNOOP
27#endif
28
760ac839 29#define VOIDUSED 1
12ae5dfc
JH
30#ifdef PERL_MICRO
31# include "uconfig.h"
32#else
33# include "config.h"
34#endif
760ac839 35
6f9d8c32 36#define PERLIO_NOT_STDIO 0
760ac839 37#if !defined(PERLIO_IS_STDIO) && !defined(USE_SFIO)
14a5cf38 38/*
71200d45 39 * #define PerlIO FILE
14a5cf38 40 */
760ac839
LW
41#endif
42/*
6f9d8c32 43 * This file provides those parts of PerlIO abstraction
88b61e10 44 * which are not #defined in perlio.h.
6f9d8c32 45 * Which these are depends on various Configure #ifdef's
760ac839
LW
46 */
47
48#include "EXTERN.h"
864dbfa3 49#define PERL_IN_PERLIO_C
760ac839
LW
50#include "perl.h"
51
32af7c23
CL
52#ifdef PERL_IMPLICIT_CONTEXT
53#undef dSYS
54#define dSYS dTHX
55#endif
56
0c4f7ff0
NIS
57#include "XSUB.h"
58
9cffb111
OS
59#ifdef __Lynx__
60/* Missing proto on LynxOS */
61int mkstemp(char*);
62#endif
63
1b7a0411 64/* Call the callback or PerlIOBase, and return failure. */
b32dd47e 65#define Perl_PerlIO_or_Base(f, callback, base, failure, args) \
1b7a0411
JH
66 if (PerlIOValid(f)) { \
67 PerlIO_funcs *tab = PerlIOBase(f)->tab; \
68 if (tab && tab->callback) \
69 return (*tab->callback) args; \
70 else \
71 return PerlIOBase_ ## base args; \
72 } \
73 else \
74 SETERRNO(EBADF, SS_IVCHAN); \
75 return failure
76
77/* Call the callback or fail, and return failure. */
b32dd47e 78#define Perl_PerlIO_or_fail(f, callback, failure, args) \
1b7a0411
JH
79 if (PerlIOValid(f)) { \
80 PerlIO_funcs *tab = PerlIOBase(f)->tab; \
81 if (tab && tab->callback) \
82 return (*tab->callback) args; \
83 SETERRNO(EINVAL, LIB_INVARG); \
84 } \
85 else \
86 SETERRNO(EBADF, SS_IVCHAN); \
87 return failure
88
89/* Call the callback or PerlIOBase, and be void. */
b32dd47e 90#define Perl_PerlIO_or_Base_void(f, callback, base, args) \
1b7a0411
JH
91 if (PerlIOValid(f)) { \
92 PerlIO_funcs *tab = PerlIOBase(f)->tab; \
93 if (tab && tab->callback) \
94 (*tab->callback) args; \
95 else \
96 PerlIOBase_ ## base args; \
1b7a0411
JH
97 } \
98 else \
99 SETERRNO(EBADF, SS_IVCHAN)
100
101/* Call the callback or fail, and be void. */
b32dd47e 102#define Perl_PerlIO_or_fail_void(f, callback, args) \
1b7a0411
JH
103 if (PerlIOValid(f)) { \
104 PerlIO_funcs *tab = PerlIOBase(f)->tab; \
105 if (tab && tab->callback) \
106 (*tab->callback) args; \
37725cdc
NIS
107 else \
108 SETERRNO(EINVAL, LIB_INVARG); \
1b7a0411
JH
109 } \
110 else \
111 SETERRNO(EBADF, SS_IVCHAN)
112
60382766 113int
f5b9d040 114perlsio_binmode(FILE *fp, int iotype, int mode)
60382766 115{
14a5cf38 116 /*
71200d45 117 * This used to be contents of do_binmode in doio.c
14a5cf38 118 */
60382766
NIS
119#ifdef DOSISH
120# if defined(atarist) || defined(__MINT__)
f5b9d040 121 if (!fflush(fp)) {
60382766 122 if (mode & O_BINARY)
14a5cf38 123 ((FILE *) fp)->_flag |= _IOBIN;
60382766 124 else
14a5cf38 125 ((FILE *) fp)->_flag &= ~_IOBIN;
60382766
NIS
126 return 1;
127 }
128 return 0;
129# else
eb73beca 130 dTHX;
14a5cf38
JH
131#ifdef NETWARE
132 if (PerlLIO_setmode(fp, mode) != -1) {
133#else
f5b9d040 134 if (PerlLIO_setmode(fileno(fp), mode) != -1) {
14a5cf38 135#endif
60382766 136# if defined(WIN32) && defined(__BORLANDC__)
14a5cf38 137 /*
71200d45 138 * The translation mode of the stream is maintained independent of
14a5cf38 139 * the translation mode of the fd in the Borland RTL (heavy
71200d45 140 * digging through their runtime sources reveal). User has to set
14a5cf38 141 * the mode explicitly for the stream (though they don't document
71200d45 142 * this anywhere). GSAR 97-5-24
60382766 143 */
14a5cf38 144 fseek(fp, 0L, 0);
60382766 145 if (mode & O_BINARY)
f5b9d040 146 fp->flags |= _F_BIN;
60382766 147 else
14a5cf38 148 fp->flags &= ~_F_BIN;
60382766
NIS
149# endif
150 return 1;
151 }
152 else
153 return 0;
154# endif
155#else
156# if defined(USEMYBINMODE)
04a0f00b 157 dTHX;
60382766
NIS
158 if (my_binmode(fp, iotype, mode) != FALSE)
159 return 1;
160 else
161 return 0;
162# else
163 return 1;
164# endif
165#endif
166}
167
06c7082d 168#ifndef O_ACCMODE
22569500 169#define O_ACCMODE 3 /* Assume traditional implementation */
06c7082d
NIS
170#endif
171
172int
173PerlIO_intmode2str(int rawmode, char *mode, int *writing)
174{
175 int result = rawmode & O_ACCMODE;
176 int ix = 0;
177 int ptype;
178 switch (result) {
179 case O_RDONLY:
180 ptype = IoTYPE_RDONLY;
181 break;
182 case O_WRONLY:
183 ptype = IoTYPE_WRONLY;
184 break;
185 case O_RDWR:
186 default:
187 ptype = IoTYPE_RDWR;
188 break;
189 }
190 if (writing)
191 *writing = (result != O_RDONLY);
192
193 if (result == O_RDONLY) {
194 mode[ix++] = 'r';
195 }
196#ifdef O_APPEND
197 else if (rawmode & O_APPEND) {
198 mode[ix++] = 'a';
199 if (result != O_WRONLY)
200 mode[ix++] = '+';
201 }
202#endif
203 else {
204 if (result == O_WRONLY)
205 mode[ix++] = 'w';
206 else {
207 mode[ix++] = 'r';
208 mode[ix++] = '+';
209 }
210 }
211 if (rawmode & O_BINARY)
212 mode[ix++] = 'b';
213 mode[ix] = '\0';
214 return ptype;
215}
216
eb73beca
NIS
217#ifndef PERLIO_LAYERS
218int
219PerlIO_apply_layers(pTHX_ PerlIO *f, const char *mode, const char *names)
220{
6874a2de
NIS
221 if (!names || !*names
222 || strEQ(names, ":crlf")
223 || strEQ(names, ":raw")
224 || strEQ(names, ":bytes")
225 ) {
14a5cf38
JH
226 return 0;
227 }
228 Perl_croak(aTHX_ "Cannot apply \"%s\" in non-PerlIO perl", names);
229 /*
71200d45 230 * NOTREACHED
14a5cf38
JH
231 */
232 return -1;
eb73beca
NIS
233}
234
13621cfb
NIS
235void
236PerlIO_destruct(pTHX)
237{
238}
239
f5b9d040
NIS
240int
241PerlIO_binmode(pTHX_ PerlIO *fp, int iotype, int mode, const char *names)
242{
92bff44d 243#ifdef USE_SFIO
14a5cf38 244 return 1;
92bff44d 245#else
14a5cf38 246 return perlsio_binmode(fp, iotype, mode);
92bff44d 247#endif
f5b9d040 248}
60382766 249
e0fa5af2 250PerlIO *
ecdeb87c 251PerlIO_fdupopen(pTHX_ PerlIO *f, CLONE_PARAMS *param, int flags)
e0fa5af2 252{
0553478e
NIS
253#ifdef PERL_MICRO
254 return NULL;
255#else
256#ifdef PERL_IMPLICIT_SYS
22569500 257 return PerlSIO_fdupopen(f);
0553478e 258#else
30753f56
NIS
259#ifdef WIN32
260 return win32_fdupopen(f);
261#else
e0fa5af2
NIS
262 if (f) {
263 int fd = PerlLIO_dup(PerlIO_fileno(f));
264 if (fd >= 0) {
06c7082d
NIS
265 char mode[8];
266 int omode = fcntl(fd, F_GETFL);
a5936e02
JH
267#ifdef DJGPP
268 omode = djgpp_get_stream_mode(f);
269#endif
06c7082d 270 PerlIO_intmode2str(omode,mode,NULL);
e0fa5af2 271 /* the r+ is a hack */
06c7082d 272 return PerlIO_fdopen(fd, mode);
e0fa5af2
NIS
273 }
274 return NULL;
275 }
276 else {
93189314 277 SETERRNO(EBADF, SS_IVCHAN);
e0fa5af2 278 }
7114a2d2 279#endif
e0fa5af2 280 return NULL;
0553478e 281#endif
30753f56 282#endif
e0fa5af2
NIS
283}
284
285
14a5cf38 286/*
71200d45 287 * De-mux PerlIO_openn() into fdopen, freopen and fopen type entries
14a5cf38 288 */
ee518936
NIS
289
290PerlIO *
14a5cf38
JH
291PerlIO_openn(pTHX_ const char *layers, const char *mode, int fd,
292 int imode, int perm, PerlIO *old, int narg, SV **args)
293{
7cf31beb
NIS
294 if (narg) {
295 if (narg > 1) {
3b8752bb 296 Perl_croak(aTHX_ "More than one argument to open");
7cf31beb 297 }
14a5cf38
JH
298 if (*args == &PL_sv_undef)
299 return PerlIO_tmpfile();
300 else {
301 char *name = SvPV_nolen(*args);
3b6c1aba 302 if (*mode == IoTYPE_NUMERIC) {
14a5cf38
JH
303 fd = PerlLIO_open3(name, imode, perm);
304 if (fd >= 0)
305 return PerlIO_fdopen(fd, (char *) mode + 1);
306 }
307 else if (old) {
308 return PerlIO_reopen(name, mode, old);
309 }
310 else {
311 return PerlIO_open(name, mode);
312 }
313 }
314 }
315 else {
316 return PerlIO_fdopen(fd, (char *) mode);
317 }
318 return NULL;
ee518936
NIS
319}
320
0c4f7ff0
NIS
321XS(XS_PerlIO__Layer__find)
322{
14a5cf38
JH
323 dXSARGS;
324 if (items < 2)
325 Perl_croak(aTHX_ "Usage class->find(name[,load])");
326 else {
327 char *name = SvPV_nolen(ST(1));
328 ST(0) = (strEQ(name, "crlf")
329 || strEQ(name, "raw")) ? &PL_sv_yes : &PL_sv_undef;
330 XSRETURN(1);
331 }
0c4f7ff0
NIS
332}
333
334
335void
336Perl_boot_core_PerlIO(pTHX)
337{
14a5cf38 338 newXS("PerlIO::Layer::find", XS_PerlIO__Layer__find, __FILE__);
0c4f7ff0
NIS
339}
340
ac27b0f5
NIS
341#endif
342
32e30700 343
6f9d8c32 344#ifdef PERLIO_IS_STDIO
760ac839
LW
345
346void
e8632036 347PerlIO_init(pTHX)
760ac839 348{
14a5cf38
JH
349 /*
350 * Does nothing (yet) except force this file to be included in perl
71200d45 351 * binary. That allows this file to force inclusion of other functions
14a5cf38 352 * that may be required by loadable extensions e.g. for
71200d45 353 * FileHandle::tmpfile
14a5cf38 354 */
760ac839
LW
355}
356
33dcbb9a
PP
357#undef PerlIO_tmpfile
358PerlIO *
8ac85365 359PerlIO_tmpfile(void)
33dcbb9a 360{
14a5cf38 361 return tmpfile();
33dcbb9a
PP
362}
363
22569500 364#else /* PERLIO_IS_STDIO */
760ac839
LW
365
366#ifdef USE_SFIO
367
368#undef HAS_FSETPOS
369#undef HAS_FGETPOS
370
14a5cf38
JH
371/*
372 * This section is just to make sure these functions get pulled in from
71200d45 373 * libsfio.a
14a5cf38 374 */
760ac839
LW
375
376#undef PerlIO_tmpfile
377PerlIO *
c78749f2 378PerlIO_tmpfile(void)
760ac839 379{
14a5cf38 380 return sftmp(0);
760ac839
LW
381}
382
383void
e8632036 384PerlIO_init(pTHX)
760ac839 385{
14a5cf38
JH
386 /*
387 * Force this file to be included in perl binary. Which allows this
388 * file to force inclusion of other functions that may be required by
71200d45 389 * loadable extensions e.g. for FileHandle::tmpfile
14a5cf38 390 */
760ac839 391
14a5cf38 392 /*
71200d45 393 * Hack sfio does its own 'autoflush' on stdout in common cases. Flush
14a5cf38 394 * results in a lot of lseek()s to regular files and lot of small
71200d45 395 * writes to pipes.
14a5cf38
JH
396 */
397 sfset(sfstdout, SF_SHARE, 0);
760ac839
LW
398}
399
b9d6bf13 400/* This is not the reverse of PerlIO_exportFILE(), PerlIO_releaseFILE() is. */
92bff44d 401PerlIO *
4b069b44 402PerlIO_importFILE(FILE *stdio, const char *mode)
92bff44d 403{
14a5cf38 404 int fd = fileno(stdio);
4b069b44 405 if (!mode || !*mode) {
81428673 406 mode = "r+";
4b069b44
NIS
407 }
408 return PerlIO_fdopen(fd, mode);
92bff44d
NIS
409}
410
411FILE *
412PerlIO_findFILE(PerlIO *pio)
413{
14a5cf38
JH
414 int fd = PerlIO_fileno(pio);
415 FILE *f = fdopen(fd, "r+");
416 PerlIO_flush(pio);
417 if (!f && errno == EINVAL)
418 f = fdopen(fd, "w");
419 if (!f && errno == EINVAL)
420 f = fdopen(fd, "r");
421 return f;
92bff44d
NIS
422}
423
424
22569500 425#else /* USE_SFIO */
6f9d8c32 426/*======================================================================================*/
14a5cf38 427/*
71200d45 428 * Implement all the PerlIO interface ourselves.
9e353e3b 429 */
760ac839 430
76ced9ad
NIS
431#include "perliol.h"
432
14a5cf38
JH
433/*
434 * We _MUST_ have <unistd.h> if we are using lseek() and may have large
71200d45 435 * files
14a5cf38 436 */
02f66e2f
NIS
437#ifdef I_UNISTD
438#include <unistd.h>
439#endif
06da4f11
NIS
440#ifdef HAS_MMAP
441#include <sys/mman.h>
442#endif
443
04fa0c70
RB
444/*
445 * Why is this here - not in perlio.h? RMB
8a521f28 446 */
14a5cf38 447void PerlIO_debug(const char *fmt, ...)
287c8091 448 __attribute__format__(__printf__, 1, 2);
6f9d8c32 449
6f9d8c32 450void
14a5cf38
JH
451PerlIO_debug(const char *fmt, ...)
452{
453 static int dbg = 0;
454 va_list ap;
455 dSYS;
456 va_start(ap, fmt);
457 if (!dbg) {
458 char *s = PerlEnv_getenv("PERLIO_DEBUG");
459 if (s && *s)
460 dbg = PerlLIO_open3(s, O_WRONLY | O_CREAT | O_APPEND, 0666);
461 else
462 dbg = -1;
463 }
464 if (dbg > 0) {
465 dTHX;
70ace5da
NIS
466#ifdef USE_ITHREADS
467 /* Use fixed buffer as sv_catpvf etc. needs SVs */
468 char buffer[1024];
469 char *s;
470 STRLEN len;
471 s = CopFILE(PL_curcop);
472 if (!s)
473 s = "(none)";
474 sprintf(buffer, "%s:%" IVdf " ", s, (IV) CopLINE(PL_curcop));
22569500 475 len = strlen(buffer);
70ace5da
NIS
476 vsprintf(buffer+len, fmt, ap);
477 PerlLIO_write(dbg, buffer, strlen(buffer));
478#else
14a5cf38
JH
479 SV *sv = newSVpvn("", 0);
480 char *s;
481 STRLEN len;
482 s = CopFILE(PL_curcop);
483 if (!s)
484 s = "(none)";
485 Perl_sv_catpvf(aTHX_ sv, "%s:%" IVdf " ", s,
486 (IV) CopLINE(PL_curcop));
487 Perl_sv_vcatpvf(aTHX_ sv, fmt, &ap);
488
489 s = SvPV(sv, len);
490 PerlLIO_write(dbg, s, len);
491 SvREFCNT_dec(sv);
70ace5da 492#endif
14a5cf38
JH
493 }
494 va_end(ap);
6f9d8c32
NIS
495}
496
9e353e3b
NIS
497/*--------------------------------------------------------------------------------------*/
498
14a5cf38 499/*
71200d45 500 * Inner level routines
14a5cf38 501 */
9e353e3b 502
14a5cf38 503/*
71200d45 504 * Table of pointers to the PerlIO structs (malloc'ed)
14a5cf38 505 */
05d1247b 506#define PERLIO_TABLE_SIZE 64
6f9d8c32 507
760ac839 508PerlIO *
5f1a76d0 509PerlIO_allocate(pTHX)
6f9d8c32 510{
14a5cf38 511 /*
71200d45 512 * Find a free slot in the table, allocating new table as necessary
14a5cf38
JH
513 */
514 PerlIO **last;
515 PerlIO *f;
a1ea730d 516 last = &PL_perlio;
14a5cf38
JH
517 while ((f = *last)) {
518 int i;
519 last = (PerlIO **) (f);
520 for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
521 if (!*++f) {
522 return f;
523 }
524 }
525 }
3a1ee7e8 526 Newz('I',f,PERLIO_TABLE_SIZE,PerlIO);
14a5cf38
JH
527 if (!f) {
528 return NULL;
529 }
530 *last = f;
531 return f + 1;
05d1247b
NIS
532}
533
a1ea730d
NIS
534#undef PerlIO_fdupopen
535PerlIO *
ecdeb87c 536PerlIO_fdupopen(pTHX_ PerlIO *f, CLONE_PARAMS *param, int flags)
a1ea730d 537{
04892f78 538 if (PerlIOValid(f)) {
a1ea730d 539 PerlIO_funcs *tab = PerlIOBase(f)->tab;
fe5a182c 540 PerlIO_debug("fdupopen f=%p param=%p\n",(void*)f,(void*)param);
210e727c
JH
541 if (tab && tab->Dup)
542 return (*tab->Dup)(aTHX_ PerlIO_allocate(aTHX), f, param, flags);
37725cdc
NIS
543 else {
544 return PerlIOBase_dup(aTHX_ PerlIO_allocate(aTHX), f, param, flags);
545 }
a1ea730d 546 }
210e727c
JH
547 else
548 SETERRNO(EBADF, SS_IVCHAN);
549
550 return NULL;
a1ea730d
NIS
551}
552
553void
5f1a76d0 554PerlIO_cleantable(pTHX_ PerlIO **tablep)
05d1247b 555{
14a5cf38
JH
556 PerlIO *table = *tablep;
557 if (table) {
558 int i;
559 PerlIO_cleantable(aTHX_(PerlIO **) & (table[0]));
560 for (i = PERLIO_TABLE_SIZE - 1; i > 0; i--) {
561 PerlIO *f = table + i;
562 if (*f) {
563 PerlIO_close(f);
564 }
565 }
3a1ee7e8 566 Safefree(table);
14a5cf38 567 *tablep = NULL;
05d1247b 568 }
05d1247b
NIS
569}
570
fcf2db38
NIS
571
572PerlIO_list_t *
3a1ee7e8 573PerlIO_list_alloc(pTHX)
fcf2db38 574{
14a5cf38
JH
575 PerlIO_list_t *list;
576 Newz('L', list, 1, PerlIO_list_t);
577 list->refcnt = 1;
578 return list;
fcf2db38
NIS
579}
580
581void
3a1ee7e8 582PerlIO_list_free(pTHX_ PerlIO_list_t *list)
fcf2db38 583{
14a5cf38
JH
584 if (list) {
585 if (--list->refcnt == 0) {
586 if (list->array) {
14a5cf38
JH
587 IV i;
588 for (i = 0; i < list->cur; i++) {
589 if (list->array[i].arg)
590 SvREFCNT_dec(list->array[i].arg);
591 }
592 Safefree(list->array);
593 }
594 Safefree(list);
595 }
596 }
fcf2db38
NIS
597}
598
599void
3a1ee7e8 600PerlIO_list_push(pTHX_ PerlIO_list_t *list, PerlIO_funcs *funcs, SV *arg)
14a5cf38 601{
14a5cf38
JH
602 PerlIO_pair_t *p;
603 if (list->cur >= list->len) {
604 list->len += 8;
605 if (list->array)
606 Renew(list->array, list->len, PerlIO_pair_t);
607 else
608 New('l', list->array, list->len, PerlIO_pair_t);
609 }
610 p = &(list->array[list->cur++]);
611 p->funcs = funcs;
612 if ((p->arg = arg)) {
613 SvREFCNT_inc(arg);
614 }
fcf2db38
NIS
615}
616
3a1ee7e8
NIS
617PerlIO_list_t *
618PerlIO_clone_list(pTHX_ PerlIO_list_t *proto, CLONE_PARAMS *param)
619{
694c95cf
JH
620 PerlIO_list_t *list = (PerlIO_list_t *) NULL;
621 if (proto) {
622 int i;
623 list = PerlIO_list_alloc(aTHX);
624 for (i=0; i < proto->cur; i++) {
625 SV *arg = Nullsv;
626 if (proto->array[i].arg)
627 arg = PerlIO_sv_dup(aTHX_ proto->array[i].arg,param);
628 PerlIO_list_push(aTHX_ list, proto->array[i].funcs, arg);
629 }
3a1ee7e8
NIS
630 }
631 return list;
632}
4a4a6116 633
05d1247b 634void
3a1ee7e8 635PerlIO_clone(pTHX_ PerlInterpreter *proto, CLONE_PARAMS *param)
9a6404c5 636{
3aaf42a7 637#ifdef USE_ITHREADS
3a1ee7e8
NIS
638 PerlIO **table = &proto->Iperlio;
639 PerlIO *f;
640 PL_perlio = NULL;
641 PL_known_layers = PerlIO_clone_list(aTHX_ proto->Iknown_layers, param);
642 PL_def_layerlist = PerlIO_clone_list(aTHX_ proto->Idef_layerlist, param);
643 PerlIO_allocate(aTHX); /* root slot is never used */
694c95cf 644 PerlIO_debug("Clone %p from %p\n",aTHX,proto);
3a1ee7e8
NIS
645 while ((f = *table)) {
646 int i;
647 table = (PerlIO **) (f++);
648 for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
649 if (*f) {
93a8090d 650 (void) fp_dup(f, 0, param);
3a1ee7e8
NIS
651 }
652 f++;
653 }
654 }
3aaf42a7 655#endif
9a6404c5
DM
656}
657
658void
13621cfb
NIS
659PerlIO_destruct(pTHX)
660{
a1ea730d 661 PerlIO **table = &PL_perlio;
14a5cf38 662 PerlIO *f;
694c95cf
JH
663#ifdef USE_ITHREADS
664 PerlIO_debug("Destruct %p\n",aTHX);
665#endif
14a5cf38
JH
666 while ((f = *table)) {
667 int i;
668 table = (PerlIO **) (f++);
669 for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
670 PerlIO *x = f;
671 PerlIOl *l;
672 while ((l = *x)) {
673 if (l->tab->kind & PERLIO_K_DESTRUCT) {
674 PerlIO_debug("Destruct popping %s\n", l->tab->name);
675 PerlIO_flush(x);
676 PerlIO_pop(aTHX_ x);
677 }
678 else {
679 x = PerlIONext(x);
680 }
681 }
682 f++;
683 }
684 }
13621cfb
NIS
685}
686
687void
a999f61b 688PerlIO_pop(pTHX_ PerlIO *f)
760ac839 689{
14a5cf38
JH
690 PerlIOl *l = *f;
691 if (l) {
fe5a182c 692 PerlIO_debug("PerlIO_pop f=%p %s\n", (void*)f, l->tab->name);
14a5cf38
JH
693 if (l->tab->Popped) {
694 /*
695 * If popped returns non-zero do not free its layer structure
696 * it has either done so itself, or it is shared and still in
71200d45 697 * use
14a5cf38 698 */
f62ce20a 699 if ((*l->tab->Popped) (aTHX_ f) != 0)
14a5cf38
JH
700 return;
701 }
b47cad08 702 *f = l->next;
3a1ee7e8 703 Safefree(l);
a8c08ecd 704 }
6f9d8c32
NIS
705}
706
39f7a870
JH
707/* Return as an array the stack of layers on a filehandle. Note that
708 * the stack is returned top-first in the array, and there are three
709 * times as many array elements as there are layers in the stack: the
710 * first element of a layer triplet is the name, the second one is the
711 * arguments, and the third one is the flags. */
712
713AV *
714PerlIO_get_layers(pTHX_ PerlIO *f)
715{
716 AV *av = newAV();
717
718 if (PerlIOValid(f)) {
39f7a870
JH
719 PerlIOl *l = PerlIOBase(f);
720
721 while (l) {
722 SV *name = l->tab && l->tab->name ?
723 newSVpv(l->tab->name, 0) : &PL_sv_undef;
724 SV *arg = l->tab && l->tab->Getarg ?
725 (*l->tab->Getarg)(aTHX_ &l, 0, 0) : &PL_sv_undef;
726 av_push(av, name);
727 av_push(av, arg);
728 av_push(av, newSViv((IV)l->flags));
729 l = l->next;
730 }
731 }
732
733 return av;
734}
735
9e353e3b 736/*--------------------------------------------------------------------------------------*/
14a5cf38 737/*
71200d45 738 * XS Interface for perl code
14a5cf38 739 */
9e353e3b 740
fcf2db38 741PerlIO_funcs *
2edd7e44 742PerlIO_find_layer(pTHX_ const char *name, STRLEN len, int load)
f3862f8b 743{
14a5cf38
JH
744 IV i;
745 if ((SSize_t) len <= 0)
746 len = strlen(name);
3a1ee7e8
NIS
747 for (i = 0; i < PL_known_layers->cur; i++) {
748 PerlIO_funcs *f = PL_known_layers->array[i].funcs;
a9f76400 749 if (memEQ(f->name, name, len) && f->name[len] == 0) {
fe5a182c 750 PerlIO_debug("%.*s => %p\n", (int) len, name, (void*)f);
14a5cf38
JH
751 return f;
752 }
753 }
3a1ee7e8
NIS
754 if (load && PL_subname && PL_def_layerlist
755 && PL_def_layerlist->cur >= 2) {
d7a09b41
SR
756 if (PL_in_load_module) {
757 Perl_croak(aTHX_ "Recursive call to Perl_load_module in PerlIO_find_layer");
758 return NULL;
759 } else {
760 SV *pkgsv = newSVpvn("PerlIO", 6);
761 SV *layer = newSVpvn(name, len);
c9bca74a
NIS
762 CV *cv = get_cv("PerlIO::Layer::NoWarnings", FALSE);
763 ENTER;
d7a09b41 764 SAVEINT(PL_in_load_module);
c9bca74a
NIS
765 if (cv) {
766 SAVESPTR(PL_warnhook);
767 PL_warnhook = (SV *) cv;
768 }
d7a09b41
SR
769 PL_in_load_module++;
770 /*
771 * The two SVs are magically freed by load_module
772 */
773 Perl_load_module(aTHX_ 0, pkgsv, Nullsv, layer, Nullsv);
774 PL_in_load_module--;
775 LEAVE;
776 return PerlIO_find_layer(aTHX_ name, len, 0);
777 }
14a5cf38
JH
778 }
779 PerlIO_debug("Cannot find %.*s\n", (int) len, name);
780 return NULL;
f3862f8b
NIS
781}
782
2a1bc955 783#ifdef USE_ATTRIBUTES_FOR_PERLIO
b13b2135
NIS
784
785static int
786perlio_mg_set(pTHX_ SV *sv, MAGIC *mg)
787{
14a5cf38
JH
788 if (SvROK(sv)) {
789 IO *io = GvIOn((GV *) SvRV(sv));
790 PerlIO *ifp = IoIFP(io);
791 PerlIO *ofp = IoOFP(io);
792 Perl_warn(aTHX_ "set %" SVf " %p %p %p", sv, io, ifp, ofp);
793 }
794 return 0;
b13b2135
NIS
795}
796
797static int
798perlio_mg_get(pTHX_ SV *sv, MAGIC *mg)
799{
14a5cf38
JH
800 if (SvROK(sv)) {
801 IO *io = GvIOn((GV *) SvRV(sv));
802 PerlIO *ifp = IoIFP(io);
803 PerlIO *ofp = IoOFP(io);
804 Perl_warn(aTHX_ "get %" SVf " %p %p %p", sv, io, ifp, ofp);
805 }
806 return 0;
b13b2135
NIS
807}
808
809static int
810perlio_mg_clear(pTHX_ SV *sv, MAGIC *mg)
811{
14a5cf38
JH
812 Perl_warn(aTHX_ "clear %" SVf, sv);
813 return 0;
b13b2135
NIS
814}
815
816static int
817perlio_mg_free(pTHX_ SV *sv, MAGIC *mg)
818{
14a5cf38
JH
819 Perl_warn(aTHX_ "free %" SVf, sv);
820 return 0;
b13b2135
NIS
821}
822
823MGVTBL perlio_vtab = {
14a5cf38
JH
824 perlio_mg_get,
825 perlio_mg_set,
22569500 826 NULL, /* len */
14a5cf38
JH
827 perlio_mg_clear,
828 perlio_mg_free
b13b2135
NIS
829};
830
831XS(XS_io_MODIFY_SCALAR_ATTRIBUTES)
832{
14a5cf38
JH
833 dXSARGS;
834 SV *sv = SvRV(ST(1));
835 AV *av = newAV();
836 MAGIC *mg;
837 int count = 0;
838 int i;
839 sv_magic(sv, (SV *) av, PERL_MAGIC_ext, NULL, 0);
840 SvRMAGICAL_off(sv);
841 mg = mg_find(sv, PERL_MAGIC_ext);
842 mg->mg_virtual = &perlio_vtab;
843 mg_magical(sv);
844 Perl_warn(aTHX_ "attrib %" SVf, sv);
845 for (i = 2; i < items; i++) {
846 STRLEN len;
847 const char *name = SvPV(ST(i), len);
848 SV *layer = PerlIO_find_layer(aTHX_ name, len, 1);
849 if (layer) {
850 av_push(av, SvREFCNT_inc(layer));
851 }
852 else {
853 ST(count) = ST(i);
854 count++;
855 }
856 }
857 SvREFCNT_dec(av);
858 XSRETURN(count);
859}
860
22569500 861#endif /* USE_ATTIBUTES_FOR_PERLIO */
2a1bc955 862
e3f3bf95
NIS
863SV *
864PerlIO_tab_sv(pTHX_ PerlIO_funcs *tab)
f3862f8b 865{
14a5cf38
JH
866 HV *stash = gv_stashpv("PerlIO::Layer", TRUE);
867 SV *sv = sv_bless(newRV_noinc(newSViv(PTR2IV(tab))), stash);
868 return sv;
e3f3bf95
NIS
869}
870
c9bca74a
NIS
871XS(XS_PerlIO__Layer__NoWarnings)
872{
37725cdc 873 /* This is used as a %SIG{__WARN__} handler to supress warnings
c9bca74a
NIS
874 during loading of layers.
875 */
876 dXSARGS;
877 if (items)
878 PerlIO_debug("warning:%s\n",SvPV_nolen(ST(0)));
879 XSRETURN(0);
880}
881
0c4f7ff0
NIS
882XS(XS_PerlIO__Layer__find)
883{
14a5cf38
JH
884 dXSARGS;
885 if (items < 2)
886 Perl_croak(aTHX_ "Usage class->find(name[,load])");
887 else {
888 STRLEN len = 0;
889 char *name = SvPV(ST(1), len);
890 bool load = (items > 2) ? SvTRUE(ST(2)) : 0;
891 PerlIO_funcs *layer = PerlIO_find_layer(aTHX_ name, len, load);
892 ST(0) =
893 (layer) ? sv_2mortal(PerlIO_tab_sv(aTHX_ layer)) :
894 &PL_sv_undef;
895 XSRETURN(1);
896 }
0c4f7ff0
NIS
897}
898
e3f3bf95
NIS
899void
900PerlIO_define_layer(pTHX_ PerlIO_funcs *tab)
901{
3a1ee7e8
NIS
902 if (!PL_known_layers)
903 PL_known_layers = PerlIO_list_alloc(aTHX);
904 PerlIO_list_push(aTHX_ PL_known_layers, tab, Nullsv);
fe5a182c 905 PerlIO_debug("define %s %p\n", tab->name, (void*)tab);
f3862f8b
NIS
906}
907
1141d9f8 908int
fcf2db38 909PerlIO_parse_layers(pTHX_ PerlIO_list_t *av, const char *names)
1141d9f8 910{
14a5cf38
JH
911 if (names) {
912 const char *s = names;
913 while (*s) {
914 while (isSPACE(*s) || *s == ':')
915 s++;
916 if (*s) {
917 STRLEN llen = 0;
918 const char *e = s;
919 const char *as = Nullch;
920 STRLEN alen = 0;
921 if (!isIDFIRST(*s)) {
922 /*
923 * Message is consistent with how attribute lists are
924 * passed. Even though this means "foo : : bar" is
71200d45 925 * seen as an invalid separator character.
14a5cf38
JH
926 */
927 char q = ((*s == '\'') ? '"' : '\'');
99ef548b 928 if (ckWARN(WARN_LAYER))
22569500 929 Perl_warner(aTHX_ packWARN(WARN_LAYER),
b4581f09 930 "Invalid separator character %c%c%c in PerlIO layer specification %s",
1e616cf5 931 q, *s, q, s);
93189314 932 SETERRNO(EINVAL, LIB_INVARG);
14a5cf38
JH
933 return -1;
934 }
935 do {
936 e++;
937 } while (isALNUM(*e));
938 llen = e - s;
939 if (*e == '(') {
940 int nesting = 1;
941 as = ++e;
942 while (nesting) {
943 switch (*e++) {
944 case ')':
945 if (--nesting == 0)
946 alen = (e - 1) - as;
947 break;
948 case '(':
949 ++nesting;
950 break;
951 case '\\':
952 /*
953 * It's a nul terminated string, not allowed
954 * to \ the terminating null. Anything other
71200d45 955 * character is passed over.
14a5cf38
JH
956 */
957 if (*e++) {
958 break;
959 }
960 /*
71200d45 961 * Drop through
14a5cf38
JH
962 */
963 case '\0':
964 e--;
22569500
NIS
965 if (ckWARN(WARN_LAYER))
966 Perl_warner(aTHX_ packWARN(WARN_LAYER),
b4581f09 967 "Argument list not closed for PerlIO layer \"%.*s\"",
14a5cf38
JH
968 (int) (e - s), s);
969 return -1;
970 default:
971 /*
71200d45 972 * boring.
14a5cf38
JH
973 */
974 break;
975 }
976 }
977 }
978 if (e > s) {
99ef548b 979 bool warn_layer = ckWARN(WARN_LAYER);
14a5cf38
JH
980 PerlIO_funcs *layer =
981 PerlIO_find_layer(aTHX_ s, llen, 1);
982 if (layer) {
3a1ee7e8 983 PerlIO_list_push(aTHX_ av, layer,
14a5cf38
JH
984 (as) ? newSVpvn(as,
985 alen) :
986 &PL_sv_undef);
987 }
988 else {
22569500 989 if (warn_layer)
b4581f09 990 Perl_warner(aTHX_ packWARN(WARN_LAYER), "Unknown PerlIO layer \"%.*s\"",
14a5cf38
JH
991 (int) llen, s);
992 return -1;
993 }
994 }
995 s = e;
996 }
997 }
998 }
999 return 0;
1141d9f8
NIS
1000}
1001
dfebf958 1002void
fcf2db38 1003PerlIO_default_buffer(pTHX_ PerlIO_list_t *av)
dfebf958 1004{
14a5cf38 1005 PerlIO_funcs *tab = &PerlIO_perlio;
35990314 1006#ifdef PERLIO_USING_CRLF
6ce75a77 1007 tab = &PerlIO_crlf;
846be114 1008#else
6ce75a77 1009 if (PerlIO_stdio.Set_ptrcnt)
22569500 1010 tab = &PerlIO_stdio;
846be114 1011#endif
14a5cf38 1012 PerlIO_debug("Pushing %s\n", tab->name);
3a1ee7e8 1013 PerlIO_list_push(aTHX_ av, PerlIO_find_layer(aTHX_ tab->name, 0, 0),
14a5cf38 1014 &PL_sv_undef);
dfebf958
NIS
1015}
1016
e3f3bf95 1017SV *
14a5cf38 1018PerlIO_arg_fetch(PerlIO_list_t *av, IV n)
e3f3bf95 1019{
14a5cf38 1020 return av->array[n].arg;
e3f3bf95
NIS
1021}
1022
f3862f8b 1023PerlIO_funcs *
14a5cf38 1024PerlIO_layer_fetch(pTHX_ PerlIO_list_t *av, IV n, PerlIO_funcs *def)
f3862f8b 1025{
14a5cf38
JH
1026 if (n >= 0 && n < av->cur) {
1027 PerlIO_debug("Layer %" IVdf " is %s\n", n,
1028 av->array[n].funcs->name);
1029 return av->array[n].funcs;
1030 }
1031 if (!def)
1032 Perl_croak(aTHX_ "panic: PerlIO layer array corrupt");
1033 return def;
e3f3bf95
NIS
1034}
1035
4ec2216f
NIS
1036IV
1037PerlIOPop_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
1038{
1039 if (PerlIOValid(f)) {
1040 PerlIO_flush(f);
1041 PerlIO_pop(aTHX_ f);
1042 return 0;
1043 }
1044 return -1;
1045}
1046
1047PerlIO_funcs PerlIO_remove = {
1048 sizeof(PerlIO_funcs),
1049 "pop",
1050 0,
1051 PERLIO_K_DUMMY | PERLIO_K_UTF8,
1052 PerlIOPop_pushed,
1053 NULL,
1054 NULL,
1055 NULL,
1056 NULL,
1057 NULL,
1058 NULL,
1059 NULL,
1060 NULL,
1061 NULL,
1062 NULL,
1063 NULL, /* flush */
1064 NULL, /* fill */
1065 NULL,
1066 NULL,
1067 NULL,
1068 NULL,
1069 NULL, /* get_base */
1070 NULL, /* get_bufsiz */
1071 NULL, /* get_ptr */
1072 NULL, /* get_cnt */
1073 NULL, /* set_ptrcnt */
1074};
1075
fcf2db38 1076PerlIO_list_t *
e3f3bf95
NIS
1077PerlIO_default_layers(pTHX)
1078{
3a1ee7e8 1079 if (!PL_def_layerlist) {
14a5cf38
JH
1080 const char *s = (PL_tainting) ? Nullch : PerlEnv_getenv("PERLIO");
1081 PerlIO_funcs *osLayer = &PerlIO_unix;
3a1ee7e8 1082 PL_def_layerlist = PerlIO_list_alloc(aTHX);
14a5cf38 1083 PerlIO_define_layer(aTHX_ & PerlIO_unix);
979e2c82 1084#if defined(WIN32)
14a5cf38 1085 PerlIO_define_layer(aTHX_ & PerlIO_win32);
2f8118af 1086#if 0
14a5cf38 1087 osLayer = &PerlIO_win32;
0c4128ad 1088#endif
2f8118af 1089#endif
14a5cf38
JH
1090 PerlIO_define_layer(aTHX_ & PerlIO_raw);
1091 PerlIO_define_layer(aTHX_ & PerlIO_perlio);
1092 PerlIO_define_layer(aTHX_ & PerlIO_stdio);
1093 PerlIO_define_layer(aTHX_ & PerlIO_crlf);
06da4f11 1094#ifdef HAS_MMAP
14a5cf38 1095 PerlIO_define_layer(aTHX_ & PerlIO_mmap);
06da4f11 1096#endif
14a5cf38 1097 PerlIO_define_layer(aTHX_ & PerlIO_utf8);
4ec2216f 1098 PerlIO_define_layer(aTHX_ & PerlIO_remove);
14a5cf38 1099 PerlIO_define_layer(aTHX_ & PerlIO_byte);
3a1ee7e8 1100 PerlIO_list_push(aTHX_ PL_def_layerlist,
14a5cf38
JH
1101 PerlIO_find_layer(aTHX_ osLayer->name, 0, 0),
1102 &PL_sv_undef);
1103 if (s) {
3a1ee7e8 1104 PerlIO_parse_layers(aTHX_ PL_def_layerlist, s);
14a5cf38
JH
1105 }
1106 else {
3a1ee7e8 1107 PerlIO_default_buffer(aTHX_ PL_def_layerlist);
14a5cf38 1108 }
1141d9f8 1109 }
3a1ee7e8
NIS
1110 if (PL_def_layerlist->cur < 2) {
1111 PerlIO_default_buffer(aTHX_ PL_def_layerlist);
f3862f8b 1112 }
3a1ee7e8 1113 return PL_def_layerlist;
e3f3bf95
NIS
1114}
1115
0c4f7ff0
NIS
1116void
1117Perl_boot_core_PerlIO(pTHX)
1118{
1119#ifdef USE_ATTRIBUTES_FOR_PERLIO
14a5cf38
JH
1120 newXS("io::MODIFY_SCALAR_ATTRIBUTES", XS_io_MODIFY_SCALAR_ATTRIBUTES,
1121 __FILE__);
0c4f7ff0 1122#endif
14a5cf38 1123 newXS("PerlIO::Layer::find", XS_PerlIO__Layer__find, __FILE__);
c9bca74a 1124 newXS("PerlIO::Layer::NoWarnings", XS_PerlIO__Layer__NoWarnings, __FILE__);
0c4f7ff0 1125}
e3f3bf95
NIS
1126
1127PerlIO_funcs *
1128PerlIO_default_layer(pTHX_ I32 n)
1129{
14a5cf38
JH
1130 PerlIO_list_t *av = PerlIO_default_layers(aTHX);
1131 if (n < 0)
1132 n += av->cur;
1133 return PerlIO_layer_fetch(aTHX_ av, n, &PerlIO_stdio);
f3862f8b
NIS
1134}
1135
a999f61b
NIS
1136#define PerlIO_default_top() PerlIO_default_layer(aTHX_ -1)
1137#define PerlIO_default_btm() PerlIO_default_layer(aTHX_ 0)
60382766
NIS
1138
1139void
1141d9f8 1140PerlIO_stdstreams(pTHX)
60382766 1141{
a1ea730d 1142 if (!PL_perlio) {
14a5cf38
JH
1143 PerlIO_allocate(aTHX);
1144 PerlIO_fdopen(0, "Ir" PERLIO_STDTEXT);
1145 PerlIO_fdopen(1, "Iw" PERLIO_STDTEXT);
1146 PerlIO_fdopen(2, "Iw" PERLIO_STDTEXT);
1147 }
60382766
NIS
1148}
1149
1150PerlIO *
14a5cf38
JH
1151PerlIO_push(pTHX_ PerlIO *f, PerlIO_funcs *tab, const char *mode, SV *arg)
1152{
2dc2558e
NIS
1153 if (tab->fsize != sizeof(PerlIO_funcs)) {
1154 mismatch:
1155 Perl_croak(aTHX_ "Layer does not match this perl");
1156 }
1157 if (tab->size) {
1158 PerlIOl *l = NULL;
1159 if (tab->size < sizeof(PerlIOl)) {
1160 goto mismatch;
1161 }
1162 /* Real layer with a data area */
1163 Newc('L',l,tab->size,char,PerlIOl);
1164 if (l && f) {
1165 Zero(l, tab->size, char);
1166 l->next = *f;
1167 l->tab = tab;
1168 *f = l;
1169 PerlIO_debug("PerlIO_push f=%p %s %s %p\n", (void*)f, tab->name,
1170 (mode) ? mode : "(Null)", (void*)arg);
210e727c
JH
1171 if (*l->tab->Pushed &&
1172 (*l->tab->Pushed) (aTHX_ f, mode, arg, tab) != 0) {
2dc2558e
NIS
1173 PerlIO_pop(aTHX_ f);
1174 return NULL;
1175 }
1176 }
1177 }
1178 else if (f) {
1179 /* Pseudo-layer where push does its own stack adjust */
00f51856
NIS
1180 PerlIO_debug("PerlIO_push f=%p %s %s %p\n", (void*)f, tab->name,
1181 (mode) ? mode : "(Null)", (void*)arg);
210e727c
JH
1182 if (tab->Pushed &&
1183 (*tab->Pushed) (aTHX_ f, mode, arg, tab) != 0) {
1184 return NULL;
14a5cf38
JH
1185 }
1186 }
1187 return f;
60382766
NIS
1188}
1189
dfebf958 1190IV
86e05cf2
NIS
1191PerlIOBase_binmode(pTHX_ PerlIO *f)
1192{
1193 if (PerlIOValid(f)) {
1194 /* Is layer suitable for raw stream ? */
1195 if (PerlIOBase(f)->tab->kind & PERLIO_K_RAW) {
1196 /* Yes - turn off UTF-8-ness, to undo UTF-8 locale effects */
1197 PerlIOBase(f)->flags &= ~PERLIO_F_UTF8;
1198 }
1199 else {
1200 /* Not suitable - pop it */
1201 PerlIO_pop(aTHX_ f);
1202 }
1203 return 0;
1204 }
1205 return -1;
1206}
1207
1208IV
2dc2558e 1209PerlIORaw_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
dfebf958 1210{
86e05cf2 1211
04892f78 1212 if (PerlIOValid(f)) {
86e05cf2
NIS
1213 PerlIO *t;
1214 PerlIOl *l;
14a5cf38 1215 PerlIO_flush(f);
86e05cf2
NIS
1216 /*
1217 * Strip all layers that are not suitable for a raw stream
1218 */
1219 t = f;
1220 while (t && (l = *t)) {
1221 if (l->tab->Binmode) {
1222 /* Has a handler - normal case */
1223 if ((*l->tab->Binmode)(aTHX_ f) == 0) {
1224 if (*t == l) {
1225 /* Layer still there - move down a layer */
1226 t = PerlIONext(t);
1227 }
1228 }
1229 else {
1230 return -1;
1231 }
14a5cf38
JH
1232 }
1233 else {
86e05cf2
NIS
1234 /* No handler - pop it */
1235 PerlIO_pop(aTHX_ t);
14a5cf38
JH
1236 }
1237 }
86e05cf2
NIS
1238 if (PerlIOValid(f)) {
1239 PerlIO_debug(":raw f=%p :%s\n", (void*)f, PerlIOBase(f)->tab->name);
1240 return 0;
1241 }
14a5cf38
JH
1242 }
1243 return -1;
dfebf958
NIS
1244}
1245
ac27b0f5 1246int
14a5cf38 1247PerlIO_apply_layera(pTHX_ PerlIO *f, const char *mode,
d9dac8cd 1248 PerlIO_list_t *layers, IV n, IV max)
14a5cf38 1249{
14a5cf38
JH
1250 int code = 0;
1251 while (n < max) {
1252 PerlIO_funcs *tab = PerlIO_layer_fetch(aTHX_ layers, n, NULL);
1253 if (tab) {
1254 if (!PerlIO_push(aTHX_ f, tab, mode, PerlIOArg)) {
1255 code = -1;
1256 break;
1257 }
1258 }
1259 n++;
1260 }
1261 return code;
e3f3bf95
NIS
1262}
1263
1264int
ac27b0f5
NIS
1265PerlIO_apply_layers(pTHX_ PerlIO *f, const char *mode, const char *names)
1266{
14a5cf38 1267 int code = 0;
53f1b6d2 1268 if (f && names) {
3a1ee7e8 1269 PerlIO_list_t *layers = PerlIO_list_alloc(aTHX);
14a5cf38
JH
1270 code = PerlIO_parse_layers(aTHX_ layers, names);
1271 if (code == 0) {
d9dac8cd 1272 code = PerlIO_apply_layera(aTHX_ f, mode, layers, 0, layers->cur);
14a5cf38 1273 }
3a1ee7e8 1274 PerlIO_list_free(aTHX_ layers);
ac27b0f5 1275 }
14a5cf38 1276 return code;
ac27b0f5
NIS
1277}
1278
f3862f8b 1279
60382766 1280/*--------------------------------------------------------------------------------------*/
14a5cf38 1281/*
71200d45 1282 * Given the abstraction above the public API functions
14a5cf38 1283 */
60382766
NIS
1284
1285int
f5b9d040 1286PerlIO_binmode(pTHX_ PerlIO *f, int iotype, int mode, const char *names)
76ced9ad 1287{
14a5cf38 1288 PerlIO_debug("PerlIO_binmode f=%p %s %c %x %s\n",
fe5a182c 1289 (void*)f, PerlIOBase(f)->tab->name, iotype, mode,
14a5cf38 1290 (names) ? names : "(Null)");
03c0554d
NIS
1291 if (names) {
1292 /* Do not flush etc. if (e.g.) switching encodings.
1293 if a pushed layer knows it needs to flush lower layers
1294 (for example :unix which is never going to call them)
1295 it can do the flush when it is pushed.
1296 */
1297 return PerlIO_apply_layers(aTHX_ f, NULL, names) == 0 ? TRUE : FALSE;
1298 }
1299 else {
86e05cf2 1300 /* Fake 5.6 legacy of using this call to turn ON O_TEXT */
35990314 1301#ifdef PERLIO_USING_CRLF
03c0554d
NIS
1302 /* Legacy binmode only has meaning if O_TEXT has a value distinct from
1303 O_BINARY so we can look for it in mode.
1304 */
1305 if (!(mode & O_BINARY)) {
1306 /* Text mode */
86e05cf2
NIS
1307 /* FIXME?: Looking down the layer stack seems wrong,
1308 but is a way of reaching past (say) an encoding layer
1309 to flip CRLF-ness of the layer(s) below
1310 */
03c0554d
NIS
1311 while (*f) {
1312 /* Perhaps we should turn on bottom-most aware layer
1313 e.g. Ilya's idea that UNIX TTY could serve
1314 */
1315 if (PerlIOBase(f)->tab->kind & PERLIO_K_CANCRLF) {
1316 if (!(PerlIOBase(f)->flags & PERLIO_F_CRLF)) {
1317 /* Not in text mode - flush any pending stuff and flip it */
1318 PerlIO_flush(f);
1319 PerlIOBase(f)->flags |= PERLIO_F_CRLF;
1320 }
1321 /* Only need to turn it on in one layer so we are done */
1322 return TRUE;
ed53a2bb 1323 }
03c0554d 1324 f = PerlIONext(f);
14a5cf38 1325 }
03c0554d
NIS
1326 /* Not finding a CRLF aware layer presumably means we are binary
1327 which is not what was requested - so we failed
1328 We _could_ push :crlf layer but so could caller
1329 */
1330 return FALSE;
14a5cf38 1331 }
6ce75a77 1332#endif
86e05cf2
NIS
1333 /* Legacy binmode is now _defined_ as being equivalent to pushing :raw
1334 So code that used to be here is now in PerlIORaw_pushed().
03c0554d 1335 */
86e05cf2 1336 return PerlIO_push(aTHX_ f, &PerlIO_raw, Nullch, Nullsv) ? TRUE : FALSE;
14a5cf38 1337 }
f5b9d040
NIS
1338}
1339
f5b9d040 1340int
e87a358a 1341PerlIO__close(pTHX_ PerlIO *f)
f5b9d040 1342{
37725cdc
NIS
1343 if (PerlIOValid(f)) {
1344 PerlIO_funcs *tab = PerlIOBase(f)->tab;
1345 if (tab && tab->Close)
1346 return (*tab->Close)(aTHX_ f);
1347 else
1348 return PerlIOBase_close(aTHX_ f);
1349 }
14a5cf38 1350 else {
93189314 1351 SETERRNO(EBADF, SS_IVCHAN);
14a5cf38
JH
1352 return -1;
1353 }
76ced9ad
NIS
1354}
1355
b931b1d9 1356int
e87a358a 1357Perl_PerlIO_close(pTHX_ PerlIO *f)
b931b1d9 1358{
37725cdc
NIS
1359 int code = PerlIO__close(aTHX_ f);
1360 while (PerlIOValid(f)) {
1361 PerlIO_pop(aTHX_ f);
f6c77cf1 1362 }
14a5cf38 1363 return code;
b931b1d9
NIS
1364}
1365
b931b1d9 1366int
e87a358a 1367Perl_PerlIO_fileno(pTHX_ PerlIO *f)
b931b1d9 1368{
b32dd47e 1369 Perl_PerlIO_or_Base(f, Fileno, fileno, -1, (aTHX_ f));
b931b1d9
NIS
1370}
1371
1141d9f8
NIS
1372static const char *
1373PerlIO_context_layers(pTHX_ const char *mode)
1374{
14a5cf38
JH
1375 const char *type = NULL;
1376 /*
71200d45 1377 * Need to supply default layer info from open.pm
14a5cf38
JH
1378 */
1379 if (PL_curcop) {
1380 SV *layers = PL_curcop->cop_io;
1381 if (layers) {
1382 STRLEN len;
1383 type = SvPV(layers, len);
1384 if (type && mode[0] != 'r') {
1385 /*
71200d45 1386 * Skip to write part
14a5cf38
JH
1387 */
1388 const char *s = strchr(type, 0);
eb160463 1389 if (s && (STRLEN)(s - type) < len) {
14a5cf38
JH
1390 type = s + 1;
1391 }
1392 }
1393 }
1394 }
1395 return type;
1141d9f8
NIS
1396}
1397
fcf2db38 1398static PerlIO_funcs *
2edd7e44
NIS
1399PerlIO_layer_from_ref(pTHX_ SV *sv)
1400{
14a5cf38 1401 /*
71200d45 1402 * For any scalar type load the handler which is bundled with perl
14a5cf38
JH
1403 */
1404 if (SvTYPE(sv) < SVt_PVAV)
e934609f 1405 return PerlIO_find_layer(aTHX_ "scalar", 6, 1);
14a5cf38
JH
1406
1407 /*
71200d45 1408 * For other types allow if layer is known but don't try and load it
14a5cf38
JH
1409 */
1410 switch (SvTYPE(sv)) {
1411 case SVt_PVAV:
1412 return PerlIO_find_layer(aTHX_ "Array", 5, 0);
1413 case SVt_PVHV:
1414 return PerlIO_find_layer(aTHX_ "Hash", 4, 0);
1415 case SVt_PVCV:
1416 return PerlIO_find_layer(aTHX_ "Code", 4, 0);
1417 case SVt_PVGV:
1418 return PerlIO_find_layer(aTHX_ "Glob", 4, 0);
1419 }
1420 return NULL;
2edd7e44
NIS
1421}
1422
fcf2db38 1423PerlIO_list_t *
14a5cf38
JH
1424PerlIO_resolve_layers(pTHX_ const char *layers,
1425 const char *mode, int narg, SV **args)
1426{
1427 PerlIO_list_t *def = PerlIO_default_layers(aTHX);
1428 int incdef = 1;
a1ea730d 1429 if (!PL_perlio)
14a5cf38
JH
1430 PerlIO_stdstreams(aTHX);
1431 if (narg) {
1432 SV *arg = *args;
1433 /*
71200d45
NIS
1434 * If it is a reference but not an object see if we have a handler
1435 * for it
14a5cf38
JH
1436 */
1437 if (SvROK(arg) && !sv_isobject(arg)) {
1438 PerlIO_funcs *handler = PerlIO_layer_from_ref(aTHX_ SvRV(arg));
1439 if (handler) {
3a1ee7e8
NIS
1440 def = PerlIO_list_alloc(aTHX);
1441 PerlIO_list_push(aTHX_ def, handler, &PL_sv_undef);
14a5cf38
JH
1442 incdef = 0;
1443 }
1444 /*
e934609f 1445 * Don't fail if handler cannot be found :via(...) etc. may do
14a5cf38 1446 * something sensible else we will just stringfy and open
71200d45 1447 * resulting string.
14a5cf38
JH
1448 */
1449 }
1450 }
1451 if (!layers)
1452 layers = PerlIO_context_layers(aTHX_ mode);
1453 if (layers && *layers) {
1454 PerlIO_list_t *av;
1455 if (incdef) {
1456 IV i = def->cur;
3a1ee7e8 1457 av = PerlIO_list_alloc(aTHX);
14a5cf38 1458 for (i = 0; i < def->cur; i++) {
3a1ee7e8 1459 PerlIO_list_push(aTHX_ av, def->array[i].funcs,
14a5cf38
JH
1460 def->array[i].arg);
1461 }
1462 }
1463 else {
1464 av = def;
1465 }
0cff2cf3
NIS
1466 if (PerlIO_parse_layers(aTHX_ av, layers) == 0) {
1467 return av;
1468 }
1469 else {
1470 PerlIO_list_free(aTHX_ av);
1471 return (PerlIO_list_t *) NULL;
1472 }
14a5cf38
JH
1473 }
1474 else {
1475 if (incdef)
1476 def->refcnt++;
1477 return def;
1478 }
ee518936
NIS
1479}
1480
1481PerlIO *
14a5cf38
JH
1482PerlIO_openn(pTHX_ const char *layers, const char *mode, int fd,
1483 int imode, int perm, PerlIO *f, int narg, SV **args)
1484{
1485 if (!f && narg == 1 && *args == &PL_sv_undef) {
1486 if ((f = PerlIO_tmpfile())) {
1487 if (!layers)
1488 layers = PerlIO_context_layers(aTHX_ mode);
1489 if (layers && *layers)
1490 PerlIO_apply_layers(aTHX_ f, mode, layers);
1491 }
1492 }
1493 else {
1494 PerlIO_list_t *layera = NULL;
1495 IV n;
1496 PerlIO_funcs *tab = NULL;
04892f78 1497 if (PerlIOValid(f)) {
14a5cf38 1498 /*
71200d45
NIS
1499 * This is "reopen" - it is not tested as perl does not use it
1500 * yet
14a5cf38
JH
1501 */
1502 PerlIOl *l = *f;
3a1ee7e8 1503 layera = PerlIO_list_alloc(aTHX);
14a5cf38 1504 while (l) {
04892f78
NIS
1505 SV *arg = (l->tab->Getarg)
1506 ? (*l->tab->Getarg) (aTHX_ &l, NULL, 0)
1507 : &PL_sv_undef;
3a1ee7e8 1508 PerlIO_list_push(aTHX_ layera, l->tab, arg);
14a5cf38
JH
1509 l = *PerlIONext(&l);
1510 }
1511 }
1512 else {
1513 layera = PerlIO_resolve_layers(aTHX_ layers, mode, narg, args);
0cff2cf3
NIS
1514 if (!layera) {
1515 return NULL;
1516 }
14a5cf38
JH
1517 }
1518 /*
71200d45 1519 * Start at "top" of layer stack
14a5cf38
JH
1520 */
1521 n = layera->cur - 1;
1522 while (n >= 0) {
1523 PerlIO_funcs *t = PerlIO_layer_fetch(aTHX_ layera, n, NULL);
1524 if (t && t->Open) {
1525 tab = t;
1526 break;
1527 }
1528 n--;
1529 }
1530 if (tab) {
1531 /*
71200d45 1532 * Found that layer 'n' can do opens - call it
14a5cf38 1533 */
7cf31beb 1534 if (narg > 1 && !(tab->kind & PERLIO_K_MULTIARG)) {
3b8752bb 1535 Perl_croak(aTHX_ "More than one argument to open(,':%s')",tab->name);
7cf31beb 1536 }
14a5cf38 1537 PerlIO_debug("openn(%s,'%s','%s',%d,%x,%o,%p,%d,%p)\n",
fe5a182c
JH
1538 tab->name, layers, mode, fd, imode, perm,
1539 (void*)f, narg, (void*)args);
210e727c
JH
1540 if (tab->Open)
1541 f = (*tab->Open) (aTHX_ tab, layera, n, mode, fd, imode, perm,
1542 f, narg, args);
1543 else {
1544 SETERRNO(EINVAL, LIB_INVARG);
1545 f = NULL;
1546 }
14a5cf38
JH
1547 if (f) {
1548 if (n + 1 < layera->cur) {
1549 /*
1550 * More layers above the one that we used to open -
71200d45 1551 * apply them now
14a5cf38 1552 */
d9dac8cd
NIS
1553 if (PerlIO_apply_layera(aTHX_ f, mode, layera, n + 1, layera->cur) != 0) {
1554 /* If pushing layers fails close the file */
1555 PerlIO_close(f);
14a5cf38
JH
1556 f = NULL;
1557 }
1558 }
1559 }
1560 }
3a1ee7e8 1561 PerlIO_list_free(aTHX_ layera);
14a5cf38
JH
1562 }
1563 return f;
ee518936 1564}
b931b1d9
NIS
1565
1566
9e353e3b 1567SSize_t
e87a358a 1568Perl_PerlIO_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
6f9d8c32 1569{
b32dd47e 1570 Perl_PerlIO_or_Base(f, Read, read, -1, (aTHX_ f, vbuf, count));
760ac839
LW
1571}
1572
313ca112 1573SSize_t
e87a358a 1574Perl_PerlIO_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
760ac839 1575{
b32dd47e 1576 Perl_PerlIO_or_Base(f, Unread, unread, -1, (aTHX_ f, vbuf, count));
760ac839
LW
1577}
1578
9e353e3b 1579SSize_t
e87a358a 1580Perl_PerlIO_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
760ac839 1581{
b32dd47e 1582 Perl_PerlIO_or_fail(f, Write, -1, (aTHX_ f, vbuf, count));
760ac839
LW
1583}
1584
6f9d8c32 1585int
e87a358a 1586Perl_PerlIO_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
760ac839 1587{
b32dd47e 1588 Perl_PerlIO_or_fail(f, Seek, -1, (aTHX_ f, offset, whence));
760ac839
LW
1589}
1590
9e353e3b 1591Off_t
e87a358a 1592Perl_PerlIO_tell(pTHX_ PerlIO *f)
760ac839 1593{
b32dd47e 1594 Perl_PerlIO_or_fail(f, Tell, -1, (aTHX_ f));
760ac839
LW
1595}
1596
6f9d8c32 1597int
e87a358a 1598Perl_PerlIO_flush(pTHX_ PerlIO *f)
760ac839 1599{
14a5cf38
JH
1600 if (f) {
1601 if (*f) {
1602 PerlIO_funcs *tab = PerlIOBase(f)->tab;
1b7a0411
JH
1603
1604 if (tab && tab->Flush)
f62ce20a 1605 return (*tab->Flush) (aTHX_ f);
1b7a0411
JH
1606 else
1607 return 0; /* If no Flush defined, silently succeed. */
14a5cf38
JH
1608 }
1609 else {
fe5a182c 1610 PerlIO_debug("Cannot flush f=%p\n", (void*)f);
93189314 1611 SETERRNO(EBADF, SS_IVCHAN);
14a5cf38
JH
1612 return -1;
1613 }
1614 }
1615 else {
1616 /*
1617 * Is it good API design to do flush-all on NULL, a potentially
1618 * errorneous input? Maybe some magical value (PerlIO*
1619 * PERLIO_FLUSH_ALL = (PerlIO*)-1;)? Yes, stdio does similar
1620 * things on fflush(NULL), but should we be bound by their design
71200d45 1621 * decisions? --jhi
14a5cf38 1622 */
a1ea730d 1623 PerlIO **table = &PL_perlio;
14a5cf38
JH
1624 int code = 0;
1625 while ((f = *table)) {
1626 int i;
1627 table = (PerlIO **) (f++);
1628 for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
1629 if (*f && PerlIO_flush(f) != 0)
1630 code = -1;
1631 f++;
1632 }
1633 }
1634 return code;
1635 }
760ac839
LW
1636}
1637
a9c883f6 1638void
f62ce20a 1639PerlIOBase_flush_linebuf(pTHX)
a9c883f6 1640{
a1ea730d 1641 PerlIO **table = &PL_perlio;
14a5cf38
JH
1642 PerlIO *f;
1643 while ((f = *table)) {
1644 int i;
1645 table = (PerlIO **) (f++);
1646 for (i = 1; i < PERLIO_TABLE_SIZE; i++) {
1647 if (*f
1648 && (PerlIOBase(f)->
1649 flags & (PERLIO_F_LINEBUF | PERLIO_F_CANWRITE))
1650 == (PERLIO_F_LINEBUF | PERLIO_F_CANWRITE))
1651 PerlIO_flush(f);
1652 f++;
1653 }
a9c883f6 1654 }
a9c883f6
NIS
1655}
1656
06da4f11 1657int
e87a358a 1658Perl_PerlIO_fill(pTHX_ PerlIO *f)
06da4f11 1659{
b32dd47e 1660 Perl_PerlIO_or_fail(f, Fill, -1, (aTHX_ f));
06da4f11
NIS
1661}
1662
f3862f8b
NIS
1663int
1664PerlIO_isutf8(PerlIO *f)
1665{
1b7a0411
JH
1666 if (PerlIOValid(f))
1667 return (PerlIOBase(f)->flags & PERLIO_F_UTF8) != 0;
1668 else
1669 SETERRNO(EBADF, SS_IVCHAN);
37725cdc 1670
1b7a0411 1671 return -1;
f3862f8b
NIS
1672}
1673
6f9d8c32 1674int
e87a358a 1675Perl_PerlIO_eof(pTHX_ PerlIO *f)
760ac839 1676{
b32dd47e 1677 Perl_PerlIO_or_Base(f, Eof, eof, -1, (aTHX_ f));
9e353e3b
NIS
1678}
1679
9e353e3b 1680int
e87a358a 1681Perl_PerlIO_error(pTHX_ PerlIO *f)
9e353e3b 1682{
b32dd47e 1683 Perl_PerlIO_or_Base(f, Error, error, -1, (aTHX_ f));
9e353e3b
NIS
1684}
1685
9e353e3b 1686void
e87a358a 1687Perl_PerlIO_clearerr(pTHX_ PerlIO *f)
9e353e3b 1688{
b32dd47e 1689 Perl_PerlIO_or_Base_void(f, Clearerr, clearerr, (aTHX_ f));
9e353e3b
NIS
1690}
1691
9e353e3b 1692void
e87a358a 1693Perl_PerlIO_setlinebuf(pTHX_ PerlIO *f)
9e353e3b 1694{
b32dd47e 1695 Perl_PerlIO_or_Base_void(f, Setlinebuf, setlinebuf, (aTHX_ f));
9e353e3b
NIS
1696}
1697
9e353e3b
NIS
1698int
1699PerlIO_has_base(PerlIO *f)
1700{
1b7a0411
JH
1701 if (PerlIOValid(f)) {
1702 PerlIO_funcs *tab = PerlIOBase(f)->tab;
1703
1704 if (tab)
1705 return (tab->Get_base != NULL);
1706 SETERRNO(EINVAL, LIB_INVARG);
1707 }
1708 else
1709 SETERRNO(EBADF, SS_IVCHAN);
1710
1711 return 0;
760ac839
LW
1712}
1713
9e353e3b
NIS
1714int
1715PerlIO_fast_gets(PerlIO *f)
760ac839 1716{
04892f78 1717 if (PerlIOValid(f) && (PerlIOBase(f)->flags & PERLIO_F_FASTGETS)) {
1b7a0411
JH
1718 PerlIO_funcs *tab = PerlIOBase(f)->tab;
1719
1720 if (tab)
1721 return (tab->Set_ptrcnt != NULL);
1722 SETERRNO(EINVAL, LIB_INVARG);
14a5cf38 1723 }
1b7a0411
JH
1724 else
1725 SETERRNO(EBADF, SS_IVCHAN);
1726
14a5cf38 1727 return 0;
9e353e3b
NIS
1728}
1729
9e353e3b
NIS
1730int
1731PerlIO_has_cntptr(PerlIO *f)
1732{
04892f78 1733 if (PerlIOValid(f)) {
14a5cf38 1734 PerlIO_funcs *tab = PerlIOBase(f)->tab;
1b7a0411
JH
1735
1736 if (tab)
1737 return (tab->Get_ptr != NULL && tab->Get_cnt != NULL);
1738 SETERRNO(EINVAL, LIB_INVARG);
14a5cf38 1739 }
1b7a0411
JH
1740 else
1741 SETERRNO(EBADF, SS_IVCHAN);
1742
14a5cf38 1743 return 0;
9e353e3b
NIS
1744}
1745
9e353e3b
NIS
1746int
1747PerlIO_canset_cnt(PerlIO *f)
1748{
04892f78 1749 if (PerlIOValid(f)) {
1b7a0411
JH
1750 PerlIO_funcs *tab = PerlIOBase(f)->tab;
1751
1752 if (tab)
1753 return (tab->Set_ptrcnt != NULL);
1754 SETERRNO(EINVAL, LIB_INVARG);
14a5cf38 1755 }
1b7a0411
JH
1756 else
1757 SETERRNO(EBADF, SS_IVCHAN);
1758
14a5cf38 1759 return 0;
760ac839
LW
1760}
1761
888911fc 1762STDCHAR *
e87a358a 1763Perl_PerlIO_get_base(pTHX_ PerlIO *f)
760ac839 1764{
b32dd47e 1765 Perl_PerlIO_or_fail(f, Get_base, NULL, (aTHX_ f));
9e353e3b
NIS
1766}
1767
9e353e3b 1768int
e87a358a 1769Perl_PerlIO_get_bufsiz(pTHX_ PerlIO *f)
9e353e3b 1770{
b32dd47e 1771 Perl_PerlIO_or_fail(f, Get_bufsiz, -1, (aTHX_ f));
9e353e3b
NIS
1772}
1773
9e353e3b 1774STDCHAR *
e87a358a 1775Perl_PerlIO_get_ptr(pTHX_ PerlIO *f)
9e353e3b 1776{
b32dd47e 1777 Perl_PerlIO_or_fail(f, Get_ptr, NULL, (aTHX_ f));
9e353e3b
NIS
1778}
1779
05d1247b 1780int
e87a358a 1781Perl_PerlIO_get_cnt(pTHX_ PerlIO *f)
9e353e3b 1782{
b32dd47e 1783 Perl_PerlIO_or_fail(f, Get_cnt, -1, (aTHX_ f));
9e353e3b
NIS
1784}
1785
9e353e3b 1786void
e87a358a 1787Perl_PerlIO_set_cnt(pTHX_ PerlIO *f, int cnt)
9e353e3b 1788{
b32dd47e 1789 Perl_PerlIO_or_fail_void(f, Set_ptrcnt, (aTHX_ f, NULL, cnt));
9e353e3b
NIS
1790}
1791
9e353e3b 1792void
e87a358a 1793Perl_PerlIO_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, int cnt)
9e353e3b 1794{
b32dd47e 1795 Perl_PerlIO_or_fail_void(f, Set_ptrcnt, (aTHX_ f, ptr, cnt));
9e353e3b
NIS
1796}
1797
4ec2216f 1798
9e353e3b 1799/*--------------------------------------------------------------------------------------*/
14a5cf38 1800/*
71200d45 1801 * utf8 and raw dummy layers
14a5cf38 1802 */
dfebf958 1803
26fb694e 1804IV
2dc2558e 1805PerlIOUtf8_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
26fb694e 1806{
00f51856 1807 if (PerlIOValid(f)) {
14a5cf38
JH
1808 if (tab->kind & PERLIO_K_UTF8)
1809 PerlIOBase(f)->flags |= PERLIO_F_UTF8;
1810 else
1811 PerlIOBase(f)->flags &= ~PERLIO_F_UTF8;
1812 return 0;
1813 }
1814 return -1;
26fb694e
NIS
1815}
1816
dfebf958 1817PerlIO_funcs PerlIO_utf8 = {
2dc2558e 1818 sizeof(PerlIO_funcs),
14a5cf38 1819 "utf8",
2dc2558e 1820 0,
6874a2de 1821 PERLIO_K_DUMMY | PERLIO_K_UTF8,
14a5cf38
JH
1822 PerlIOUtf8_pushed,
1823 NULL,
1824 NULL,
1825 NULL,
1826 NULL,
1827 NULL,
1828 NULL,
1829 NULL,
1830 NULL,
1831 NULL,
1832 NULL,
22569500
NIS
1833 NULL, /* flush */
1834 NULL, /* fill */
14a5cf38
JH
1835 NULL,
1836 NULL,
1837 NULL,
1838 NULL,
22569500
NIS
1839 NULL, /* get_base */
1840 NULL, /* get_bufsiz */
1841 NULL, /* get_ptr */
1842 NULL, /* get_cnt */
1843 NULL, /* set_ptrcnt */
26fb694e
NIS
1844};
1845
1846PerlIO_funcs PerlIO_byte = {
2dc2558e 1847 sizeof(PerlIO_funcs),
14a5cf38 1848 "bytes",
2dc2558e 1849 0,
14a5cf38
JH
1850 PERLIO_K_DUMMY,
1851 PerlIOUtf8_pushed,
1852 NULL,
1853 NULL,
1854 NULL,
1855 NULL,
1856 NULL,
1857 NULL,
1858 NULL,
1859 NULL,
1860 NULL,
1861 NULL,
22569500
NIS
1862 NULL, /* flush */
1863 NULL, /* fill */
14a5cf38
JH
1864 NULL,
1865 NULL,
1866 NULL,
1867 NULL,
22569500
NIS
1868 NULL, /* get_base */
1869 NULL, /* get_bufsiz */
1870 NULL, /* get_ptr */
1871 NULL, /* get_cnt */
1872 NULL, /* set_ptrcnt */
dfebf958
NIS
1873};
1874
1875PerlIO *
14a5cf38
JH
1876PerlIORaw_open(pTHX_ PerlIO_funcs *self, PerlIO_list_t *layers,
1877 IV n, const char *mode, int fd, int imode, int perm,
1878 PerlIO *old, int narg, SV **args)
dfebf958 1879{
14a5cf38 1880 PerlIO_funcs *tab = PerlIO_default_btm();
210e727c
JH
1881 if (tab && tab->Open)
1882 return (*tab->Open) (aTHX_ tab, layers, n - 1, mode, fd, imode, perm,
1883 old, narg, args);
1884 SETERRNO(EINVAL, LIB_INVARG);
1885 return NULL;
dfebf958
NIS
1886}
1887
1888PerlIO_funcs PerlIO_raw = {
2dc2558e 1889 sizeof(PerlIO_funcs),
14a5cf38 1890 "raw",
2dc2558e 1891 0,
14a5cf38
JH
1892 PERLIO_K_DUMMY,
1893 PerlIORaw_pushed,
1894 PerlIOBase_popped,
1895 PerlIORaw_open,
1896 NULL,
1897 NULL,
1898 NULL,
1899 NULL,
1900 NULL,
1901 NULL,
1902 NULL,
1903 NULL,
22569500
NIS
1904 NULL, /* flush */
1905 NULL, /* fill */
14a5cf38
JH
1906 NULL,
1907 NULL,
1908 NULL,
1909 NULL,
22569500
NIS
1910 NULL, /* get_base */
1911 NULL, /* get_bufsiz */
1912 NULL, /* get_ptr */
1913 NULL, /* get_cnt */
1914 NULL, /* set_ptrcnt */
dfebf958
NIS
1915};
1916/*--------------------------------------------------------------------------------------*/
1917/*--------------------------------------------------------------------------------------*/
14a5cf38 1918/*
71200d45 1919 * "Methods" of the "base class"
14a5cf38 1920 */
9e353e3b
NIS
1921
1922IV
f62ce20a 1923PerlIOBase_fileno(pTHX_ PerlIO *f)
9e353e3b 1924{
04892f78 1925 return PerlIOValid(f) ? PerlIO_fileno(PerlIONext(f)) : -1;
9e353e3b
NIS
1926}
1927
f5b9d040 1928char *
81428673 1929PerlIO_modestr(PerlIO * f, char *buf)
14a5cf38
JH
1930{
1931 char *s = buf;
81428673
NIS
1932 if (PerlIOValid(f)) {
1933 IV flags = PerlIOBase(f)->flags;
1934 if (flags & PERLIO_F_APPEND) {
1935 *s++ = 'a';
1936 if (flags & PERLIO_F_CANREAD) {
1937 *s++ = '+';
1938 }
14a5cf38 1939 }
81428673
NIS
1940 else if (flags & PERLIO_F_CANREAD) {
1941 *s++ = 'r';
1942 if (flags & PERLIO_F_CANWRITE)
1943 *s++ = '+';
1944 }
1945 else if (flags & PERLIO_F_CANWRITE) {
1946 *s++ = 'w';
1947 if (flags & PERLIO_F_CANREAD) {
1948 *s++ = '+';
1949 }
14a5cf38 1950 }
35990314 1951#ifdef PERLIO_USING_CRLF
81428673
NIS
1952 if (!(flags & PERLIO_F_CRLF))
1953 *s++ = 'b';
5f1a76d0 1954#endif
81428673 1955 }
14a5cf38
JH
1956 *s = '\0';
1957 return buf;
f5b9d040
NIS
1958}
1959
81428673 1960
76ced9ad 1961IV
2dc2558e 1962PerlIOBase_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
9e353e3b 1963{
14a5cf38 1964 PerlIOl *l = PerlIOBase(f);
b7953727 1965#if 0
14a5cf38
JH
1966 const char *omode = mode;
1967 char temp[8];
b7953727 1968#endif
14a5cf38
JH
1969 l->flags &= ~(PERLIO_F_CANREAD | PERLIO_F_CANWRITE |
1970 PERLIO_F_TRUNCATE | PERLIO_F_APPEND);
1971 if (tab->Set_ptrcnt != NULL)
1972 l->flags |= PERLIO_F_FASTGETS;
1973 if (mode) {
3b6c1aba 1974 if (*mode == IoTYPE_NUMERIC || *mode == IoTYPE_IMPLICIT)
14a5cf38
JH
1975 mode++;
1976 switch (*mode++) {
1977 case 'r':
1978 l->flags |= PERLIO_F_CANREAD;
1979 break;
1980 case 'a':
1981 l->flags |= PERLIO_F_APPEND | PERLIO_F_CANWRITE;
1982 break;
1983 case 'w':
1984 l->flags |= PERLIO_F_TRUNCATE | PERLIO_F_CANWRITE;
1985 break;
1986 default:
93189314 1987 SETERRNO(EINVAL, LIB_INVARG);
14a5cf38
JH
1988 return -1;
1989 }
1990 while (*mode) {
1991 switch (*mode++) {
1992 case '+':
1993 l->flags |= PERLIO_F_CANREAD | PERLIO_F_CANWRITE;
1994 break;
1995 case 'b':
1996 l->flags &= ~PERLIO_F_CRLF;
1997 break;
1998 case 't':
1999 l->flags |= PERLIO_F_CRLF;
2000 break;
2001 default:
93189314 2002 SETERRNO(EINVAL, LIB_INVARG);
14a5cf38
JH
2003 return -1;
2004 }
2005 }
2006 }
2007 else {
2008 if (l->next) {
2009 l->flags |= l->next->flags &
2010 (PERLIO_F_CANREAD | PERLIO_F_CANWRITE | PERLIO_F_TRUNCATE |
2011 PERLIO_F_APPEND);
2012 }
2013 }
5e2ab84b 2014#if 0
14a5cf38
JH
2015 PerlIO_debug("PerlIOBase_pushed f=%p %s %s fl=%08" UVxf " (%s)\n",
2016 f, PerlIOBase(f)->tab->name, (omode) ? omode : "(Null)",
2017 l->flags, PerlIO_modestr(f, temp));
5e2ab84b 2018#endif
14a5cf38 2019 return 0;
76ced9ad
NIS
2020}
2021
2022IV
f62ce20a 2023PerlIOBase_popped(pTHX_ PerlIO *f)
76ced9ad 2024{
14a5cf38 2025 return 0;
760ac839
LW
2026}
2027
9e353e3b 2028SSize_t
f62ce20a 2029PerlIOBase_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
9e353e3b 2030{
14a5cf38 2031 /*
71200d45 2032 * Save the position as current head considers it
14a5cf38
JH
2033 */
2034 Off_t old = PerlIO_tell(f);
2035 SSize_t done;
2036 PerlIO_push(aTHX_ f, &PerlIO_pending, "r", Nullsv);
2037 PerlIOSelf(f, PerlIOBuf)->posn = old;
f62ce20a 2038 done = PerlIOBuf_unread(aTHX_ f, vbuf, count);
14a5cf38 2039 return done;
9e353e3b
NIS
2040}
2041
f6c77cf1 2042SSize_t
f62ce20a 2043PerlIOBase_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
f6c77cf1 2044{
14a5cf38
JH
2045 STDCHAR *buf = (STDCHAR *) vbuf;
2046 if (f) {
263df5f1
JH
2047 if (!(PerlIOBase(f)->flags & PERLIO_F_CANREAD)) {
2048 PerlIOBase(f)->flags |= PERLIO_F_ERROR;
2049 SETERRNO(EBADF, SS_IVCHAN);
2050 return 0;
2051 }
14a5cf38
JH
2052 while (count > 0) {
2053 SSize_t avail = PerlIO_get_cnt(f);
2054 SSize_t take = 0;
2055 if (avail > 0)
eb160463 2056 take = ((SSize_t)count < avail) ? count : avail;
14a5cf38
JH
2057 if (take > 0) {
2058 STDCHAR *ptr = PerlIO_get_ptr(f);
2059 Copy(ptr, buf, take, STDCHAR);
2060 PerlIO_set_ptrcnt(f, ptr + take, (avail -= take));
2061 count -= take;
2062 buf += take;
2063 }
2064 if (count > 0 && avail <= 0) {
2065 if (PerlIO_fill(f) != 0)
2066 break;
2067 }
2068 }
2069 return (buf - (STDCHAR *) vbuf);
2070 }
f6c77cf1 2071 return 0;
f6c77cf1
NIS
2072}
2073
9e353e3b 2074IV
f62ce20a 2075PerlIOBase_noop_ok(pTHX_ PerlIO *f)
9e353e3b 2076{
14a5cf38 2077 return 0;
9e353e3b
NIS
2078}
2079
2080IV
f62ce20a 2081PerlIOBase_noop_fail(pTHX_ PerlIO *f)
06da4f11 2082{
14a5cf38 2083 return -1;
06da4f11
NIS
2084}
2085
2086IV
f62ce20a 2087PerlIOBase_close(pTHX_ PerlIO *f)
9e353e3b 2088{
37725cdc
NIS
2089 IV code = -1;
2090 if (PerlIOValid(f)) {
2091 PerlIO *n = PerlIONext(f);
2092 code = PerlIO_flush(f);
2093 PerlIOBase(f)->flags &=
2094 ~(PERLIO_F_CANREAD | PERLIO_F_CANWRITE | PERLIO_F_OPEN);
2095 while (PerlIOValid(n)) {
2096 PerlIO_funcs *tab = PerlIOBase(n)->tab;
2097 if (tab && tab->Close) {
2098 if ((*tab->Close)(aTHX_ n) != 0)
2099 code = -1;
2100 break;
2101 }
2102 else {
2103 PerlIOBase(n)->flags &=
2104 ~(PERLIO_F_CANREAD | PERLIO_F_CANWRITE | PERLIO_F_OPEN);
2105 }
2106 n = PerlIONext(n);
2107 }
2108 }
2109 else {
2110 SETERRNO(EBADF, SS_IVCHAN);
2111 }
14a5cf38 2112 return code;
9e353e3b
NIS
2113}
2114
2115IV
f62ce20a 2116PerlIOBase_eof(pTHX_ PerlIO *f)
9e353e3b 2117{
04892f78 2118 if (PerlIOValid(f)) {
14a5cf38
JH
2119 return (PerlIOBase(f)->flags & PERLIO_F_EOF) != 0;
2120 }
2121 return 1;
9e353e3b
NIS
2122}
2123
2124IV
f62ce20a 2125PerlIOBase_error(pTHX_ PerlIO *f)
9e353e3b 2126{
04892f78 2127 if (PerlIOValid(f)) {
14a5cf38
JH
2128 return (PerlIOBase(f)->flags & PERLIO_F_ERROR) != 0;
2129 }
2130 return 1;
9e353e3b
NIS
2131}
2132
2133void
f62ce20a 2134PerlIOBase_clearerr(pTHX_ PerlIO *f)
9e353e3b 2135{
04892f78 2136 if (PerlIOValid(f)) {
14a5cf38
JH
2137 PerlIO *n = PerlIONext(f);
2138 PerlIOBase(f)->flags &= ~(PERLIO_F_ERROR | PERLIO_F_EOF);
04892f78 2139 if (PerlIOValid(n))
14a5cf38
JH
2140 PerlIO_clearerr(n);
2141 }
9e353e3b
NIS
2142}
2143
2144void
f62ce20a 2145PerlIOBase_setlinebuf(pTHX_ PerlIO *f)
9e353e3b 2146{
04892f78 2147 if (PerlIOValid(f)) {
14a5cf38
JH
2148 PerlIOBase(f)->flags |= PERLIO_F_LINEBUF;
2149 }
9e353e3b
NIS
2150}
2151
93a8090d
NIS
2152SV *
2153PerlIO_sv_dup(pTHX_ SV *arg, CLONE_PARAMS *param)
2154{
2155 if (!arg)
2156 return Nullsv;
2157#ifdef sv_dup
2158 if (param) {
2159 return sv_dup(arg, param);
2160 }
2161 else {
2162 return newSVsv(arg);
2163 }
2164#else
2165 return newSVsv(arg);
2166#endif
2167}
2168
2169PerlIO *
ecdeb87c 2170PerlIOBase_dup(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags)
93a8090d
NIS
2171{
2172 PerlIO *nexto = PerlIONext(o);
04892f78 2173 if (PerlIOValid(nexto)) {
93a8090d 2174 PerlIO_funcs *tab = PerlIOBase(nexto)->tab;
37725cdc
NIS
2175 if (tab && tab->Dup)
2176 f = (*tab->Dup)(aTHX_ f, nexto, param, flags);
2177 else
2178 f = PerlIOBase_dup(aTHX_ f, nexto, param, flags);
93a8090d
NIS
2179 }
2180 if (f) {
2181 PerlIO_funcs *self = PerlIOBase(o)->tab;
210e727c 2182 SV *arg;
93a8090d 2183 char buf[8];
fe5a182c
JH
2184 PerlIO_debug("PerlIOBase_dup %s f=%p o=%p param=%p\n",
2185 self->name, (void*)f, (void*)o, (void*)param);
210e727c
JH
2186 if (self->Getarg)
2187 arg = (*self->Getarg)(aTHX_ o, param, flags);
2188 else {
37725cdc 2189 arg = Nullsv;
93a8090d
NIS
2190 }
2191 f = PerlIO_push(aTHX_ f, self, PerlIO_modestr(o,buf), arg);
ecdeb87c 2192 if (arg) {
93a8090d
NIS
2193 SvREFCNT_dec(arg);
2194 }
2195 }
2196 return f;
2197}
2198
2199#define PERLIO_MAX_REFCOUNTABLE_FD 2048
168d5872 2200#ifdef USE_THREADS
93a8090d 2201perl_mutex PerlIO_mutex;
93a8090d 2202#endif
168d5872 2203int PerlIO_fd_refcnt[PERLIO_MAX_REFCOUNTABLE_FD];
93a8090d
NIS
2204
2205void
2206PerlIO_init(pTHX)
2207{
2208 /* Place holder for stdstreams call ??? */
168d5872 2209#ifdef USE_THREADS
93a8090d
NIS
2210 MUTEX_INIT(&PerlIO_mutex);
2211#endif
2212}
2213
168d5872
NIS
2214void
2215PerlIOUnix_refcnt_inc(int fd)
2216{
2217 if (fd >= 0 && fd < PERLIO_MAX_REFCOUNTABLE_FD) {
2218#ifdef USE_THREADS
2219 MUTEX_LOCK(&PerlIO_mutex);
2220#endif
2221 PerlIO_fd_refcnt[fd]++;
2222 PerlIO_debug("fd %d refcnt=%d\n",fd,PerlIO_fd_refcnt[fd]);
2223#ifdef USE_THREADS
2224 MUTEX_UNLOCK(&PerlIO_mutex);
2225#endif
2226 }
2227}
2228
168d5872
NIS
2229int
2230PerlIOUnix_refcnt_dec(int fd)
2231{
2232 int cnt = 0;
2233 if (fd >= 0 && fd < PERLIO_MAX_REFCOUNTABLE_FD) {
2234#ifdef USE_THREADS
2235 MUTEX_LOCK(&PerlIO_mutex);
2236#endif
2237 cnt = --PerlIO_fd_refcnt[fd];
2238 PerlIO_debug("fd %d refcnt=%d\n",fd,cnt);
2239#ifdef USE_THREADS
2240 MUTEX_UNLOCK(&PerlIO_mutex);
2241#endif
2242 }
2243 return cnt;
2244}
2245
694c95cf
JH
2246void
2247PerlIO_cleanup(pTHX)
2248{
2249 int i;
2250#ifdef USE_ITHREADS
9f4bd222
NIS
2251 PerlIO_debug("Cleanup layers for %p\n",aTHX);
2252#else
2253 PerlIO_debug("Cleanup layers\n");
694c95cf
JH
2254#endif
2255 /* Raise STDIN..STDERR refcount so we don't close them */
2256 for (i=0; i < 3; i++)
2257 PerlIOUnix_refcnt_inc(i);
2258 PerlIO_cleantable(aTHX_ &PL_perlio);
2259 /* Restore STDIN..STDERR refcount */
2260 for (i=0; i < 3; i++)
2261 PerlIOUnix_refcnt_dec(i);
9f4bd222
NIS
2262
2263 if (PL_known_layers) {
2264 PerlIO_list_free(aTHX_ PL_known_layers);
2265 PL_known_layers = NULL;
2266 }
2267 if(PL_def_layerlist) {
2268 PerlIO_list_free(aTHX_ PL_def_layerlist);
2269 PL_def_layerlist = NULL;
2270 }
694c95cf
JH
2271}
2272
2273
2274
9e353e3b 2275/*--------------------------------------------------------------------------------------*/
14a5cf38 2276/*
71200d45 2277 * Bottom-most level for UNIX-like case
14a5cf38 2278 */
9e353e3b 2279
14a5cf38 2280typedef struct {
22569500
NIS
2281 struct _PerlIO base; /* The generic part */
2282 int fd; /* UNIX like file descriptor */
2283 int oflags; /* open/fcntl flags */
9e353e3b
NIS
2284} PerlIOUnix;
2285
6f9d8c32 2286int
9e353e3b 2287PerlIOUnix_oflags(const char *mode)
760ac839 2288{
14a5cf38 2289 int oflags = -1;
3b6c1aba 2290 if (*mode == IoTYPE_IMPLICIT || *mode == IoTYPE_NUMERIC)
14a5cf38
JH
2291 mode++;
2292 switch (*mode) {
2293 case 'r':
2294 oflags = O_RDONLY;
2295 if (*++mode == '+') {
2296 oflags = O_RDWR;
2297 mode++;
2298 }
2299 break;
2300
2301 case 'w':
2302 oflags = O_CREAT | O_TRUNC;
2303 if (*++mode == '+') {
2304 oflags |= O_RDWR;
2305 mode++;
2306 }
2307 else
2308 oflags |= O_WRONLY;
2309 break;
2310
2311 case 'a':
2312 oflags = O_CREAT | O_APPEND;
2313 if (*++mode == '+') {
2314 oflags |= O_RDWR;
2315 mode++;
2316 }
2317 else
2318 oflags |= O_WRONLY;
2319 break;
2320 }
2321 if (*mode == 'b') {
2322 oflags |= O_BINARY;
2323 oflags &= ~O_TEXT;
2324 mode++;
2325 }
2326 else if (*mode == 't') {
2327 oflags |= O_TEXT;
2328 oflags &= ~O_BINARY;
2329 mode++;
2330 }
2331 /*
71200d45 2332 * Always open in binary mode
14a5cf38
JH
2333 */
2334 oflags |= O_BINARY;
2335 if (*mode || oflags == -1) {
93189314 2336 SETERRNO(EINVAL, LIB_INVARG);
14a5cf38
JH
2337 oflags = -1;
2338 }
2339 return oflags;
9e353e3b
NIS
2340}
2341
2342IV
f62ce20a 2343PerlIOUnix_fileno(pTHX_ PerlIO *f)
9e353e3b 2344{
14a5cf38 2345 return PerlIOSelf(f, PerlIOUnix)->fd;
9e353e3b
NIS
2346}
2347
aa063c35
NIS
2348static void
2349PerlIOUnix_setfd(pTHX_ PerlIO *f, int fd, int imode)
4b803d04 2350{
93a8090d 2351 PerlIOUnix *s = PerlIOSelf(f, PerlIOUnix);
6caa5a9c 2352#if defined(WIN32)
aa063c35
NIS
2353 Stat_t st;
2354 if (PerlLIO_fstat(fd, &st) == 0) {
6caa5a9c 2355 if (!S_ISREG(st.st_mode)) {
aa063c35 2356 PerlIO_debug("%d is not regular file\n",fd);
6caa5a9c
NIS
2357 PerlIOBase(f)->flags |= PERLIO_F_NOTREG;
2358 }
aa063c35
NIS
2359 else {
2360 PerlIO_debug("%d _is_ a regular file\n",fd);
2361 }
6caa5a9c
NIS
2362 }
2363#endif
aa063c35
NIS
2364 s->fd = fd;
2365 s->oflags = imode;
2366 PerlIOUnix_refcnt_inc(fd);
2367}
2368
2369IV
2370PerlIOUnix_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
2371{
2372 IV code = PerlIOBase_pushed(aTHX_ f, mode, arg, tab);
14a5cf38 2373 if (*PerlIONext(f)) {
4b069b44 2374 /* We never call down so do any pending stuff now */
03c0554d 2375 PerlIO_flush(PerlIONext(f));
14a5cf38 2376 /*
71200d45 2377 * XXX could (or should) we retrieve the oflags from the open file
14a5cf38 2378 * handle rather than believing the "mode" we are passed in? XXX
71200d45 2379 * Should the value on NULL mode be 0 or -1?
14a5cf38 2380 */
acbd16bf 2381 PerlIOUnix_setfd(aTHX_ f, PerlIO_fileno(PerlIONext(f)),
aa063c35 2382 mode ? PerlIOUnix_oflags(mode) : -1);
14a5cf38
JH
2383 }
2384 PerlIOBase(f)->flags |= PERLIO_F_OPEN;
6caa5a9c 2385
14a5cf38 2386 return code;
4b803d04
NIS
2387}
2388
c2fcde81
JH
2389IV
2390PerlIOUnix_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
2391{
2392 int fd = PerlIOSelf(f, PerlIOUnix)->fd;
2393 Off_t new;
2394 if (PerlIOBase(f)->flags & PERLIO_F_NOTREG) {
2395#ifdef ESPIPE
2396 SETERRNO(ESPIPE, LIB_INVARG);
2397#else
2398 SETERRNO(EINVAL, LIB_INVARG);
2399#endif
2400 return -1;
2401 }
2402 new = PerlLIO_lseek(fd, offset, whence);
2403 if (new == (Off_t) - 1)
2404 {
2405 return -1;
2406 }
2407 PerlIOBase(f)->flags &= ~PERLIO_F_EOF;
2408 return 0;
2409}
2410
9e353e3b 2411PerlIO *
14a5cf38
JH
2412PerlIOUnix_open(pTHX_ PerlIO_funcs *self, PerlIO_list_t *layers,
2413 IV n, const char *mode, int fd, int imode,
2414 int perm, PerlIO *f, int narg, SV **args)
2415{
d9dac8cd 2416 if (PerlIOValid(f)) {
14a5cf38 2417 if (PerlIOBase(f)->flags & PERLIO_F_OPEN)
f62ce20a 2418 (*PerlIOBase(f)->tab->Close)(aTHX_ f);
14a5cf38
JH
2419 }
2420 if (narg > 0) {
2421 char *path = SvPV_nolen(*args);
3b6c1aba 2422 if (*mode == IoTYPE_NUMERIC)
14a5cf38
JH
2423 mode++;
2424 else {
2425 imode = PerlIOUnix_oflags(mode);
2426 perm = 0666;
2427 }
2428 if (imode != -1) {
2429 fd = PerlLIO_open3(path, imode, perm);
2430 }
2431 }
2432 if (fd >= 0) {
3b6c1aba 2433 if (*mode == IoTYPE_IMPLICIT)
14a5cf38
JH
2434 mode++;
2435 if (!f) {
2436 f = PerlIO_allocate(aTHX);
d9dac8cd
NIS
2437 }
2438 if (!PerlIOValid(f)) {
a33cf58c
NIS
2439 if (!(f = PerlIO_push(aTHX_ f, self, mode, PerlIOArg))) {
2440 return NULL;
2441 }
d9dac8cd 2442 }
aa063c35 2443 PerlIOUnix_setfd(aTHX_ f, fd, imode);
14a5cf38 2444 PerlIOBase(f)->flags |= PERLIO_F_OPEN;
c2fcde81
JH
2445 if (*mode == IoTYPE_APPEND)
2446 PerlIOUnix_seek(aTHX_ f, 0, SEEK_END);
14a5cf38
JH
2447 return f;
2448 }
2449 else {
2450 if (f) {
2451 /*
71200d45 2452 * FIXME: pop layers ???
14a5cf38
JH
2453 */
2454 }
2455 return NULL;
2456 }
9e353e3b
NIS
2457}
2458
71200d45 2459PerlIO *
ecdeb87c 2460PerlIOUnix_dup(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags)
71200d45
NIS
2461{
2462 PerlIOUnix *os = PerlIOSelf(o, PerlIOUnix);
93a8090d 2463 int fd = os->fd;
ecdeb87c
NIS
2464 if (flags & PERLIO_DUP_FD) {
2465 fd = PerlLIO_dup(fd);
2466 }
93a8090d 2467 if (fd >= 0 && fd < PERLIO_MAX_REFCOUNTABLE_FD) {
ecdeb87c 2468 f = PerlIOBase_dup(aTHX_ f, o, param, flags);
71200d45
NIS
2469 if (f) {
2470 /* If all went well overwrite fd in dup'ed lay with the dup()'ed fd */
aa063c35 2471 PerlIOUnix_setfd(aTHX_ f, fd, os->oflags);
71200d45
NIS
2472 return f;
2473 }
71200d45
NIS
2474 }
2475 return NULL;
2476}
2477
2478
9e353e3b 2479SSize_t
f62ce20a 2480PerlIOUnix_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
9e353e3b 2481{
14a5cf38 2482 int fd = PerlIOSelf(f, PerlIOUnix)->fd;
81428673 2483 if (!(PerlIOBase(f)->flags & PERLIO_F_CANREAD) ||
1fd8f4ce 2484 PerlIOBase(f)->flags & (PERLIO_F_EOF|PERLIO_F_ERROR)) {
263df5f1 2485 return 0;
1fd8f4ce 2486 }
14a5cf38
JH
2487 while (1) {
2488 SSize_t len = PerlLIO_read(fd, vbuf, count);
2489 if (len >= 0 || errno != EINTR) {
ba85f2ea
NIS
2490 if (len < 0) {
2491 if (errno != EAGAIN) {
2492 PerlIOBase(f)->flags |= PERLIO_F_ERROR;
2493 }
2494 }
2495 else if (len == 0 && count != 0) {
14a5cf38 2496 PerlIOBase(f)->flags |= PERLIO_F_EOF;
ba85f2ea
NIS
2497 SETERRNO(0,0);
2498 }
14a5cf38
JH
2499 return len;
2500 }
2501 PERL_ASYNC_CHECK();
2502 }
9e353e3b
NIS
2503}
2504
2505SSize_t
f62ce20a 2506PerlIOUnix_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
9e353e3b 2507{
14a5cf38
JH
2508 int fd = PerlIOSelf(f, PerlIOUnix)->fd;
2509 while (1) {
2510 SSize_t len = PerlLIO_write(fd, vbuf, count);
2511 if (len >= 0 || errno != EINTR) {
ba85f2ea
NIS
2512 if (len < 0) {
2513 if (errno != EAGAIN) {
2514 PerlIOBase(f)->flags |= PERLIO_F_ERROR;
2515 }
2516 }
14a5cf38
JH
2517 return len;
2518 }
2519 PERL_ASYNC_CHECK();
06da4f11 2520 }
9e353e3b
NIS
2521}
2522
9e353e3b 2523Off_t
f62ce20a 2524PerlIOUnix_tell(pTHX_ PerlIO *f)
9e353e3b 2525{
14a5cf38 2526 return PerlLIO_lseek(PerlIOSelf(f, PerlIOUnix)->fd, 0, SEEK_CUR);
9e353e3b
NIS
2527}
2528
71200d45 2529
9e353e3b 2530IV
f62ce20a 2531PerlIOUnix_close(pTHX_ PerlIO *f)
9e353e3b 2532{
14a5cf38
JH
2533 int fd = PerlIOSelf(f, PerlIOUnix)->fd;
2534 int code = 0;
168d5872
NIS
2535 if (PerlIOBase(f)->flags & PERLIO_F_OPEN) {
2536 if (PerlIOUnix_refcnt_dec(fd) > 0) {
93a8090d
NIS
2537 PerlIOBase(f)->flags &= ~PERLIO_F_OPEN;
2538 return 0;
22569500 2539 }
93a8090d
NIS
2540 }
2541 else {
93189314 2542 SETERRNO(EBADF,SS_IVCHAN);
93a8090d
NIS
2543 return -1;
2544 }
14a5cf38
JH
2545 while (PerlLIO_close(fd) != 0) {
2546 if (errno != EINTR) {
2547 code = -1;
2548 break;
2549 }
2550 PERL_ASYNC_CHECK();
2551 }
2552 if (code == 0) {
2553 PerlIOBase(f)->flags &= ~PERLIO_F_OPEN;
2554 }
2555 return code;
9e353e3b
NIS
2556}
2557
2558PerlIO_funcs PerlIO_unix = {
2dc2558e 2559 sizeof(PerlIO_funcs),
14a5cf38
JH
2560 "unix",
2561 sizeof(PerlIOUnix),
2562 PERLIO_K_RAW,
2563 PerlIOUnix_pushed,
44798d05 2564 PerlIOBase_popped,
14a5cf38 2565 PerlIOUnix_open,
86e05cf2 2566 PerlIOBase_binmode, /* binmode */
14a5cf38
JH
2567 NULL,
2568 PerlIOUnix_fileno,
71200d45 2569 PerlIOUnix_dup,
14a5cf38
JH
2570 PerlIOUnix_read,
2571 PerlIOBase_unread,
2572 PerlIOUnix_write,
2573 PerlIOUnix_seek,
2574 PerlIOUnix_tell,
2575 PerlIOUnix_close,
22569500
NIS
2576 PerlIOBase_noop_ok, /* flush */
2577 PerlIOBase_noop_fail, /* fill */
14a5cf38
JH
2578 PerlIOBase_eof,
2579 PerlIOBase_error,
2580 PerlIOBase_clearerr,
2581 PerlIOBase_setlinebuf,
22569500
NIS
2582 NULL, /* get_base */
2583 NULL, /* get_bufsiz */
2584 NULL, /* get_ptr */
2585 NULL, /* get_cnt */
2586 NULL, /* set_ptrcnt */
9e353e3b
NIS
2587};
2588
2589/*--------------------------------------------------------------------------------------*/
14a5cf38 2590/*
71200d45 2591 * stdio as a layer
14a5cf38 2592 */
9e353e3b 2593
313e59c8
NIS
2594#if defined(VMS) && !defined(STDIO_BUFFER_WRITABLE)
2595/* perl5.8 - This ensures the last minute VMS ungetc fix is not
2596 broken by the last second glibc 2.3 fix
2597 */
2598#define STDIO_BUFFER_WRITABLE
2599#endif
2600
2601
14a5cf38
JH
2602typedef struct {
2603 struct _PerlIO base;
22569500 2604 FILE *stdio; /* The stream */
9e353e3b
NIS
2605} PerlIOStdio;
2606
2607IV
f62ce20a 2608PerlIOStdio_fileno(pTHX_ PerlIO *f)
9e353e3b 2609{
439ba545 2610 FILE *s;
81428673 2611 if (PerlIOValid(f) && (s = PerlIOSelf(f, PerlIOStdio)->stdio)) {
439ba545
NIS
2612 return PerlSIO_fileno(s);
2613 }
2614 errno = EBADF;
2615 return -1;
9e353e3b
NIS
2616}
2617
766a733e 2618char *
14a5cf38
JH
2619PerlIOStdio_mode(const char *mode, char *tmode)
2620{
2621 char *ret = tmode;
a0625d38
SR
2622 if (mode) {
2623 while (*mode) {
2624 *tmode++ = *mode++;
2625 }
14a5cf38 2626 }
95005ad8 2627#if defined(PERLIO_USING_CRLF) || defined(__CYGWIN__)
6ce75a77
JH
2628 *tmode++ = 'b';
2629#endif
14a5cf38
JH
2630 *tmode = '\0';
2631 return ret;
2632}
2633
4b803d04 2634IV
2dc2558e 2635PerlIOStdio_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
4b803d04 2636{
1fd8f4ce
NIS
2637 PerlIO *n;
2638 if (PerlIOValid(f) && PerlIOValid(n = PerlIONext(f))) {
2639 PerlIO_funcs *toptab = PerlIOBase(n)->tab;
2640 if (toptab == tab) {
2641 /* Top is already stdio - pop self (duplicate) and use original */
2642 PerlIO_pop(aTHX_ f);
2643 return 0;
2644 } else {
2645 int fd = PerlIO_fileno(n);
2646 char tmode[8];
2647 FILE *stdio;
81428673 2648 if (fd >= 0 && (stdio = PerlSIO_fdopen(fd,
1fd8f4ce
NIS
2649 mode = PerlIOStdio_mode(mode, tmode)))) {
2650 PerlIOSelf(f, PerlIOStdio)->stdio = stdio;
2651 /* We never call down so do any pending stuff now */
2652 PerlIO_flush(PerlIONext(f));
81428673 2653 }
1fd8f4ce
NIS
2654 else {
2655 return -1;
2656 }
2657 }
14a5cf38 2658 }
2dc2558e 2659 return PerlIOBase_pushed(aTHX_ f, mode, arg, tab);
4b803d04
NIS
2660}
2661
22569500 2662
9e353e3b 2663PerlIO *
4b069b44 2664PerlIO_importFILE(FILE *stdio, const char *mode)
9e353e3b 2665{
14a5cf38
JH
2666 dTHX;
2667 PerlIO *f = NULL;
2668 if (stdio) {
22569500 2669 PerlIOStdio *s;
4b069b44
NIS
2670 if (!mode || !*mode) {
2671 /* We need to probe to see how we can open the stream
2672 so start with read/write and then try write and read
2673 we dup() so that we can fclose without loosing the fd.
2674
2675 Note that the errno value set by a failing fdopen
2676 varies between stdio implementations.
2677 */
2678 int fd = PerlLIO_dup(fileno(stdio));
a33cf58c 2679 FILE *f2 = PerlSIO_fdopen(fd, (mode = "r+"));
4b069b44 2680 if (!f2) {
a33cf58c 2681 f2 = PerlSIO_fdopen(fd, (mode = "w"));
4b069b44
NIS
2682 }
2683 if (!f2) {
a33cf58c 2684 f2 = PerlSIO_fdopen(fd, (mode = "r"));
4b069b44
NIS
2685 }
2686 if (!f2) {
2687 /* Don't seem to be able to open */
2688 PerlLIO_close(fd);
2689 return f;
2690 }
2691 fclose(f2);
22569500 2692 }
a33cf58c
NIS
2693 if ((f = PerlIO_push(aTHX_(f = PerlIO_allocate(aTHX)), &PerlIO_stdio, mode, Nullsv))) {
2694 s = PerlIOSelf(f, PerlIOStdio);
2695 s->stdio = stdio;
2696 }
14a5cf38
JH
2697 }
2698 return f;
9e353e3b
NIS
2699}
2700
2701PerlIO *
14a5cf38
JH
2702PerlIOStdio_open(pTHX_ PerlIO_funcs *self, PerlIO_list_t *layers,
2703 IV n, const char *mode, int fd, int imode,
2704 int perm, PerlIO *f, int narg, SV **args)
2705{
2706 char tmode[8];
d9dac8cd 2707 if (PerlIOValid(f)) {
14a5cf38
JH
2708 char *path = SvPV_nolen(*args);
2709 PerlIOStdio *s = PerlIOSelf(f, PerlIOStdio);
1751d015
NIS
2710 FILE *stdio;
2711 PerlIOUnix_refcnt_dec(fileno(s->stdio));
2712 stdio = PerlSIO_freopen(path, (mode = PerlIOStdio_mode(mode, tmode)),
14a5cf38
JH
2713 s->stdio);
2714 if (!s->stdio)
2715 return NULL;
2716 s->stdio = stdio;
1751d015 2717 PerlIOUnix_refcnt_inc(fileno(s->stdio));
14a5cf38
JH
2718 return f;
2719 }
2720 else {
2721 if (narg > 0) {
2722 char *path = SvPV_nolen(*args);
3b6c1aba 2723 if (*mode == IoTYPE_NUMERIC) {
14a5cf38
JH
2724 mode++;
2725 fd = PerlLIO_open3(path, imode, perm);
2726 }
2727 else {
95005ad8
GH
2728 FILE *stdio;
2729 bool appended = FALSE;
2730#ifdef __CYGWIN__
2731 /* Cygwin wants its 'b' early. */
2732 appended = TRUE;
2733 mode = PerlIOStdio_mode(mode, tmode);
2734#endif
2735 stdio = PerlSIO_fopen(path, mode);
6f0313ac
JH
2736 if (stdio) {
2737 PerlIOStdio *s;
2738 if (!f) {
2739 f = PerlIO_allocate(aTHX);
2740 }
95005ad8
GH
2741 if (!appended)
2742 mode = PerlIOStdio_mode(mode, tmode);
2743 f = PerlIO_push(aTHX_ f, self, mode, PerlIOArg);
2744 if (f) {
6f0313ac
JH
2745 s = PerlIOSelf(f, PerlIOStdio);
2746 s->stdio = stdio;
2747 PerlIOUnix_refcnt_inc(fileno(s->stdio));
2748 }
2749 return f;
2750 }
2751 else {
2752 return NULL;
2753 }
14a5cf38
JH
2754 }
2755 }
2756 if (fd >= 0) {
2757 FILE *stdio = NULL;
2758 int init = 0;
3b6c1aba 2759 if (*mode == IoTYPE_IMPLICIT) {
14a5cf38
JH
2760 init = 1;
2761 mode++;
2762 }
2763 if (init) {
2764 switch (fd) {
2765 case 0:
2766 stdio = PerlSIO_stdin;
2767 break;
2768 case 1:
2769 stdio = PerlSIO_stdout;
2770 break;
2771 case 2:
2772 stdio = PerlSIO_stderr;
2773 break;
2774 }
2775 }
2776 else {
2777 stdio = PerlSIO_fdopen(fd, mode =
2778 PerlIOStdio_mode(mode, tmode));
2779 }
2780 if (stdio) {
d9dac8cd
NIS
2781 PerlIOStdio *s;
2782 if (!f) {
2783 f = PerlIO_allocate(aTHX);
2784 }
a33cf58c
NIS
2785 if ((f = PerlIO_push(aTHX_ f, self, mode, PerlIOArg))) {
2786 s = PerlIOSelf(f, PerlIOStdio);
2787 s->stdio = stdio;
2788 PerlIOUnix_refcnt_inc(fileno(s->stdio));
2789 }
14a5cf38
JH
2790 return f;
2791 }
2792 }
2793 }
ee518936 2794 return NULL;
9e353e3b
NIS
2795}
2796
1751d015 2797PerlIO *
ecdeb87c 2798PerlIOStdio_dup(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags)
1751d015
NIS
2799{
2800 /* This assumes no layers underneath - which is what
2801 happens, but is not how I remember it. NI-S 2001/10/16
2802 */
ecdeb87c 2803 if ((f = PerlIOBase_dup(aTHX_ f, o, param, flags))) {
694c95cf 2804 FILE *stdio = PerlIOSelf(o, PerlIOStdio)->stdio;
9217ff3f
NIS
2805 int fd = fileno(stdio);
2806 char mode[8];
ecdeb87c 2807 if (flags & PERLIO_DUP_FD) {
9217ff3f
NIS
2808 int dfd = PerlLIO_dup(fileno(stdio));
2809 if (dfd >= 0) {
2810 stdio = PerlSIO_fdopen(dfd, PerlIO_modestr(o,mode));
2811 goto set_this;
ecdeb87c
NIS
2812 }
2813 else {
2814 /* FIXME: To avoid messy error recovery if dup fails
2815 re-use the existing stdio as though flag was not set
2816 */
2817 }
2818 }
9217ff3f
NIS
2819 stdio = PerlSIO_fdopen(fd, PerlIO_modestr(o,mode));
2820 set_this:
694c95cf
JH
2821 PerlIOSelf(f, PerlIOStdio)->stdio = stdio;
2822 PerlIOUnix_refcnt_inc(fileno(stdio));
1751d015
NIS
2823 }
2824 return f;
2825}
2826
0d7a5398
NIS
2827static int
2828PerlIOStdio_invalidate_fileno(pTHX_ FILE *f)
2829{
2830 /* XXX this could use PerlIO_canset_fileno() and
37725cdc 2831 * PerlIO_set_fileno() support from Configure
0d7a5398 2832 */
ef8eacb8
AT
2833# if defined(__UCLIBC__)
2834 /* uClibc must come before glibc because it defines __GLIBC__ as well. */
2835 f->__filedes = -1;
2836 return 1;
2837# elif defined(__GLIBC__)
0d7a5398 2838 /* There may be a better way for GLIBC:
37725cdc 2839 - libio.h defines a flag to not close() on cleanup
0d7a5398
NIS
2840 */
2841 f->_fileno = -1;
2842 return 1;
2843# elif defined(__sun__)
2844# if defined(_LP64)
2845 /* On solaris, if _LP64 is defined, the FILE structure is this:
2846 *
2847 * struct FILE {
2848 * long __pad[16];
2849 * };
2850 *
37725cdc 2851 * It turns out that the fd is stored in the top 32 bits of
0d7a5398
NIS
2852 * file->__pad[4]. The lower 32 bits contain flags. file->pad[5] appears
2853 * to contain a pointer or offset into another structure. All the
2854 * remaining fields are zero.
2855 *
2856 * We set the top bits to -1 (0xFFFFFFFF).
2857 */
2858 f->__pad[4] |= 0xffffffff00000000L;
2859 assert(fileno(f) == 0xffffffff);
2860# else /* !defined(_LP64) */
37725cdc
NIS
2861 /* _file is just a unsigned char :-(
2862 Not clear why we dup() rather than using -1
2863 even if that would be treated as 0xFF - so will
0d7a5398
NIS
2864 a dup fail ...
2865 */
673c27c1 2866 f->_file = PerlLIO_dup(fileno(f));
0d7a5398
NIS
2867# endif /* defined(_LP64) */
2868 return 1;
2869# elif defined(__hpux)
2870 f->__fileH = 0xff;
2871 f->__fileL = 0xff;
2872 return 1;
9837d373 2873 /* Next one ->_file seems to be a reasonable fallback, i.e. if
37725cdc 2874 your platform does not have special entry try this one.
9837d373
NIS
2875 [For OSF only have confirmation for Tru64 (alpha)
2876 but assume other OSFs will be similar.]
37725cdc 2877 */
9837d373 2878# elif defined(_AIX) || defined(__osf__) || defined(__irix__)
0d7a5398
NIS
2879 f->_file = -1;
2880 return 1;
2881# elif defined(__FreeBSD__)
2882 /* There may be a better way on FreeBSD:
37725cdc
NIS
2883 - we could insert a dummy func in the _close function entry
2884 f->_close = (int (*)(void *)) dummy_close;
0d7a5398
NIS
2885 */
2886 f->_file = -1;
2887 return 1;
59ad941d
IZ
2888# elif defined(__EMX__)
2889 /* f->_flags &= ~_IOOPEN; */ /* Will leak stream->_buffer */
2890 f->_handle = -1;
2891 return 1;
0d7a5398
NIS
2892# elif defined(__CYGWIN__)
2893 /* There may be a better way on CYGWIN:
37725cdc
NIS
2894 - we could insert a dummy func in the _close function entry
2895 f->_close = (int (*)(void *)) dummy_close;
0d7a5398
NIS
2896 */
2897 f->_file = -1;
2898 return 1;
2899# elif defined(WIN32)
2900# if defined(__BORLANDC__)
2901 f->fd = PerlLIO_dup(fileno(f));
b475b3e6
JH
2902# elif defined(UNDER_CE)
2903 /* WIN_CE does not have access to FILE internals, it hardly has FILE
2904 structure at all
2905 */
0d7a5398
NIS
2906# else
2907 f->_file = -1;
2908# endif
2909 return 1;
2910# else
2911#if 0
37725cdc 2912 /* Sarathy's code did this - we fall back to a dup/dup2 hack
0d7a5398 2913 (which isn't thread safe) instead
37725cdc 2914 */
0d7a5398
NIS
2915# error "Don't know how to set FILE.fileno on your platform"
2916#endif
2917 return 0;
2918# endif
2919}
2920
1751d015 2921IV
f62ce20a 2922PerlIOStdio_close(pTHX_ PerlIO *f)
1751d015 2923{
1751d015 2924 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
439ba545
NIS
2925 if (!stdio) {
2926 errno = EBADF;
2927 return -1;
2928 }
9217ff3f
NIS
2929 else {
2930 int fd = fileno(stdio);
0d7a5398
NIS
2931 int socksfd = 0;
2932 int invalidate = 0;
bbfd922f 2933 IV result = 0;
0d7a5398
NIS
2934 int saveerr = 0;
2935 int dupfd = 0;
2936#ifdef SOCKS5_VERSION_NAME
37725cdc
NIS
2937 /* Socks lib overrides close() but stdio isn't linked to
2938 that library (though we are) - so we must call close()
2939 on sockets on stdio's behalf.
2940 */
0d7a5398
NIS
2941 int optval;
2942 Sock_size_t optlen = sizeof(int);
2943 if (getsockopt(fd, SOL_SOCKET, SO_TYPE, (void *) &optval, &optlen) == 0) {
2944 socksfd = 1;
37725cdc 2945 invalidate = 1;
0d7a5398
NIS
2946 }
2947#endif
9217ff3f
NIS
2948 if (PerlIOUnix_refcnt_dec(fd) > 0) {
2949 /* File descriptor still in use */
0d7a5398
NIS
2950 invalidate = 1;
2951 socksfd = 0;
37725cdc 2952 }
0d7a5398 2953 if (invalidate) {
37725cdc
NIS
2954 /* For STD* handles don't close the stdio at all
2955 this is because we have shared the FILE * too
0d7a5398
NIS
2956 */
2957 if (stdio == stdin) {
2958 /* Some stdios are buggy fflush-ing inputs */
2959 return 0;
2960 }
2961 else if (stdio == stdout || stdio == stderr) {
9217ff3f
NIS
2962 return PerlIO_flush(f);
2963 }
37725cdc
NIS
2964 /* Tricky - must fclose(stdio) to free memory but not close(fd)
2965 Use Sarathy's trick from maint-5.6 to invalidate the
2966 fileno slot of the FILE *
2967 */
bbfd922f 2968 result = PerlIO_flush(f);
0d7a5398
NIS
2969 saveerr = errno;
2970 if (!(invalidate = PerlIOStdio_invalidate_fileno(aTHX_ stdio))) {
9217ff3f
NIS
2971 dupfd = PerlLIO_dup(fd);
2972 }
37725cdc 2973 }
0d7a5398 2974 result = PerlSIO_fclose(stdio);
37725cdc
NIS
2975 /* We treat error from stdio as success if we invalidated
2976 errno may NOT be expected EBADF
e8529473
NIS
2977 */
2978 if (invalidate && result != 0) {
0d7a5398
NIS
2979 errno = saveerr;
2980 result = 0;
37725cdc 2981 }
0d7a5398
NIS
2982 if (socksfd) {
2983 /* in SOCKS case let close() determine return value */
2984 result = close(fd);
2985 }
2986 if (dupfd) {
2987 PerlLIO_dup2(dupfd,fd);
8a521f28 2988 PerlLIO_close(dupfd);
9217ff3f
NIS
2989 }
2990 return result;
37725cdc 2991 }
1751d015
NIS
2992}
2993
9e353e3b 2994SSize_t
f62ce20a 2995PerlIOStdio_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
9e353e3b 2996{
14a5cf38
JH
2997 FILE *s = PerlIOSelf(f, PerlIOStdio)->stdio;
2998 SSize_t got = 0;
4d948241
NIS
2999 for (;;) {
3000 if (count == 1) {
3001 STDCHAR *buf = (STDCHAR *) vbuf;
3002 /*
3003 * Perl is expecting PerlIO_getc() to fill the buffer Linux's
3004 * stdio does not do that for fread()
3005 */
3006 int ch = PerlSIO_fgetc(s);
3007 if (ch != EOF) {
3008 *buf = ch;
3009 got = 1;
3010 }
14a5cf38 3011 }
4d948241
NIS
3012 else
3013 got = PerlSIO_fread(vbuf, 1, count, s);
b1d8b47a
CS
3014 if (got == 0 && PerlSIO_ferror(s))
3015 got = -1;
42a7a32f 3016 if (got >= 0 || errno != EINTR)
4d948241
NIS
3017 break;
3018 PERL_ASYNC_CHECK();
42a7a32f 3019 SETERRNO(0,0); /* just in case */
14a5cf38 3020 }
14a5cf38 3021 return got;
9e353e3b
NIS
3022}
3023
3024SSize_t
f62ce20a 3025PerlIOStdio_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
9e353e3b 3026{
14a5cf38 3027 SSize_t unread = 0;
93679785
NIS
3028 FILE *s = PerlIOSelf(f, PerlIOStdio)->stdio;
3029
313e59c8 3030#ifdef STDIO_BUFFER_WRITABLE
9f7cd136 3031 if (PerlIO_fast_gets(f) && PerlIO_has_base(f)) {
93679785
NIS
3032 STDCHAR *buf = ((STDCHAR *) vbuf) + count;
3033 STDCHAR *base = PerlIO_get_base(f);
3034 SSize_t cnt = PerlIO_get_cnt(f);
3035 STDCHAR *ptr = PerlIO_get_ptr(f);
3036 SSize_t avail = ptr - base;
3037 if (avail > 0) {
3038 if (avail > count) {
3039 avail = count;
3040 }
3041 ptr -= avail;
3042 Move(buf-avail,ptr,avail,STDCHAR);
3043 count -= avail;
3044 unread += avail;
3045 PerlIO_set_ptrcnt(f,ptr,cnt+avail);
9f7cd136
NIS
3046 if (PerlSIO_feof(s) && unread >= 0)
3047 PerlSIO_clearerr(s);
3048 }
3049 }
313e59c8
NIS
3050 else
3051#endif
3052 if (PerlIO_has_cntptr(f)) {
9f7cd136
NIS
3053 /* We can get pointer to buffer but not its base
3054 Do ungetc() but check chars are ending up in the
3055 buffer
3056 */
3057 STDCHAR *eptr = (STDCHAR*)PerlSIO_get_ptr(s);
3058 STDCHAR *buf = ((STDCHAR *) vbuf) + count;
3059 while (count > 0) {
3060 int ch = *--buf & 0xFF;
3061 if (ungetc(ch,s) != ch) {
3062 /* ungetc did not work */
3063 break;
3064 }
3065 if ((STDCHAR*)PerlSIO_get_ptr(s) != --eptr || ((*eptr & 0xFF) != ch)) {
3066 /* Did not change pointer as expected */
3067 fgetc(s); /* get char back again */
3068 break;
3069 }
3070 /* It worked ! */
3071 count--;
3072 unread++;
93679785
NIS
3073 }
3074 }
3075
3076 if (count > 0) {
3077 unread += PerlIOBase_unread(aTHX_ f, vbuf, count);
14a5cf38
JH
3078 }
3079 return unread;
9e353e3b
NIS
3080}
3081
3082SSize_t
f62ce20a 3083PerlIOStdio_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
9e353e3b 3084{
4d948241
NIS
3085 SSize_t got;
3086 for (;;) {
3087 got = PerlSIO_fwrite(vbuf, 1, count,
3088 PerlIOSelf(f, PerlIOStdio)->stdio);
42a7a32f 3089 if (got >= 0 || errno != EINTR)
4d948241
NIS
3090 break;
3091 PERL_ASYNC_CHECK();
42a7a32f 3092 SETERRNO(0,0); /* just in case */
4d948241
NIS
3093 }
3094 return got;
9e353e3b
NIS
3095}
3096
94a175e1 3097IV
f62ce20a 3098PerlIOStdio_seek(pTHX_ PerlIO *f, Off_t offset, int whence)
9e353e3b 3099{
14a5cf38 3100 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
94a175e1 3101 return PerlSIO_fseek(stdio, offset, whence);
9e353e3b
NIS
3102}
3103
3104Off_t
f62ce20a 3105PerlIOStdio_tell(pTHX_ PerlIO *f)
9e353e3b 3106{
14a5cf38 3107 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
94a175e1 3108 return PerlSIO_ftell(stdio);
9e353e3b
NIS
3109}
3110
3111IV
f62ce20a 3112PerlIOStdio_flush(pTHX_ PerlIO *f)
9e353e3b 3113{
14a5cf38
JH
3114 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3115 if (PerlIOBase(f)->flags & PERLIO_F_CANWRITE) {
3116 return PerlSIO_fflush(stdio);
3117 }
3118 else {
88b61e10 3119#if 0
14a5cf38
JH
3120 /*
3121 * FIXME: This discards ungetc() and pre-read stuff which is not
71200d45 3122 * right if this is just a "sync" from a layer above Suspect right
14a5cf38 3123 * design is to do _this_ but not have layer above flush this
71200d45 3124 * layer read-to-read
14a5cf38
JH
3125 */
3126 /*
71200d45 3127 * Not writeable - sync by attempting a seek
14a5cf38
JH
3128 */
3129 int err = errno;
3130 if (PerlSIO_fseek(stdio, (Off_t) 0, SEEK_CUR) != 0)
3131 errno = err;
88b61e10 3132#endif
14a5cf38
JH
3133 }
3134 return 0;
9e353e3b
NIS
3135}
3136
3137IV
f62ce20a 3138PerlIOStdio_eof(pTHX_ PerlIO *f)
9e353e3b 3139{
14a5cf38 3140 return PerlSIO_feof(PerlIOSelf(f, PerlIOStdio)->stdio);
9e353e3b
NIS
3141}
3142
3143IV
f62ce20a 3144PerlIOStdio_error(pTHX_ PerlIO *f)
9e353e3b 3145{
263df5f1 3146 return PerlSIO_ferror(PerlIOSelf(f, PerlIOStdio)->stdio);
9e353e3b
NIS
3147}
3148
3149void
f62ce20a 3150PerlIOStdio_clearerr(pTHX_ PerlIO *f)
9e353e3b 3151{
14a5cf38 3152 PerlSIO_clearerr(PerlIOSelf(f, PerlIOStdio)->stdio);
9e353e3b
NIS
3153}
3154
3155void
f62ce20a 3156PerlIOStdio_setlinebuf(pTHX_ PerlIO *f)
9e353e3b
NIS
3157{
3158#ifdef HAS_SETLINEBUF
14a5cf38 3159 PerlSIO_setlinebuf(PerlIOSelf(f, PerlIOStdio)->stdio);
9e353e3b 3160#else
14a5cf38 3161 PerlSIO_setvbuf(PerlIOSelf(f, PerlIOStdio)->stdio, Nullch, _IOLBF, 0);
9e353e3b
NIS
3162#endif
3163}
3164
3165#ifdef FILE_base
3166STDCHAR *
f62ce20a 3167PerlIOStdio_get_base(pTHX_ PerlIO *f)
9e353e3b 3168{
14a5cf38 3169 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
cc00df79 3170 return (STDCHAR*)PerlSIO_get_base(stdio);
9e353e3b
NIS
3171}
3172
3173Size_t
f62ce20a 3174PerlIOStdio_get_bufsiz(pTHX_ PerlIO *f)
9e353e3b 3175{
14a5cf38
JH
3176 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3177 return PerlSIO_get_bufsiz(stdio);
9e353e3b
NIS
3178}
3179#endif
3180
3181#ifdef USE_STDIO_PTR
3182STDCHAR *
f62ce20a 3183PerlIOStdio_get_ptr(pTHX_ PerlIO *f)
9e353e3b 3184{
14a5cf38 3185 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
cc00df79 3186 return (STDCHAR*)PerlSIO_get_ptr(stdio);
9e353e3b
NIS
3187}
3188
3189SSize_t
f62ce20a 3190PerlIOStdio_get_cnt(pTHX_ PerlIO *f)
9e353e3b 3191{
14a5cf38
JH
3192 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3193 return PerlSIO_get_cnt(stdio);
9e353e3b
NIS
3194}
3195
3196void
f62ce20a 3197PerlIOStdio_set_ptrcnt(pTHX_ PerlIO *f, STDCHAR * ptr, SSize_t cnt)
9e353e3b 3198{
14a5cf38 3199 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
14a5cf38 3200 if (ptr != NULL) {
9e353e3b 3201#ifdef STDIO_PTR_LVALUE
22569500 3202 PerlSIO_set_ptr(stdio, (void*)ptr); /* LHS STDCHAR* cast non-portable */
9e353e3b 3203#ifdef STDIO_PTR_LVAL_SETS_CNT
14a5cf38 3204 if (PerlSIO_get_cnt(stdio) != (cnt)) {
14a5cf38
JH
3205 assert(PerlSIO_get_cnt(stdio) == (cnt));
3206 }
9e353e3b
NIS
3207#endif
3208#if (!defined(STDIO_PTR_LVAL_NOCHANGE_CNT))
14a5cf38 3209 /*
71200d45 3210 * Setting ptr _does_ change cnt - we are done
14a5cf38
JH
3211 */
3212 return;
9e353e3b 3213#endif
22569500 3214#else /* STDIO_PTR_LVALUE */
14a5cf38 3215 PerlProc_abort();
22569500 3216#endif /* STDIO_PTR_LVALUE */
14a5cf38
JH
3217 }
3218 /*
71200d45 3219 * Now (or only) set cnt
14a5cf38 3220 */
9e353e3b 3221#ifdef STDIO_CNT_LVALUE
14a5cf38 3222 PerlSIO_set_cnt(stdio, cnt);
22569500 3223#else /* STDIO_CNT_LVALUE */
9e353e3b 3224#if (defined(STDIO_PTR_LVALUE) && defined(STDIO_PTR_LVAL_SETS_CNT))
14a5cf38
JH
3225 PerlSIO_set_ptr(stdio,
3226 PerlSIO_get_ptr(stdio) + (PerlSIO_get_cnt(stdio) -
3227 cnt));
22569500 3228#else /* STDIO_PTR_LVAL_SETS_CNT */
14a5cf38 3229 PerlProc_abort();
22569500
NIS
3230#endif /* STDIO_PTR_LVAL_SETS_CNT */
3231#endif /* STDIO_CNT_LVALUE */
9e353e3b
NIS
3232}
3233
93679785 3234
9e353e3b
NIS
3235#endif
3236
93679785
NIS
3237IV
3238PerlIOStdio_fill(pTHX_ PerlIO *f)
3239{
3240 FILE *stdio = PerlIOSelf(f, PerlIOStdio)->stdio;
3241 int c;
3242 /*
3243 * fflush()ing read-only streams can cause trouble on some stdio-s
3244 */
3245 if ((PerlIOBase(f)->flags & PERLIO_F_CANWRITE)) {
3246 if (PerlSIO_fflush(stdio) != 0)
3247 return EOF;
3248 }
3249 c = PerlSIO_fgetc(stdio);
3250 if (c == EOF)
3251 return EOF;
3252
3253#if (defined(STDIO_PTR_LVALUE) && (defined(STDIO_CNT_LVALUE) || defined(STDIO_PTR_LVAL_SETS_CNT)))
313e59c8
NIS
3254
3255#ifdef STDIO_BUFFER_WRITABLE
9f7cd136 3256 if (PerlIO_fast_gets(f) && PerlIO_has_base(f)) {
93679785
NIS
3257 /* Fake ungetc() to the real buffer in case system's ungetc
3258 goes elsewhere
3259 */
3260 STDCHAR *base = (STDCHAR*)PerlSIO_get_base(stdio);
3261 SSize_t cnt = PerlSIO_get_cnt(stdio);
3262 STDCHAR *ptr = (STDCHAR*)PerlSIO_get_ptr(stdio);
3263 if (ptr == base+1) {
3264 *--ptr = (STDCHAR) c;
3265 PerlIOStdio_set_ptrcnt(aTHX_ f,ptr,cnt+1);
3266 if (PerlSIO_feof(stdio))
3267 PerlSIO_clearerr(stdio);
3268 return 0;
3269 }
3270 }
313e59c8
NIS
3271 else
3272#endif
3273 if (PerlIO_has_cntptr(f)) {
9f7cd136
NIS
3274 STDCHAR ch = c;
3275 if (PerlIOStdio_unread(aTHX_ f,&ch,1) == 1) {
3276 return 0;
3277 }
3278 }
93679785
NIS
3279#endif
3280
3281#if defined(VMS)
3282 /* An ungetc()d char is handled separately from the regular
3283 * buffer, so we stuff it in the buffer ourselves.
3284 * Should never get called as should hit code above
3285 */
bad9695d
NIS
3286 *(--((*stdio)->_ptr)) = (unsigned char) c;
3287 (*stdio)->_cnt++;
93679785
NIS
3288#else
3289 /* If buffer snoop scheme above fails fall back to
9f7cd136 3290 using ungetc().
93679785
NIS
3291 */
3292 if (PerlSIO_ungetc(c, stdio) != c)
3293 return EOF;
3294#endif
3295 return 0;
3296}
3297
3298
3299
9e353e3b 3300PerlIO_funcs PerlIO_stdio = {
2dc2558e 3301 sizeof(PerlIO_funcs),
14a5cf38
JH
3302 "stdio",
3303 sizeof(PerlIOStdio),
86e05cf2 3304 PERLIO_K_BUFFERED|PERLIO_K_RAW,
1fd8f4ce 3305 PerlIOStdio_pushed,
44798d05 3306 PerlIOBase_popped,
14a5cf38 3307 PerlIOStdio_open,
86e05cf2 3308 PerlIOBase_binmode, /* binmode */
14a5cf38
JH
3309 NULL,
3310 PerlIOStdio_fileno,
71200d45 3311 PerlIOStdio_dup,
14a5cf38
JH
3312 PerlIOStdio_read,
3313 PerlIOStdio_unread,
3314 PerlIOStdio_write,
3315 PerlIOStdio_seek,
3316 PerlIOStdio_tell,
3317 PerlIOStdio_close,
3318 PerlIOStdio_flush,
3319 PerlIOStdio_fill,
3320 PerlIOStdio_eof,
3321 PerlIOStdio_error,
3322 PerlIOStdio_clearerr,
3323 PerlIOStdio_setlinebuf,
9e353e3b 3324#ifdef FILE_base
14a5cf38
JH
3325 PerlIOStdio_get_base,
3326 PerlIOStdio_get_bufsiz,
9e353e3b 3327#else
14a5cf38
JH
3328 NULL,
3329 NULL,
9e353e3b
NIS
3330#endif
3331#ifdef USE_STDIO_PTR
14a5cf38
JH
3332 PerlIOStdio_get_ptr,
3333 PerlIOStdio_get_cnt,
15b61c98 3334# if defined(HAS_FAST_STDIO) && defined(USE_FAST_STDIO)
79ed0f43 3335 PerlIOStdio_set_ptrcnt,
15b61c98
JH
3336# else
3337 NULL,
3338# endif /* HAS_FAST_STDIO && USE_FAST_STDIO */
3339#else
3340 NULL,
14a5cf38
JH
3341 NULL,
3342 NULL,
15b61c98 3343#endif /* USE_STDIO_PTR */
9e353e3b
NIS
3344};
3345
b9d6bf13
JH
3346/* Note that calls to PerlIO_exportFILE() are reversed using
3347 * PerlIO_releaseFILE(), not importFILE. */
9e353e3b 3348FILE *
81428673 3349PerlIO_exportFILE(PerlIO * f, const char *mode)
9e353e3b 3350{
e87a358a 3351 dTHX;
81428673
NIS
3352 FILE *stdio = NULL;
3353 if (PerlIOValid(f)) {
3354 char buf[8];
3355 PerlIO_flush(f);
3356 if (!mode || !*mode) {
3357 mode = PerlIO_modestr(f, buf);
3358 }
3359 stdio = PerlSIO_fdopen(PerlIO_fileno(f), mode);
3360 if (stdio) {
3361 PerlIOl *l = *f;
9f75cc58 3362 PerlIO *f2;
81428673
NIS
3363 /* De-link any lower layers so new :stdio sticks */
3364 *f = NULL;
9f75cc58
RGS
3365 if ((f2 = PerlIO_push(aTHX_ f, &PerlIO_stdio, buf, Nullsv))) {
3366 PerlIOStdio *s = PerlIOSelf((f = f2), PerlIOStdio);
81428673
NIS
3367 s->stdio = stdio;
3368 /* Link previous lower layers under new one */
3369 *PerlIONext(f) = l;
3370 }
3371 else {
3372 /* restore layers list */
3373 *f = l;
3374 }
a33cf58c 3375 }
14a5cf38
JH
3376 }
3377 return stdio;
9e353e3b
NIS
3378}
3379
81428673 3380
9e353e3b
NIS
3381FILE *
3382PerlIO_findFILE(PerlIO *f)
3383{
14a5cf38
JH
3384 PerlIOl *l = *f;
3385 while (l) {
3386 if (l->tab == &PerlIO_stdio) {
3387 PerlIOStdio *s = PerlIOSelf(&l, PerlIOStdio);
3388 return s->stdio;
3389 }
3390 l = *PerlIONext(&l);
f7e7eb72 3391 }
4b069b44
NIS
3392 /* Uses fallback "mode" via PerlIO_modestr() in PerlIO_exportFILE */
3393 return PerlIO_exportFILE(f, Nullch);
9e353e3b
NIS
3394}
3395
b9d6bf13 3396/* Use this to reverse PerlIO_exportFILE calls. */
9e353e3b
NIS
3397void
3398PerlIO_releaseFILE(PerlIO *p, FILE *f)
3399{
22569500
NIS
3400 PerlIOl *l;
3401 while ((l = *p)) {
3402 if (l->tab == &PerlIO_stdio) {
3403 PerlIOStdio *s = PerlIOSelf(&l, PerlIOStdio);
3404 if (s->stdio == f) {
3405 dTHX;
3406 PerlIO_pop(aTHX_ p);
3407 return;
3408 }
3409 }
3410 p = PerlIONext(p);
3411 }
3412 return;
9e353e3b
NIS
3413}
3414
3415/*--------------------------------------------------------------------------------------*/
14a5cf38 3416/*
71200d45 3417 * perlio buffer layer
14a5cf38 3418 */
9e353e3b 3419
5e2ab84b 3420IV
2dc2558e 3421PerlIOBuf_pushed(pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
5e2ab84b 3422{
14a5cf38
JH
3423 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3424 int fd = PerlIO_fileno(f);
14a5cf38
JH
3425 if (fd >= 0 && PerlLIO_isatty(fd)) {
3426 PerlIOBase(f)->flags |= PERLIO_F_LINEBUF | PERLIO_F_TTY;
3427 }
4b069b44
NIS
3428 if (*PerlIONext(f)) {
3429 Off_t posn = PerlIO_tell(PerlIONext(f));
3430 if (posn != (Off_t) - 1) {
3431 b->posn = posn;
3432 }
14a5cf38 3433 }
2dc2558e 3434 return PerlIOBase_pushed(aTHX_ f, mode, arg, tab);
5e2ab84b
NIS
3435}
3436
9e353e3b 3437PerlIO *
14a5cf38
JH
3438PerlIOBuf_open(pTHX_ PerlIO_funcs *self, PerlIO_list_t *layers,
3439 IV n, const char *mode, int fd, int imode, int perm,
3440 PerlIO *f, int narg, SV **args)
3441{
04892f78 3442 if (PerlIOValid(f)) {
14a5cf38 3443 PerlIO *next = PerlIONext(f);
67363c0d
JH
3444 PerlIO_funcs *tab =
3445 PerlIO_layer_fetch(aTHX_ layers, n - 1, PerlIOBase(next)->tab);
3446 if (tab && tab->Open)
3447 next =
3448 (*tab->Open)(aTHX_ tab, layers, n - 1, mode, fd, imode, perm,
3449 next, narg, args);
2dc2558e 3450 if (!next || (*PerlIOBase(f)->tab->Pushed) (aTHX_ f, mode, PerlIOArg, self) != 0) {
14a5cf38
JH
3451 return NULL;
3452 }
3453 }
3454 else {
04892f78 3455 PerlIO_funcs *tab = PerlIO_layer_fetch(aTHX_ layers, n - 1, PerlIO_default_btm());
14a5cf38 3456 int init = 0;
3b6c1aba 3457 if (*mode == IoTYPE_IMPLICIT) {
14a5cf38
JH
3458 init = 1;
3459 /*
71200d45 3460 * mode++;
14a5cf38
JH
3461 */
3462 }
67363c0d
JH
3463 if (tab && tab->Open)
3464 f = (*tab->Open)(aTHX_ tab, layers, n - 1, mode, fd, imode, perm,
3465 f, narg, args);
3466 else
3467 SETERRNO(EINVAL, LIB_INVARG);
14a5cf38 3468 if (f) {
22569500 3469 if (PerlIO_push(aTHX_ f, self, mode, PerlIOArg) == 0) {
b26b1ab5
NC
3470 /*
3471 * if push fails during open, open fails. close will pop us.
3472 */
3473 PerlIO_close (f);
3474 return NULL;
3475 } else {
3476 fd = PerlIO_fileno(f);
b26b1ab5
NC
3477 if (init && fd == 2) {
3478 /*
3479 * Initial stderr is unbuffered
3480 */
3481 PerlIOBase(f)->flags |= PERLIO_F_UNBUF;
3482 }
23b84778
IZ
3483#ifdef PERLIO_USING_CRLF
3484# ifdef PERLIO_IS_BINMODE_FD
3485 if (PERLIO_IS_BINMODE_FD(fd))
5c728af0 3486 PerlIO_binmode(aTHX_ f, '<'/*not used*/, O_BINARY, Nullch);
23b84778
IZ
3487 else
3488# endif
3489 /*
3490 * do something about failing setmode()? --jhi
3491 */
3492 PerlLIO_setmode(fd, O_BINARY);
3493#endif
14a5cf38
JH
3494 }
3495 }
ee518936 3496 }
14a5cf38 3497 return f;
9e353e3b
NIS
3498}
3499
14a5cf38
JH
3500/*
3501 * This "flush" is akin to sfio's sync in that it handles files in either
71200d45 3502 * read or write state
14a5cf38 3503 */
9e353e3b 3504IV
f62ce20a 3505PerlIOBuf_flush(pTHX_ PerlIO *f)
6f9d8c32 3506{
14a5cf38
JH
3507 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3508 int code = 0;
04892f78 3509 PerlIO *n = PerlIONext(f);
14a5cf38
JH
3510 if (PerlIOBase(f)->flags & PERLIO_F_WRBUF) {
3511 /*
71200d45 3512 * write() the buffer
14a5cf38
JH
3513 */
3514 STDCHAR *buf = b->buf;
3515 STDCHAR *p = buf;
14a5cf38
JH
3516 while (p < b->ptr) {
3517 SSize_t count = PerlIO_write(n, p, b->ptr - p);
3518 if (count > 0) {
3519 p += count;
3520 }
3521 else if (count < 0 || PerlIO_error(n)) {
3522 PerlIOBase(f)->flags |= PERLIO_F_ERROR;
3523 code = -1;
3524 break;
3525 }
3526 }
3527 b->posn += (p - buf);
3528 }
3529 else if (PerlIOBase(f)->flags & PERLIO_F_RDBUF) {
3530 STDCHAR *buf = PerlIO_get_base(f);
3531 /*
71200d45 3532 * Note position change
14a5cf38
JH
3533 */
3534 b->posn += (b->ptr - buf);
3535 if (b->ptr < b->end) {
4b069b44
NIS
3536 /* We did not consume all of it - try and seek downstream to
3537 our logical position
14a5cf38 3538 */
4b069b44 3539 if (PerlIOValid(n) && PerlIO_seek(n, b->posn, SEEK_SET) == 0) {
04892f78
NIS
3540 /* Reload n as some layers may pop themselves on seek */
3541 b->posn = PerlIO_tell(n = PerlIONext(f));
14a5cf38 3542 }
ba5c3fe9 3543 else {
4b069b44
NIS
3544 /* Seek failed (e.g. pipe or tty). Do NOT clear buffer or pre-read
3545 data is lost for good - so return saying "ok" having undone
3546 the position adjust
3547 */
3548 b->posn -= (b->ptr - buf);
ba5c3fe9
NIS
3549 return code;
3550 }
14a5cf38
JH
3551 }
3552 }
3553 b->ptr = b->end = b->buf;
3554 PerlIOBase(f)->flags &= ~(PERLIO_F_RDBUF | PERLIO_F_WRBUF);
04892f78 3555 /* We check for Valid because of dubious decision to make PerlIO_flush(NULL) flush all */
04892f78 3556 if (PerlIOValid(n) && PerlIO_flush(n) != 0)
14a5cf38
JH
3557 code = -1;
3558 return code;
6f9d8c32
NIS
3559}
3560
06da4f11 3561IV
f62ce20a 3562PerlIOBuf_fill(pTHX_ PerlIO *f)
06da4f11 3563{
14a5cf38
JH
3564 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3565 PerlIO *n = PerlIONext(f);
3566 SSize_t avail;
3567 /*
4b069b44
NIS
3568 * Down-stream flush is defined not to loose read data so is harmless.
3569 * we would not normally be fill'ing if there was data left in anycase.
14a5cf38
JH
3570 */
3571 if (PerlIO_flush(f) != 0)
3572 return -1;
3573 if (PerlIOBase(f)->flags & PERLIO_F_TTY)
f62ce20a 3574 PerlIOBase_flush_linebuf(aTHX);
14a5cf38
JH
3575
3576 if (!b->buf)
22569500 3577 PerlIO_get_base(f); /* allocate via vtable */
14a5cf38
JH
3578
3579 b->ptr = b->end = b->buf;
4b069b44
NIS
3580
3581 if (!PerlIOValid(n)) {
3582 PerlIOBase(f)->flags |= PERLIO_F_EOF;
3583 return -1;
3584 }
3585
14a5cf38
JH
3586 if (PerlIO_fast_gets(n)) {
3587 /*
04892f78 3588 * Layer below is also buffered. We do _NOT_ want to call its
14a5cf38
JH
3589 * ->Read() because that will loop till it gets what we asked for
3590 * which may hang on a pipe etc. Instead take anything it has to
71200d45 3591 * hand, or ask it to fill _once_.
14a5cf38
JH
3592 */
3593 avail = PerlIO_get_cnt(n);
3594 if (avail <= 0) {
3595 avail = PerlIO_fill(n);
3596 if (avail == 0)
3597 avail = PerlIO_get_cnt(n);
3598 else {
3599 if (!PerlIO_error(n) && PerlIO_eof(n))
3600 avail = 0;
3601 }
3602 }
3603 if (avail > 0) {
3604 STDCHAR *ptr = PerlIO_get_ptr(n);
3605 SSize_t cnt = avail;
eb160463 3606 if (avail > (SSize_t)b->bufsiz)
14a5cf38
JH
3607 avail = b->bufsiz;
3608 Copy(ptr, b->buf, avail, STDCHAR);
3609 PerlIO_set_ptrcnt(n, ptr + avail, cnt - avail);
3610 }
3611 }
3612 else {
3613 avail = PerlIO_read(n, b->ptr, b->bufsiz);
3614 }
3615 if (avail <= 0) {
3616 if (avail == 0)
3617 PerlIOBase(f)->flags |= PERLIO_F_EOF;
3618 else
3619 PerlIOBase(f)->flags |= PERLIO_F_ERROR;
3620 return -1;
3621 }
3622 b->end = b->buf + avail;
3623 PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
3624 return 0;
06da4f11
NIS
3625}
3626
6f9d8c32 3627SSize_t
f62ce20a 3628PerlIOBuf_read(pTHX_ PerlIO *f, void *vbuf, Size_t count)
6f9d8c32 3629{
14a5cf38 3630 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
04892f78 3631 if (PerlIOValid(f)) {
14a5cf38
JH
3632 if (!b->ptr)
3633 PerlIO_get_base(f);
f62ce20a 3634 return PerlIOBase_read(aTHX_ f, vbuf, count);
14a5cf38
JH
3635 }
3636 return 0;
6f9d8c32
NIS
3637}
3638
9e353e3b 3639SSize_t
f62ce20a 3640PerlIOBuf_unread(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
760ac839 3641{
14a5cf38
JH
3642 const STDCHAR *buf = (const STDCHAR *) vbuf + count;
3643 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3644 SSize_t unread = 0;
3645 SSize_t avail;
3646 if (PerlIOBase(f)->flags & PERLIO_F_WRBUF)
3647 PerlIO_flush(f);
3648 if (!b->buf)
3649 PerlIO_get_base(f);
3650 if (b->buf) {
3651 if (PerlIOBase(f)->flags & PERLIO_F_RDBUF) {
3652 /*
3653 * Buffer is already a read buffer, we can overwrite any chars
71200d45 3654 * which have been read back to buffer start
14a5cf38
JH
3655 */
3656 avail = (b->ptr - b->buf);
3657 }
3658 else {
3659 /*
3660 * Buffer is idle, set it up so whole buffer is available for
71200d45 3661 * unread
14a5cf38
JH
3662 */
3663 avail = b->bufsiz;
3664 b->end = b->buf + avail;
3665 b->ptr = b->end;
3666 PerlIOBase(f)->flags |= PERLIO_F_RDBUF;
3667 /*
71200d45 3668 * Buffer extends _back_ from where we are now
14a5cf38
JH
3669 */
3670 b->posn -= b->bufsiz;
3671 }
3672 if (avail > (SSize_t) count) {
3673 /*
71200d45 3674 * If we have space for more than count, just move count
14a5cf38
JH
3675 */
3676 avail = count;
3677 }
3678 if (avail > 0) {
3679 b->ptr -= avail;
3680 buf -= avail;
3681 /*
3682 * In simple stdio-like ungetc() case chars will be already
71200d45 3683 * there
14a5cf38
JH
3684 */
3685 if (buf != b->ptr) {
3686 Copy(buf, b->ptr, avail, STDCHAR);
3687 }
3688 count -= avail;
3689 unread += avail;
3690 PerlIOBase(f)->flags &= ~PERLIO_F_EOF;
3691 }
3692 }
93679785
NIS
3693 if (count > 0) {
3694 unread += PerlIOBase_unread(aTHX_ f, vbuf, count);
3695 }
14a5cf38 3696 return unread;
760ac839
LW
3697}
3698
9e353e3b 3699SSize_t
f62ce20a 3700PerlIOBuf_write(pTHX_ PerlIO *f, const void *vbuf, Size_t count)
760ac839 3701{
14a5cf38
JH
3702 PerlIOBuf *b = PerlIOSelf(f, PerlIOBuf);
3703 const STDCHAR *buf = (const STDCHAR *) vbuf;
ee56a6b9 3704 const STDCHAR *flushptr = buf;
14a5cf38
JH
3705 Size_t written = 0;
3706 if (!b->buf)
3707 PerlIO_get_base(f);
3708 if (!(PerlIOBase(f)->flags & PERLIO_F_CANWRITE))
3709 return 0;
0678cb22
NIS
3710 if (PerlIOBase(f)->flags & PERLIO_F_RDBUF) {
3711 if (PerlIO_flush(f) != 0) {
3712 return 0;
3713 }
3714 }
ee56a6b9
CS
3715 if (PerlIOBase(f)->flags & PERLIO_F_LINEBUF) {
3716 flushptr = buf + count;
3717 while (flushptr > buf && *(flushptr - 1) != '\n')
3718 --flushptr;
3719 }
14a5cf38
JH
3720 while (count > 0) {
372