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