This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
config.over is generated on some platforms, .gitignore it
[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 (ckWARN_d(WARN_UTF8)) {
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         EXTEND(SP,1);
1275         gv = cGVOP_gv;
1276       do_fstat:
1277         if (gv == PL_defgv)
1278             return PL_laststatval;
1279         io = GvIO(gv);
1280         do_fstat_have_io:
1281         PL_laststype = OP_STAT;
1282         PL_statgv = gv ? gv : (GV *)io;
1283         sv_setpvs(PL_statname, "");
1284         if(io) {
1285             if (IoIFP(io)) {
1286                 return (PL_laststatval = PerlLIO_fstat(PerlIO_fileno(IoIFP(io)), &PL_statcache));
1287             } else if (IoDIRP(io)) {
1288                 return (PL_laststatval = PerlLIO_fstat(my_dirfd(IoDIRP(io)), &PL_statcache));
1289             }
1290         }
1291         PL_laststatval = -1;
1292         report_evil_fh(gv);
1293         return -1;
1294     }
1295     else if (PL_op->op_private & OPpFT_STACKED) {
1296         return PL_laststatval;
1297     }
1298     else {
1299         SV* const sv = POPs;
1300         const char *s;
1301         STRLEN len;
1302         PUTBACK;
1303         if ((gv = MAYBE_DEREF_GV_flags(sv,flags))) {
1304             goto do_fstat;
1305         }
1306         else if (SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVIO) {
1307             io = MUTABLE_IO(SvRV(sv));
1308             gv = NULL;
1309             goto do_fstat_have_io;
1310         }
1311
1312         s = SvPV_flags_const(sv, len, flags);
1313         PL_statgv = NULL;
1314         sv_setpvn(PL_statname, s, len);
1315         s = SvPVX_const(PL_statname);           /* s now NUL-terminated */
1316         PL_laststype = OP_STAT;
1317         PL_laststatval = PerlLIO_stat(s, &PL_statcache);
1318         if (PL_laststatval < 0 && ckWARN(WARN_NEWLINE) && strchr(s, '\n'))
1319             Perl_warner(aTHX_ packWARN(WARN_NEWLINE), PL_warn_nl, "stat");
1320         return PL_laststatval;
1321     }
1322 }
1323
1324
1325 I32
1326 Perl_my_lstat_flags(pTHX_ const U32 flags)
1327 {
1328     dVAR;
1329     static const char no_prev_lstat[] = "The stat preceding -l _ wasn't an lstat";
1330     dSP;
1331     SV *sv;
1332     const char *file;
1333     if (PL_op->op_flags & OPf_REF) {
1334         EXTEND(SP,1);
1335         if (cGVOP_gv == PL_defgv) {
1336             if (PL_laststype != OP_LSTAT)
1337                 Perl_croak(aTHX_ no_prev_lstat);
1338             return PL_laststatval;
1339         }
1340         PL_laststatval = -1;
1341         if (ckWARN(WARN_IO)) {
1342             Perl_warner(aTHX_ packWARN(WARN_IO),
1343                              "Use of -l on filehandle %"HEKf,
1344                               HEKfARG(GvENAME_HEK(cGVOP_gv)));
1345         }
1346         return -1;
1347     }
1348     else if (PL_op->op_private & OPpFT_STACKED) {
1349       if (PL_laststype != OP_LSTAT)
1350         Perl_croak(aTHX_ no_prev_lstat);
1351       return PL_laststatval;
1352     } 
1353
1354     PL_laststype = OP_LSTAT;
1355     PL_statgv = NULL;
1356     sv = POPs;
1357     PUTBACK;
1358     file = SvPV_flags_const_nolen(sv, flags);
1359     sv_setpv(PL_statname,file);
1360     PL_laststatval = PerlLIO_lstat(file,&PL_statcache);
1361     if (PL_laststatval < 0 && ckWARN(WARN_NEWLINE) && strchr(file, '\n'))
1362         Perl_warner(aTHX_ packWARN(WARN_NEWLINE), PL_warn_nl, "lstat");
1363     return PL_laststatval;
1364 }
1365
1366 static void
1367 S_exec_failed(pTHX_ const char *cmd, int fd, int do_report)
1368 {
1369     const int e = errno;
1370     PERL_ARGS_ASSERT_EXEC_FAILED;
1371     if (ckWARN(WARN_EXEC))
1372         Perl_warner(aTHX_ packWARN(WARN_EXEC), "Can't exec \"%s\": %s",
1373                     cmd, Strerror(e));
1374     if (do_report) {
1375         PerlLIO_write(fd, (void*)&e, sizeof(int));
1376         PerlLIO_close(fd);
1377     }
1378 }
1379
1380 bool
1381 Perl_do_aexec5(pTHX_ SV *really, register SV **mark, register SV **sp,
1382                int fd, int do_report)
1383 {
1384     dVAR;
1385     PERL_ARGS_ASSERT_DO_AEXEC5;
1386 #if defined(__SYMBIAN32__) || defined(__LIBCATAMOUNT__)
1387     Perl_croak(aTHX_ "exec? I'm not *that* kind of operating system");
1388 #else
1389     if (sp > mark) {
1390         const char **a;
1391         const char *tmps = NULL;
1392         Newx(PL_Argv, sp - mark + 1, const char*);
1393         a = PL_Argv;
1394
1395         while (++mark <= sp) {
1396             if (*mark)
1397                 *a++ = SvPV_nolen_const(*mark);
1398             else
1399                 *a++ = "";
1400         }
1401         *a = NULL;
1402         if (really)
1403             tmps = SvPV_nolen_const(really);
1404         if ((!really && *PL_Argv[0] != '/') ||
1405             (really && *tmps != '/'))           /* will execvp use PATH? */
1406             TAINT_ENV();                /* testing IFS here is overkill, probably */
1407         PERL_FPU_PRE_EXEC
1408         if (really && *tmps)
1409             PerlProc_execvp(tmps,EXEC_ARGV_CAST(PL_Argv));
1410         else
1411             PerlProc_execvp(PL_Argv[0],EXEC_ARGV_CAST(PL_Argv));
1412         PERL_FPU_POST_EXEC
1413         S_exec_failed(aTHX_ (really ? tmps : PL_Argv[0]), fd, do_report);
1414     }
1415     do_execfree();
1416 #endif
1417     return FALSE;
1418 }
1419
1420 void
1421 Perl_do_execfree(pTHX)
1422 {
1423     dVAR;
1424     Safefree(PL_Argv);
1425     PL_Argv = NULL;
1426     Safefree(PL_Cmd);
1427     PL_Cmd = NULL;
1428 }
1429
1430 #ifdef PERL_DEFAULT_DO_EXEC3_IMPLEMENTATION
1431
1432 bool
1433 Perl_do_exec3(pTHX_ const char *incmd, int fd, int do_report)
1434 {
1435     dVAR;
1436     register const char **a;
1437     register char *s;
1438     char *buf;
1439     char *cmd;
1440     /* Make a copy so we can change it */
1441     const Size_t cmdlen = strlen(incmd) + 1;
1442
1443     PERL_ARGS_ASSERT_DO_EXEC3;
1444
1445     Newx(buf, cmdlen, char);
1446     cmd = buf;
1447     memcpy(cmd, incmd, cmdlen);
1448
1449     while (*cmd && isSPACE(*cmd))
1450         cmd++;
1451
1452     /* save an extra exec if possible */
1453
1454 #ifdef CSH
1455     {
1456         char flags[PERL_FLAGS_MAX];
1457         if (strnEQ(cmd,PL_cshname,PL_cshlen) &&
1458             strnEQ(cmd+PL_cshlen," -c",3)) {
1459           my_strlcpy(flags, "-c", PERL_FLAGS_MAX);
1460           s = cmd+PL_cshlen+3;
1461           if (*s == 'f') {
1462               s++;
1463               my_strlcat(flags, "f", PERL_FLAGS_MAX - 2);
1464           }
1465           if (*s == ' ')
1466               s++;
1467           if (*s++ == '\'') {
1468               char * const ncmd = s;
1469
1470               while (*s)
1471                   s++;
1472               if (s[-1] == '\n')
1473                   *--s = '\0';
1474               if (s[-1] == '\'') {
1475                   *--s = '\0';
1476                   PERL_FPU_PRE_EXEC
1477                   PerlProc_execl(PL_cshname, "csh", flags, ncmd, (char*)NULL);
1478                   PERL_FPU_POST_EXEC
1479                   *s = '\'';
1480                   S_exec_failed(aTHX_ PL_cshname, fd, do_report);
1481                   Safefree(buf);
1482                   return FALSE;
1483               }
1484           }
1485         }
1486     }
1487 #endif /* CSH */
1488
1489     /* see if there are shell metacharacters in it */
1490
1491     if (*cmd == '.' && isSPACE(cmd[1]))
1492         goto doshell;
1493
1494     if (strnEQ(cmd,"exec",4) && isSPACE(cmd[4]))
1495         goto doshell;
1496
1497     s = cmd;
1498     while (isALNUM(*s))
1499         s++;    /* catch VAR=val gizmo */
1500     if (*s == '=')
1501         goto doshell;
1502
1503     for (s = cmd; *s; s++) {
1504         if (*s != ' ' && !isALPHA(*s) &&
1505             strchr("$&*(){}[]'\";\\|?<>~`\n",*s)) {
1506             if (*s == '\n' && !s[1]) {
1507                 *s = '\0';
1508                 break;
1509             }
1510             /* handle the 2>&1 construct at the end */
1511             if (*s == '>' && s[1] == '&' && s[2] == '1'
1512                 && s > cmd + 1 && s[-1] == '2' && isSPACE(s[-2])
1513                 && (!s[3] || isSPACE(s[3])))
1514             {
1515                 const char *t = s + 3;
1516
1517                 while (*t && isSPACE(*t))
1518                     ++t;
1519                 if (!*t && (PerlLIO_dup2(1,2) != -1)) {
1520                     s[-2] = '\0';
1521                     break;
1522                 }
1523             }
1524           doshell:
1525             PERL_FPU_PRE_EXEC
1526             PerlProc_execl(PL_sh_path, "sh", "-c", cmd, (char *)NULL);
1527             PERL_FPU_POST_EXEC
1528             S_exec_failed(aTHX_ PL_sh_path, fd, do_report);
1529             Safefree(buf);
1530             return FALSE;
1531         }
1532     }
1533
1534     Newx(PL_Argv, (s - cmd) / 2 + 2, const char*);
1535     PL_Cmd = savepvn(cmd, s-cmd);
1536     a = PL_Argv;
1537     for (s = PL_Cmd; *s;) {
1538         while (isSPACE(*s))
1539             s++;
1540         if (*s)
1541             *(a++) = s;
1542         while (*s && !isSPACE(*s))
1543             s++;
1544         if (*s)
1545             *s++ = '\0';
1546     }
1547     *a = NULL;
1548     if (PL_Argv[0]) {
1549         PERL_FPU_PRE_EXEC
1550         PerlProc_execvp(PL_Argv[0],EXEC_ARGV_CAST(PL_Argv));
1551         PERL_FPU_POST_EXEC
1552         if (errno == ENOEXEC) {         /* for system V NIH syndrome */
1553             do_execfree();
1554             goto doshell;
1555         }
1556         S_exec_failed(aTHX_ PL_Argv[0], fd, do_report);
1557     }
1558     do_execfree();
1559     Safefree(buf);
1560     return FALSE;
1561 }
1562
1563 #endif /* OS2 || WIN32 */
1564
1565 I32
1566 Perl_apply(pTHX_ I32 type, register SV **mark, register SV **sp)
1567 {
1568     dVAR;
1569     register I32 val;
1570     register I32 tot = 0;
1571     const char *const what = PL_op_name[type];
1572     const char *s;
1573     STRLEN len;
1574     SV ** const oldmark = mark;
1575
1576     PERL_ARGS_ASSERT_APPLY;
1577
1578     /* Doing this ahead of the switch statement preserves the old behaviour,
1579        where attempting to use kill as a taint test test would fail on
1580        platforms where kill was not defined.  */
1581 #ifndef HAS_KILL
1582     if (type == OP_KILL)
1583         Perl_die(aTHX_ PL_no_func, what);
1584 #endif
1585 #ifndef HAS_CHOWN
1586     if (type == OP_CHOWN)
1587         Perl_die(aTHX_ PL_no_func, what);
1588 #endif
1589
1590
1591 #define APPLY_TAINT_PROPER() \
1592     STMT_START {                                                        \
1593         if (PL_tainted) { TAINT_PROPER(what); }                         \
1594     } STMT_END
1595
1596     /* This is a first heuristic; it doesn't catch tainting magic. */
1597     if (PL_tainting) {
1598         while (++mark <= sp) {
1599             if (SvTAINTED(*mark)) {
1600                 TAINT;
1601                 break;
1602             }
1603         }
1604         mark = oldmark;
1605     }
1606     switch (type) {
1607     case OP_CHMOD:
1608         APPLY_TAINT_PROPER();
1609         if (++mark <= sp) {
1610             val = SvIV(*mark);
1611             APPLY_TAINT_PROPER();
1612             tot = sp - mark;
1613             while (++mark <= sp) {
1614                 GV* gv;
1615                 if ((gv = MAYBE_DEREF_GV(*mark))) {
1616                     if (GvIO(gv) && IoIFP(GvIOp(gv))) {
1617 #ifdef HAS_FCHMOD
1618                         APPLY_TAINT_PROPER();
1619                         if (fchmod(PerlIO_fileno(IoIFP(GvIOn(gv))), val))
1620                             tot--;
1621 #else
1622                         Perl_die(aTHX_ PL_no_func, "fchmod");
1623 #endif
1624                     }
1625                     else {
1626                         tot--;
1627                     }
1628                 }
1629                 else {
1630                     const char *name = SvPV_nomg_const_nolen(*mark);
1631                     APPLY_TAINT_PROPER();
1632                     if (PerlLIO_chmod(name, val))
1633                         tot--;
1634                 }
1635             }
1636         }
1637         break;
1638 #ifdef HAS_CHOWN
1639     case OP_CHOWN:
1640         APPLY_TAINT_PROPER();
1641         if (sp - mark > 2) {
1642             register I32 val2;
1643             val = SvIVx(*++mark);
1644             val2 = SvIVx(*++mark);
1645             APPLY_TAINT_PROPER();
1646             tot = sp - mark;
1647             while (++mark <= sp) {
1648                 GV* gv;
1649                 if ((gv = MAYBE_DEREF_GV(*mark))) {
1650                     if (GvIO(gv) && IoIFP(GvIOp(gv))) {
1651 #ifdef HAS_FCHOWN
1652                         APPLY_TAINT_PROPER();
1653                         if (fchown(PerlIO_fileno(IoIFP(GvIOn(gv))), val, val2))
1654                             tot--;
1655 #else
1656                         Perl_die(aTHX_ PL_no_func, "fchown");
1657 #endif
1658                     }
1659                     else {
1660                         tot--;
1661                     }
1662                 }
1663                 else {
1664                     const char *name = SvPV_nomg_const_nolen(*mark);
1665                     APPLY_TAINT_PROPER();
1666                     if (PerlLIO_chown(name, val, val2))
1667                         tot--;
1668                 }
1669             }
1670         }
1671         break;
1672 #endif
1673 /*
1674 XXX Should we make lchown() directly available from perl?
1675 For now, we'll let Configure test for HAS_LCHOWN, but do
1676 nothing in the core.
1677     --AD  5/1998
1678 */
1679 #ifdef HAS_KILL
1680     case OP_KILL:
1681         APPLY_TAINT_PROPER();
1682         if (mark == sp)
1683             break;
1684         s = SvPVx_const(*++mark, len);
1685         if (isALPHA(*s)) {
1686             if (*s == 'S' && s[1] == 'I' && s[2] == 'G') {
1687                 s += 3;
1688                 len -= 3;
1689             }
1690            if ((val = whichsig_pvn(s, len)) < 0)
1691                Perl_croak(aTHX_ "Unrecognized signal name \"%"SVf"\"", SVfARG(*mark));
1692         }
1693         else
1694             val = SvIV(*mark);
1695         APPLY_TAINT_PROPER();
1696         tot = sp - mark;
1697 #ifdef VMS
1698         /* kill() doesn't do process groups (job trees?) under VMS */
1699         if (val < 0) val = -val;
1700         if (val == SIGKILL) {
1701 #           include <starlet.h>
1702             /* Use native sys$delprc() to insure that target process is
1703              * deleted; supervisor-mode images don't pay attention to
1704              * CRTL's emulation of Unix-style signals and kill()
1705              */
1706             while (++mark <= sp) {
1707                 I32 proc;
1708                 register unsigned long int __vmssts;
1709                 SvGETMAGIC(*mark);
1710                 if (!(SvIOK(*mark) || SvNOK(*mark) || looks_like_number(*mark)))
1711                     Perl_croak(aTHX_ "Can't kill a non-numeric process ID");
1712                 proc = SvIV_nomg(*mark);
1713                 APPLY_TAINT_PROPER();
1714                 if (!((__vmssts = sys$delprc(&proc,0)) & 1)) {
1715                     tot--;
1716                     switch (__vmssts) {
1717                         case SS$_NONEXPR:
1718                         case SS$_NOSUCHNODE:
1719                             SETERRNO(ESRCH,__vmssts);
1720                             break;
1721                         case SS$_NOPRIV:
1722                             SETERRNO(EPERM,__vmssts);
1723                             break;
1724                         default:
1725                             SETERRNO(EVMSERR,__vmssts);
1726                     }
1727                 }
1728             }
1729             PERL_ASYNC_CHECK();
1730             break;
1731         }
1732 #endif
1733         if (val < 0) {
1734             val = -val;
1735             while (++mark <= sp) {
1736                 I32 proc;
1737                 SvGETMAGIC(*mark);
1738                 if (!(SvIOK(*mark) || SvNOK(*mark) || looks_like_number(*mark)))
1739                     Perl_croak(aTHX_ "Can't kill a non-numeric process ID");
1740                 proc = SvIV_nomg(*mark);
1741                 APPLY_TAINT_PROPER();
1742 #ifdef HAS_KILLPG
1743                 if (PerlProc_killpg(proc,val))  /* BSD */
1744 #else
1745                 if (PerlProc_kill(-proc,val))   /* SYSV */
1746 #endif
1747                     tot--;
1748             }
1749         }
1750         else {
1751             while (++mark <= sp) {
1752                 I32 proc;
1753                 SvGETMAGIC(*mark);
1754                 if (!(SvIOK(*mark) || SvNOK(*mark) || looks_like_number(*mark)))
1755                     Perl_croak(aTHX_ "Can't kill a non-numeric process ID");
1756                 proc = SvIV_nomg(*mark);
1757                 APPLY_TAINT_PROPER();
1758                 if (PerlProc_kill(proc, val))
1759                     tot--;
1760             }
1761         }
1762         PERL_ASYNC_CHECK();
1763         break;
1764 #endif
1765     case OP_UNLINK:
1766         APPLY_TAINT_PROPER();
1767         tot = sp - mark;
1768         while (++mark <= sp) {
1769             s = SvPV_nolen_const(*mark);
1770             APPLY_TAINT_PROPER();
1771             if (PL_euid || PL_unsafe) {
1772                 if (UNLINK(s))
1773                     tot--;
1774             }
1775             else {      /* don't let root wipe out directories without -U */
1776                 if (PerlLIO_lstat(s,&PL_statbuf) < 0 || S_ISDIR(PL_statbuf.st_mode))
1777                     tot--;
1778                 else {
1779                     if (UNLINK(s))
1780                         tot--;
1781                 }
1782             }
1783         }
1784         break;
1785 #if defined(HAS_UTIME) || defined(HAS_FUTIMES)
1786     case OP_UTIME:
1787         APPLY_TAINT_PROPER();
1788         if (sp - mark > 2) {
1789 #if defined(HAS_FUTIMES)
1790             struct timeval utbuf[2];
1791             void *utbufp = utbuf;
1792 #elif defined(I_UTIME) || defined(VMS)
1793             struct utimbuf utbuf;
1794             struct utimbuf *utbufp = &utbuf;
1795 #else
1796             struct {
1797                 Time_t  actime;
1798                 Time_t  modtime;
1799             } utbuf;
1800             void *utbufp = &utbuf;
1801 #endif
1802
1803            SV* const accessed = *++mark;
1804            SV* const modified = *++mark;
1805
1806            /* Be like C, and if both times are undefined, let the C
1807             * library figure out what to do.  This usually means
1808             * "current time". */
1809
1810            if ( accessed == &PL_sv_undef && modified == &PL_sv_undef )
1811                 utbufp = NULL;
1812            else {
1813                 Zero(&utbuf, sizeof utbuf, char);
1814 #ifdef HAS_FUTIMES
1815                 utbuf[0].tv_sec = (long)SvIV(accessed);  /* time accessed */
1816                 utbuf[0].tv_usec = 0;
1817                 utbuf[1].tv_sec = (long)SvIV(modified);  /* time modified */
1818                 utbuf[1].tv_usec = 0;
1819 #elif defined(BIG_TIME)
1820                 utbuf.actime = (Time_t)SvNV(accessed);  /* time accessed */
1821                 utbuf.modtime = (Time_t)SvNV(modified); /* time modified */
1822 #else
1823                 utbuf.actime = (Time_t)SvIV(accessed);  /* time accessed */
1824                 utbuf.modtime = (Time_t)SvIV(modified); /* time modified */
1825 #endif
1826             }
1827             APPLY_TAINT_PROPER();
1828             tot = sp - mark;
1829             while (++mark <= sp) {
1830                 GV* gv;
1831                 if ((gv = MAYBE_DEREF_GV(*mark))) {
1832                     if (GvIO(gv) && IoIFP(GvIOp(gv))) {
1833 #ifdef HAS_FUTIMES
1834                         APPLY_TAINT_PROPER();
1835                         if (futimes(PerlIO_fileno(IoIFP(GvIOn(gv))),
1836                             (struct timeval *) utbufp))
1837                             tot--;
1838 #else
1839                         Perl_die(aTHX_ PL_no_func, "futimes");
1840 #endif
1841                     }
1842                     else {
1843                         tot--;
1844                     }
1845                 }
1846                 else {
1847                     const char * const name = SvPV_nomg_const_nolen(*mark);
1848                     APPLY_TAINT_PROPER();
1849 #ifdef HAS_FUTIMES
1850                     if (utimes(name, (struct timeval *)utbufp))
1851 #else
1852                     if (PerlLIO_utime(name, utbufp))
1853 #endif
1854                         tot--;
1855                 }
1856
1857             }
1858         }
1859         else
1860             tot = 0;
1861         break;
1862 #endif
1863     }
1864     return tot;
1865
1866 #undef APPLY_TAINT_PROPER
1867 }
1868
1869 /* Do the permissions allow some operation?  Assumes statcache already set. */
1870 #ifndef VMS /* VMS' cando is in vms.c */
1871 bool
1872 Perl_cando(pTHX_ Mode_t mode, bool effective, register const Stat_t *statbufp)
1873 /* effective is a flag, true for EUID, or for checking if the effective gid
1874  *  is in the list of groups returned from getgroups().
1875  */
1876 {
1877     dVAR;
1878
1879     PERL_ARGS_ASSERT_CANDO;
1880
1881 #ifdef DOSISH
1882     /* [Comments and code from Len Reed]
1883      * MS-DOS "user" is similar to UNIX's "superuser," but can't write
1884      * to write-protected files.  The execute permission bit is set
1885      * by the Microsoft C library stat() function for the following:
1886      *          .exe files
1887      *          .com files
1888      *          .bat files
1889      *          directories
1890      * All files and directories are readable.
1891      * Directories and special files, e.g. "CON", cannot be
1892      * write-protected.
1893      * [Comment by Tom Dinger -- a directory can have the write-protect
1894      *          bit set in the file system, but DOS permits changes to
1895      *          the directory anyway.  In addition, all bets are off
1896      *          here for networked software, such as Novell and
1897      *          Sun's PC-NFS.]
1898      */
1899
1900      /* Atari stat() does pretty much the same thing. we set x_bit_set_in_stat
1901       * too so it will actually look into the files for magic numbers
1902       */
1903      return (mode & statbufp->st_mode) ? TRUE : FALSE;
1904
1905 #else /* ! DOSISH */
1906 # ifdef __CYGWIN__
1907     if (ingroup(544,effective)) {     /* member of Administrators */
1908 # else
1909     if ((effective ? PL_euid : PL_uid) == 0) {  /* root is special */
1910 # endif
1911         if (mode == S_IXUSR) {
1912             if (statbufp->st_mode & 0111 || S_ISDIR(statbufp->st_mode))
1913                 return TRUE;
1914         }
1915         else
1916             return TRUE;                /* root reads and writes anything */
1917         return FALSE;
1918     }
1919     if (statbufp->st_uid == (effective ? PL_euid : PL_uid) ) {
1920         if (statbufp->st_mode & mode)
1921             return TRUE;        /* ok as "user" */
1922     }
1923     else if (ingroup(statbufp->st_gid,effective)) {
1924         if (statbufp->st_mode & mode >> 3)
1925             return TRUE;        /* ok as "group" */
1926     }
1927     else if (statbufp->st_mode & mode >> 6)
1928         return TRUE;    /* ok as "other" */
1929     return FALSE;
1930 #endif /* ! DOSISH */
1931 }
1932 #endif /* ! VMS */
1933
1934 static bool
1935 S_ingroup(pTHX_ Gid_t testgid, bool effective)
1936 {
1937     dVAR;
1938     if (testgid == (effective ? PL_egid : PL_gid))
1939         return TRUE;
1940 #ifdef HAS_GETGROUPS
1941     {
1942         Groups_t *gary = NULL;
1943         I32 anum;
1944         bool rc = FALSE;
1945
1946         anum = getgroups(0, gary);
1947         Newx(gary, anum, Groups_t);
1948         anum = getgroups(anum, gary);
1949         while (--anum >= 0)
1950             if (gary[anum] == testgid) {
1951                 rc = TRUE;
1952                 break;
1953             }
1954
1955         Safefree(gary);
1956         return rc;
1957     }
1958 #else
1959     return FALSE;
1960 #endif
1961 }
1962
1963 #if defined(HAS_MSG) || defined(HAS_SEM) || defined(HAS_SHM)
1964
1965 I32
1966 Perl_do_ipcget(pTHX_ I32 optype, SV **mark, SV **sp)
1967 {
1968     dVAR;
1969     const key_t key = (key_t)SvNVx(*++mark);
1970     SV *nsv = optype == OP_MSGGET ? NULL : *++mark;
1971     const I32 flags = SvIVx(*++mark);
1972
1973     PERL_ARGS_ASSERT_DO_IPCGET;
1974     PERL_UNUSED_ARG(sp);
1975
1976     SETERRNO(0,0);
1977     switch (optype)
1978     {
1979 #ifdef HAS_MSG
1980     case OP_MSGGET:
1981         return msgget(key, flags);
1982 #endif
1983 #ifdef HAS_SEM
1984     case OP_SEMGET:
1985         return semget(key, (int) SvIV(nsv), flags);
1986 #endif
1987 #ifdef HAS_SHM
1988     case OP_SHMGET:
1989         return shmget(key, (size_t) SvUV(nsv), flags);
1990 #endif
1991 #if !defined(HAS_MSG) || !defined(HAS_SEM) || !defined(HAS_SHM)
1992     default:
1993         /* diag_listed_as: msg%s not implemented */
1994         Perl_croak(aTHX_ "%s not implemented", PL_op_desc[optype]);
1995 #endif
1996     }
1997     return -1;                  /* should never happen */
1998 }
1999
2000 I32
2001 Perl_do_ipcctl(pTHX_ I32 optype, SV **mark, SV **sp)
2002 {
2003     dVAR;
2004     char *a;
2005     I32 ret = -1;
2006     const I32 id  = SvIVx(*++mark);
2007 #ifdef Semctl
2008     const I32 n   = (optype == OP_SEMCTL) ? SvIVx(*++mark) : 0;
2009 #endif
2010     const I32 cmd = SvIVx(*++mark);
2011     SV * const astr = *++mark;
2012     STRLEN infosize = 0;
2013     I32 getinfo = (cmd == IPC_STAT);
2014
2015     PERL_ARGS_ASSERT_DO_IPCCTL;
2016     PERL_UNUSED_ARG(sp);
2017
2018     switch (optype)
2019     {
2020 #ifdef HAS_MSG
2021     case OP_MSGCTL:
2022         if (cmd == IPC_STAT || cmd == IPC_SET)
2023             infosize = sizeof(struct msqid_ds);
2024         break;
2025 #endif
2026 #ifdef HAS_SHM
2027     case OP_SHMCTL:
2028         if (cmd == IPC_STAT || cmd == IPC_SET)
2029             infosize = sizeof(struct shmid_ds);
2030         break;
2031 #endif
2032 #ifdef HAS_SEM
2033     case OP_SEMCTL:
2034 #ifdef Semctl
2035         if (cmd == IPC_STAT || cmd == IPC_SET)
2036             infosize = sizeof(struct semid_ds);
2037         else if (cmd == GETALL || cmd == SETALL)
2038         {
2039             struct semid_ds semds;
2040             union semun semun;
2041 #ifdef EXTRA_F_IN_SEMUN_BUF
2042             semun.buff = &semds;
2043 #else
2044             semun.buf = &semds;
2045 #endif
2046             getinfo = (cmd == GETALL);
2047             if (Semctl(id, 0, IPC_STAT, semun) == -1)
2048                 return -1;
2049             infosize = semds.sem_nsems * sizeof(short);
2050                 /* "short" is technically wrong but much more portable
2051                    than guessing about u_?short(_t)? */
2052         }
2053 #else
2054         /* diag_listed_as: sem%s not implemented */
2055         Perl_croak(aTHX_ "%s not implemented", PL_op_desc[optype]);
2056 #endif
2057         break;
2058 #endif
2059 #if !defined(HAS_MSG) || !defined(HAS_SEM) || !defined(HAS_SHM)
2060     default:
2061         /* diag_listed_as: shm%s not implemented */
2062         Perl_croak(aTHX_ "%s not implemented", PL_op_desc[optype]);
2063 #endif
2064     }
2065
2066     if (infosize)
2067     {
2068         if (getinfo)
2069         {
2070             SvPV_force_nolen(astr);
2071             a = SvGROW(astr, infosize+1);
2072         }
2073         else
2074         {
2075             STRLEN len;
2076             a = SvPV(astr, len);
2077             if (len != infosize)
2078                 Perl_croak(aTHX_ "Bad arg length for %s, is %lu, should be %ld",
2079                       PL_op_desc[optype],
2080                       (unsigned long)len,
2081                       (long)infosize);
2082         }
2083     }
2084     else
2085     {
2086         const IV i = SvIV(astr);
2087         a = INT2PTR(char *,i);          /* ouch */
2088     }
2089     SETERRNO(0,0);
2090     switch (optype)
2091     {
2092 #ifdef HAS_MSG
2093     case OP_MSGCTL:
2094         ret = msgctl(id, cmd, (struct msqid_ds *)a);
2095         break;
2096 #endif
2097 #ifdef HAS_SEM
2098     case OP_SEMCTL: {
2099 #ifdef Semctl
2100             union semun unsemds;
2101
2102 #ifdef EXTRA_F_IN_SEMUN_BUF
2103             unsemds.buff = (struct semid_ds *)a;
2104 #else
2105             unsemds.buf = (struct semid_ds *)a;
2106 #endif
2107             ret = Semctl(id, n, cmd, unsemds);
2108 #else
2109             /* diag_listed_as: sem%s not implemented */
2110             Perl_croak(aTHX_ "%s not implemented", PL_op_desc[optype]);
2111 #endif
2112         }
2113         break;
2114 #endif
2115 #ifdef HAS_SHM
2116     case OP_SHMCTL:
2117         ret = shmctl(id, cmd, (struct shmid_ds *)a);
2118         break;
2119 #endif
2120     }
2121     if (getinfo && ret >= 0) {
2122         SvCUR_set(astr, infosize);
2123         *SvEND(astr) = '\0';
2124         SvSETMAGIC(astr);
2125     }
2126     return ret;
2127 }
2128
2129 I32
2130 Perl_do_msgsnd(pTHX_ SV **mark, SV **sp)
2131 {
2132     dVAR;
2133 #ifdef HAS_MSG
2134     STRLEN len;
2135     const I32 id = SvIVx(*++mark);
2136     SV * const mstr = *++mark;
2137     const I32 flags = SvIVx(*++mark);
2138     const char * const mbuf = SvPV_const(mstr, len);
2139     const I32 msize = len - sizeof(long);
2140
2141     PERL_ARGS_ASSERT_DO_MSGSND;
2142     PERL_UNUSED_ARG(sp);
2143
2144     if (msize < 0)
2145         Perl_croak(aTHX_ "Arg too short for msgsnd");
2146     SETERRNO(0,0);
2147     return msgsnd(id, (struct msgbuf *)mbuf, msize, flags);
2148 #else
2149     PERL_UNUSED_ARG(sp);
2150     PERL_UNUSED_ARG(mark);
2151     /* diag_listed_as: msg%s not implemented */
2152     Perl_croak(aTHX_ "msgsnd not implemented");
2153 #endif
2154 }
2155
2156 I32
2157 Perl_do_msgrcv(pTHX_ SV **mark, SV **sp)
2158 {
2159 #ifdef HAS_MSG
2160     dVAR;
2161     char *mbuf;
2162     long mtype;
2163     I32 msize, flags, ret;
2164     const I32 id = SvIVx(*++mark);
2165     SV * const mstr = *++mark;
2166
2167     PERL_ARGS_ASSERT_DO_MSGRCV;
2168     PERL_UNUSED_ARG(sp);
2169
2170     /* suppress warning when reading into undef var --jhi */
2171     if (! SvOK(mstr))
2172         sv_setpvs(mstr, "");
2173     msize = SvIVx(*++mark);
2174     mtype = (long)SvIVx(*++mark);
2175     flags = SvIVx(*++mark);
2176     SvPV_force_nolen(mstr);
2177     mbuf = SvGROW(mstr, sizeof(long)+msize+1);
2178
2179     SETERRNO(0,0);
2180     ret = msgrcv(id, (struct msgbuf *)mbuf, msize, mtype, flags);
2181     if (ret >= 0) {
2182         SvCUR_set(mstr, sizeof(long)+ret);
2183         *SvEND(mstr) = '\0';
2184 #ifndef INCOMPLETE_TAINTS
2185         /* who knows who has been playing with this message? */
2186         SvTAINTED_on(mstr);
2187 #endif
2188     }
2189     return ret;
2190 #else
2191     PERL_UNUSED_ARG(sp);
2192     PERL_UNUSED_ARG(mark);
2193     /* diag_listed_as: msg%s not implemented */
2194     Perl_croak(aTHX_ "msgrcv not implemented");
2195 #endif
2196 }
2197
2198 I32
2199 Perl_do_semop(pTHX_ SV **mark, SV **sp)
2200 {
2201 #ifdef HAS_SEM
2202     dVAR;
2203     STRLEN opsize;
2204     const I32 id = SvIVx(*++mark);
2205     SV * const opstr = *++mark;
2206     const char * const opbuf = SvPV_const(opstr, opsize);
2207
2208     PERL_ARGS_ASSERT_DO_SEMOP;
2209     PERL_UNUSED_ARG(sp);
2210
2211     if (opsize < 3 * SHORTSIZE
2212         || (opsize % (3 * SHORTSIZE))) {
2213         SETERRNO(EINVAL,LIB_INVARG);
2214         return -1;
2215     }
2216     SETERRNO(0,0);
2217     /* We can't assume that sizeof(struct sembuf) == 3 * sizeof(short). */
2218     {
2219         const int nsops  = opsize / (3 * sizeof (short));
2220         int i      = nsops;
2221         short * const ops = (short *) opbuf;
2222         short *o   = ops;
2223         struct sembuf *temps, *t;
2224         I32 result;
2225
2226         Newx (temps, nsops, struct sembuf);
2227         t = temps;
2228         while (i--) {
2229             t->sem_num = *o++;
2230             t->sem_op  = *o++;
2231             t->sem_flg = *o++;
2232             t++;
2233         }
2234         result = semop(id, temps, nsops);
2235         t = temps;
2236         o = ops;
2237         i = nsops;
2238         while (i--) {
2239             *o++ = t->sem_num;
2240             *o++ = t->sem_op;
2241             *o++ = t->sem_flg;
2242             t++;
2243         }
2244         Safefree(temps);
2245         return result;
2246     }
2247 #else
2248     /* diag_listed_as: sem%s not implemented */
2249     Perl_croak(aTHX_ "semop not implemented");
2250 #endif
2251 }
2252
2253 I32
2254 Perl_do_shmio(pTHX_ I32 optype, SV **mark, SV **sp)
2255 {
2256 #ifdef HAS_SHM
2257     dVAR;
2258     char *shm;
2259     struct shmid_ds shmds;
2260     const I32 id = SvIVx(*++mark);
2261     SV * const mstr = *++mark;
2262     const I32 mpos = SvIVx(*++mark);
2263     const I32 msize = SvIVx(*++mark);
2264
2265     PERL_ARGS_ASSERT_DO_SHMIO;
2266     PERL_UNUSED_ARG(sp);
2267
2268     SETERRNO(0,0);
2269     if (shmctl(id, IPC_STAT, &shmds) == -1)
2270         return -1;
2271     if (mpos < 0 || msize < 0
2272         || (size_t)mpos + msize > (size_t)shmds.shm_segsz) {
2273         SETERRNO(EFAULT,SS_ACCVIO);             /* can't do as caller requested */
2274         return -1;
2275     }
2276     shm = (char *)shmat(id, NULL, (optype == OP_SHMREAD) ? SHM_RDONLY : 0);
2277     if (shm == (char *)-1)      /* I hate System V IPC, I really do */
2278         return -1;
2279     if (optype == OP_SHMREAD) {
2280         char *mbuf;
2281         /* suppress warning when reading into undef var (tchrist 3/Mar/00) */
2282         if (! SvOK(mstr))
2283             sv_setpvs(mstr, "");
2284         SvUPGRADE(mstr, SVt_PV);
2285         SvPOK_only(mstr);
2286         mbuf = SvGROW(mstr, (STRLEN)msize+1);
2287
2288         Copy(shm + mpos, mbuf, msize, char);
2289         SvCUR_set(mstr, msize);
2290         *SvEND(mstr) = '\0';
2291         SvSETMAGIC(mstr);
2292 #ifndef INCOMPLETE_TAINTS
2293         /* who knows who has been playing with this shared memory? */
2294         SvTAINTED_on(mstr);
2295 #endif
2296     }
2297     else {
2298         STRLEN len;
2299
2300         const char *mbuf = SvPV_const(mstr, len);
2301         const I32 n = ((I32)len > msize) ? msize : (I32)len;
2302         Copy(mbuf, shm + mpos, n, char);
2303         if (n < msize)
2304             memzero(shm + mpos + n, msize - n);
2305     }
2306     return shmdt(shm);
2307 #else
2308     /* diag_listed_as: shm%s not implemented */
2309     Perl_croak(aTHX_ "shm I/O not implemented");
2310 #endif
2311 }
2312
2313 #endif /* SYSV IPC */
2314
2315 /*
2316 =head1 IO Functions
2317
2318 =for apidoc start_glob
2319
2320 Function called by C<do_readline> to spawn a glob (or do the glob inside
2321 perl on VMS). This code used to be inline, but now perl uses C<File::Glob>
2322 this glob starter is only used by miniperl during the build process.
2323 Moving it away shrinks pp_hot.c; shrinking pp_hot.c helps speed perl up.
2324
2325 =cut
2326 */
2327
2328 PerlIO *
2329 Perl_start_glob (pTHX_ SV *tmpglob, IO *io)
2330 {
2331     dVAR;
2332     SV * const tmpcmd = newSV(0);
2333     PerlIO *fp;
2334
2335     PERL_ARGS_ASSERT_START_GLOB;
2336
2337     ENTER;
2338     SAVEFREESV(tmpcmd);
2339 #ifdef VMS /* expand the wildcards right here, rather than opening a pipe, */
2340            /* since spawning off a process is a real performance hit */
2341
2342 PerlIO * 
2343 Perl_vms_start_glob
2344    (pTHX_ SV *tmpglob,
2345     IO *io);
2346
2347     fp = Perl_vms_start_glob(aTHX_ tmpglob, io);
2348
2349 #else /* !VMS */
2350 #ifdef DOSISH
2351 #ifdef OS2
2352     sv_setpv(tmpcmd, "for a in ");
2353     sv_catsv(tmpcmd, tmpglob);
2354     sv_catpv(tmpcmd, "; do echo \"$a\\0\\c\"; done |");
2355 #else
2356 #ifdef DJGPP
2357     sv_setpv(tmpcmd, "/dev/dosglob/"); /* File System Extension */
2358     sv_catsv(tmpcmd, tmpglob);
2359 #else
2360     sv_setpv(tmpcmd, "perlglob ");
2361     sv_catsv(tmpcmd, tmpglob);
2362     sv_catpv(tmpcmd, " |");
2363 #endif /* !DJGPP */
2364 #endif /* !OS2 */
2365 #else /* !DOSISH */
2366 #if defined(CSH)
2367     sv_setpvn(tmpcmd, PL_cshname, PL_cshlen);
2368     sv_catpv(tmpcmd, " -cf 'set nonomatch; glob ");
2369     sv_catsv(tmpcmd, tmpglob);
2370     sv_catpv(tmpcmd, "' 2>/dev/null |");
2371 #else
2372     sv_setpv(tmpcmd, "echo ");
2373     sv_catsv(tmpcmd, tmpglob);
2374 #if 'z' - 'a' == 25
2375     sv_catpv(tmpcmd, "|tr -s ' \t\f\r' '\\012\\012\\012\\012'|");
2376 #else
2377     sv_catpv(tmpcmd, "|tr -s ' \t\f\r' '\\n\\n\\n\\n'|");
2378 #endif
2379 #endif /* !CSH */
2380 #endif /* !DOSISH */
2381     {
2382         GV * const envgv = gv_fetchpvs("ENV", 0, SVt_PVHV);
2383         SV ** const home = hv_fetchs(GvHV(envgv), "HOME", 0);
2384         if (home && *home) SvGETMAGIC(*home);
2385         save_hash(gv_fetchpvs("ENV", 0, SVt_PVHV));
2386         if (home && *home) SvSETMAGIC(*home);
2387     }
2388     (void)do_open(PL_last_in_gv, (char*)SvPVX_const(tmpcmd), SvCUR(tmpcmd),
2389                   FALSE, O_RDONLY, 0, NULL);
2390     fp = IoIFP(io);
2391 #endif /* !VMS */
2392     LEAVE;
2393     return fp;
2394 }
2395
2396 /*
2397  * Local variables:
2398  * c-indentation-style: bsd
2399  * c-basic-offset: 4
2400  * indent-tabs-mode: t
2401  * End:
2402  *
2403  * ex: set ts=8 sts=4 sw=4 noet:
2404  */