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