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