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