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