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