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