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