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