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