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