This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Quiet t/op/stash.t output
[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                     if (ckWARN_d(WARN_INPLACE)) 
762                         Perl_warner(aTHX_ packWARN(WARN_INPLACE),
763                             "Can't do inplace edit: %s is not a regular file",
764                             PL_oldname );
765                     do_close(gv,FALSE);
766                     continue;
767                 }
768                 if (*PL_inplace) {
769                     const char *star = strchr(PL_inplace, '*');
770                     if (star) {
771                         const char *begin = PL_inplace;
772                         sv_setpvs(sv, "");
773                         do {
774                             sv_catpvn(sv, begin, star - begin);
775                             sv_catpvn(sv, PL_oldname, oldlen);
776                             begin = ++star;
777                         } while ((star = strchr(begin, '*')));
778                         if (*begin)
779                             sv_catpv(sv,begin);
780                     }
781                     else {
782                         sv_catpv(sv,PL_inplace);
783                     }
784 #ifndef FLEXFILENAMES
785                     if ((PerlLIO_stat(SvPVX_const(sv),&PL_statbuf) >= 0
786                          && PL_statbuf.st_dev == filedev
787                          && PL_statbuf.st_ino == fileino)
788 #ifdef DJGPP
789                         || ((_djstat_fail_bits & _STFAIL_TRUENAME)!=0)
790 #endif
791                       )
792                     {
793                         if (ckWARN_d(WARN_INPLACE))     
794                             Perl_warner(aTHX_ packWARN(WARN_INPLACE),
795                               "Can't do inplace edit: %"SVf" would not be unique",
796                               SVfARG(sv));
797                         do_close(gv,FALSE);
798                         continue;
799                     }
800 #endif
801 #ifdef HAS_RENAME
802 #if !defined(DOSISH) && !defined(__CYGWIN__) && !defined(EPOC)
803                     if (PerlLIO_rename(PL_oldname,SvPVX_const(sv)) < 0) {
804                         if (ckWARN_d(WARN_INPLACE))     
805                             Perl_warner(aTHX_ packWARN(WARN_INPLACE),
806                               "Can't rename %s to %"SVf": %s, skipping file",
807                               PL_oldname, SVfARG(sv), Strerror(errno));
808                         do_close(gv,FALSE);
809                         continue;
810                     }
811 #else
812                     do_close(gv,FALSE);
813                     (void)PerlLIO_unlink(SvPVX_const(sv));
814                     (void)PerlLIO_rename(PL_oldname,SvPVX_const(sv));
815                     do_open(gv,(char*)SvPVX_const(sv),SvCUR(sv),TRUE,O_RDONLY,0,NULL);
816 #endif /* DOSISH */
817 #else
818                     (void)UNLINK(SvPVX_const(sv));
819                     if (link(PL_oldname,SvPVX_const(sv)) < 0) {
820                         if (ckWARN_d(WARN_INPLACE))     
821                             Perl_warner(aTHX_ packWARN(WARN_INPLACE),
822                               "Can't rename %s to %"SVf": %s, skipping file",
823                               PL_oldname, SVfARG(sv), Strerror(errno) );
824                         do_close(gv,FALSE);
825                         continue;
826                     }
827                     (void)UNLINK(PL_oldname);
828 #endif
829                 }
830                 else {
831 #if !defined(DOSISH) && !defined(AMIGAOS)
832 #  ifndef VMS  /* Don't delete; use automatic file versioning */
833                     if (UNLINK(PL_oldname) < 0) {
834                         if (ckWARN_d(WARN_INPLACE))     
835                             Perl_warner(aTHX_ packWARN(WARN_INPLACE),
836                               "Can't remove %s: %s, skipping file",
837                               PL_oldname, Strerror(errno) );
838                         do_close(gv,FALSE);
839                         continue;
840                     }
841 #  endif
842 #else
843                     Perl_croak(aTHX_ "Can't do inplace edit without backup");
844 #endif
845                 }
846
847                 sv_setpvn(sv,PL_oldname,oldlen);
848                 SETERRNO(0,0);          /* in case sprintf set errno */
849                 if (!Perl_do_openn(aTHX_ PL_argvoutgv, (char*)SvPVX_const(sv),
850                                    SvCUR(sv), TRUE,
851 #ifdef VMS
852                                    O_WRONLY|O_CREAT|O_TRUNC,0,
853 #else
854                                    O_WRONLY|O_CREAT|OPEN_EXCL,0600,
855 #endif
856                                    NULL, NULL, 0)) {
857                     if (ckWARN_d(WARN_INPLACE)) 
858                         Perl_warner(aTHX_ packWARN(WARN_INPLACE), "Can't do inplace edit on %s: %s",
859                           PL_oldname, Strerror(errno) );
860                     do_close(gv,FALSE);
861                     continue;
862                 }
863                 setdefout(PL_argvoutgv);
864                 PL_lastfd = PerlIO_fileno(IoIFP(GvIOp(PL_argvoutgv)));
865                 (void)PerlLIO_fstat(PL_lastfd,&PL_statbuf);
866 #ifdef HAS_FCHMOD
867                 (void)fchmod(PL_lastfd,PL_filemode);
868 #else
869 #  if !(defined(WIN32) && defined(__BORLANDC__))
870                 /* Borland runtime creates a readonly file! */
871                 (void)PerlLIO_chmod(PL_oldname,PL_filemode);
872 #  endif
873 #endif
874                 if (fileuid != PL_statbuf.st_uid || filegid != PL_statbuf.st_gid) {
875 #ifdef HAS_FCHOWN
876                     (void)fchown(PL_lastfd,fileuid,filegid);
877 #else
878 #ifdef HAS_CHOWN
879                     (void)PerlLIO_chown(PL_oldname,fileuid,filegid);
880 #endif
881 #endif
882                 }
883             }
884             return IoIFP(GvIOp(gv));
885         }
886         else {
887             if (ckWARN_d(WARN_INPLACE)) {
888                 const int eno = errno;
889                 if (PerlLIO_stat(PL_oldname, &PL_statbuf) >= 0
890                     && !S_ISREG(PL_statbuf.st_mode))    
891                 {
892                     Perl_warner(aTHX_ packWARN(WARN_INPLACE),
893                                 "Can't do inplace edit: %s is not a regular file",
894                                 PL_oldname);
895                 }
896                 else
897                     Perl_warner(aTHX_ packWARN(WARN_INPLACE), "Can't open %s: %s",
898                                 PL_oldname, Strerror(eno));
899             }
900         }
901     }
902     if (io && (IoFLAGS(io) & IOf_ARGV))
903         IoFLAGS(io) |= IOf_START;
904     if (PL_inplace) {
905         (void)do_close(PL_argvoutgv,FALSE);
906         if (io && (IoFLAGS(io) & IOf_ARGV)
907             && PL_argvout_stack && AvFILLp(PL_argvout_stack) >= 0)
908         {
909             GV * const oldout = MUTABLE_GV(av_pop(PL_argvout_stack));
910             setdefout(oldout);
911             SvREFCNT_dec(oldout);
912             return NULL;
913         }
914         setdefout(gv_fetchpvs("STDOUT", GV_ADD|GV_NOTQUAL, SVt_PVIO));
915     }
916     return NULL;
917 }
918
919 /* explicit renamed to avoid C++ conflict    -- kja */
920 bool
921 Perl_do_close(pTHX_ GV *gv, bool not_implicit)
922 {
923     dVAR;
924     bool retval;
925     IO *io;
926
927     if (!gv)
928         gv = PL_argvgv;
929     if (!gv || !isGV_with_GP(gv)) {
930         if (not_implicit)
931             SETERRNO(EBADF,SS_IVCHAN);
932         return FALSE;
933     }
934     io = GvIO(gv);
935     if (!io) {          /* never opened */
936         if (not_implicit) {
937             if (ckWARN(WARN_UNOPENED)) /* no check for closed here */
938                 report_evil_fh(gv, io, PL_op->op_type);
939             SETERRNO(EBADF,SS_IVCHAN);
940         }
941         return FALSE;
942     }
943     retval = io_close(io, not_implicit);
944     if (not_implicit) {
945         IoLINES(io) = 0;
946         IoPAGE(io) = 0;
947         IoLINES_LEFT(io) = IoPAGE_LEN(io);
948     }
949     IoTYPE(io) = IoTYPE_CLOSED;
950     return retval;
951 }
952
953 bool
954 Perl_io_close(pTHX_ IO *io, bool not_implicit)
955 {
956     dVAR;
957     bool retval = FALSE;
958
959     PERL_ARGS_ASSERT_IO_CLOSE;
960
961     if (IoIFP(io)) {
962         if (IoTYPE(io) == IoTYPE_PIPE) {
963             const int status = PerlProc_pclose(IoIFP(io));
964             if (not_implicit) {
965                 STATUS_NATIVE_CHILD_SET(status);
966                 retval = (STATUS_UNIX == 0);
967             }
968             else {
969                 retval = (status != -1);
970             }
971         }
972         else if (IoTYPE(io) == IoTYPE_STD)
973             retval = TRUE;
974         else {
975             if (IoOFP(io) && IoOFP(io) != IoIFP(io)) {          /* a socket */
976                 const bool prev_err = PerlIO_error(IoOFP(io));
977                 retval = (PerlIO_close(IoOFP(io)) != EOF && !prev_err);
978                 PerlIO_close(IoIFP(io));        /* clear stdio, fd already closed */
979             }
980             else {
981                 const bool prev_err = PerlIO_error(IoIFP(io));
982                 retval = (PerlIO_close(IoIFP(io)) != EOF && !prev_err);
983             }
984         }
985         IoOFP(io) = IoIFP(io) = NULL;
986     }
987     else if (not_implicit) {
988         SETERRNO(EBADF,SS_IVCHAN);
989     }
990
991     return retval;
992 }
993
994 bool
995 Perl_do_eof(pTHX_ GV *gv)
996 {
997     dVAR;
998     register IO * const io = GvIO(gv);
999
1000     PERL_ARGS_ASSERT_DO_EOF;
1001
1002     if (!io)
1003         return TRUE;
1004     else if ((IoTYPE(io) == IoTYPE_WRONLY) && ckWARN(WARN_IO))
1005         report_evil_fh(gv, io, OP_phoney_OUTPUT_ONLY);
1006
1007     while (IoIFP(io)) {
1008         if (PerlIO_has_cntptr(IoIFP(io))) {     /* (the code works without this) */
1009             if (PerlIO_get_cnt(IoIFP(io)) > 0)  /* cheat a little, since */
1010                 return FALSE;                   /* this is the most usual case */
1011         }
1012
1013         {
1014              /* getc and ungetc can stomp on errno */
1015             dSAVE_ERRNO;
1016             const int ch = PerlIO_getc(IoIFP(io));
1017             if (ch != EOF) {
1018                 (void)PerlIO_ungetc(IoIFP(io),ch);
1019                 RESTORE_ERRNO;
1020                 return FALSE;
1021             }
1022             RESTORE_ERRNO;
1023         }
1024
1025         if (PerlIO_has_cntptr(IoIFP(io)) && PerlIO_canset_cnt(IoIFP(io))) {
1026             if (PerlIO_get_cnt(IoIFP(io)) < -1)
1027                 PerlIO_set_cnt(IoIFP(io),-1);
1028         }
1029         if (PL_op->op_flags & OPf_SPECIAL) { /* not necessarily a real EOF yet? */
1030             if (gv != PL_argvgv || !nextargv(gv))       /* get another fp handy */
1031                 return TRUE;
1032         }
1033         else
1034             return TRUE;                /* normal fp, definitely end of file */
1035     }
1036     return TRUE;
1037 }
1038
1039 Off_t
1040 Perl_do_tell(pTHX_ GV *gv)
1041 {
1042     dVAR;
1043     register IO *io = NULL;
1044     register PerlIO *fp;
1045
1046     PERL_ARGS_ASSERT_DO_TELL;
1047
1048     if (gv && (io = GvIO(gv)) && (fp = IoIFP(io))) {
1049 #ifdef ULTRIX_STDIO_BOTCH
1050         if (PerlIO_eof(fp))
1051             (void)PerlIO_seek(fp, 0L, 2);       /* ultrix 1.2 workaround */
1052 #endif
1053         return PerlIO_tell(fp);
1054     }
1055     if (ckWARN2(WARN_UNOPENED,WARN_CLOSED))
1056         report_evil_fh(gv, io, PL_op->op_type);
1057     SETERRNO(EBADF,RMS_IFI);
1058     return (Off_t)-1;
1059 }
1060
1061 bool
1062 Perl_do_seek(pTHX_ GV *gv, Off_t pos, int whence)
1063 {
1064     dVAR;
1065     register IO *io = NULL;
1066     register PerlIO *fp;
1067
1068     if (gv && (io = GvIO(gv)) && (fp = IoIFP(io))) {
1069 #ifdef ULTRIX_STDIO_BOTCH
1070         if (PerlIO_eof(fp))
1071             (void)PerlIO_seek(fp, 0L, 2);       /* ultrix 1.2 workaround */
1072 #endif
1073         return PerlIO_seek(fp, pos, whence) >= 0;
1074     }
1075     if (ckWARN2(WARN_UNOPENED,WARN_CLOSED))
1076         report_evil_fh(gv, io, PL_op->op_type);
1077     SETERRNO(EBADF,RMS_IFI);
1078     return FALSE;
1079 }
1080
1081 Off_t
1082 Perl_do_sysseek(pTHX_ GV *gv, Off_t pos, int whence)
1083 {
1084     dVAR;
1085     register IO *io = NULL;
1086     register PerlIO *fp;
1087
1088     PERL_ARGS_ASSERT_DO_SYSSEEK;
1089
1090     if (gv && (io = GvIO(gv)) && (fp = IoIFP(io)))
1091         return PerlLIO_lseek(PerlIO_fileno(fp), pos, whence);
1092     if (ckWARN2(WARN_UNOPENED,WARN_CLOSED))
1093         report_evil_fh(gv, io, PL_op->op_type);
1094     SETERRNO(EBADF,RMS_IFI);
1095     return (Off_t)-1;
1096 }
1097
1098 int
1099 Perl_mode_from_discipline(pTHX_ const char *s, STRLEN len)
1100 {
1101     int mode = O_BINARY;
1102     if (s) {
1103         while (*s) {
1104             if (*s == ':') {
1105                 switch (s[1]) {
1106                 case 'r':
1107                     if (s[2] == 'a' && s[3] == 'w'
1108                         && (!s[4] || s[4] == ':' || isSPACE(s[4])))
1109                     {
1110                         mode = O_BINARY;
1111                         s += 4;
1112                         len -= 4;
1113                         break;
1114                     }
1115                     /* FALL THROUGH */
1116                 case 'c':
1117                     if (s[2] == 'r' && s[3] == 'l' && s[4] == 'f'
1118                         && (!s[5] || s[5] == ':' || isSPACE(s[5])))
1119                     {
1120                         mode = O_TEXT;
1121                         s += 5;
1122                         len -= 5;
1123                         break;
1124                     }
1125                     /* FALL THROUGH */
1126                 default:
1127                     goto fail_discipline;
1128                 }
1129             }
1130             else if (isSPACE(*s)) {
1131                 ++s;
1132                 --len;
1133             }
1134             else {
1135                 const char *end;
1136 fail_discipline:
1137                 end = strchr(s+1, ':');
1138                 if (!end)
1139                     end = s+len;
1140 #ifndef PERLIO_LAYERS
1141                 Perl_croak(aTHX_ "IO layers (like '%.*s') unavailable", end-s, s);
1142 #else
1143                 len -= end-s;
1144                 s = end;
1145 #endif
1146             }
1147         }
1148     }
1149     return mode;
1150 }
1151
1152 #if !defined(HAS_TRUNCATE) && !defined(HAS_CHSIZE)
1153 I32
1154 my_chsize(int fd, Off_t length)
1155 {
1156 #ifdef F_FREESP
1157         /* code courtesy of William Kucharski */
1158 #define HAS_CHSIZE
1159
1160     Stat_t filebuf;
1161
1162     if (PerlLIO_fstat(fd, &filebuf) < 0)
1163         return -1;
1164
1165     if (filebuf.st_size < length) {
1166
1167         /* extend file length */
1168
1169         if ((PerlLIO_lseek(fd, (length - 1), 0)) < 0)
1170             return -1;
1171
1172         /* write a "0" byte */
1173
1174         if ((PerlLIO_write(fd, "", 1)) != 1)
1175             return -1;
1176     }
1177     else {
1178         /* truncate length */
1179         struct flock fl;
1180         fl.l_whence = 0;
1181         fl.l_len = 0;
1182         fl.l_start = length;
1183         fl.l_type = F_WRLCK;    /* write lock on file space */
1184
1185         /*
1186         * This relies on the UNDOCUMENTED F_FREESP argument to
1187         * fcntl(2), which truncates the file so that it ends at the
1188         * position indicated by fl.l_start.
1189         *
1190         * Will minor miracles never cease?
1191         */
1192
1193         if (fcntl(fd, F_FREESP, &fl) < 0)
1194             return -1;
1195
1196     }
1197     return 0;
1198 #else
1199     Perl_croak_nocontext("truncate not implemented");
1200 #endif /* F_FREESP */
1201     return -1;
1202 }
1203 #endif /* !HAS_TRUNCATE && !HAS_CHSIZE */
1204
1205 bool
1206 Perl_do_print(pTHX_ register SV *sv, PerlIO *fp)
1207 {
1208     dVAR;
1209
1210     PERL_ARGS_ASSERT_DO_PRINT;
1211
1212     /* assuming fp is checked earlier */
1213     if (!sv)
1214         return TRUE;
1215     if (SvTYPE(sv) == SVt_IV && SvIOK(sv)) {
1216         assert(!SvGMAGICAL(sv));
1217         if (SvIsUV(sv))
1218             PerlIO_printf(fp, "%"UVuf, (UV)SvUVX(sv));
1219         else
1220             PerlIO_printf(fp, "%"IVdf, (IV)SvIVX(sv));
1221         return !PerlIO_error(fp);
1222     }
1223     else {
1224         STRLEN len;
1225         /* Do this first to trigger any overloading.  */
1226         const char *tmps = SvPV_const(sv, len);
1227         U8 *tmpbuf = NULL;
1228         bool happy = TRUE;
1229
1230         if (PerlIO_isutf8(fp)) {
1231             if (!SvUTF8(sv)) {
1232                 /* We don't modify the original scalar.  */
1233                 tmpbuf = bytes_to_utf8((const U8*) tmps, &len);
1234                 tmps = (char *) tmpbuf;
1235             }
1236         }
1237         else if (DO_UTF8(sv)) {
1238             STRLEN tmplen = len;
1239             bool utf8 = TRUE;
1240             U8 * const result = bytes_from_utf8((const U8*) tmps, &tmplen, &utf8);
1241             if (!utf8) {
1242                 tmpbuf = result;
1243                 tmps = (char *) tmpbuf;
1244                 len = tmplen;
1245             }
1246             else {
1247                 assert((char *)result == tmps);
1248                 if (ckWARN_d(WARN_UTF8)) {
1249                     Perl_warner(aTHX_ packWARN(WARN_UTF8),
1250                                 "Wide character in print");
1251                 }
1252             }
1253         }
1254         /* To detect whether the process is about to overstep its
1255          * filesize limit we would need getrlimit().  We could then
1256          * also transparently raise the limit with setrlimit() --
1257          * but only until the system hard limit/the filesystem limit,
1258          * at which we would get EPERM.  Note that when using buffered
1259          * io the write failure can be delayed until the flush/close. --jhi */
1260         if (len && (PerlIO_write(fp,tmps,len) == 0))
1261             happy = FALSE;
1262         Safefree(tmpbuf);
1263         return happy ? !PerlIO_error(fp) : FALSE;
1264     }
1265 }
1266
1267 I32
1268 Perl_my_stat(pTHX)
1269 {
1270     dVAR;
1271     dSP;
1272     IO *io;
1273     GV* gv;
1274
1275     if (PL_op->op_flags & OPf_REF) {
1276         EXTEND(SP,1);
1277         gv = cGVOP_gv;
1278       do_fstat:
1279         if (gv == PL_defgv)
1280             return PL_laststatval;
1281         io = GvIO(gv);
1282         do_fstat_have_io:
1283         PL_laststype = OP_STAT;
1284         PL_statgv = gv;
1285         sv_setpvs(PL_statname, "");
1286         if(io) {
1287             if (IoIFP(io)) {
1288                 return (PL_laststatval = PerlLIO_fstat(PerlIO_fileno(IoIFP(io)), &PL_statcache));
1289             } else if (IoDIRP(io)) {
1290                 return (PL_laststatval = PerlLIO_fstat(my_dirfd(IoDIRP(io)), &PL_statcache));
1291             } else {
1292                 if (ckWARN2(WARN_UNOPENED,WARN_CLOSED))
1293                     report_evil_fh(gv, io, PL_op->op_type);
1294                 return (PL_laststatval = -1);
1295             }
1296         } else {
1297             if (ckWARN2(WARN_UNOPENED,WARN_CLOSED))
1298                 report_evil_fh(gv, io, PL_op->op_type);
1299             return (PL_laststatval = -1);
1300         }
1301     }
1302     else if (PL_op->op_private & OPpFT_STACKED) {
1303         return PL_laststatval;
1304     }
1305     else {
1306         SV* const sv = POPs;
1307         const char *s;
1308         STRLEN len;
1309         PUTBACK;
1310         if (isGV_with_GP(sv)) {
1311             gv = MUTABLE_GV(sv);
1312             goto do_fstat;
1313         }
1314         else if (SvROK(sv) && isGV_with_GP(SvRV(sv))) {
1315             gv = MUTABLE_GV(SvRV(sv));
1316             goto do_fstat;
1317         }
1318         else if (SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVIO) {
1319             io = MUTABLE_IO(SvRV(sv));
1320             gv = NULL;
1321             goto do_fstat_have_io;
1322         }
1323
1324         s = SvPV_const(sv, len);
1325         PL_statgv = NULL;
1326         sv_setpvn(PL_statname, s, len);
1327         s = SvPVX_const(PL_statname);           /* s now NUL-terminated */
1328         PL_laststype = OP_STAT;
1329         PL_laststatval = PerlLIO_stat(s, &PL_statcache);
1330         if (PL_laststatval < 0 && ckWARN(WARN_NEWLINE) && strchr(s, '\n'))
1331             Perl_warner(aTHX_ packWARN(WARN_NEWLINE), PL_warn_nl, "stat");
1332         return PL_laststatval;
1333     }
1334 }
1335
1336
1337 I32
1338 Perl_my_lstat(pTHX)
1339 {
1340     dVAR;
1341     static const char no_prev_lstat[] = "The stat preceding -l _ wasn't an lstat";
1342     dSP;
1343     SV *sv;
1344     const char *file;
1345     if (PL_op->op_flags & OPf_REF) {
1346         EXTEND(SP,1);
1347         if (cGVOP_gv == PL_defgv) {
1348             if (PL_laststype != OP_LSTAT)
1349                 Perl_croak(aTHX_ no_prev_lstat);
1350             return PL_laststatval;
1351         }
1352         if (ckWARN(WARN_IO)) {
1353             Perl_warner(aTHX_ packWARN(WARN_IO), "Use of -l on filehandle %s",
1354                     GvENAME(cGVOP_gv));
1355             return (PL_laststatval = -1);
1356         }
1357     }
1358     else if (PL_laststype != OP_LSTAT
1359             && (PL_op->op_private & OPpFT_STACKED) && ckWARN(WARN_IO))
1360         Perl_croak(aTHX_ no_prev_lstat);
1361
1362     PL_laststype = OP_LSTAT;
1363     PL_statgv = NULL;
1364     sv = POPs;
1365     PUTBACK;
1366     if (SvROK(sv) && isGV_with_GP(SvRV(sv)) && ckWARN(WARN_IO)) {
1367         Perl_warner(aTHX_ packWARN(WARN_IO), "Use of -l on filehandle %s",
1368                 GvENAME((const GV *)SvRV(sv)));
1369         return (PL_laststatval = -1);
1370     }
1371     file = SvPV_nolen_const(sv);
1372     sv_setpv(PL_statname,file);
1373     PL_laststatval = PerlLIO_lstat(file,&PL_statcache);
1374     if (PL_laststatval < 0 && ckWARN(WARN_NEWLINE) && strchr(file, '\n'))
1375         Perl_warner(aTHX_ packWARN(WARN_NEWLINE), PL_warn_nl, "lstat");
1376     return PL_laststatval;
1377 }
1378
1379 static void
1380 S_exec_failed(pTHX_ const char *cmd, int fd, int do_report)
1381 {
1382     const int e = errno;
1383     PERL_ARGS_ASSERT_EXEC_FAILED;
1384     if (ckWARN(WARN_EXEC))
1385         Perl_warner(aTHX_ packWARN(WARN_EXEC), "Can't exec \"%s\": %s",
1386                     cmd, Strerror(e));
1387     if (do_report) {
1388         PerlLIO_write(fd, (void*)&e, sizeof(int));
1389         PerlLIO_close(fd);
1390     }
1391 }
1392
1393 bool
1394 Perl_do_aexec5(pTHX_ SV *really, register SV **mark, register SV **sp,
1395                int fd, int do_report)
1396 {
1397     dVAR;
1398     PERL_ARGS_ASSERT_DO_AEXEC5;
1399 #if defined(__SYMBIAN32__) || defined(__LIBCATAMOUNT__)
1400     Perl_croak(aTHX_ "exec? I'm not *that* kind of operating system");
1401 #else
1402     if (sp > mark) {
1403         const char **a;
1404         const char *tmps = NULL;
1405         Newx(PL_Argv, sp - mark + 1, const char*);
1406         a = PL_Argv;
1407
1408         while (++mark <= sp) {
1409             if (*mark)
1410                 *a++ = SvPV_nolen_const(*mark);
1411             else
1412                 *a++ = "";
1413         }
1414         *a = NULL;
1415         if (really)
1416             tmps = SvPV_nolen_const(really);
1417         if ((!really && *PL_Argv[0] != '/') ||
1418             (really && *tmps != '/'))           /* will execvp use PATH? */
1419             TAINT_ENV();                /* testing IFS here is overkill, probably */
1420         PERL_FPU_PRE_EXEC
1421         if (really && *tmps)
1422             PerlProc_execvp(tmps,EXEC_ARGV_CAST(PL_Argv));
1423         else
1424             PerlProc_execvp(PL_Argv[0],EXEC_ARGV_CAST(PL_Argv));
1425         PERL_FPU_POST_EXEC
1426         S_exec_failed(aTHX_ (really ? tmps : PL_Argv[0]), fd, do_report);
1427     }
1428     do_execfree();
1429 #endif
1430     return FALSE;
1431 }
1432
1433 void
1434 Perl_do_execfree(pTHX)
1435 {
1436     dVAR;
1437     Safefree(PL_Argv);
1438     PL_Argv = NULL;
1439     Safefree(PL_Cmd);
1440     PL_Cmd = NULL;
1441 }
1442
1443 #ifdef PERL_DEFAULT_DO_EXEC3_IMPLEMENTATION
1444
1445 bool
1446 Perl_do_exec3(pTHX_ const char *incmd, int fd, int do_report)
1447 {
1448     dVAR;
1449     register const char **a;
1450     register char *s;
1451     char *buf;
1452     char *cmd;
1453     /* Make a copy so we can change it */
1454     const Size_t cmdlen = strlen(incmd) + 1;
1455
1456     PERL_ARGS_ASSERT_DO_EXEC3;
1457
1458     Newx(buf, cmdlen, char);
1459     cmd = buf;
1460     memcpy(cmd, incmd, cmdlen);
1461
1462     while (*cmd && isSPACE(*cmd))
1463         cmd++;
1464
1465     /* save an extra exec if possible */
1466
1467 #ifdef CSH
1468     {
1469         char flags[PERL_FLAGS_MAX];
1470         if (strnEQ(cmd,PL_cshname,PL_cshlen) &&
1471             strnEQ(cmd+PL_cshlen," -c",3)) {
1472           my_strlcpy(flags, "-c", PERL_FLAGS_MAX);
1473           s = cmd+PL_cshlen+3;
1474           if (*s == 'f') {
1475               s++;
1476               my_strlcat(flags, "f", PERL_FLAGS_MAX - 2);
1477           }
1478           if (*s == ' ')
1479               s++;
1480           if (*s++ == '\'') {
1481               char * const ncmd = s;
1482
1483               while (*s)
1484                   s++;
1485               if (s[-1] == '\n')
1486                   *--s = '\0';
1487               if (s[-1] == '\'') {
1488                   *--s = '\0';
1489                   PERL_FPU_PRE_EXEC
1490                   PerlProc_execl(PL_cshname, "csh", flags, ncmd, (char*)NULL);
1491                   PERL_FPU_POST_EXEC
1492                   *s = '\'';
1493                   S_exec_failed(aTHX_ PL_cshname, fd, do_report);
1494                   Safefree(buf);
1495                   return FALSE;
1496               }
1497           }
1498         }
1499     }
1500 #endif /* CSH */
1501
1502     /* see if there are shell metacharacters in it */
1503
1504     if (*cmd == '.' && isSPACE(cmd[1]))
1505         goto doshell;
1506
1507     if (strnEQ(cmd,"exec",4) && isSPACE(cmd[4]))
1508         goto doshell;
1509
1510     s = cmd;
1511     while (isALNUM(*s))
1512         s++;    /* catch VAR=val gizmo */
1513     if (*s == '=')
1514         goto doshell;
1515
1516     for (s = cmd; *s; s++) {
1517         if (*s != ' ' && !isALPHA(*s) &&
1518             strchr("$&*(){}[]'\";\\|?<>~`\n",*s)) {
1519             if (*s == '\n' && !s[1]) {
1520                 *s = '\0';
1521                 break;
1522             }
1523             /* handle the 2>&1 construct at the end */
1524             if (*s == '>' && s[1] == '&' && s[2] == '1'
1525                 && s > cmd + 1 && s[-1] == '2' && isSPACE(s[-2])
1526                 && (!s[3] || isSPACE(s[3])))
1527             {
1528                 const char *t = s + 3;
1529
1530                 while (*t && isSPACE(*t))
1531                     ++t;
1532                 if (!*t && (PerlLIO_dup2(1,2) != -1)) {
1533                     s[-2] = '\0';
1534                     break;
1535                 }
1536             }
1537           doshell:
1538             PERL_FPU_PRE_EXEC
1539             PerlProc_execl(PL_sh_path, "sh", "-c", cmd, (char *)NULL);
1540             PERL_FPU_POST_EXEC
1541             S_exec_failed(aTHX_ PL_sh_path, fd, do_report);
1542             Safefree(buf);
1543             return FALSE;
1544         }
1545     }
1546
1547     Newx(PL_Argv, (s - cmd) / 2 + 2, const char*);
1548     PL_Cmd = savepvn(cmd, s-cmd);
1549     a = PL_Argv;
1550     for (s = PL_Cmd; *s;) {
1551         while (isSPACE(*s))
1552             s++;
1553         if (*s)
1554             *(a++) = s;
1555         while (*s && !isSPACE(*s))
1556             s++;
1557         if (*s)
1558             *s++ = '\0';
1559     }
1560     *a = NULL;
1561     if (PL_Argv[0]) {
1562         PERL_FPU_PRE_EXEC
1563         PerlProc_execvp(PL_Argv[0],EXEC_ARGV_CAST(PL_Argv));
1564         PERL_FPU_POST_EXEC
1565         if (errno == ENOEXEC) {         /* for system V NIH syndrome */
1566             do_execfree();
1567             goto doshell;
1568         }
1569         S_exec_failed(aTHX_ PL_Argv[0], fd, do_report);
1570     }
1571     do_execfree();
1572     Safefree(buf);
1573     return FALSE;
1574 }
1575
1576 #endif /* OS2 || WIN32 */
1577
1578 I32
1579 Perl_apply(pTHX_ I32 type, register SV **mark, register SV **sp)
1580 {
1581     dVAR;
1582     register I32 val;
1583     register I32 tot = 0;
1584     const char *const what = PL_op_name[type];
1585     const char *s;
1586     SV ** const oldmark = mark;
1587
1588     PERL_ARGS_ASSERT_APPLY;
1589
1590     /* Doing this ahead of the switch statement preserves the old behaviour,
1591        where attempting to use kill as a taint test test would fail on
1592        platforms where kill was not defined.  */
1593 #ifndef HAS_KILL
1594     if (type == OP_KILL)
1595         Perl_die(aTHX_ PL_no_func, what);
1596 #endif
1597 #ifndef HAS_CHOWN
1598     if (type == OP_CHOWN)
1599         Perl_die(aTHX_ PL_no_func, what);
1600 #endif
1601
1602
1603 #define APPLY_TAINT_PROPER() \
1604     STMT_START {                                                        \
1605         if (PL_tainted) { TAINT_PROPER(what); }                         \
1606     } STMT_END
1607
1608     /* This is a first heuristic; it doesn't catch tainting magic. */
1609     if (PL_tainting) {
1610         while (++mark <= sp) {
1611             if (SvTAINTED(*mark)) {
1612                 TAINT;
1613                 break;
1614             }
1615         }
1616         mark = oldmark;
1617     }
1618     switch (type) {
1619     case OP_CHMOD:
1620         APPLY_TAINT_PROPER();
1621         if (++mark <= sp) {
1622             val = SvIV(*mark);
1623             APPLY_TAINT_PROPER();
1624             tot = sp - mark;
1625             while (++mark <= sp) {
1626                 GV* gv;
1627                 if (isGV_with_GP(*mark)) {
1628                     gv = MUTABLE_GV(*mark);
1629                 do_fchmod:
1630                     if (GvIO(gv) && IoIFP(GvIOp(gv))) {
1631 #ifdef HAS_FCHMOD
1632                         APPLY_TAINT_PROPER();
1633                         if (fchmod(PerlIO_fileno(IoIFP(GvIOn(gv))), val))
1634                             tot--;
1635 #else
1636                         Perl_die(aTHX_ PL_no_func, "fchmod");
1637 #endif
1638                     }
1639                     else {
1640                         tot--;
1641                     }
1642                 }
1643                 else if (SvROK(*mark) && isGV_with_GP(SvRV(*mark))) {
1644                     gv = MUTABLE_GV(SvRV(*mark));
1645                     goto do_fchmod;
1646                 }
1647                 else {
1648                     const char *name = SvPV_nolen_const(*mark);
1649                     APPLY_TAINT_PROPER();
1650                     if (PerlLIO_chmod(name, val))
1651                         tot--;
1652                 }
1653             }
1654         }
1655         break;
1656 #ifdef HAS_CHOWN
1657     case OP_CHOWN:
1658         APPLY_TAINT_PROPER();
1659         if (sp - mark > 2) {
1660             register I32 val2;
1661             val = SvIVx(*++mark);
1662             val2 = SvIVx(*++mark);
1663             APPLY_TAINT_PROPER();
1664             tot = sp - mark;
1665             while (++mark <= sp) {
1666                 GV* gv;
1667                 if (isGV_with_GP(*mark)) {
1668                     gv = MUTABLE_GV(*mark);
1669                 do_fchown:
1670                     if (GvIO(gv) && IoIFP(GvIOp(gv))) {
1671 #ifdef HAS_FCHOWN
1672                         APPLY_TAINT_PROPER();
1673                         if (fchown(PerlIO_fileno(IoIFP(GvIOn(gv))), val, val2))
1674                             tot--;
1675 #else
1676                         Perl_die(aTHX_ PL_no_func, "fchown");
1677 #endif
1678                     }
1679                     else {
1680                         tot--;
1681                     }
1682                 }
1683                 else if (SvROK(*mark) && isGV_with_GP(SvRV(*mark))) {
1684                     gv = MUTABLE_GV(SvRV(*mark));
1685                     goto do_fchown;
1686                 }
1687                 else {
1688                     const char *name = SvPV_nolen_const(*mark);
1689                     APPLY_TAINT_PROPER();
1690                     if (PerlLIO_chown(name, val, val2))
1691                         tot--;
1692                 }
1693             }
1694         }
1695         break;
1696 #endif
1697 /*
1698 XXX Should we make lchown() directly available from perl?
1699 For now, we'll let Configure test for HAS_LCHOWN, but do
1700 nothing in the core.
1701     --AD  5/1998
1702 */
1703 #ifdef HAS_KILL
1704     case OP_KILL:
1705         APPLY_TAINT_PROPER();
1706         if (mark == sp)
1707             break;
1708         s = SvPVx_nolen_const(*++mark);
1709         if (isALPHA(*s)) {
1710             if (*s == 'S' && s[1] == 'I' && s[2] == 'G')
1711                 s += 3;
1712             if ((val = whichsig(s)) < 0)
1713                 Perl_croak(aTHX_ "Unrecognized signal name \"%s\"",s);
1714         }
1715         else
1716             val = SvIV(*mark);
1717         APPLY_TAINT_PROPER();
1718         tot = sp - mark;
1719 #ifdef VMS
1720         /* kill() doesn't do process groups (job trees?) under VMS */
1721         if (val < 0) val = -val;
1722         if (val == SIGKILL) {
1723 #           include <starlet.h>
1724             /* Use native sys$delprc() to insure that target process is
1725              * deleted; supervisor-mode images don't pay attention to
1726              * CRTL's emulation of Unix-style signals and kill()
1727              */
1728             while (++mark <= sp) {
1729                 I32 proc = SvIV(*mark);
1730                 register unsigned long int __vmssts;
1731                 APPLY_TAINT_PROPER();
1732                 if (!((__vmssts = sys$delprc(&proc,0)) & 1)) {
1733                     tot--;
1734                     switch (__vmssts) {
1735                         case SS$_NONEXPR:
1736                         case SS$_NOSUCHNODE:
1737                             SETERRNO(ESRCH,__vmssts);
1738                             break;
1739                         case SS$_NOPRIV:
1740                             SETERRNO(EPERM,__vmssts);
1741                             break;
1742                         default:
1743                             SETERRNO(EVMSERR,__vmssts);
1744                     }
1745                 }
1746             }
1747             break;
1748         }
1749 #endif
1750         if (val < 0) {
1751             val = -val;
1752             while (++mark <= sp) {
1753                 const I32 proc = SvIV(*mark);
1754                 APPLY_TAINT_PROPER();
1755 #ifdef HAS_KILLPG
1756                 if (PerlProc_killpg(proc,val))  /* BSD */
1757 #else
1758                 if (PerlProc_kill(-proc,val))   /* SYSV */
1759 #endif
1760                     tot--;
1761             }
1762         }
1763         else {
1764             while (++mark <= sp) {
1765                 const I32 proc = SvIV(*mark);
1766                 APPLY_TAINT_PROPER();
1767                 if (PerlProc_kill(proc, val))
1768                     tot--;
1769             }
1770         }
1771         break;
1772 #endif
1773     case OP_UNLINK:
1774         APPLY_TAINT_PROPER();
1775         tot = sp - mark;
1776         while (++mark <= sp) {
1777             s = SvPV_nolen_const(*mark);
1778             APPLY_TAINT_PROPER();
1779             if (PL_euid || PL_unsafe) {
1780                 if (UNLINK(s))
1781                     tot--;
1782             }
1783             else {      /* don't let root wipe out directories without -U */
1784                 if (PerlLIO_lstat(s,&PL_statbuf) < 0 || S_ISDIR(PL_statbuf.st_mode))
1785                     tot--;
1786                 else {
1787                     if (UNLINK(s))
1788                         tot--;
1789                 }
1790             }
1791         }
1792         break;
1793 #if defined(HAS_UTIME) || defined(HAS_FUTIMES)
1794     case OP_UTIME:
1795         APPLY_TAINT_PROPER();
1796         if (sp - mark > 2) {
1797 #if defined(HAS_FUTIMES)
1798             struct timeval utbuf[2];
1799             void *utbufp = utbuf;
1800 #elif defined(I_UTIME) || defined(VMS)
1801             struct utimbuf utbuf;
1802             struct utimbuf *utbufp = &utbuf;
1803 #else
1804             struct {
1805                 Time_t  actime;
1806                 Time_t  modtime;
1807             } utbuf;
1808             void *utbufp = &utbuf;
1809 #endif
1810
1811            SV* const accessed = *++mark;
1812            SV* const modified = *++mark;
1813
1814            /* Be like C, and if both times are undefined, let the C
1815             * library figure out what to do.  This usually means
1816             * "current time". */
1817
1818            if ( accessed == &PL_sv_undef && modified == &PL_sv_undef )
1819                 utbufp = NULL;
1820            else {
1821                 Zero(&utbuf, sizeof utbuf, char);
1822 #ifdef HAS_FUTIMES
1823                 utbuf[0].tv_sec = (long)SvIV(accessed);  /* time accessed */
1824                 utbuf[0].tv_usec = 0;
1825                 utbuf[1].tv_sec = (long)SvIV(modified);  /* time modified */
1826                 utbuf[1].tv_usec = 0;
1827 #elif defined(BIG_TIME)
1828                 utbuf.actime = (Time_t)SvNV(accessed);  /* time accessed */
1829                 utbuf.modtime = (Time_t)SvNV(modified); /* time modified */
1830 #else
1831                 utbuf.actime = (Time_t)SvIV(accessed);  /* time accessed */
1832                 utbuf.modtime = (Time_t)SvIV(modified); /* time modified */
1833 #endif
1834             }
1835             APPLY_TAINT_PROPER();
1836             tot = sp - mark;
1837             while (++mark <= sp) {
1838                 GV* gv;
1839                 if (isGV_with_GP(*mark)) {
1840                     gv = MUTABLE_GV(*mark);
1841                 do_futimes:
1842                     if (GvIO(gv) && IoIFP(GvIOp(gv))) {
1843 #ifdef HAS_FUTIMES
1844                         APPLY_TAINT_PROPER();
1845                         if (futimes(PerlIO_fileno(IoIFP(GvIOn(gv))),
1846                             (struct timeval *) utbufp))
1847                             tot--;
1848 #else
1849                         Perl_die(aTHX_ PL_no_func, "futimes");
1850 #endif
1851                     }
1852                     else {
1853                         tot--;
1854                     }
1855                 }
1856                 else if (SvROK(*mark) && isGV_with_GP(SvRV(*mark))) {
1857                     gv = MUTABLE_GV(SvRV(*mark));
1858                     goto do_futimes;
1859                 }
1860                 else {
1861                     const char * const name = SvPV_nolen_const(*mark);
1862                     APPLY_TAINT_PROPER();
1863 #ifdef HAS_FUTIMES
1864                     if (utimes(name, (struct timeval *)utbufp))
1865 #else
1866                     if (PerlLIO_utime(name, utbufp))
1867 #endif
1868                         tot--;
1869                 }
1870
1871             }
1872         }
1873         else
1874             tot = 0;
1875         break;
1876 #endif
1877     }
1878     return tot;
1879
1880 #undef APPLY_TAINT_PROPER
1881 }
1882
1883 /* Do the permissions allow some operation?  Assumes statcache already set. */
1884 #ifndef VMS /* VMS' cando is in vms.c */
1885 bool
1886 Perl_cando(pTHX_ Mode_t mode, bool effective, register const Stat_t *statbufp)
1887 /* effective is a flag, true for EUID, or for checking if the effective gid
1888  *  is in the list of groups returned from getgroups().
1889  */
1890 {
1891     dVAR;
1892
1893     PERL_ARGS_ASSERT_CANDO;
1894
1895 #ifdef DOSISH
1896     /* [Comments and code from Len Reed]
1897      * MS-DOS "user" is similar to UNIX's "superuser," but can't write
1898      * to write-protected files.  The execute permission bit is set
1899      * by the Miscrosoft C library stat() function for the following:
1900      *          .exe files
1901      *          .com files
1902      *          .bat files
1903      *          directories
1904      * All files and directories are readable.
1905      * Directories and special files, e.g. "CON", cannot be
1906      * write-protected.
1907      * [Comment by Tom Dinger -- a directory can have the write-protect
1908      *          bit set in the file system, but DOS permits changes to
1909      *          the directory anyway.  In addition, all bets are off
1910      *          here for networked software, such as Novell and
1911      *          Sun's PC-NFS.]
1912      */
1913
1914      /* Atari stat() does pretty much the same thing. we set x_bit_set_in_stat
1915       * too so it will actually look into the files for magic numbers
1916       */
1917      return (mode & statbufp->st_mode) ? TRUE : FALSE;
1918
1919 #else /* ! DOSISH */
1920     if ((effective ? PL_euid : PL_uid) == 0) {  /* root is special */
1921         if (mode == S_IXUSR) {
1922             if (statbufp->st_mode & 0111 || S_ISDIR(statbufp->st_mode))
1923                 return TRUE;
1924         }
1925         else
1926             return TRUE;                /* root reads and writes anything */
1927         return FALSE;
1928     }
1929     if (statbufp->st_uid == (effective ? PL_euid : PL_uid) ) {
1930         if (statbufp->st_mode & mode)
1931             return TRUE;        /* ok as "user" */
1932     }
1933     else if (ingroup(statbufp->st_gid,effective)) {
1934         if (statbufp->st_mode & mode >> 3)
1935             return TRUE;        /* ok as "group" */
1936     }
1937     else if (statbufp->st_mode & mode >> 6)
1938         return TRUE;    /* ok as "other" */
1939     return FALSE;
1940 #endif /* ! DOSISH */
1941 }
1942 #endif /* ! VMS */
1943
1944 static bool
1945 S_ingroup(pTHX_ Gid_t testgid, bool effective)
1946 {
1947     dVAR;
1948     if (testgid == (effective ? PL_egid : PL_gid))
1949         return TRUE;
1950 #ifdef HAS_GETGROUPS
1951     {
1952         Groups_t *gary = NULL;
1953         I32 anum;
1954         bool rc = FALSE;
1955
1956         anum = getgroups(0, gary);
1957         Newx(gary, anum, Groups_t);
1958         anum = getgroups(anum, gary);
1959         while (--anum >= 0)
1960             if (gary[anum] == testgid) {
1961                 rc = TRUE;
1962                 break;
1963             }
1964
1965         Safefree(gary);
1966         return rc;
1967     }
1968 #else
1969     return FALSE;
1970 #endif
1971 }
1972
1973 #if defined(HAS_MSG) || defined(HAS_SEM) || defined(HAS_SHM)
1974
1975 I32
1976 Perl_do_ipcget(pTHX_ I32 optype, SV **mark, SV **sp)
1977 {
1978     dVAR;
1979     const key_t key = (key_t)SvNVx(*++mark);
1980     SV *nsv = optype == OP_MSGGET ? NULL : *++mark;
1981     const I32 flags = SvIVx(*++mark);
1982
1983     PERL_ARGS_ASSERT_DO_IPCGET;
1984     PERL_UNUSED_ARG(sp);
1985
1986     SETERRNO(0,0);
1987     switch (optype)
1988     {
1989 #ifdef HAS_MSG
1990     case OP_MSGGET:
1991         return msgget(key, flags);
1992 #endif
1993 #ifdef HAS_SEM
1994     case OP_SEMGET:
1995         return semget(key, (int) SvIV(nsv), flags);
1996 #endif
1997 #ifdef HAS_SHM
1998     case OP_SHMGET:
1999         return shmget(key, (size_t) SvUV(nsv), flags);
2000 #endif
2001 #if !defined(HAS_MSG) || !defined(HAS_SEM) || !defined(HAS_SHM)
2002     default:
2003         /* diag_listed_as: msg%s not implemented */
2004         Perl_croak(aTHX_ "%s not implemented", PL_op_desc[optype]);
2005 #endif
2006     }
2007     return -1;                  /* should never happen */
2008 }
2009
2010 I32
2011 Perl_do_ipcctl(pTHX_ I32 optype, SV **mark, SV **sp)
2012 {
2013     dVAR;
2014     char *a;
2015     I32 ret = -1;
2016     const I32 id  = SvIVx(*++mark);
2017 #ifdef Semctl
2018     const I32 n   = (optype == OP_SEMCTL) ? SvIVx(*++mark) : 0;
2019 #endif
2020     const I32 cmd = SvIVx(*++mark);
2021     SV * const astr = *++mark;
2022     STRLEN infosize = 0;
2023     I32 getinfo = (cmd == IPC_STAT);
2024
2025     PERL_ARGS_ASSERT_DO_IPCCTL;
2026     PERL_UNUSED_ARG(sp);
2027
2028     switch (optype)
2029     {
2030 #ifdef HAS_MSG
2031     case OP_MSGCTL:
2032         if (cmd == IPC_STAT || cmd == IPC_SET)
2033             infosize = sizeof(struct msqid_ds);
2034         break;
2035 #endif
2036 #ifdef HAS_SHM
2037     case OP_SHMCTL:
2038         if (cmd == IPC_STAT || cmd == IPC_SET)
2039             infosize = sizeof(struct shmid_ds);
2040         break;
2041 #endif
2042 #ifdef HAS_SEM
2043     case OP_SEMCTL:
2044 #ifdef Semctl
2045         if (cmd == IPC_STAT || cmd == IPC_SET)
2046             infosize = sizeof(struct semid_ds);
2047         else if (cmd == GETALL || cmd == SETALL)
2048         {
2049             struct semid_ds semds;
2050             union semun semun;
2051 #ifdef EXTRA_F_IN_SEMUN_BUF
2052             semun.buff = &semds;
2053 #else
2054             semun.buf = &semds;
2055 #endif
2056             getinfo = (cmd == GETALL);
2057             if (Semctl(id, 0, IPC_STAT, semun) == -1)
2058                 return -1;
2059             infosize = semds.sem_nsems * sizeof(short);
2060                 /* "short" is technically wrong but much more portable
2061                    than guessing about u_?short(_t)? */
2062         }
2063 #else
2064         /* diag_listed_as: sem%s not implemented */
2065         Perl_croak(aTHX_ "%s not implemented", PL_op_desc[optype]);
2066 #endif
2067         break;
2068 #endif
2069 #if !defined(HAS_MSG) || !defined(HAS_SEM) || !defined(HAS_SHM)
2070     default:
2071         /* diag_listed_as: shm%s not implemented */
2072         Perl_croak(aTHX_ "%s not implemented", PL_op_desc[optype]);
2073 #endif
2074     }
2075
2076     if (infosize)
2077     {
2078         if (getinfo)
2079         {
2080             SvPV_force_nolen(astr);
2081             a = SvGROW(astr, infosize+1);
2082         }
2083         else
2084         {
2085             STRLEN len;
2086             a = SvPV(astr, len);
2087             if (len != infosize)
2088                 Perl_croak(aTHX_ "Bad arg length for %s, is %lu, should be %ld",
2089                       PL_op_desc[optype],
2090                       (unsigned long)len,
2091                       (long)infosize);
2092         }
2093     }
2094     else
2095     {
2096         const IV i = SvIV(astr);
2097         a = INT2PTR(char *,i);          /* ouch */
2098     }
2099     SETERRNO(0,0);
2100     switch (optype)
2101     {
2102 #ifdef HAS_MSG
2103     case OP_MSGCTL:
2104         ret = msgctl(id, cmd, (struct msqid_ds *)a);
2105         break;
2106 #endif
2107 #ifdef HAS_SEM
2108     case OP_SEMCTL: {
2109 #ifdef Semctl
2110             union semun unsemds;
2111
2112 #ifdef EXTRA_F_IN_SEMUN_BUF
2113             unsemds.buff = (struct semid_ds *)a;
2114 #else
2115             unsemds.buf = (struct semid_ds *)a;
2116 #endif
2117             ret = Semctl(id, n, cmd, unsemds);
2118 #else
2119             /* diag_listed_as: sem%s not implemented */
2120             Perl_croak(aTHX_ "%s not implemented", PL_op_desc[optype]);
2121 #endif
2122         }
2123         break;
2124 #endif
2125 #ifdef HAS_SHM
2126     case OP_SHMCTL:
2127         ret = shmctl(id, cmd, (struct shmid_ds *)a);
2128         break;
2129 #endif
2130     }
2131     if (getinfo && ret >= 0) {
2132         SvCUR_set(astr, infosize);
2133         *SvEND(astr) = '\0';
2134         SvSETMAGIC(astr);
2135     }
2136     return ret;
2137 }
2138
2139 I32
2140 Perl_do_msgsnd(pTHX_ SV **mark, SV **sp)
2141 {
2142     dVAR;
2143 #ifdef HAS_MSG
2144     STRLEN len;
2145     const I32 id = SvIVx(*++mark);
2146     SV * const mstr = *++mark;
2147     const I32 flags = SvIVx(*++mark);
2148     const char * const mbuf = SvPV_const(mstr, len);
2149     const I32 msize = len - sizeof(long);
2150
2151     PERL_ARGS_ASSERT_DO_MSGSND;
2152     PERL_UNUSED_ARG(sp);
2153
2154     if (msize < 0)
2155         Perl_croak(aTHX_ "Arg too short for msgsnd");
2156     SETERRNO(0,0);
2157     return msgsnd(id, (struct msgbuf *)mbuf, msize, flags);
2158 #else
2159     PERL_UNUSED_ARG(sp);
2160     PERL_UNUSED_ARG(mark);
2161     /* diag_listed_as: msg%s not implemented */
2162     Perl_croak(aTHX_ "msgsnd not implemented");
2163 #endif
2164 }
2165
2166 I32
2167 Perl_do_msgrcv(pTHX_ SV **mark, SV **sp)
2168 {
2169 #ifdef HAS_MSG
2170     dVAR;
2171     char *mbuf;
2172     long mtype;
2173     I32 msize, flags, ret;
2174     const I32 id = SvIVx(*++mark);
2175     SV * const mstr = *++mark;
2176
2177     PERL_ARGS_ASSERT_DO_MSGRCV;
2178     PERL_UNUSED_ARG(sp);
2179
2180     /* suppress warning when reading into undef var --jhi */
2181     if (! SvOK(mstr))
2182         sv_setpvs(mstr, "");
2183     msize = SvIVx(*++mark);
2184     mtype = (long)SvIVx(*++mark);
2185     flags = SvIVx(*++mark);
2186     SvPV_force_nolen(mstr);
2187     mbuf = SvGROW(mstr, sizeof(long)+msize+1);
2188
2189     SETERRNO(0,0);
2190     ret = msgrcv(id, (struct msgbuf *)mbuf, msize, mtype, flags);
2191     if (ret >= 0) {
2192         SvCUR_set(mstr, sizeof(long)+ret);
2193         *SvEND(mstr) = '\0';
2194 #ifndef INCOMPLETE_TAINTS
2195         /* who knows who has been playing with this message? */
2196         SvTAINTED_on(mstr);
2197 #endif
2198     }
2199     return ret;
2200 #else
2201     PERL_UNUSED_ARG(sp);
2202     PERL_UNUSED_ARG(mark);
2203     /* diag_listed_as: msg%s not implemented */
2204     Perl_croak(aTHX_ "msgrcv not implemented");
2205 #endif
2206 }
2207
2208 I32
2209 Perl_do_semop(pTHX_ SV **mark, SV **sp)
2210 {
2211 #ifdef HAS_SEM
2212     dVAR;
2213     STRLEN opsize;
2214     const I32 id = SvIVx(*++mark);
2215     SV * const opstr = *++mark;
2216     const char * const opbuf = SvPV_const(opstr, opsize);
2217
2218     PERL_ARGS_ASSERT_DO_SEMOP;
2219     PERL_UNUSED_ARG(sp);
2220
2221     if (opsize < 3 * SHORTSIZE
2222         || (opsize % (3 * SHORTSIZE))) {
2223         SETERRNO(EINVAL,LIB_INVARG);
2224         return -1;
2225     }
2226     SETERRNO(0,0);
2227     /* We can't assume that sizeof(struct sembuf) == 3 * sizeof(short). */
2228     {
2229         const int nsops  = opsize / (3 * sizeof (short));
2230         int i      = nsops;
2231         short * const ops = (short *) opbuf;
2232         short *o   = ops;
2233         struct sembuf *temps, *t;
2234         I32 result;
2235
2236         Newx (temps, nsops, struct sembuf);
2237         t = temps;
2238         while (i--) {
2239             t->sem_num = *o++;
2240             t->sem_op  = *o++;
2241             t->sem_flg = *o++;
2242             t++;
2243         }
2244         result = semop(id, temps, nsops);
2245         t = temps;
2246         o = ops;
2247         i = nsops;
2248         while (i--) {
2249             *o++ = t->sem_num;
2250             *o++ = t->sem_op;
2251             *o++ = t->sem_flg;
2252             t++;
2253         }
2254         Safefree(temps);
2255         return result;
2256     }
2257 #else
2258     /* diag_listed_as: sem%s not implemented */
2259     Perl_croak(aTHX_ "semop not implemented");
2260 #endif
2261 }
2262
2263 I32
2264 Perl_do_shmio(pTHX_ I32 optype, SV **mark, SV **sp)
2265 {
2266 #ifdef HAS_SHM
2267     dVAR;
2268     char *shm;
2269     struct shmid_ds shmds;
2270     const I32 id = SvIVx(*++mark);
2271     SV * const mstr = *++mark;
2272     const I32 mpos = SvIVx(*++mark);
2273     const I32 msize = SvIVx(*++mark);
2274
2275     PERL_ARGS_ASSERT_DO_SHMIO;
2276     PERL_UNUSED_ARG(sp);
2277
2278     SETERRNO(0,0);
2279     if (shmctl(id, IPC_STAT, &shmds) == -1)
2280         return -1;
2281     if (mpos < 0 || msize < 0
2282         || (size_t)mpos + msize > (size_t)shmds.shm_segsz) {
2283         SETERRNO(EFAULT,SS_ACCVIO);             /* can't do as caller requested */
2284         return -1;
2285     }
2286     shm = (char *)shmat(id, NULL, (optype == OP_SHMREAD) ? SHM_RDONLY : 0);
2287     if (shm == (char *)-1)      /* I hate System V IPC, I really do */
2288         return -1;
2289     if (optype == OP_SHMREAD) {
2290         char *mbuf;
2291         /* suppress warning when reading into undef var (tchrist 3/Mar/00) */
2292         if (! SvOK(mstr))
2293             sv_setpvs(mstr, "");
2294         SvPV_force_nolen(mstr);
2295         mbuf = SvGROW(mstr, (STRLEN)msize+1);
2296
2297         Copy(shm + mpos, mbuf, msize, char);
2298         SvCUR_set(mstr, msize);
2299         *SvEND(mstr) = '\0';
2300         SvSETMAGIC(mstr);
2301 #ifndef INCOMPLETE_TAINTS
2302         /* who knows who has been playing with this shared memory? */
2303         SvTAINTED_on(mstr);
2304 #endif
2305     }
2306     else {
2307         STRLEN len;
2308
2309         const char *mbuf = SvPV_const(mstr, len);
2310         const I32 n = ((I32)len > msize) ? msize : (I32)len;
2311         Copy(mbuf, shm + mpos, n, char);
2312         if (n < msize)
2313             memzero(shm + mpos + n, msize - n);
2314     }
2315     return shmdt(shm);
2316 #else
2317     /* diag_listed_as: shm%s not implemented */
2318     Perl_croak(aTHX_ "shm I/O not implemented");
2319 #endif
2320 }
2321
2322 #endif /* SYSV IPC */
2323
2324 /*
2325 =head1 IO Functions
2326
2327 =for apidoc start_glob
2328
2329 Function called by C<do_readline> to spawn a glob (or do the glob inside
2330 perl on VMS). This code used to be inline, but now perl uses C<File::Glob>
2331 this glob starter is only used by miniperl during the build process.
2332 Moving it away shrinks pp_hot.c; shrinking pp_hot.c helps speed perl up.
2333
2334 =cut
2335 */
2336
2337 PerlIO *
2338 Perl_start_glob (pTHX_ SV *tmpglob, IO *io)
2339 {
2340     dVAR;
2341     SV * const tmpcmd = newSV(0);
2342     PerlIO *fp;
2343
2344     PERL_ARGS_ASSERT_START_GLOB;
2345
2346     ENTER;
2347     SAVEFREESV(tmpcmd);
2348 #ifdef VMS /* expand the wildcards right here, rather than opening a pipe, */
2349            /* since spawning off a process is a real performance hit */
2350
2351 PerlIO * 
2352 Perl_vms_start_glob
2353    (pTHX_ SV *tmpglob,
2354     IO *io);
2355
2356     fp = Perl_vms_start_glob(aTHX_ tmpglob, io);
2357
2358 #else /* !VMS */
2359 #ifdef DOSISH
2360 #ifdef OS2
2361     sv_setpv(tmpcmd, "for a in ");
2362     sv_catsv(tmpcmd, tmpglob);
2363     sv_catpv(tmpcmd, "; do echo \"$a\\0\\c\"; done |");
2364 #else
2365 #ifdef DJGPP
2366     sv_setpv(tmpcmd, "/dev/dosglob/"); /* File System Extension */
2367     sv_catsv(tmpcmd, tmpglob);
2368 #else
2369     sv_setpv(tmpcmd, "perlglob ");
2370     sv_catsv(tmpcmd, tmpglob);
2371     sv_catpv(tmpcmd, " |");
2372 #endif /* !DJGPP */
2373 #endif /* !OS2 */
2374 #else /* !DOSISH */
2375 #if defined(CSH)
2376     sv_setpvn(tmpcmd, PL_cshname, PL_cshlen);
2377     sv_catpv(tmpcmd, " -cf 'set nonomatch; glob ");
2378     sv_catsv(tmpcmd, tmpglob);
2379     sv_catpv(tmpcmd, "' 2>/dev/null |");
2380 #else
2381     sv_setpv(tmpcmd, "echo ");
2382     sv_catsv(tmpcmd, tmpglob);
2383 #if 'z' - 'a' == 25
2384     sv_catpv(tmpcmd, "|tr -s ' \t\f\r' '\\012\\012\\012\\012'|");
2385 #else
2386     sv_catpv(tmpcmd, "|tr -s ' \t\f\r' '\\n\\n\\n\\n'|");
2387 #endif
2388 #endif /* !CSH */
2389 #endif /* !DOSISH */
2390     (void)do_open(PL_last_in_gv, (char*)SvPVX_const(tmpcmd), SvCUR(tmpcmd),
2391                   FALSE, O_RDONLY, 0, NULL);
2392     fp = IoIFP(io);
2393 #endif /* !VMS */
2394     LEAVE;
2395     return fp;
2396 }
2397
2398 /*
2399  * Local variables:
2400  * c-indentation-style: bsd
2401  * c-basic-offset: 4
2402  * indent-tabs-mode: t
2403  * End:
2404  *
2405  * ex: set ts=8 sts=4 sw=4 noet:
2406  */