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