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