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