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