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