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