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