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