This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
[perl #127183] Non-canonical hexadecimal floats are parsed prematurely
[perl5.git] / doio.c
1 /*    doio.c
2  *
3  *    Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
4  *    2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 by Larry Wall and others
5  *
6  *    You may distribute under the terms of either the GNU General Public
7  *    License or the Artistic License, as specified in the README file.
8  *
9  */
10
11 /*
12  *  Far below them they saw the white waters pour into a foaming bowl, and
13  *  then swirl darkly about a deep oval basin in the rocks, until they found
14  *  their way out again through a narrow gate, and flowed away, fuming and
15  *  chattering, into calmer and more level reaches.
16  *
17  *     [p.684 of _The Lord of the Rings_, IV/vi: "The Forbidden Pool"]
18  */
19
20 /* This file contains functions that do the actual I/O on behalf of ops.
21  * For example, pp_print() calls the do_print() function in this file for
22  * each argument needing printing.
23  */
24
25 #include "EXTERN.h"
26 #define PERL_IN_DOIO_C
27 #include "perl.h"
28
29 #if defined(HAS_MSG) || defined(HAS_SEM) || defined(HAS_SHM)
30 #ifndef HAS_SEM
31 #include <sys/ipc.h>
32 #endif
33 #ifdef HAS_MSG
34 #include <sys/msg.h>
35 #endif
36 #ifdef HAS_SHM
37 #include <sys/shm.h>
38 # ifndef HAS_SHMAT_PROTOTYPE
39     extern Shmat_t shmat (int, char *, int);
40 # endif
41 #endif
42 #endif
43
44 #ifdef I_UTIME
45 #  if defined(_MSC_VER) || defined(__MINGW32__)
46 #    include <sys/utime.h>
47 #  else
48 #    include <utime.h>
49 #  endif
50 #endif
51
52 #ifdef O_EXCL
53 #  define OPEN_EXCL O_EXCL
54 #else
55 #  define OPEN_EXCL 0
56 #endif
57
58 #define PERL_MODE_MAX 8
59 #define PERL_FLAGS_MAX 10
60
61 #include <signal.h>
62
63 static IO *
64 S_openn_setup(pTHX_ GV *gv, char *mode, PerlIO **saveifp, PerlIO **saveofp,
65               int *savefd,  char *savetype)
66 {
67     IO * const io = GvIOn(gv);
68
69     PERL_ARGS_ASSERT_OPENN_SETUP;
70
71     *saveifp = NULL;
72     *saveofp = NULL;
73     *savefd = -1;
74     *savetype = IoTYPE_CLOSED;
75
76     Zero(mode,sizeof(mode),char);
77     PL_forkprocess = 1;         /* assume true if no fork */
78
79     /* If currently open - close before we re-open */
80     if (IoIFP(io)) {
81         if (IoTYPE(io) == IoTYPE_STD) {
82             /* This is a clone of one of STD* handles */
83         }
84         else {
85             const int old_fd = PerlIO_fileno(IoIFP(io));
86
87             if (old_fd >= 0 && old_fd <= PL_maxsysfd) {
88                 /* This is one of the original STD* handles */
89                 *saveifp  = IoIFP(io);
90                 *saveofp  = IoOFP(io);
91                 *savetype = IoTYPE(io);
92                 *savefd   = old_fd;
93             }
94             else {
95                 int result;
96
97                 if (IoTYPE(io) == IoTYPE_PIPE)
98                     result = PerlProc_pclose(IoIFP(io));
99                 else if (IoIFP(io) != IoOFP(io)) {
100                     if (IoOFP(io)) {
101                         result = PerlIO_close(IoOFP(io));
102                         PerlIO_close(IoIFP(io)); /* clear stdio, fd already closed */
103                     }
104                     else
105                         result = PerlIO_close(IoIFP(io));
106                 }
107                 else
108                     result = PerlIO_close(IoIFP(io));
109
110                 if (result == EOF && old_fd > PL_maxsysfd) {
111                     /* Why is this not Perl_warn*() call ? */
112                     PerlIO_printf(Perl_error_log,
113                                   "Warning: unable to close filehandle %"HEKf" properly.\n",
114                                   HEKfARG(GvENAME_HEK(gv))
115                         );
116                 }
117             }
118         }
119         IoOFP(io) = IoIFP(io) = NULL;
120     }
121     return io;
122 }
123
124 bool
125 Perl_do_openn(pTHX_ GV *gv, const char *oname, I32 len, int as_raw,
126               int rawmode, int rawperm, PerlIO *supplied_fp, SV **svp,
127               I32 num_svs)
128 {
129     PERL_ARGS_ASSERT_DO_OPENN;
130
131     if (as_raw) {
132         /* sysopen style args, i.e. integer mode and permissions */
133
134         if (num_svs != 0) {
135             Perl_croak(aTHX_ "panic: sysopen with multiple args, num_svs=%ld",
136                        (long) num_svs);
137         }
138         return do_open_raw(gv, oname, len, rawmode, rawperm);
139     }
140     return do_open6(gv, oname, len, supplied_fp, svp, num_svs);
141 }
142
143 bool
144 Perl_do_open_raw(pTHX_ GV *gv, const char *oname, STRLEN len,
145                  int rawmode, int rawperm)
146 {
147     PerlIO *saveifp;
148     PerlIO *saveofp;
149     int savefd;
150     char savetype;
151     char mode[PERL_MODE_MAX];   /* file mode ("r\0", "rb\0", "ab\0" etc.) */
152     IO * const io = openn_setup(gv, mode, &saveifp, &saveofp, &savefd, &savetype);
153     int writing = 0;
154     PerlIO *fp;
155
156     PERL_ARGS_ASSERT_DO_OPEN_RAW;
157
158     /* For ease of blame back to 5.000, keep the existing indenting. */
159     {
160         /* sysopen style args, i.e. integer mode and permissions */
161         STRLEN ix = 0;
162         const int appendtrunc =
163              0
164 #ifdef O_APPEND /* Not fully portable. */
165              |O_APPEND
166 #endif
167 #ifdef O_TRUNC  /* Not fully portable. */
168              |O_TRUNC
169 #endif
170              ;
171         const int modifyingmode = O_WRONLY|O_RDWR|O_CREAT|appendtrunc;
172         int ismodifying;
173         SV *namesv;
174
175         /* It's not always
176
177            O_RDONLY 0
178            O_WRONLY 1
179            O_RDWR   2
180
181            It might be (in OS/390 and Mac OS Classic it is)
182
183            O_WRONLY 1
184            O_RDONLY 2
185            O_RDWR   3
186
187            This means that simple & with O_RDWR would look
188            like O_RDONLY is present.  Therefore we have to
189            be more careful.
190         */
191         if ((ismodifying = (rawmode & modifyingmode))) {
192              if ((ismodifying & O_WRONLY) == O_WRONLY ||
193                  (ismodifying & O_RDWR)   == O_RDWR   ||
194                  (ismodifying & (O_CREAT|appendtrunc)))
195                   TAINT_PROPER("sysopen");
196         }
197         mode[ix++] = IoTYPE_NUMERIC; /* Marker to openn to use numeric "sysopen" */
198
199 #if defined(USE_64_BIT_RAWIO) && defined(O_LARGEFILE)
200         rawmode |= O_LARGEFILE; /* Transparently largefiley. */
201 #endif
202
203         IoTYPE(io) = PerlIO_intmode2str(rawmode, &mode[ix], &writing);
204
205         namesv = newSVpvn_flags(oname, len, SVs_TEMP);
206         fp = PerlIO_openn(aTHX_ NULL, mode, -1, rawmode, rawperm, NULL, 1, &namesv);
207     }
208     return openn_cleanup(gv, io, fp, mode, oname, saveifp, saveofp, savefd,
209                          savetype, writing, 0, NULL);
210 }
211
212 bool
213 Perl_do_open6(pTHX_ GV *gv, const char *oname, STRLEN len,
214               PerlIO *supplied_fp, SV **svp, U32 num_svs)
215 {
216     PerlIO *saveifp;
217     PerlIO *saveofp;
218     int savefd;
219     char savetype;
220     char mode[PERL_MODE_MAX];   /* file mode ("r\0", "rb\0", "ab\0" etc.) */
221     IO * const io = openn_setup(gv, mode, &saveifp, &saveofp, &savefd, &savetype);
222     int writing = 0;
223     PerlIO *fp;
224     bool was_fdopen = FALSE;
225     char *type  = NULL;
226
227     PERL_ARGS_ASSERT_DO_OPEN6;
228
229     /* For ease of blame back to 5.000, keep the existing indenting. */
230     {
231         /* Regular (non-sys) open */
232         char *name;
233         STRLEN olen = len;
234         char *tend;
235         int dodup = 0;
236         bool in_raw = 0, in_crlf = 0, out_raw = 0, out_crlf = 0;
237
238         /* Collect default raw/crlf info from the op */
239         if (PL_op && PL_op->op_type == OP_OPEN) {
240             /* set up IO layers */
241             const U8 flags = PL_op->op_private;
242             in_raw = (flags & OPpOPEN_IN_RAW);
243             in_crlf = (flags & OPpOPEN_IN_CRLF);
244             out_raw = (flags & OPpOPEN_OUT_RAW);
245             out_crlf = (flags & OPpOPEN_OUT_CRLF);
246         }
247
248         type = savepvn(oname, len);
249         tend = type+len;
250         SAVEFREEPV(type);
251
252         /* Lose leading and trailing white space */
253         while (isSPACE(*type))
254             type++;
255         while (tend > type && isSPACE(tend[-1]))
256             *--tend = '\0';
257
258         if (num_svs) {
259             const char *p;
260             STRLEN nlen = 0;
261             /* New style explicit name, type is just mode and layer info */
262 #ifdef USE_STDIO
263             if (SvROK(*svp) && !strchr(oname,'&')) {
264                 if (ckWARN(WARN_IO))
265                     Perl_warner(aTHX_ packWARN(WARN_IO),
266                             "Can't open a reference");
267                 SETERRNO(EINVAL, LIB_INVARG);
268                 fp = NULL;
269                 goto say_false;
270             }
271 #endif /* USE_STDIO */
272             p = (SvOK(*svp) || SvGMAGICAL(*svp)) ? SvPV(*svp, nlen) : NULL;
273
274             if (p && !IS_SAFE_PATHNAME(p, nlen, "open")) {
275                 fp = NULL;
276                 goto say_false;
277             }
278
279             name = p ? savepvn(p, nlen) : savepvs("");
280
281             SAVEFREEPV(name);
282         }
283         else {
284             name = type;
285             len  = tend-type;
286         }
287         IoTYPE(io) = *type;
288         if ((*type == IoTYPE_RDWR) && /* scary */
289            (*(type+1) == IoTYPE_RDONLY || *(type+1) == IoTYPE_WRONLY) &&
290             ((!num_svs || (tend > type+1 && tend[-1] != IoTYPE_PIPE)))) {
291             TAINT_PROPER("open");
292             mode[1] = *type++;
293             writing = 1;
294         }
295
296         if (*type == IoTYPE_PIPE) {
297             if (num_svs) {
298                 if (type[1] != IoTYPE_STD) {
299                   unknown_open_mode:
300                     Perl_croak(aTHX_ "Unknown open() mode '%.*s'", (int)olen, oname);
301                 }
302                 type++;
303             }
304             do {
305                 type++;
306             } while (isSPACE(*type));
307             if (!num_svs) {
308                 name = type;
309                 len = tend-type;
310             }
311             if (*name == '\0') {
312                 /* command is missing 19990114 */
313                 if (ckWARN(WARN_PIPE))
314                     Perl_warner(aTHX_ packWARN(WARN_PIPE), "Missing command in piped open");
315                 errno = EPIPE;
316                 fp = NULL;
317                 goto say_false;
318             }
319             if (!(*name == '-' && name[1] == '\0') || num_svs)
320                 TAINT_ENV();
321             TAINT_PROPER("piped open");
322             if (!num_svs && name[len-1] == '|') {
323                 name[--len] = '\0' ;
324                 if (ckWARN(WARN_PIPE))
325                     Perl_warner(aTHX_ packWARN(WARN_PIPE), "Can't open bidirectional pipe");
326             }
327             mode[0] = 'w';
328             writing = 1;
329             if (out_raw)
330                 mode[1] = 'b';
331             else if (out_crlf)
332                 mode[1] = 't';
333             if (num_svs > 1) {
334                 fp = PerlProc_popen_list(mode, num_svs, svp);
335             }
336             else {
337                 fp = PerlProc_popen(name,mode);
338             }
339             if (num_svs) {
340                 if (*type) {
341                     if (PerlIO_apply_layers(aTHX_ fp, mode, type) != 0) {
342                         fp = NULL;
343                         goto say_false;
344                     }
345                 }
346             }
347         } /* IoTYPE_PIPE */
348         else if (*type == IoTYPE_WRONLY) {
349             TAINT_PROPER("open");
350             type++;
351             if (*type == IoTYPE_WRONLY) {
352                 /* Two IoTYPE_WRONLYs in a row make for an IoTYPE_APPEND. */
353                 mode[0] = IoTYPE(io) = IoTYPE_APPEND;
354                 type++;
355             }
356             else {
357                 mode[0] = 'w';
358             }
359             writing = 1;
360
361             if (out_raw)
362                 mode[1] = 'b';
363             else if (out_crlf)
364                 mode[1] = 't';
365             if (*type == '&') {
366               duplicity:
367                 dodup = PERLIO_DUP_FD;
368                 type++;
369                 if (*type == '=') {
370                     dodup = 0;
371                     type++;
372                 }
373                 if (!num_svs && !*type && supplied_fp) {
374                     /* "<+&" etc. is used by typemaps */
375                     fp = supplied_fp;
376                 }
377                 else {
378                     PerlIO *that_fp = NULL;
379                     int wanted_fd;
380                     UV uv;
381                     if (num_svs > 1) {
382                         /* diag_listed_as: More than one argument to '%s' open */
383                         Perl_croak(aTHX_ "More than one argument to '%c&' open",IoTYPE(io));
384                     }
385                     while (isSPACE(*type))
386                         type++;
387                     if (num_svs && (
388                              SvIOK(*svp)
389                           || (SvPOKp(*svp) && looks_like_number(*svp))
390                        )) {
391                         wanted_fd = SvUV(*svp);
392                         num_svs = 0;
393                     }
394                     else if (isDIGIT(*type)
395                         && grok_atoUV(type, &uv, NULL)
396                         && uv <= INT_MAX
397                     ) {
398                         wanted_fd = (int)uv;
399                     }
400                     else {
401                         const IO* thatio;
402                         if (num_svs) {
403                             thatio = sv_2io(*svp);
404                         }
405                         else {
406                             GV * const thatgv = gv_fetchpvn_flags(type, tend - type,
407                                                        0, SVt_PVIO);
408                             thatio = GvIO(thatgv);
409                         }
410                         if (!thatio) {
411 #ifdef EINVAL
412                             SETERRNO(EINVAL,SS_IVCHAN);
413 #endif
414                             fp = NULL;
415                             goto say_false;
416                         }
417                         if ((that_fp = IoIFP(thatio))) {
418                             /* Flush stdio buffer before dup. --mjd
419                              * Unfortunately SEEK_CURing 0 seems to
420                              * be optimized away on most platforms;
421                              * only Solaris and Linux seem to flush
422                              * on that. --jhi */
423                             /* On the other hand, do all platforms
424                              * take gracefully to flushing a read-only
425                              * filehandle?  Perhaps we should do
426                              * fsetpos(src)+fgetpos(dst)?  --nik */
427                             PerlIO_flush(that_fp);
428                             wanted_fd = PerlIO_fileno(that_fp);
429                             /* When dup()ing STDIN, STDOUT or STDERR
430                              * explicitly set appropriate access mode */
431                             if (that_fp == PerlIO_stdout()
432                                 || that_fp == PerlIO_stderr())
433                                 IoTYPE(io) = IoTYPE_WRONLY;
434                             else if (that_fp == PerlIO_stdin())
435                                 IoTYPE(io) = IoTYPE_RDONLY;
436                             /* When dup()ing a socket, say result is
437                              * one as well */
438                             else if (IoTYPE(thatio) == IoTYPE_SOCKET)
439                                 IoTYPE(io) = IoTYPE_SOCKET;
440                         }
441                         else {
442                             SETERRNO(EBADF, RMS_IFI);
443                             fp = NULL;
444                             goto say_false;
445                         }
446                     }
447                     if (!num_svs)
448                         type = NULL;
449                     if (that_fp) {
450                         fp = PerlIO_fdupopen(aTHX_ that_fp, NULL, dodup);
451                     }
452                     else {
453                         if (dodup)
454                             wanted_fd = PerlLIO_dup(wanted_fd);
455                         else
456                             was_fdopen = TRUE;
457                         if (!(fp = PerlIO_openn(aTHX_ type,mode,wanted_fd,0,0,NULL,num_svs,svp))) {
458                             if (dodup && wanted_fd >= 0)
459                                 PerlLIO_close(wanted_fd);
460                         }
461                     }
462                 }
463             } /* & */
464             else {
465                 while (isSPACE(*type))
466                     type++;
467                 if (*type == IoTYPE_STD && (!type[1] || isSPACE(type[1]) || type[1] == ':')) {
468                     type++;
469                     fp = PerlIO_stdout();
470                     IoTYPE(io) = IoTYPE_STD;
471                     if (num_svs > 1) {
472                         /* diag_listed_as: More than one argument to '%s' open */
473                         Perl_croak(aTHX_ "More than one argument to '>%c' open",IoTYPE_STD);
474                     }
475                 }
476                 else  {
477                     if (num_svs) {
478                         fp = PerlIO_openn(aTHX_ type,mode,-1,0,0,NULL,num_svs,svp);
479                     }
480                     else {
481                         SV *namesv = newSVpvn_flags(type, tend - type, SVs_TEMP);
482                         type = NULL;
483                         fp = PerlIO_openn(aTHX_ type,mode,-1,0,0,NULL,1,&namesv);
484                     }
485                 }
486             } /* !& */
487             if (!fp && type && *type && *type != ':' && !isIDFIRST(*type))
488                goto unknown_open_mode;
489         } /* IoTYPE_WRONLY */
490         else if (*type == IoTYPE_RDONLY) {
491             do {
492                 type++;
493             } while (isSPACE(*type));
494             mode[0] = 'r';
495             if (in_raw)
496                 mode[1] = 'b';
497             else if (in_crlf)
498                 mode[1] = 't';
499             if (*type == '&') {
500                 goto duplicity;
501             }
502             if (*type == IoTYPE_STD && (!type[1] || isSPACE(type[1]) || type[1] == ':')) {
503                 type++;
504                 fp = PerlIO_stdin();
505                 IoTYPE(io) = IoTYPE_STD;
506                 if (num_svs > 1) {
507                     /* diag_listed_as: More than one argument to '%s' open */
508                     Perl_croak(aTHX_ "More than one argument to '<%c' open",IoTYPE_STD);
509                 }
510             }
511             else {
512                 if (num_svs) {
513                     fp = PerlIO_openn(aTHX_ type,mode,-1,0,0,NULL,num_svs,svp);
514                 }
515                 else {
516                     SV *namesv  = newSVpvn_flags(type, tend - type, SVs_TEMP);
517                     type = NULL;
518                     fp = PerlIO_openn(aTHX_ type,mode,-1,0,0,NULL,1,&namesv);
519                 }
520             }
521             if (!fp && type && *type && *type != ':' && !isIDFIRST(*type))
522                goto unknown_open_mode;
523         } /* IoTYPE_RDONLY */
524         else if ((num_svs && /* '-|...' or '...|' */
525                   type[0] == IoTYPE_STD && type[1] == IoTYPE_PIPE) ||
526                  (!num_svs && tend > type+1 && tend[-1] == IoTYPE_PIPE)) {
527             if (num_svs) {
528                 type += 2;   /* skip over '-|' */
529             }
530             else {
531                 *--tend = '\0';
532                 while (tend > type && isSPACE(tend[-1]))
533                     *--tend = '\0';
534                 for (; isSPACE(*type); type++)
535                     ;
536                 name = type;
537                 len  = tend-type;
538             }
539             if (*name == '\0') {
540                 /* command is missing 19990114 */
541                 if (ckWARN(WARN_PIPE))
542                     Perl_warner(aTHX_ packWARN(WARN_PIPE), "Missing command in piped open");
543                 errno = EPIPE;
544                 fp = NULL;
545                 goto say_false;
546             }
547             if (!(*name == '-' && name[1] == '\0') || num_svs)
548                 TAINT_ENV();
549             TAINT_PROPER("piped open");
550             mode[0] = 'r';
551
552             if (in_raw)
553                 mode[1] = 'b';
554             else if (in_crlf)
555                 mode[1] = 't';
556
557             if (num_svs > 1) {
558                 fp = PerlProc_popen_list(mode,num_svs,svp);
559             }
560             else {
561                 fp = PerlProc_popen(name,mode);
562             }
563             IoTYPE(io) = IoTYPE_PIPE;
564             if (num_svs) {
565                 while (isSPACE(*type))
566                     type++;
567                 if (*type) {
568                     if (PerlIO_apply_layers(aTHX_ fp, mode, type) != 0) {
569                         fp = NULL;
570                         goto say_false;
571                     }
572                 }
573             }
574         }
575         else { /* layer(Args) */
576             if (num_svs)
577                 goto unknown_open_mode;
578             name = type;
579             IoTYPE(io) = IoTYPE_RDONLY;
580             for (; isSPACE(*name); name++)
581                 ;
582             mode[0] = 'r';
583
584             if (in_raw)
585                 mode[1] = 'b';
586             else if (in_crlf)
587                 mode[1] = 't';
588
589             if (*name == '-' && name[1] == '\0') {
590                 fp = PerlIO_stdin();
591                 IoTYPE(io) = IoTYPE_STD;
592             }
593             else {
594                 if (num_svs) {
595                     fp = PerlIO_openn(aTHX_ type,mode,-1,0,0,NULL,num_svs,svp);
596                 }
597                 else {
598                     SV *namesv = newSVpvn_flags(type, tend - type, SVs_TEMP);
599                     type = NULL;
600                     fp = PerlIO_openn(aTHX_ type,mode,-1,0,0,NULL,1,&namesv);
601                 }
602             }
603         }
604     }
605
606   say_false:
607     return openn_cleanup(gv, io, fp, mode, oname, saveifp, saveofp, savefd,
608                          savetype, writing, was_fdopen, type);
609 }
610
611 /* Yes, this is ugly, but it's private, and I don't see a cleaner way to
612    simplify the two-headed public interface of do_openn. */
613 static bool
614 S_openn_cleanup(pTHX_ GV *gv, IO *io, PerlIO *fp, char *mode, const char *oname,
615                 PerlIO *saveifp, PerlIO *saveofp, int savefd, char savetype,
616                 int writing, bool was_fdopen, const char *type)
617 {
618     int fd;
619
620     PERL_ARGS_ASSERT_OPENN_CLEANUP;
621
622     if (!fp) {
623         if (IoTYPE(io) == IoTYPE_RDONLY && ckWARN(WARN_NEWLINE)
624             && should_warn_nl(oname)
625             
626         )
627         {
628             GCC_DIAG_IGNORE(-Wformat-nonliteral); /* PL_warn_nl is constant */
629             Perl_warner(aTHX_ packWARN(WARN_NEWLINE), PL_warn_nl, "open");
630             GCC_DIAG_RESTORE;
631         }
632         goto say_false;
633     }
634
635     if (ckWARN(WARN_IO)) {
636         if ((IoTYPE(io) == IoTYPE_RDONLY) &&
637             (fp == PerlIO_stdout() || fp == PerlIO_stderr())) {
638                 Perl_warner(aTHX_ packWARN(WARN_IO),
639                             "Filehandle STD%s reopened as %"HEKf
640                             " only for input",
641                             ((fp == PerlIO_stdout()) ? "OUT" : "ERR"),
642                             HEKfARG(GvENAME_HEK(gv)));
643         }
644         else if ((IoTYPE(io) == IoTYPE_WRONLY) && fp == PerlIO_stdin()) {
645                 Perl_warner(aTHX_ packWARN(WARN_IO),
646                     "Filehandle STDIN reopened as %"HEKf" only for output",
647                      HEKfARG(GvENAME_HEK(gv))
648                 );
649         }
650     }
651
652     fd = PerlIO_fileno(fp);
653     /* Do NOT do: "if (fd < 0) goto say_false;" here.  If there is no
654      * fd assume it isn't a socket - this covers PerlIO::scalar -
655      * otherwise unless we "know" the type probe for socket-ness.
656      */
657     if (IoTYPE(io) && IoTYPE(io) != IoTYPE_PIPE && IoTYPE(io) != IoTYPE_STD && fd >= 0) {
658         if (PerlLIO_fstat(fd,&PL_statbuf) < 0) {
659             /* If PerlIO claims to have fd we had better be able to fstat() it. */
660             (void) PerlIO_close(fp);
661             goto say_false;
662         }
663 #ifndef PERL_MICRO
664         if (S_ISSOCK(PL_statbuf.st_mode))
665             IoTYPE(io) = IoTYPE_SOCKET; /* in case a socket was passed in to us */
666 #ifdef HAS_SOCKET
667         else if (
668             !(PL_statbuf.st_mode & S_IFMT)
669             && IoTYPE(io) != IoTYPE_WRONLY  /* Dups of STD* filehandles already have */
670             && IoTYPE(io) != IoTYPE_RDONLY  /* type so they aren't marked as sockets */
671         ) {                                 /* on OS's that return 0 on fstat()ed pipe */
672              char tmpbuf[256];
673              Sock_size_t buflen = sizeof tmpbuf;
674              if (PerlSock_getsockname(fd, (struct sockaddr *)tmpbuf, &buflen) >= 0
675                       || errno != ENOTSOCK)
676                     IoTYPE(io) = IoTYPE_SOCKET; /* some OS's return 0 on fstat()ed socket */
677                                                 /* but some return 0 for streams too, sigh */
678         }
679 #endif /* HAS_SOCKET */
680 #endif /* !PERL_MICRO */
681     }
682
683     /* Eeek - FIXME !!!
684      * If this is a standard handle we discard all the layer stuff
685      * and just dup the fd into whatever was on the handle before !
686      */
687
688     if (saveifp) {              /* must use old fp? */
689         /* If fd is less that PL_maxsysfd i.e. STDIN..STDERR
690            then dup the new fileno down
691          */
692         if (saveofp) {
693             PerlIO_flush(saveofp);      /* emulate PerlIO_close() */
694             if (saveofp != saveifp) {   /* was a socket? */
695                 PerlIO_close(saveofp);
696             }
697         }
698         if (savefd != fd) {
699             /* Still a small can-of-worms here if (say) PerlIO::scalar
700                is assigned to (say) STDOUT - for now let dup2() fail
701                and provide the error
702              */
703             if (fd < 0) {
704                 SETERRNO(EBADF,RMS_IFI);
705                 goto say_false;
706             } else if (PerlLIO_dup2(fd, savefd) < 0) {
707                 (void)PerlIO_close(fp);
708                 goto say_false;
709             }
710 #ifdef VMS
711             if (savefd != PerlIO_fileno(PerlIO_stdin())) {
712                 char newname[FILENAME_MAX+1];
713                 if (PerlIO_getname(fp, newname)) {
714                     if (fd == PerlIO_fileno(PerlIO_stdout()))
715                         vmssetuserlnm("SYS$OUTPUT", newname);
716                     if (fd == PerlIO_fileno(PerlIO_stderr()))
717                         vmssetuserlnm("SYS$ERROR", newname);
718                 }
719             }
720 #endif
721
722 #if !defined(WIN32)
723            /* PL_fdpid isn't used on Windows, so avoid this useless work.
724             * XXX Probably the same for a lot of other places. */
725             {
726                 Pid_t pid;
727                 SV *sv;
728
729                 sv = *av_fetch(PL_fdpid,fd,TRUE);
730                 SvUPGRADE(sv, SVt_IV);
731                 pid = SvIVX(sv);
732                 SvIV_set(sv, 0);
733                 sv = *av_fetch(PL_fdpid,savefd,TRUE);
734                 SvUPGRADE(sv, SVt_IV);
735                 SvIV_set(sv, pid);
736             }
737 #endif
738
739             if (was_fdopen) {
740                 /* need to close fp without closing underlying fd */
741                 int ofd = PerlIO_fileno(fp);
742                 int dupfd = ofd >= 0 ? PerlLIO_dup(ofd) : -1;
743 #if defined(HAS_FCNTL) && defined(F_SETFD)
744                 /* Assume if we have F_SETFD we have F_GETFD. */
745                 /* Get a copy of all the fd flags. */
746                 int fd_flags = ofd >= 0 ? fcntl(ofd, F_GETFD) : -1;
747                 if (fd_flags < 0) {
748                     if (dupfd >= 0)
749                         PerlLIO_close(dupfd);
750                     goto say_false;
751                 }
752 #endif
753                 if (ofd < 0 || dupfd < 0) {
754                     if (dupfd >= 0)
755                         PerlLIO_close(dupfd);
756                     goto say_false;
757                 }
758                 PerlIO_close(fp);
759                 PerlLIO_dup2(dupfd, ofd);
760 #if defined(HAS_FCNTL) && defined(F_SETFD)
761                 /* The dup trick has lost close-on-exec on ofd,
762                  * and possibly any other flags, so restore them. */
763                 fcntl(ofd,F_SETFD, fd_flags);
764 #endif
765                 PerlLIO_close(dupfd);
766             }
767             else
768                 PerlIO_close(fp);
769         }
770         fp = saveifp;
771         PerlIO_clearerr(fp);
772         fd = PerlIO_fileno(fp);
773     }
774 #if defined(HAS_FCNTL) && defined(F_SETFD) && defined(FD_CLOEXEC)
775     if (fd >= 0 && fd > PL_maxsysfd && fcntl(fd, F_SETFD, FD_CLOEXEC) < 0) {
776         PerlLIO_close(fd);
777         goto say_false;
778     }
779 #endif
780     IoIFP(io) = fp;
781
782     IoFLAGS(io) &= ~IOf_NOLINE;
783     if (writing) {
784         if (IoTYPE(io) == IoTYPE_SOCKET
785             || (IoTYPE(io) == IoTYPE_WRONLY && fd >= 0 && S_ISCHR(PL_statbuf.st_mode)) ) {
786             char *s = mode;
787             if (*s == IoTYPE_IMPLICIT || *s == IoTYPE_NUMERIC)
788               s++;
789             *s = 'w';
790             if (!(IoOFP(io) = PerlIO_openn(aTHX_ type,s,fd,0,0,NULL,0,NULL))) {
791                 PerlIO_close(fp);
792                 goto say_false;
793             }
794         }
795         else
796             IoOFP(io) = fp;
797     }
798     return TRUE;
799
800   say_false:
801     IoIFP(io) = saveifp;
802     IoOFP(io) = saveofp;
803     IoTYPE(io) = savetype;
804     return FALSE;
805 }
806
807 PerlIO *
808 Perl_nextargv(pTHX_ GV *gv, bool nomagicopen)
809 {
810     IO * const io = GvIOp(gv);
811
812     PERL_ARGS_ASSERT_NEXTARGV;
813
814     if (!PL_argvoutgv)
815         PL_argvoutgv = gv_fetchpvs("ARGVOUT", GV_ADD|GV_NOTQUAL, SVt_PVIO);
816     if (io && (IoFLAGS(io) & (IOf_ARGV|IOf_START)) == (IOf_ARGV|IOf_START)) {
817         IoFLAGS(io) &= ~IOf_START;
818         if (PL_inplace) {
819             assert(PL_defoutgv);
820             Perl_av_create_and_push(aTHX_ &PL_argvout_stack,
821                                     SvREFCNT_inc_simple_NN(PL_defoutgv));
822         }
823     }
824     if (PL_filemode & (S_ISUID|S_ISGID)) {
825         PerlIO_flush(IoIFP(GvIOn(PL_argvoutgv)));  /* chmod must follow last write */
826 #ifdef HAS_FCHMOD
827         if (PL_lastfd != -1)
828             (void)fchmod(PL_lastfd,PL_filemode);
829 #else
830         (void)PerlLIO_chmod(PL_oldname,PL_filemode);
831 #endif
832     }
833     PL_lastfd = -1;
834     PL_filemode = 0;
835     if (!GvAV(gv))
836         return NULL;
837     while (av_tindex(GvAV(gv)) >= 0) {
838         Stat_t statbuf;
839         STRLEN oldlen;
840         SV *const sv = av_shift(GvAV(gv));
841         SAVEFREESV(sv);
842         SvTAINTED_off(GvSVn(gv)); /* previous tainting irrelevant */
843         sv_setsv(GvSVn(gv),sv);
844         SvSETMAGIC(GvSV(gv));
845         PL_oldname = SvPVx(GvSV(gv), oldlen);
846         if (LIKELY(!PL_inplace)) {
847             if (nomagicopen
848                     ? do_open6(gv, "<", 1, NULL, &GvSV(gv), 1)
849                     : do_open6(gv, PL_oldname, oldlen, NULL, NULL, 0)
850                ) {
851                 return IoIFP(GvIOp(gv));
852             }
853         }
854         else {
855             /* This very long block ends with return IoIFP(GvIOp(gv));
856                Both this block and the block above fall through on open
857                failure to the warning code, and then the while loop above tries
858                the next entry. */
859             if (do_open_raw(gv, PL_oldname, oldlen, O_RDONLY, 0)) {
860 #ifndef FLEXFILENAMES
861                 int filedev;
862                 int fileino;
863 #endif
864                 Uid_t fileuid;
865                 Gid_t filegid;
866
867                 TAINT_PROPER("inplace open");
868                 if (oldlen == 1 && *PL_oldname == '-') {
869                     setdefout(gv_fetchpvs("STDOUT", GV_ADD|GV_NOTQUAL,
870                                           SVt_PVIO));
871                     return IoIFP(GvIOp(gv));
872                 }
873 #ifndef FLEXFILENAMES
874                 filedev = PL_statbuf.st_dev;
875                 fileino = PL_statbuf.st_ino;
876 #endif
877                 PL_filemode = PL_statbuf.st_mode;
878                 fileuid = PL_statbuf.st_uid;
879                 filegid = PL_statbuf.st_gid;
880                 if (!S_ISREG(PL_filemode)) {
881                     Perl_ck_warner_d(aTHX_ packWARN(WARN_INPLACE),
882                                      "Can't do inplace edit: %s is not a regular file",
883                                      PL_oldname );
884                     do_close(gv,FALSE);
885                     continue;
886                 }
887                 if (*PL_inplace && strNE(PL_inplace, "*")) {
888                     const char *star = strchr(PL_inplace, '*');
889                     if (star) {
890                         const char *begin = PL_inplace;
891                         sv_setpvs(sv, "");
892                         do {
893                             sv_catpvn(sv, begin, star - begin);
894                             sv_catpvn(sv, PL_oldname, oldlen);
895                             begin = ++star;
896                         } while ((star = strchr(begin, '*')));
897                         if (*begin)
898                             sv_catpv(sv,begin);
899                     }
900                     else {
901                         sv_catpv(sv,PL_inplace);
902                     }
903 #ifndef FLEXFILENAMES
904                     if ((PerlLIO_stat(SvPVX_const(sv),&PL_statbuf) >= 0
905                          && PL_statbuf.st_dev == filedev
906                          && PL_statbuf.st_ino == fileino)
907 #ifdef DJGPP
908                         || ((_djstat_fail_bits & _STFAIL_TRUENAME)!=0)
909 #endif
910                       )
911                     {
912                         Perl_ck_warner_d(aTHX_ packWARN(WARN_INPLACE),
913                                          "Can't do inplace edit: %"SVf" would not be unique",
914                                          SVfARG(sv));
915                         do_close(gv,FALSE);
916                         continue;
917                     }
918 #endif
919 #ifdef HAS_RENAME
920 #if !defined(DOSISH) && !defined(__CYGWIN__)
921                     if (PerlLIO_rename(PL_oldname,SvPVX_const(sv)) < 0) {
922                         Perl_ck_warner_d(aTHX_ packWARN(WARN_INPLACE),
923                                          "Can't rename %s to %"SVf": %s, skipping file",
924                                          PL_oldname, SVfARG(sv), Strerror(errno));
925                         do_close(gv,FALSE);
926                         continue;
927                     }
928 #else
929                     do_close(gv,FALSE);
930                     (void)PerlLIO_unlink(SvPVX_const(sv));
931                     (void)PerlLIO_rename(PL_oldname,SvPVX_const(sv));
932                     do_open_raw(gv, SvPVX_const(sv), SvCUR(sv), O_RDONLY, 0);
933 #endif /* DOSISH */
934 #else
935                     (void)UNLINK(SvPVX_const(sv));
936                     if (link(PL_oldname,SvPVX_const(sv)) < 0) {
937                         Perl_ck_warner_d(aTHX_ packWARN(WARN_INPLACE),
938                                          "Can't rename %s to %"SVf": %s, skipping file",
939                                          PL_oldname, SVfARG(sv), Strerror(errno) );
940                         do_close(gv,FALSE);
941                         continue;
942                     }
943                     (void)UNLINK(PL_oldname);
944 #endif
945                 }
946                 else {
947 #if !defined(DOSISH) && !defined(__amigaos4__)
948 #  ifndef VMS  /* Don't delete; use automatic file versioning */
949                     if (UNLINK(PL_oldname) < 0) {
950                         Perl_ck_warner_d(aTHX_ packWARN(WARN_INPLACE),
951                                          "Can't remove %s: %s, skipping file",
952                                          PL_oldname, Strerror(errno) );
953                         do_close(gv,FALSE);
954                         continue;
955                     }
956 #  endif
957 #else
958                     Perl_croak(aTHX_ "Can't do inplace edit without backup");
959 #endif
960                 }
961
962                 sv_setpvn(sv,PL_oldname,oldlen);
963                 SETERRNO(0,0);          /* in case sprintf set errno */
964                 if (!Perl_do_open_raw(aTHX_ PL_argvoutgv, SvPVX_const(sv),
965                                       SvCUR(sv),
966 #ifdef VMS
967                                       O_WRONLY|O_CREAT|O_TRUNC, 0
968 #else
969                                       O_WRONLY|O_CREAT|OPEN_EXCL, 0600
970 #endif
971                         )) {
972                     Perl_ck_warner_d(aTHX_ packWARN(WARN_INPLACE), "Can't do inplace edit on %s: %s",
973                                      PL_oldname, Strerror(errno) );
974                     do_close(gv,FALSE);
975                     continue;
976                 }
977                 setdefout(PL_argvoutgv);
978                 PL_lastfd = PerlIO_fileno(IoIFP(GvIOp(PL_argvoutgv)));
979                 if (PL_lastfd >= 0) {
980                     (void)PerlLIO_fstat(PL_lastfd,&statbuf);
981 #ifdef HAS_FCHMOD
982                     (void)fchmod(PL_lastfd,PL_filemode);
983 #else
984                     (void)PerlLIO_chmod(PL_oldname,PL_filemode);
985 #endif
986                     if (fileuid != statbuf.st_uid || filegid != statbuf.st_gid) {
987                         /* XXX silently ignore failures */
988 #ifdef HAS_FCHOWN
989                         PERL_UNUSED_RESULT(fchown(PL_lastfd,fileuid,filegid));
990 #else
991 #ifdef HAS_CHOWN
992                         PERL_UNUSED_RESULT(PerlLIO_chown(PL_oldname,fileuid,filegid));
993 #endif
994 #endif
995                     }
996                 }
997                 return IoIFP(GvIOp(gv));
998             }
999         } /* successful do_open_raw(), PL_inplace non-NULL */
1000
1001         if (ckWARN_d(WARN_INPLACE)) {
1002             const int eno = errno;
1003             if (PerlLIO_stat(PL_oldname, &statbuf) >= 0
1004                 && !S_ISREG(statbuf.st_mode)) {
1005                 Perl_warner(aTHX_ packWARN(WARN_INPLACE),
1006                             "Can't do inplace edit: %s is not a regular file",
1007                             PL_oldname);
1008             }
1009             else {
1010                 Perl_warner(aTHX_ packWARN(WARN_INPLACE), "Can't open %s: %s",
1011                             PL_oldname, Strerror(eno));
1012             }
1013         }
1014     }
1015     if (io && (IoFLAGS(io) & IOf_ARGV))
1016         IoFLAGS(io) |= IOf_START;
1017     if (PL_inplace) {
1018         (void)do_close(PL_argvoutgv,FALSE);
1019         if (io && (IoFLAGS(io) & IOf_ARGV)
1020             && PL_argvout_stack && AvFILLp(PL_argvout_stack) >= 0)
1021         {
1022             GV * const oldout = MUTABLE_GV(av_pop(PL_argvout_stack));
1023             setdefout(oldout);
1024             SvREFCNT_dec_NN(oldout);
1025             return NULL;
1026         }
1027         setdefout(gv_fetchpvs("STDOUT", GV_ADD|GV_NOTQUAL, SVt_PVIO));
1028     }
1029     return NULL;
1030 }
1031
1032 /* explicit renamed to avoid C++ conflict    -- kja */
1033 bool
1034 Perl_do_close(pTHX_ GV *gv, bool not_implicit)
1035 {
1036     bool retval;
1037     IO *io;
1038
1039     if (!gv)
1040         gv = PL_argvgv;
1041     if (!gv || !isGV_with_GP(gv)) {
1042         if (not_implicit)
1043             SETERRNO(EBADF,SS_IVCHAN);
1044         return FALSE;
1045     }
1046     io = GvIO(gv);
1047     if (!io) {          /* never opened */
1048         if (not_implicit) {
1049             report_evil_fh(gv);
1050             SETERRNO(EBADF,SS_IVCHAN);
1051         }
1052         return FALSE;
1053     }
1054     retval = io_close(io, NULL, not_implicit, FALSE);
1055     if (not_implicit) {
1056         IoLINES(io) = 0;
1057         IoPAGE(io) = 0;
1058         IoLINES_LEFT(io) = IoPAGE_LEN(io);
1059     }
1060     IoTYPE(io) = IoTYPE_CLOSED;
1061     return retval;
1062 }
1063
1064 bool
1065 Perl_io_close(pTHX_ IO *io, GV *gv, bool not_implicit, bool warn_on_fail)
1066 {
1067     bool retval = FALSE;
1068
1069     PERL_ARGS_ASSERT_IO_CLOSE;
1070
1071     if (IoIFP(io)) {
1072         if (IoTYPE(io) == IoTYPE_PIPE) {
1073             const int status = PerlProc_pclose(IoIFP(io));
1074             if (not_implicit) {
1075                 STATUS_NATIVE_CHILD_SET(status);
1076                 retval = (STATUS_UNIX == 0);
1077             }
1078             else {
1079                 retval = (status != -1);
1080             }
1081         }
1082         else if (IoTYPE(io) == IoTYPE_STD)
1083             retval = TRUE;
1084         else {
1085             if (IoOFP(io) && IoOFP(io) != IoIFP(io)) {          /* a socket */
1086                 const bool prev_err = PerlIO_error(IoOFP(io));
1087 #ifdef USE_PERLIO
1088                 if (prev_err)
1089                     PerlIO_restore_errno(IoOFP(io));
1090 #endif
1091                 retval = (PerlIO_close(IoOFP(io)) != EOF && !prev_err);
1092                 PerlIO_close(IoIFP(io));        /* clear stdio, fd already closed */
1093             }
1094             else {
1095                 const bool prev_err = PerlIO_error(IoIFP(io));
1096 #ifdef USE_PERLIO
1097                 if (prev_err)
1098                     PerlIO_restore_errno(IoIFP(io));
1099 #endif
1100                 retval = (PerlIO_close(IoIFP(io)) != EOF && !prev_err);
1101             }
1102         }
1103         IoOFP(io) = IoIFP(io) = NULL;
1104
1105         if (warn_on_fail && !retval) {
1106             if (gv)
1107                 Perl_ck_warner_d(aTHX_ packWARN(WARN_IO),
1108                                 "Warning: unable to close filehandle %"
1109                                  HEKf" properly: %"SVf,
1110                                  HEKfARG(GvNAME_HEK(gv)),
1111                                  SVfARG(get_sv("!",GV_ADD)));
1112             else
1113                 Perl_ck_warner_d(aTHX_ packWARN(WARN_IO),
1114                                 "Warning: unable to close filehandle "
1115                                 "properly: %"SVf,
1116                                  SVfARG(get_sv("!",GV_ADD)));
1117         }
1118     }
1119     else if (not_implicit) {
1120         SETERRNO(EBADF,SS_IVCHAN);
1121     }
1122
1123     return retval;
1124 }
1125
1126 bool
1127 Perl_do_eof(pTHX_ GV *gv)
1128 {
1129     IO * const io = GvIO(gv);
1130
1131     PERL_ARGS_ASSERT_DO_EOF;
1132
1133     if (!io)
1134         return TRUE;
1135     else if (IoTYPE(io) == IoTYPE_WRONLY)
1136         report_wrongway_fh(gv, '>');
1137
1138     while (IoIFP(io)) {
1139         if (PerlIO_has_cntptr(IoIFP(io))) {     /* (the code works without this) */
1140             if (PerlIO_get_cnt(IoIFP(io)) > 0)  /* cheat a little, since */
1141                 return FALSE;                   /* this is the most usual case */
1142         }
1143
1144         {
1145              /* getc and ungetc can stomp on errno */
1146             dSAVE_ERRNO;
1147             const int ch = PerlIO_getc(IoIFP(io));
1148             if (ch != EOF) {
1149                 (void)PerlIO_ungetc(IoIFP(io),ch);
1150                 RESTORE_ERRNO;
1151                 return FALSE;
1152             }
1153             RESTORE_ERRNO;
1154         }
1155
1156         if (PerlIO_has_cntptr(IoIFP(io)) && PerlIO_canset_cnt(IoIFP(io))) {
1157             if (PerlIO_get_cnt(IoIFP(io)) < -1)
1158                 PerlIO_set_cnt(IoIFP(io),-1);
1159         }
1160         if (PL_op->op_flags & OPf_SPECIAL) { /* not necessarily a real EOF yet? */
1161             if (gv != PL_argvgv || !nextargv(gv, FALSE))        /* get another fp handy */
1162                 return TRUE;
1163         }
1164         else
1165             return TRUE;                /* normal fp, definitely end of file */
1166     }
1167     return TRUE;
1168 }
1169
1170 Off_t
1171 Perl_do_tell(pTHX_ GV *gv)
1172 {
1173     IO *const io = GvIO(gv);
1174     PerlIO *fp;
1175
1176     PERL_ARGS_ASSERT_DO_TELL;
1177
1178     if (io && (fp = IoIFP(io))) {
1179         return PerlIO_tell(fp);
1180     }
1181     report_evil_fh(gv);
1182     SETERRNO(EBADF,RMS_IFI);
1183     return (Off_t)-1;
1184 }
1185
1186 bool
1187 Perl_do_seek(pTHX_ GV *gv, Off_t pos, int whence)
1188 {
1189     IO *const io = GvIO(gv);
1190     PerlIO *fp;
1191
1192     if (io && (fp = IoIFP(io))) {
1193         return PerlIO_seek(fp, pos, whence) >= 0;
1194     }
1195     report_evil_fh(gv);
1196     SETERRNO(EBADF,RMS_IFI);
1197     return FALSE;
1198 }
1199
1200 Off_t
1201 Perl_do_sysseek(pTHX_ GV *gv, Off_t pos, int whence)
1202 {
1203     IO *const io = GvIO(gv);
1204     PerlIO *fp;
1205
1206     PERL_ARGS_ASSERT_DO_SYSSEEK;
1207
1208     if (io && (fp = IoIFP(io))) {
1209         int fd = PerlIO_fileno(fp);
1210         if (fd < 0 || (whence == SEEK_SET && pos < 0)) {
1211             SETERRNO(EINVAL,LIB_INVARG);
1212             return -1;
1213         } else {
1214             return PerlLIO_lseek(fd, pos, whence);
1215         }
1216     }
1217     report_evil_fh(gv);
1218     SETERRNO(EBADF,RMS_IFI);
1219     return (Off_t)-1;
1220 }
1221
1222 int
1223 Perl_mode_from_discipline(pTHX_ const char *s, STRLEN len)
1224 {
1225     int mode = O_BINARY;
1226     PERL_UNUSED_CONTEXT;
1227     if (s) {
1228         while (*s) {
1229             if (*s == ':') {
1230                 switch (s[1]) {
1231                 case 'r':
1232                     if (s[2] == 'a' && s[3] == 'w'
1233                         && (!s[4] || s[4] == ':' || isSPACE(s[4])))
1234                     {
1235                         mode = O_BINARY;
1236                         s += 4;
1237                         len -= 4;
1238                         break;
1239                     }
1240                     /* FALLTHROUGH */
1241                 case 'c':
1242                     if (s[2] == 'r' && s[3] == 'l' && s[4] == 'f'
1243                         && (!s[5] || s[5] == ':' || isSPACE(s[5])))
1244                     {
1245                         mode = O_TEXT;
1246                         s += 5;
1247                         len -= 5;
1248                         break;
1249                     }
1250                     /* FALLTHROUGH */
1251                 default:
1252                     goto fail_discipline;
1253                 }
1254             }
1255             else if (isSPACE(*s)) {
1256                 ++s;
1257                 --len;
1258             }
1259             else {
1260                 const char *end;
1261   fail_discipline:
1262                 end = strchr(s+1, ':');
1263                 if (!end)
1264                     end = s+len;
1265 #ifndef PERLIO_LAYERS
1266                 Perl_croak(aTHX_ "IO layers (like '%.*s') unavailable", end-s, s);
1267 #else
1268                 len -= end-s;
1269                 s = end;
1270 #endif
1271             }
1272         }
1273     }
1274     return mode;
1275 }
1276
1277 #if !defined(HAS_TRUNCATE) && !defined(HAS_CHSIZE)
1278 I32
1279 my_chsize(int fd, Off_t length)
1280 {
1281 #ifdef F_FREESP
1282         /* code courtesy of William Kucharski */
1283 #define HAS_CHSIZE
1284
1285     Stat_t filebuf;
1286
1287     if (PerlLIO_fstat(fd, &filebuf) < 0)
1288         return -1;
1289
1290     if (filebuf.st_size < length) {
1291
1292         /* extend file length */
1293
1294         if ((PerlLIO_lseek(fd, (length - 1), 0)) < 0)
1295             return -1;
1296
1297         /* write a "0" byte */
1298
1299         if ((PerlLIO_write(fd, "", 1)) != 1)
1300             return -1;
1301     }
1302     else {
1303         /* truncate length */
1304         struct flock fl;
1305         fl.l_whence = 0;
1306         fl.l_len = 0;
1307         fl.l_start = length;
1308         fl.l_type = F_WRLCK;    /* write lock on file space */
1309
1310         /*
1311         * This relies on the UNDOCUMENTED F_FREESP argument to
1312         * fcntl(2), which truncates the file so that it ends at the
1313         * position indicated by fl.l_start.
1314         *
1315         * Will minor miracles never cease?
1316         */
1317
1318         if (fcntl(fd, F_FREESP, &fl) < 0)
1319             return -1;
1320
1321     }
1322     return 0;
1323 #else
1324     Perl_croak_nocontext("truncate not implemented");
1325 #endif /* F_FREESP */
1326     return -1;
1327 }
1328 #endif /* !HAS_TRUNCATE && !HAS_CHSIZE */
1329
1330 bool
1331 Perl_do_print(pTHX_ SV *sv, PerlIO *fp)
1332 {
1333     PERL_ARGS_ASSERT_DO_PRINT;
1334
1335     /* assuming fp is checked earlier */
1336     if (!sv)
1337         return TRUE;
1338     if (SvTYPE(sv) == SVt_IV && SvIOK(sv)) {
1339         assert(!SvGMAGICAL(sv));
1340         if (SvIsUV(sv))
1341             PerlIO_printf(fp, "%"UVuf, (UV)SvUVX(sv));
1342         else
1343             PerlIO_printf(fp, "%"IVdf, (IV)SvIVX(sv));
1344         return !PerlIO_error(fp);
1345     }
1346     else {
1347         STRLEN len;
1348         /* Do this first to trigger any overloading.  */
1349         const char *tmps = SvPV_const(sv, len);
1350         U8 *tmpbuf = NULL;
1351         bool happy = TRUE;
1352
1353         if (PerlIO_isutf8(fp)) { /* If the stream is utf8 ... */
1354             if (!SvUTF8(sv)) {  /* Convert to utf8 if necessary */
1355                 /* We don't modify the original scalar.  */
1356                 tmpbuf = bytes_to_utf8((const U8*) tmps, &len);
1357                 tmps = (char *) tmpbuf;
1358             }
1359             else if (ckWARN4_d(WARN_UTF8, WARN_SURROGATE, WARN_NON_UNICODE, WARN_NONCHAR)) {
1360                 (void) check_utf8_print((const U8*) tmps, len);
1361             }
1362         } /* else stream isn't utf8 */
1363         else if (DO_UTF8(sv)) { /* But if is utf8 internally, attempt to
1364                                    convert to bytes */
1365             STRLEN tmplen = len;
1366             bool utf8 = TRUE;
1367             U8 * const result = bytes_from_utf8((const U8*) tmps, &tmplen, &utf8);
1368             if (!utf8) {
1369
1370                 /* Here, succeeded in downgrading from utf8.  Set up to below
1371                  * output the converted value */
1372                 tmpbuf = result;
1373                 tmps = (char *) tmpbuf;
1374                 len = tmplen;
1375             }
1376             else {  /* Non-utf8 output stream, but string only representable in
1377                        utf8 */
1378                 assert((char *)result == tmps);
1379                 Perl_ck_warner_d(aTHX_ packWARN(WARN_UTF8),
1380                                  "Wide character in %s",
1381                                    PL_op ? OP_DESC(PL_op) : "print"
1382                                 );
1383                     /* Could also check that isn't one of the things to avoid
1384                      * in utf8 by using check_utf8_print(), but not doing so,
1385                      * since the stream isn't a UTF8 stream */
1386             }
1387         }
1388         /* To detect whether the process is about to overstep its
1389          * filesize limit we would need getrlimit().  We could then
1390          * also transparently raise the limit with setrlimit() --
1391          * but only until the system hard limit/the filesystem limit,
1392          * at which we would get EPERM.  Note that when using buffered
1393          * io the write failure can be delayed until the flush/close. --jhi */
1394         if (len && (PerlIO_write(fp,tmps,len) == 0))
1395             happy = FALSE;
1396         Safefree(tmpbuf);
1397         return happy ? !PerlIO_error(fp) : FALSE;
1398     }
1399 }
1400
1401 I32
1402 Perl_my_stat_flags(pTHX_ const U32 flags)
1403 {
1404     dSP;
1405     IO *io;
1406     GV* gv;
1407
1408     if (PL_op->op_flags & OPf_REF) {
1409         gv = cGVOP_gv;
1410       do_fstat:
1411         if (gv == PL_defgv)
1412             return PL_laststatval;
1413         io = GvIO(gv);
1414         do_fstat_have_io:
1415         PL_laststype = OP_STAT;
1416         PL_statgv = gv ? gv : (GV *)io;
1417         sv_setpvs(PL_statname, "");
1418         if (io) {
1419             if (IoIFP(io)) {
1420                 int fd = PerlIO_fileno(IoIFP(io));
1421                 if (fd < 0) {
1422                     /* E.g. PerlIO::scalar has no real fd. */
1423                     return (PL_laststatval = -1);
1424                 } else {
1425                     return (PL_laststatval = PerlLIO_fstat(fd, &PL_statcache));
1426                 }
1427             } else if (IoDIRP(io)) {
1428                 return (PL_laststatval = PerlLIO_fstat(my_dirfd(IoDIRP(io)), &PL_statcache));
1429             }
1430         }
1431         PL_laststatval = -1;
1432         report_evil_fh(gv);
1433         return -1;
1434     }
1435     else if ((PL_op->op_private & (OPpFT_STACKED|OPpFT_AFTER_t))
1436              == OPpFT_STACKED)
1437         return PL_laststatval;
1438     else {
1439         SV* const sv = TOPs;
1440         const char *s;
1441         STRLEN len;
1442         if ((gv = MAYBE_DEREF_GV_flags(sv,flags))) {
1443             goto do_fstat;
1444         }
1445         else if (SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVIO) {
1446             io = MUTABLE_IO(SvRV(sv));
1447             gv = NULL;
1448             goto do_fstat_have_io;
1449         }
1450
1451         s = SvPV_flags_const(sv, len, flags);
1452         PL_statgv = NULL;
1453         sv_setpvn(PL_statname, s, len);
1454         s = SvPVX_const(PL_statname);           /* s now NUL-terminated */
1455         PL_laststype = OP_STAT;
1456         PL_laststatval = PerlLIO_stat(s, &PL_statcache);
1457         if (PL_laststatval < 0 && ckWARN(WARN_NEWLINE) && should_warn_nl(s)) {
1458             GCC_DIAG_IGNORE(-Wformat-nonliteral); /* PL_warn_nl is constant */
1459             Perl_warner(aTHX_ packWARN(WARN_NEWLINE), PL_warn_nl, "stat");
1460             GCC_DIAG_RESTORE;
1461         }
1462         return PL_laststatval;
1463     }
1464 }
1465
1466
1467 I32
1468 Perl_my_lstat_flags(pTHX_ const U32 flags)
1469 {
1470     static const char* const no_prev_lstat = "The stat preceding -l _ wasn't an lstat";
1471     dSP;
1472     const char *file;
1473     SV* const sv = TOPs;
1474     bool isio = FALSE;
1475     if (PL_op->op_flags & OPf_REF) {
1476         if (cGVOP_gv == PL_defgv) {
1477             if (PL_laststype != OP_LSTAT)
1478                 Perl_croak(aTHX_ "%s", no_prev_lstat);
1479             return PL_laststatval;
1480         }
1481         PL_laststatval = -1;
1482         if (ckWARN(WARN_IO)) {
1483             /* diag_listed_as: Use of -l on filehandle%s */
1484             Perl_warner(aTHX_ packWARN(WARN_IO),
1485                              "Use of -l on filehandle %"HEKf,
1486                               HEKfARG(GvENAME_HEK(cGVOP_gv)));
1487         }
1488         return -1;
1489     }
1490     if ((PL_op->op_private & (OPpFT_STACKED|OPpFT_AFTER_t))
1491              == OPpFT_STACKED) {
1492       if (PL_laststype != OP_LSTAT)
1493         Perl_croak(aTHX_ "%s", no_prev_lstat);
1494       return PL_laststatval;
1495     }
1496
1497     PL_laststype = OP_LSTAT;
1498     PL_statgv = NULL;
1499     if ( (  (SvROK(sv) && (  isGV_with_GP(SvRV(sv))
1500                           || (isio = SvTYPE(SvRV(sv)) == SVt_PVIO)  )
1501             )
1502          || isGV_with_GP(sv)
1503          )
1504       && ckWARN(WARN_IO)) {
1505         if (isio)
1506             /* diag_listed_as: Use of -l on filehandle%s */
1507             Perl_warner(aTHX_ packWARN(WARN_IO),
1508                              "Use of -l on filehandle");
1509         else
1510             /* diag_listed_as: Use of -l on filehandle%s */
1511             Perl_warner(aTHX_ packWARN(WARN_IO),
1512                              "Use of -l on filehandle %"HEKf,
1513                               HEKfARG(GvENAME_HEK((const GV *)
1514                                           (SvROK(sv) ? SvRV(sv) : sv))));
1515     }
1516     file = SvPV_flags_const_nolen(sv, flags);
1517     sv_setpv(PL_statname,file);
1518     PL_laststatval = PerlLIO_lstat(file,&PL_statcache);
1519     if (PL_laststatval < 0 && ckWARN(WARN_NEWLINE) && should_warn_nl(file)) {
1520         GCC_DIAG_IGNORE(-Wformat-nonliteral); /* PL_warn_nl is constant */
1521         Perl_warner(aTHX_ packWARN(WARN_NEWLINE), PL_warn_nl, "lstat");
1522         GCC_DIAG_RESTORE;
1523     }
1524     return PL_laststatval;
1525 }
1526
1527 static void
1528 S_exec_failed(pTHX_ const char *cmd, int fd, int do_report)
1529 {
1530     const int e = errno;
1531     PERL_ARGS_ASSERT_EXEC_FAILED;
1532
1533     if (ckWARN(WARN_EXEC))
1534         Perl_warner(aTHX_ packWARN(WARN_EXEC), "Can't exec \"%s\": %s",
1535                     cmd, Strerror(e));
1536     if (do_report) {
1537         /* XXX silently ignore failures */
1538         PERL_UNUSED_RESULT(PerlLIO_write(fd, (void*)&e, sizeof(int)));
1539         PerlLIO_close(fd);
1540     }
1541 }
1542
1543 bool
1544 Perl_do_aexec5(pTHX_ SV *really, SV **mark, SV **sp,
1545                int fd, int do_report)
1546 {
1547     dVAR;
1548     PERL_ARGS_ASSERT_DO_AEXEC5;
1549 #if defined(__SYMBIAN32__) || defined(__LIBCATAMOUNT__)
1550     Perl_croak(aTHX_ "exec? I'm not *that* kind of operating system");
1551 #else
1552     if (sp > mark) {
1553         const char **a;
1554         const char *tmps = NULL;
1555         Newx(PL_Argv, sp - mark + 1, const char*);
1556         a = PL_Argv;
1557
1558         while (++mark <= sp) {
1559             if (*mark)
1560                 *a++ = SvPV_nolen_const(*mark);
1561             else
1562                 *a++ = "";
1563         }
1564         *a = NULL;
1565         if (really)
1566             tmps = SvPV_nolen_const(really);
1567         if ((!really && *PL_Argv[0] != '/') ||
1568             (really && *tmps != '/'))           /* will execvp use PATH? */
1569             TAINT_ENV();                /* testing IFS here is overkill, probably */
1570         PERL_FPU_PRE_EXEC
1571         if (really && *tmps) {
1572             PerlProc_execvp(tmps,EXEC_ARGV_CAST(PL_Argv));
1573         } else {
1574             PerlProc_execvp(PL_Argv[0],EXEC_ARGV_CAST(PL_Argv));
1575         }
1576         PERL_FPU_POST_EXEC
1577         S_exec_failed(aTHX_ (really ? tmps : PL_Argv[0]), fd, do_report);
1578     }
1579     do_execfree();
1580 #endif
1581     return FALSE;
1582 }
1583
1584 void
1585 Perl_do_execfree(pTHX)
1586 {
1587     Safefree(PL_Argv);
1588     PL_Argv = NULL;
1589     Safefree(PL_Cmd);
1590     PL_Cmd = NULL;
1591 }
1592
1593 #ifdef PERL_DEFAULT_DO_EXEC3_IMPLEMENTATION
1594
1595 bool
1596 Perl_do_exec3(pTHX_ const char *incmd, int fd, int do_report)
1597 {
1598     dVAR;
1599     const char **a;
1600     char *s;
1601     char *buf;
1602     char *cmd;
1603     /* Make a copy so we can change it */
1604     const Size_t cmdlen = strlen(incmd) + 1;
1605
1606     PERL_ARGS_ASSERT_DO_EXEC3;
1607
1608     Newx(buf, cmdlen, char);
1609     cmd = buf;
1610     memcpy(cmd, incmd, cmdlen);
1611
1612     while (*cmd && isSPACE(*cmd))
1613         cmd++;
1614
1615     /* save an extra exec if possible */
1616
1617 #ifdef CSH
1618     {
1619         char flags[PERL_FLAGS_MAX];
1620         if (strnEQ(cmd,PL_cshname,PL_cshlen) &&
1621             strnEQ(cmd+PL_cshlen," -c",3)) {
1622           my_strlcpy(flags, "-c", PERL_FLAGS_MAX);
1623           s = cmd+PL_cshlen+3;
1624           if (*s == 'f') {
1625               s++;
1626               my_strlcat(flags, "f", PERL_FLAGS_MAX - 2);
1627           }
1628           if (*s == ' ')
1629               s++;
1630           if (*s++ == '\'') {
1631               char * const ncmd = s;
1632
1633               while (*s)
1634                   s++;
1635               if (s[-1] == '\n')
1636                   *--s = '\0';
1637               if (s[-1] == '\'') {
1638                   *--s = '\0';
1639                   PERL_FPU_PRE_EXEC
1640                   PerlProc_execl(PL_cshname, "csh", flags, ncmd, (char*)NULL);
1641                   PERL_FPU_POST_EXEC
1642                   *s = '\'';
1643                   S_exec_failed(aTHX_ PL_cshname, fd, do_report);
1644                   Safefree(buf);
1645                   return FALSE;
1646               }
1647           }
1648         }
1649     }
1650 #endif /* CSH */
1651
1652     /* see if there are shell metacharacters in it */
1653
1654     if (*cmd == '.' && isSPACE(cmd[1]))
1655         goto doshell;
1656
1657     if (strnEQ(cmd,"exec",4) && isSPACE(cmd[4]))
1658         goto doshell;
1659
1660     s = cmd;
1661     while (isWORDCHAR(*s))
1662         s++;    /* catch VAR=val gizmo */
1663     if (*s == '=')
1664         goto doshell;
1665
1666     for (s = cmd; *s; s++) {
1667         if (*s != ' ' && !isALPHA(*s) &&
1668             strchr("$&*(){}[]'\";\\|?<>~`\n",*s)) {
1669             if (*s == '\n' && !s[1]) {
1670                 *s = '\0';
1671                 break;
1672             }
1673             /* handle the 2>&1 construct at the end */
1674             if (*s == '>' && s[1] == '&' && s[2] == '1'
1675                 && s > cmd + 1 && s[-1] == '2' && isSPACE(s[-2])
1676                 && (!s[3] || isSPACE(s[3])))
1677             {
1678                 const char *t = s + 3;
1679
1680                 while (*t && isSPACE(*t))
1681                     ++t;
1682                 if (!*t && (PerlLIO_dup2(1,2) != -1)) {
1683                     s[-2] = '\0';
1684                     break;
1685                 }
1686             }
1687           doshell:
1688             PERL_FPU_PRE_EXEC
1689             PerlProc_execl(PL_sh_path, "sh", "-c", cmd, (char *)NULL);
1690             PERL_FPU_POST_EXEC
1691             S_exec_failed(aTHX_ PL_sh_path, fd, do_report);
1692             Safefree(buf);
1693             return FALSE;
1694         }
1695     }
1696
1697     Newx(PL_Argv, (s - cmd) / 2 + 2, const char*);
1698     PL_Cmd = savepvn(cmd, s-cmd);
1699     a = PL_Argv;
1700     for (s = PL_Cmd; *s;) {
1701         while (isSPACE(*s))
1702             s++;
1703         if (*s)
1704             *(a++) = s;
1705         while (*s && !isSPACE(*s))
1706             s++;
1707         if (*s)
1708             *s++ = '\0';
1709     }
1710     *a = NULL;
1711     if (PL_Argv[0]) {
1712         PERL_FPU_PRE_EXEC
1713         PerlProc_execvp(PL_Argv[0],EXEC_ARGV_CAST(PL_Argv));
1714         PERL_FPU_POST_EXEC
1715         if (errno == ENOEXEC) {         /* for system V NIH syndrome */
1716             do_execfree();
1717             goto doshell;
1718         }
1719         S_exec_failed(aTHX_ PL_Argv[0], fd, do_report);
1720     }
1721     do_execfree();
1722     Safefree(buf);
1723     return FALSE;
1724 }
1725
1726 #endif /* OS2 || WIN32 */
1727
1728 I32
1729 Perl_apply(pTHX_ I32 type, SV **mark, SV **sp)
1730 {
1731     I32 val;
1732     I32 tot = 0;
1733     const char *const what = PL_op_name[type];
1734     const char *s;
1735     STRLEN len;
1736     SV ** const oldmark = mark;
1737     bool killgp = FALSE;
1738
1739     PERL_ARGS_ASSERT_APPLY;
1740
1741     PERL_UNUSED_VAR(what); /* may not be used depending on compile options */
1742
1743     /* Doing this ahead of the switch statement preserves the old behaviour,
1744        where attempting to use kill as a taint test test would fail on
1745        platforms where kill was not defined.  */
1746 #ifndef HAS_KILL
1747     if (type == OP_KILL)
1748         Perl_die(aTHX_ PL_no_func, what);
1749 #endif
1750 #ifndef HAS_CHOWN
1751     if (type == OP_CHOWN)
1752         Perl_die(aTHX_ PL_no_func, what);
1753 #endif
1754
1755
1756 #define APPLY_TAINT_PROPER() \
1757     STMT_START {                                                        \
1758         if (TAINT_get) { TAINT_PROPER(what); }                          \
1759     } STMT_END
1760
1761     /* This is a first heuristic; it doesn't catch tainting magic. */
1762     if (TAINTING_get) {
1763         while (++mark <= sp) {
1764             if (SvTAINTED(*mark)) {
1765                 TAINT;
1766                 break;
1767             }
1768         }
1769         mark = oldmark;
1770     }
1771     switch (type) {
1772     case OP_CHMOD:
1773         APPLY_TAINT_PROPER();
1774         if (++mark <= sp) {
1775             val = SvIV(*mark);
1776             APPLY_TAINT_PROPER();
1777             tot = sp - mark;
1778             while (++mark <= sp) {
1779                 GV* gv;
1780                 if ((gv = MAYBE_DEREF_GV(*mark))) {
1781                     if (GvIO(gv) && IoIFP(GvIOp(gv))) {
1782 #ifdef HAS_FCHMOD
1783                         int fd = PerlIO_fileno(IoIFP(GvIOn(gv)));
1784                         APPLY_TAINT_PROPER();
1785                         if (fd < 0) {
1786                             SETERRNO(EBADF,RMS_IFI);
1787                             tot--;
1788                         } else if (fchmod(fd, val))
1789                             tot--;
1790 #else
1791                         Perl_die(aTHX_ PL_no_func, "fchmod");
1792 #endif
1793                     }
1794                     else {
1795                         SETERRNO(EBADF,RMS_IFI);
1796                         tot--;
1797                     }
1798                 }
1799                 else {
1800                     const char *name = SvPV_nomg_const(*mark, len);
1801                     APPLY_TAINT_PROPER();
1802                     if (!IS_SAFE_PATHNAME(name, len, "chmod") ||
1803                         PerlLIO_chmod(name, val)) {
1804                         tot--;
1805                     }
1806                 }
1807             }
1808         }
1809         break;
1810 #ifdef HAS_CHOWN
1811     case OP_CHOWN:
1812         APPLY_TAINT_PROPER();
1813         if (sp - mark > 2) {
1814             I32 val2;
1815             val = SvIVx(*++mark);
1816             val2 = SvIVx(*++mark);
1817             APPLY_TAINT_PROPER();
1818             tot = sp - mark;
1819             while (++mark <= sp) {
1820                 GV* gv;
1821                 if ((gv = MAYBE_DEREF_GV(*mark))) {
1822                     if (GvIO(gv) && IoIFP(GvIOp(gv))) {
1823 #ifdef HAS_FCHOWN
1824                         int fd = PerlIO_fileno(IoIFP(GvIOn(gv)));
1825                         APPLY_TAINT_PROPER();
1826                         if (fd < 0) {
1827                             SETERRNO(EBADF,RMS_IFI);
1828                             tot--;
1829                         } else if (fchown(fd, val, val2))
1830                             tot--;
1831 #else
1832                         Perl_die(aTHX_ PL_no_func, "fchown");
1833 #endif
1834                     }
1835                     else {
1836                         SETERRNO(EBADF,RMS_IFI);
1837                         tot--;
1838                     }
1839                 }
1840                 else {
1841                     const char *name = SvPV_nomg_const(*mark, len);
1842                     APPLY_TAINT_PROPER();
1843                     if (!IS_SAFE_PATHNAME(name, len, "chown") ||
1844                         PerlLIO_chown(name, val, val2)) {
1845                         tot--;
1846                     }
1847                 }
1848             }
1849         }
1850         break;
1851 #endif
1852 /*
1853 XXX Should we make lchown() directly available from perl?
1854 For now, we'll let Configure test for HAS_LCHOWN, but do
1855 nothing in the core.
1856     --AD  5/1998
1857 */
1858 #ifdef HAS_KILL
1859     case OP_KILL:
1860         APPLY_TAINT_PROPER();
1861         if (mark == sp)
1862             break;
1863         s = SvPVx_const(*++mark, len);
1864         if (*s == '-' && isALPHA(s[1]))
1865         {
1866             s++;
1867             len--;
1868             killgp = TRUE;
1869         }
1870         if (isALPHA(*s)) {
1871             if (*s == 'S' && s[1] == 'I' && s[2] == 'G') {
1872                 s += 3;
1873                 len -= 3;
1874             }
1875            if ((val = whichsig_pvn(s, len)) < 0)
1876                Perl_croak(aTHX_ "Unrecognized signal name \"%"SVf"\"", SVfARG(*mark));
1877         }
1878         else
1879         {
1880             val = SvIV(*mark);
1881             if (val < 0)
1882             {
1883                 killgp = TRUE;
1884                 val = -val;
1885             }
1886         }
1887         APPLY_TAINT_PROPER();
1888         tot = sp - mark;
1889
1890         while (++mark <= sp) {
1891             Pid_t proc;
1892             SvGETMAGIC(*mark);
1893             if (!(SvNIOK(*mark) || looks_like_number(*mark)))
1894                 Perl_croak(aTHX_ "Can't kill a non-numeric process ID");
1895             proc = SvIV_nomg(*mark);
1896             APPLY_TAINT_PROPER();
1897 #ifdef HAS_KILLPG
1898             /* use killpg in preference, as the killpg() wrapper for Win32
1899              * understands process groups, but the kill() wrapper doesn't */
1900             if (killgp ? PerlProc_killpg(proc, val)
1901                        : PerlProc_kill(proc, val))
1902 #else
1903             if (PerlProc_kill(killgp ? -proc: proc, val))
1904 #endif
1905                 tot--;
1906         }
1907         PERL_ASYNC_CHECK();
1908         break;
1909 #endif
1910     case OP_UNLINK:
1911         APPLY_TAINT_PROPER();
1912         tot = sp - mark;
1913         while (++mark <= sp) {
1914             s = SvPV_const(*mark, len);
1915             APPLY_TAINT_PROPER();
1916             if (!IS_SAFE_PATHNAME(s, len, "unlink")) {
1917                 tot--;
1918             }
1919             else if (PL_unsafe) {
1920                 if (UNLINK(s))
1921                 {
1922                     tot--;
1923                 }
1924 #if defined(__amigaos4__) && defined(NEWLIB)
1925                 else
1926                 {
1927                   /* Under AmigaOS4 unlink only 'fails' if the
1928                    * filename is invalid.  It may not remove the file
1929                    * if it's locked, so check if it's still around. */
1930                   if ((access(s,F_OK) != -1))
1931                   {
1932                     tot--;
1933                   }
1934                 }
1935 #endif
1936             }
1937             else {      /* don't let root wipe out directories without -U */
1938                 Stat_t statbuf;
1939                 if (PerlLIO_lstat(s, &statbuf) < 0)
1940                     tot--;
1941                 else if (S_ISDIR(statbuf.st_mode)) {
1942                     SETERRNO(EISDIR, SS_NOPRIV);
1943                     tot--;
1944                 }
1945                 else {
1946                     if (UNLINK(s))
1947                     {
1948                                 tot--;
1949                         }
1950 #if defined(__amigaos4__) && defined(NEWLIB)
1951                         else
1952                         {
1953                                 /* Under AmigaOS4 unlink only 'fails' if the filename is invalid */
1954                                 /* It may not remove the file if it's Locked, so check if it's still */
1955                                 /* arround */
1956                                 if((access(s,F_OK) != -1))
1957                                 {
1958                                         tot--;
1959                                 }
1960                         }       
1961 #endif
1962                 }
1963             }
1964         }
1965         break;
1966 #if defined(HAS_UTIME) || defined(HAS_FUTIMES)
1967     case OP_UTIME:
1968         APPLY_TAINT_PROPER();
1969         if (sp - mark > 2) {
1970 #if defined(HAS_FUTIMES)
1971             struct timeval utbuf[2];
1972             void *utbufp = utbuf;
1973 #elif defined(I_UTIME) || defined(VMS)
1974             struct utimbuf utbuf;
1975             struct utimbuf *utbufp = &utbuf;
1976 #else
1977             struct {
1978                 Time_t  actime;
1979                 Time_t  modtime;
1980             } utbuf;
1981             void *utbufp = &utbuf;
1982 #endif
1983
1984            SV* const accessed = *++mark;
1985            SV* const modified = *++mark;
1986
1987            /* Be like C, and if both times are undefined, let the C
1988             * library figure out what to do.  This usually means
1989             * "current time". */
1990
1991            if ( accessed == &PL_sv_undef && modified == &PL_sv_undef )
1992                 utbufp = NULL;
1993            else {
1994                 Zero(&utbuf, sizeof utbuf, char);
1995 #ifdef HAS_FUTIMES
1996                 utbuf[0].tv_sec = (long)SvIV(accessed);  /* time accessed */
1997                 utbuf[0].tv_usec = 0;
1998                 utbuf[1].tv_sec = (long)SvIV(modified);  /* time modified */
1999                 utbuf[1].tv_usec = 0;
2000 #elif defined(BIG_TIME)
2001                 utbuf.actime = (Time_t)SvNV(accessed);  /* time accessed */
2002                 utbuf.modtime = (Time_t)SvNV(modified); /* time modified */
2003 #else
2004                 utbuf.actime = (Time_t)SvIV(accessed);  /* time accessed */
2005                 utbuf.modtime = (Time_t)SvIV(modified); /* time modified */
2006 #endif
2007             }
2008             APPLY_TAINT_PROPER();
2009             tot = sp - mark;
2010             while (++mark <= sp) {
2011                 GV* gv;
2012                 if ((gv = MAYBE_DEREF_GV(*mark))) {
2013                     if (GvIO(gv) && IoIFP(GvIOp(gv))) {
2014 #ifdef HAS_FUTIMES
2015                         int fd =  PerlIO_fileno(IoIFP(GvIOn(gv)));
2016                         APPLY_TAINT_PROPER();
2017                         if (fd < 0) {
2018                             SETERRNO(EBADF,RMS_IFI);
2019                             tot--;
2020                         } else if (futimes(fd, (struct timeval *) utbufp))
2021                             tot--;
2022 #else
2023                         Perl_die(aTHX_ PL_no_func, "futimes");
2024 #endif
2025                     }
2026                     else {
2027                         tot--;
2028                     }
2029                 }
2030                 else {
2031                     const char * const name = SvPV_nomg_const(*mark, len);
2032                     APPLY_TAINT_PROPER();
2033                     if (!IS_SAFE_PATHNAME(name, len, "utime")) {
2034                         tot--;
2035                     }
2036                     else
2037 #ifdef HAS_FUTIMES
2038                     if (utimes(name, (struct timeval *)utbufp))
2039 #else
2040                     if (PerlLIO_utime(name, utbufp))
2041 #endif
2042                         tot--;
2043                 }
2044
2045             }
2046         }
2047         else
2048             tot = 0;
2049         break;
2050 #endif
2051     }
2052     return tot;
2053
2054 #undef APPLY_TAINT_PROPER
2055 }
2056
2057 /* Do the permissions allow some operation?  Assumes statcache already set. */
2058 #ifndef VMS /* VMS' cando is in vms.c */
2059 bool
2060 Perl_cando(pTHX_ Mode_t mode, bool effective, const Stat_t *statbufp)
2061 /* effective is a flag, true for EUID, or for checking if the effective gid
2062  *  is in the list of groups returned from getgroups().
2063  */
2064 {
2065     PERL_ARGS_ASSERT_CANDO;
2066     PERL_UNUSED_CONTEXT;
2067
2068 #ifdef DOSISH
2069     /* [Comments and code from Len Reed]
2070      * MS-DOS "user" is similar to UNIX's "superuser," but can't write
2071      * to write-protected files.  The execute permission bit is set
2072      * by the Microsoft C library stat() function for the following:
2073      *          .exe files
2074      *          .com files
2075      *          .bat files
2076      *          directories
2077      * All files and directories are readable.
2078      * Directories and special files, e.g. "CON", cannot be
2079      * write-protected.
2080      * [Comment by Tom Dinger -- a directory can have the write-protect
2081      *          bit set in the file system, but DOS permits changes to
2082      *          the directory anyway.  In addition, all bets are off
2083      *          here for networked software, such as Novell and
2084      *          Sun's PC-NFS.]
2085      */
2086
2087      /* Atari stat() does pretty much the same thing. we set x_bit_set_in_stat
2088       * too so it will actually look into the files for magic numbers
2089       */
2090      return (mode & statbufp->st_mode) ? TRUE : FALSE;
2091
2092 #else /* ! DOSISH */
2093 # ifdef __CYGWIN__
2094     if (ingroup(544,effective)) {     /* member of Administrators */
2095 # else
2096     if ((effective ? PerlProc_geteuid() : PerlProc_getuid()) == 0) {    /* root is special */
2097 # endif
2098         if (mode == S_IXUSR) {
2099             if (statbufp->st_mode & 0111 || S_ISDIR(statbufp->st_mode))
2100                 return TRUE;
2101         }
2102         else
2103             return TRUE;                /* root reads and writes anything */
2104         return FALSE;
2105     }
2106     if (statbufp->st_uid == (effective ? PerlProc_geteuid() : PerlProc_getuid()) ) {
2107         if (statbufp->st_mode & mode)
2108             return TRUE;        /* ok as "user" */
2109     }
2110     else if (ingroup(statbufp->st_gid,effective)) {
2111         if (statbufp->st_mode & mode >> 3)
2112             return TRUE;        /* ok as "group" */
2113     }
2114     else if (statbufp->st_mode & mode >> 6)
2115         return TRUE;    /* ok as "other" */
2116     return FALSE;
2117 #endif /* ! DOSISH */
2118 }
2119 #endif /* ! VMS */
2120
2121 static bool
2122 S_ingroup(pTHX_ Gid_t testgid, bool effective)
2123 {
2124 #ifndef PERL_IMPLICIT_SYS
2125     /* PERL_IMPLICIT_SYS like Win32: getegid() etc. require the context. */
2126     PERL_UNUSED_CONTEXT;
2127 #endif
2128     if (testgid == (effective ? PerlProc_getegid() : PerlProc_getgid()))
2129         return TRUE;
2130 #ifdef HAS_GETGROUPS
2131     {
2132         Groups_t *gary = NULL;
2133         I32 anum;
2134         bool rc = FALSE;
2135
2136         anum = getgroups(0, gary);
2137         if (anum > 0) {
2138             Newx(gary, anum, Groups_t);
2139             anum = getgroups(anum, gary);
2140             while (--anum >= 0)
2141                 if (gary[anum] == testgid) {
2142                     rc = TRUE;
2143                     break;
2144                 }
2145
2146             Safefree(gary);
2147         }
2148         return rc;
2149     }
2150 #else
2151     return FALSE;
2152 #endif
2153 }
2154
2155 #if defined(HAS_MSG) || defined(HAS_SEM) || defined(HAS_SHM)
2156
2157 I32
2158 Perl_do_ipcget(pTHX_ I32 optype, SV **mark, SV **sp)
2159 {
2160     const key_t key = (key_t)SvNVx(*++mark);
2161     SV *nsv = optype == OP_MSGGET ? NULL : *++mark;
2162     const I32 flags = SvIVx(*++mark);
2163
2164     PERL_ARGS_ASSERT_DO_IPCGET;
2165     PERL_UNUSED_ARG(sp);
2166
2167     SETERRNO(0,0);
2168     switch (optype)
2169     {
2170 #ifdef HAS_MSG
2171     case OP_MSGGET:
2172         return msgget(key, flags);
2173 #endif
2174 #ifdef HAS_SEM
2175     case OP_SEMGET:
2176         return semget(key, (int) SvIV(nsv), flags);
2177 #endif
2178 #ifdef HAS_SHM
2179     case OP_SHMGET:
2180         return shmget(key, (size_t) SvUV(nsv), flags);
2181 #endif
2182 #if !defined(HAS_MSG) || !defined(HAS_SEM) || !defined(HAS_SHM)
2183     default:
2184         /* diag_listed_as: msg%s not implemented */
2185         Perl_croak(aTHX_ "%s not implemented", PL_op_desc[optype]);
2186 #endif
2187     }
2188     return -1;                  /* should never happen */
2189 }
2190
2191 I32
2192 Perl_do_ipcctl(pTHX_ I32 optype, SV **mark, SV **sp)
2193 {
2194     char *a;
2195     I32 ret = -1;
2196     const I32 id  = SvIVx(*++mark);
2197 #ifdef Semctl
2198     const I32 n   = (optype == OP_SEMCTL) ? SvIVx(*++mark) : 0;
2199 #endif
2200     const I32 cmd = SvIVx(*++mark);
2201     SV * const astr = *++mark;
2202     STRLEN infosize = 0;
2203     I32 getinfo = (cmd == IPC_STAT);
2204
2205     PERL_ARGS_ASSERT_DO_IPCCTL;
2206     PERL_UNUSED_ARG(sp);
2207
2208     switch (optype)
2209     {
2210 #ifdef HAS_MSG
2211     case OP_MSGCTL:
2212         if (cmd == IPC_STAT || cmd == IPC_SET)
2213             infosize = sizeof(struct msqid_ds);
2214         break;
2215 #endif
2216 #ifdef HAS_SHM
2217     case OP_SHMCTL:
2218         if (cmd == IPC_STAT || cmd == IPC_SET)
2219             infosize = sizeof(struct shmid_ds);
2220         break;
2221 #endif
2222 #ifdef HAS_SEM
2223     case OP_SEMCTL:
2224 #ifdef Semctl
2225         if (cmd == IPC_STAT || cmd == IPC_SET)
2226             infosize = sizeof(struct semid_ds);
2227         else if (cmd == GETALL || cmd == SETALL)
2228         {
2229             struct semid_ds semds;
2230             union semun semun;
2231 #ifdef EXTRA_F_IN_SEMUN_BUF
2232             semun.buff = &semds;
2233 #else
2234             semun.buf = &semds;
2235 #endif
2236             getinfo = (cmd == GETALL);
2237             if (Semctl(id, 0, IPC_STAT, semun) == -1)
2238                 return -1;
2239             infosize = semds.sem_nsems * sizeof(short);
2240                 /* "short" is technically wrong but much more portable
2241                    than guessing about u_?short(_t)? */
2242         }
2243 #else
2244         /* diag_listed_as: sem%s not implemented */
2245         Perl_croak(aTHX_ "%s not implemented", PL_op_desc[optype]);
2246 #endif
2247         break;
2248 #endif
2249 #if !defined(HAS_MSG) || !defined(HAS_SEM) || !defined(HAS_SHM)
2250     default:
2251         /* diag_listed_as: shm%s not implemented */
2252         Perl_croak(aTHX_ "%s not implemented", PL_op_desc[optype]);
2253 #endif
2254     }
2255
2256     if (infosize)
2257     {
2258         if (getinfo)
2259         {
2260             SvPV_force_nolen(astr);
2261             a = SvGROW(astr, infosize+1);
2262         }
2263         else
2264         {
2265             STRLEN len;
2266             a = SvPV(astr, len);
2267             if (len != infosize)
2268                 Perl_croak(aTHX_ "Bad arg length for %s, is %lu, should be %ld",
2269                       PL_op_desc[optype],
2270                       (unsigned long)len,
2271                       (long)infosize);
2272         }
2273     }
2274     else
2275     {
2276         const IV i = SvIV(astr);
2277         a = INT2PTR(char *,i);          /* ouch */
2278     }
2279     SETERRNO(0,0);
2280     switch (optype)
2281     {
2282 #ifdef HAS_MSG
2283     case OP_MSGCTL:
2284         ret = msgctl(id, cmd, (struct msqid_ds *)a);
2285         break;
2286 #endif
2287 #ifdef HAS_SEM
2288     case OP_SEMCTL: {
2289 #ifdef Semctl
2290             union semun unsemds;
2291
2292             if(cmd == SETVAL) {
2293                 unsemds.val = PTR2nat(a);
2294             }
2295             else {
2296 #ifdef EXTRA_F_IN_SEMUN_BUF
2297                 unsemds.buff = (struct semid_ds *)a;
2298 #else
2299                 unsemds.buf = (struct semid_ds *)a;
2300 #endif
2301             }
2302             ret = Semctl(id, n, cmd, unsemds);
2303 #else
2304             /* diag_listed_as: sem%s not implemented */
2305             Perl_croak(aTHX_ "%s not implemented", PL_op_desc[optype]);
2306 #endif
2307         }
2308         break;
2309 #endif
2310 #ifdef HAS_SHM
2311     case OP_SHMCTL:
2312         ret = shmctl(id, cmd, (struct shmid_ds *)a);
2313         break;
2314 #endif
2315     }
2316     if (getinfo && ret >= 0) {
2317         SvCUR_set(astr, infosize);
2318         *SvEND(astr) = '\0';
2319         SvSETMAGIC(astr);
2320     }
2321     return ret;
2322 }
2323
2324 I32
2325 Perl_do_msgsnd(pTHX_ SV **mark, SV **sp)
2326 {
2327 #ifdef HAS_MSG
2328     STRLEN len;
2329     const I32 id = SvIVx(*++mark);
2330     SV * const mstr = *++mark;
2331     const I32 flags = SvIVx(*++mark);
2332     const char * const mbuf = SvPV_const(mstr, len);
2333     const I32 msize = len - sizeof(long);
2334
2335     PERL_ARGS_ASSERT_DO_MSGSND;
2336     PERL_UNUSED_ARG(sp);
2337
2338     if (msize < 0)
2339         Perl_croak(aTHX_ "Arg too short for msgsnd");
2340     SETERRNO(0,0);
2341     if (id >= 0 && flags >= 0) {
2342       return msgsnd(id, (struct msgbuf *)mbuf, msize, flags);
2343     } else {
2344       SETERRNO(EINVAL,LIB_INVARG);
2345       return -1;
2346     }
2347 #else
2348     PERL_UNUSED_ARG(sp);
2349     PERL_UNUSED_ARG(mark);
2350     /* diag_listed_as: msg%s not implemented */
2351     Perl_croak(aTHX_ "msgsnd not implemented");
2352     return -1;
2353 #endif
2354 }
2355
2356 I32
2357 Perl_do_msgrcv(pTHX_ SV **mark, SV **sp)
2358 {
2359 #ifdef HAS_MSG
2360     char *mbuf;
2361     long mtype;
2362     I32 msize, flags, ret;
2363     const I32 id = SvIVx(*++mark);
2364     SV * const mstr = *++mark;
2365
2366     PERL_ARGS_ASSERT_DO_MSGRCV;
2367     PERL_UNUSED_ARG(sp);
2368
2369     /* suppress warning when reading into undef var --jhi */
2370     if (! SvOK(mstr))
2371         sv_setpvs(mstr, "");
2372     msize = SvIVx(*++mark);
2373     mtype = (long)SvIVx(*++mark);
2374     flags = SvIVx(*++mark);
2375     SvPV_force_nolen(mstr);
2376     mbuf = SvGROW(mstr, sizeof(long)+msize+1);
2377
2378     SETERRNO(0,0);
2379     if (id >= 0 && msize >= 0 && flags >= 0) {
2380         ret = msgrcv(id, (struct msgbuf *)mbuf, msize, mtype, flags);
2381     } else {
2382         SETERRNO(EINVAL,LIB_INVARG);
2383         ret = -1;
2384     }
2385     if (ret >= 0) {
2386         SvCUR_set(mstr, sizeof(long)+ret);
2387         *SvEND(mstr) = '\0';
2388         /* who knows who has been playing with this message? */
2389         SvTAINTED_on(mstr);
2390     }
2391     return ret;
2392 #else
2393     PERL_UNUSED_ARG(sp);
2394     PERL_UNUSED_ARG(mark);
2395     /* diag_listed_as: msg%s not implemented */
2396     Perl_croak(aTHX_ "msgrcv not implemented");
2397     return -1;
2398 #endif
2399 }
2400
2401 I32
2402 Perl_do_semop(pTHX_ SV **mark, SV **sp)
2403 {
2404 #ifdef HAS_SEM
2405     STRLEN opsize;
2406     const I32 id = SvIVx(*++mark);
2407     SV * const opstr = *++mark;
2408     const char * const opbuf = SvPV_const(opstr, opsize);
2409
2410     PERL_ARGS_ASSERT_DO_SEMOP;
2411     PERL_UNUSED_ARG(sp);
2412
2413     if (opsize < 3 * SHORTSIZE
2414         || (opsize % (3 * SHORTSIZE))) {
2415         SETERRNO(EINVAL,LIB_INVARG);
2416         return -1;
2417     }
2418     SETERRNO(0,0);
2419     /* We can't assume that sizeof(struct sembuf) == 3 * sizeof(short). */
2420     {
2421         const int nsops  = opsize / (3 * sizeof (short));
2422         int i      = nsops;
2423         short * const ops = (short *) opbuf;
2424         short *o   = ops;
2425         struct sembuf *temps, *t;
2426         I32 result;
2427
2428         Newx (temps, nsops, struct sembuf);
2429         t = temps;
2430         while (i--) {
2431             t->sem_num = *o++;
2432             t->sem_op  = *o++;
2433             t->sem_flg = *o++;
2434             t++;
2435         }
2436         result = semop(id, temps, nsops);
2437         Safefree(temps);
2438         return result;
2439     }
2440 #else
2441     /* diag_listed_as: sem%s not implemented */
2442     Perl_croak(aTHX_ "semop not implemented");
2443 #endif
2444 }
2445
2446 I32
2447 Perl_do_shmio(pTHX_ I32 optype, SV **mark, SV **sp)
2448 {
2449 #ifdef HAS_SHM
2450     char *shm;
2451     struct shmid_ds shmds;
2452     const I32 id = SvIVx(*++mark);
2453     SV * const mstr = *++mark;
2454     const I32 mpos = SvIVx(*++mark);
2455     const I32 msize = SvIVx(*++mark);
2456
2457     PERL_ARGS_ASSERT_DO_SHMIO;
2458     PERL_UNUSED_ARG(sp);
2459
2460     SETERRNO(0,0);
2461     if (shmctl(id, IPC_STAT, &shmds) == -1)
2462         return -1;
2463     if (mpos < 0 || msize < 0
2464         || (size_t)mpos + msize > (size_t)shmds.shm_segsz) {
2465         SETERRNO(EFAULT,SS_ACCVIO);             /* can't do as caller requested */
2466         return -1;
2467     }
2468     if (id >= 0) {
2469         shm = (char *)shmat(id, NULL, (optype == OP_SHMREAD) ? SHM_RDONLY : 0);
2470     } else {
2471         SETERRNO(EINVAL,LIB_INVARG);
2472         return -1;
2473     }
2474     if (shm == (char *)-1)      /* I hate System V IPC, I really do */
2475         return -1;
2476     if (optype == OP_SHMREAD) {
2477         char *mbuf;
2478         /* suppress warning when reading into undef var (tchrist 3/Mar/00) */
2479         SvGETMAGIC(mstr);
2480         SvUPGRADE(mstr, SVt_PV);
2481         if (! SvOK(mstr))
2482             sv_setpvs(mstr, "");
2483         SvPOK_only(mstr);
2484         mbuf = SvGROW(mstr, (STRLEN)msize+1);
2485
2486         Copy(shm + mpos, mbuf, msize, char);
2487         SvCUR_set(mstr, msize);
2488         *SvEND(mstr) = '\0';
2489         SvSETMAGIC(mstr);
2490         /* who knows who has been playing with this shared memory? */
2491         SvTAINTED_on(mstr);
2492     }
2493     else {
2494         STRLEN len;
2495
2496         const char *mbuf = SvPV_const(mstr, len);
2497         const I32 n = ((I32)len > msize) ? msize : (I32)len;
2498         Copy(mbuf, shm + mpos, n, char);
2499         if (n < msize)
2500             memzero(shm + mpos + n, msize - n);
2501     }
2502     return shmdt(shm);
2503 #else
2504     /* diag_listed_as: shm%s not implemented */
2505     Perl_croak(aTHX_ "shm I/O not implemented");
2506     return -1;
2507 #endif
2508 }
2509
2510 #endif /* SYSV IPC */
2511
2512 /*
2513 =head1 IO Functions
2514
2515 =for apidoc start_glob
2516
2517 Function called by C<do_readline> to spawn a glob (or do the glob inside
2518 perl on VMS).  This code used to be inline, but now perl uses C<File::Glob>
2519 this glob starter is only used by miniperl during the build process,
2520 or when PERL_EXTERNAL_GLOB is defined.
2521 Moving it away shrinks F<pp_hot.c>; shrinking F<pp_hot.c> helps speed perl up.
2522
2523 =cut
2524 */
2525
2526 PerlIO *
2527 Perl_start_glob (pTHX_ SV *tmpglob, IO *io)
2528 {
2529     SV * const tmpcmd = newSV(0);
2530     PerlIO *fp;
2531     STRLEN len;
2532     const char *s = SvPV(tmpglob, len);
2533
2534     PERL_ARGS_ASSERT_START_GLOB;
2535
2536     if (!IS_SAFE_SYSCALL(s, len, "pattern", "glob"))
2537         return NULL;
2538
2539     ENTER;
2540     SAVEFREESV(tmpcmd);
2541 #ifdef VMS /* expand the wildcards right here, rather than opening a pipe, */
2542            /* since spawning off a process is a real performance hit */
2543
2544 PerlIO * 
2545 Perl_vms_start_glob
2546    (pTHX_ SV *tmpglob,
2547     IO *io);
2548
2549     fp = Perl_vms_start_glob(aTHX_ tmpglob, io);
2550
2551 #else /* !VMS */
2552 #ifdef DOSISH
2553 #ifdef OS2
2554     sv_setpv(tmpcmd, "for a in ");
2555     sv_catsv(tmpcmd, tmpglob);
2556     sv_catpv(tmpcmd, "; do echo \"$a\\0\\c\"; done |");
2557 #else
2558 #ifdef DJGPP
2559     sv_setpv(tmpcmd, "/dev/dosglob/"); /* File System Extension */
2560     sv_catsv(tmpcmd, tmpglob);
2561 #else
2562     sv_setpv(tmpcmd, "perlglob ");
2563     sv_catsv(tmpcmd, tmpglob);
2564     sv_catpv(tmpcmd, " |");
2565 #endif /* !DJGPP */
2566 #endif /* !OS2 */
2567 #else /* !DOSISH */
2568 #if defined(CSH)
2569     sv_setpvn(tmpcmd, PL_cshname, PL_cshlen);
2570     sv_catpv(tmpcmd, " -cf 'set nonomatch; glob ");
2571     sv_catsv(tmpcmd, tmpglob);
2572     sv_catpv(tmpcmd, "' 2>/dev/null |");
2573 #else
2574     sv_setpv(tmpcmd, "echo ");
2575     sv_catsv(tmpcmd, tmpglob);
2576     sv_catpv(tmpcmd, "|tr -s ' \t\f\r' '\\n\\n\\n\\n'|");
2577 #endif /* !CSH */
2578 #endif /* !DOSISH */
2579     {
2580         GV * const envgv = gv_fetchpvs("ENV", 0, SVt_PVHV);
2581         SV ** const home = hv_fetchs(GvHV(envgv), "HOME", 0);
2582         SV ** const path = hv_fetchs(GvHV(envgv), "PATH", 0);
2583         if (home && *home) SvGETMAGIC(*home);
2584         if (path && *path) SvGETMAGIC(*path);
2585         save_hash(gv_fetchpvs("ENV", 0, SVt_PVHV));
2586         if (home && *home) SvSETMAGIC(*home);
2587         if (path && *path) SvSETMAGIC(*path);
2588     }
2589     (void)do_open6(PL_last_in_gv, SvPVX_const(tmpcmd), SvCUR(tmpcmd),
2590                    NULL, NULL, 0);
2591     fp = IoIFP(io);
2592 #endif /* !VMS */
2593     LEAVE;
2594
2595     if (!fp && ckWARN(WARN_GLOB)) {
2596         Perl_warner(aTHX_ packWARN(WARN_GLOB), "glob failed (can't start child: %s)",
2597                     Strerror(errno));
2598     }
2599
2600     return fp;
2601 }
2602
2603 /*
2604  * ex: set ts=8 sts=4 sw=4 et:
2605  */