Make Perl_gv_fetchpvn_flags actually heed the passed in length.
[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_fetchpvn_flags(type, tend - type,
340                                                        0, SVt_PVIO);
341                             thatio = GvIO(thatgv);
342                         }
343                         if (!thatio) {
344 #ifdef EINVAL
345                             SETERRNO(EINVAL,SS_IVCHAN);
346 #endif
347                             goto say_false;
348                         }
349                         if ((that_fp = IoIFP(thatio))) {
350                             /* Flush stdio buffer before dup. --mjd
351                              * Unfortunately SEEK_CURing 0 seems to
352                              * be optimized away on most platforms;
353                              * only Solaris and Linux seem to flush
354                              * on that. --jhi */
355 #ifdef USE_SFIO
356                             /* sfio fails to clear error on next
357                                sfwrite, contrary to documentation.
358                                -- Nicholas Clark */
359                             if (PerlIO_seek(that_fp, 0, SEEK_CUR) == -1)
360                                 PerlIO_clearerr(that_fp);
361 #endif
362                             /* On the other hand, do all platforms
363                              * take gracefully to flushing a read-only
364                              * filehandle?  Perhaps we should do
365                              * fsetpos(src)+fgetpos(dst)?  --nik */
366                             PerlIO_flush(that_fp);
367                             fd = PerlIO_fileno(that_fp);
368                             /* When dup()ing STDIN, STDOUT or STDERR
369                              * explicitly set appropriate access mode */
370                             if (that_fp == PerlIO_stdout()
371                                 || that_fp == PerlIO_stderr())
372                                 IoTYPE(io) = IoTYPE_WRONLY;
373                             else if (that_fp == PerlIO_stdin())
374                                 IoTYPE(io) = IoTYPE_RDONLY;
375                             /* When dup()ing a socket, say result is
376                              * one as well */
377                             else if (IoTYPE(thatio) == IoTYPE_SOCKET)
378                                 IoTYPE(io) = IoTYPE_SOCKET;
379                         }
380                         else
381                             fd = -1;
382                     }
383                     if (!num_svs)
384                         type = Nullch;
385                     if (that_fp) {
386                         fp = PerlIO_fdupopen(aTHX_ that_fp, NULL, dodup);
387                     }
388                     else {
389                         if (dodup)
390                             fd = PerlLIO_dup(fd);
391                         else
392                             was_fdopen = TRUE;
393                         if (!(fp = PerlIO_openn(aTHX_ type,mode,fd,0,0,NULL,num_svs,svp))) {
394                             if (dodup && fd >= 0)
395                                 PerlLIO_close(fd);
396                         }
397                     }
398                 }
399             } /* & */
400             else {
401                 for (; isSPACE(*type); type++) ;
402                 if (*type == IoTYPE_STD && (!type[1] || isSPACE(type[1]) || type[1] == ':')) {
403                     type++;
404                     fp = PerlIO_stdout();
405                     IoTYPE(io) = IoTYPE_STD;
406                     if (num_svs > 1) {
407                         Perl_croak(aTHX_ "More than one argument to '>%c' open",IoTYPE_STD);
408                     }
409                 }
410                 else  {
411                     if (!num_svs) {
412                         namesv = sv_2mortal(newSVpvn(type,tend - type));
413                         num_svs = 1;
414                         svp = &namesv;
415                         type = Nullch;
416                     }
417                     fp = PerlIO_openn(aTHX_ type,mode,-1,0,0,NULL,num_svs,svp);
418                 }
419             } /* !& */
420             if (!fp && type && *type && *type != ':' && !isIDFIRST(*type))
421                goto unknown_open_mode;
422         } /* IoTYPE_WRONLY */
423         else if (*type == IoTYPE_RDONLY) {
424             for (type++; isSPACE(*type); type++) ;
425             mode[0] = 'r';
426 #ifdef HAS_STRLCAT
427             if (in_raw)
428                 strlcat(mode, "b", PERL_MODE_MAX);
429             else if (in_crlf)
430                 strlcat(mode, "t", PERL_MODE_MAX);
431 #else
432             if (in_raw)
433                 strcat(mode, "b");
434             else if (in_crlf)
435                 strcat(mode, "t");
436 #endif
437             if (*type == '&') {
438                 goto duplicity;
439             }
440             if (*type == IoTYPE_STD && (!type[1] || isSPACE(type[1]) || type[1] == ':')) {
441                 type++;
442                 fp = PerlIO_stdin();
443                 IoTYPE(io) = IoTYPE_STD;
444                 if (num_svs > 1) {
445                     Perl_croak(aTHX_ "More than one argument to '<%c' open",IoTYPE_STD);
446                 }
447             }
448             else {
449                 if (!num_svs) {
450                     namesv = sv_2mortal(newSVpvn(type,tend - type));
451                     num_svs = 1;
452                     svp = &namesv;
453                     type = Nullch;
454                 }
455                 fp = PerlIO_openn(aTHX_ type,mode,-1,0,0,NULL,num_svs,svp);
456             }
457             if (!fp && type && *type && *type != ':' && !isIDFIRST(*type))
458                goto unknown_open_mode;
459         } /* IoTYPE_RDONLY */
460         else if ((num_svs && /* '-|...' or '...|' */
461                   type[0] == IoTYPE_STD && type[1] == IoTYPE_PIPE) ||
462                  (!num_svs && tend > type+1 && tend[-1] == IoTYPE_PIPE)) {
463             if (num_svs) {
464                 type += 2;   /* skip over '-|' */
465             }
466             else {
467                 *--tend = '\0';
468                 while (tend > type && isSPACE(tend[-1]))
469                     *--tend = '\0';
470                 for (; isSPACE(*type); type++)
471                     ;
472                 name = type;
473                 len  = tend-type;
474             }
475             if (*name == '\0') {
476                 /* command is missing 19990114 */
477                 if (ckWARN(WARN_PIPE))
478                     Perl_warner(aTHX_ packWARN(WARN_PIPE), "Missing command in piped open");
479                 errno = EPIPE;
480                 goto say_false;
481             }
482             if (!(*name == '-' && name[1] == '\0') || num_svs)
483                 TAINT_ENV();
484             TAINT_PROPER("piped open");
485             mode[0] = 'r';
486
487 #ifdef HAS_STRLCAT
488             if (in_raw)
489                 strlcat(mode, "b", PERL_MODE_MAX);
490             else if (in_crlf)
491                 strlcat(mode, "t", PERL_MODE_MAX);
492 #else
493             if (in_raw)
494                 strcat(mode, "b");
495             else if (in_crlf)
496                 strcat(mode, "t");
497 #endif
498
499             if (num_svs > 1) {
500                 fp = PerlProc_popen_list(mode,num_svs,svp);
501             }
502             else {
503                 fp = PerlProc_popen(name,mode);
504             }
505             IoTYPE(io) = IoTYPE_PIPE;
506             if (num_svs) {
507                 for (; isSPACE(*type); type++) ;
508                 if (*type) {
509                     if (PerlIO_apply_layers(aTHX_ fp, mode, type) != 0) {
510                         goto say_false;
511                     }
512                 }
513             }
514         }
515         else { /* layer(Args) */
516             if (num_svs)
517                 goto unknown_open_mode;
518             name = type;
519             IoTYPE(io) = IoTYPE_RDONLY;
520             for (; isSPACE(*name); name++)
521                 ;
522             mode[0] = 'r';
523
524 #ifdef HAS_STRLCAT
525             if (in_raw)
526                 strlcat(mode, "b", PERL_MODE_MAX);
527             else if (in_crlf)
528                 strlcat(mode, "t", PERL_MODE_MAX);
529 #else
530             if (in_raw)
531                 strcat(mode, "b");
532             else if (in_crlf)
533                 strcat(mode, "t");
534 #endif
535
536             if (*name == '-' && name[1] == '\0') {
537                 fp = PerlIO_stdin();
538                 IoTYPE(io) = IoTYPE_STD;
539             }
540             else {
541                 if (!num_svs) {
542                     namesv = sv_2mortal(newSVpvn(type,tend - type));
543                     num_svs = 1;
544                     svp = &namesv;
545                     type = Nullch;
546                 }
547                 fp = PerlIO_openn(aTHX_ type,mode,-1,0,0,NULL,num_svs,svp);
548             }
549         }
550     }
551     if (!fp) {
552         if (IoTYPE(io) == IoTYPE_RDONLY && ckWARN(WARN_NEWLINE)
553             && strchr(oname, '\n')
554             
555         )
556             Perl_warner(aTHX_ packWARN(WARN_NEWLINE), PL_warn_nl, "open");
557         goto say_false;
558     }
559
560     if (ckWARN(WARN_IO)) {
561         if ((IoTYPE(io) == IoTYPE_RDONLY) &&
562             (fp == PerlIO_stdout() || fp == PerlIO_stderr())) {
563                 Perl_warner(aTHX_ packWARN(WARN_IO),
564                             "Filehandle STD%s reopened as %s only for input",
565                             ((fp == PerlIO_stdout()) ? "OUT" : "ERR"),
566                             GvENAME(gv));
567         }
568         else if ((IoTYPE(io) == IoTYPE_WRONLY) && fp == PerlIO_stdin()) {
569                 Perl_warner(aTHX_ packWARN(WARN_IO),
570                             "Filehandle STDIN reopened as %s only for output",
571                             GvENAME(gv));
572         }
573     }
574
575     fd = PerlIO_fileno(fp);
576     /* If there is no fd (e.g. PerlIO::scalar) assume it isn't a
577      * socket - this covers PerlIO::scalar - otherwise unless we "know" the
578      * type probe for socket-ness.
579      */
580     if (IoTYPE(io) && IoTYPE(io) != IoTYPE_PIPE && IoTYPE(io) != IoTYPE_STD && fd >= 0) {
581         if (PerlLIO_fstat(fd,&PL_statbuf) < 0) {
582             /* If PerlIO claims to have fd we had better be able to fstat() it. */
583             (void) PerlIO_close(fp);
584             goto say_false;
585         }
586 #ifndef PERL_MICRO
587         if (S_ISSOCK(PL_statbuf.st_mode))
588             IoTYPE(io) = IoTYPE_SOCKET; /* in case a socket was passed in to us */
589 #ifdef HAS_SOCKET
590         else if (
591 #ifdef S_IFMT
592             !(PL_statbuf.st_mode & S_IFMT)
593 #else
594             !PL_statbuf.st_mode
595 #endif
596             && IoTYPE(io) != IoTYPE_WRONLY  /* Dups of STD* filehandles already have */
597             && IoTYPE(io) != IoTYPE_RDONLY  /* type so they aren't marked as sockets */
598         ) {                                 /* on OS's that return 0 on fstat()ed pipe */
599              char tmpbuf[256];
600              Sock_size_t buflen = sizeof tmpbuf;
601              if (PerlSock_getsockname(fd, (struct sockaddr *)tmpbuf, &buflen) >= 0
602                       || errno != ENOTSOCK)
603                     IoTYPE(io) = IoTYPE_SOCKET; /* some OS's return 0 on fstat()ed socket */
604                                                 /* but some return 0 for streams too, sigh */
605         }
606 #endif /* HAS_SOCKET */
607 #endif /* !PERL_MICRO */
608     }
609
610     /* Eeek - FIXME !!!
611      * If this is a standard handle we discard all the layer stuff
612      * and just dup the fd into whatever was on the handle before !
613      */
614
615     if (saveifp) {              /* must use old fp? */
616         /* If fd is less that PL_maxsysfd i.e. STDIN..STDERR
617            then dup the new fileno down
618          */
619         if (saveofp) {
620             PerlIO_flush(saveofp);      /* emulate PerlIO_close() */
621             if (saveofp != saveifp) {   /* was a socket? */
622                 PerlIO_close(saveofp);
623             }
624         }
625         if (savefd != fd) {
626             /* Still a small can-of-worms here if (say) PerlIO::scalar
627                is assigned to (say) STDOUT - for now let dup2() fail
628                and provide the error
629              */
630             if (PerlLIO_dup2(fd, savefd) < 0) {
631                 (void)PerlIO_close(fp);
632                 goto say_false;
633             }
634 #ifdef VMS
635             if (savefd != PerlIO_fileno(PerlIO_stdin())) {
636                 char newname[FILENAME_MAX+1];
637                 if (PerlIO_getname(fp, newname)) {
638                     if (fd == PerlIO_fileno(PerlIO_stdout()))
639                         Perl_vmssetuserlnm(aTHX_ "SYS$OUTPUT", newname);
640                     if (fd == PerlIO_fileno(PerlIO_stderr()))
641                         Perl_vmssetuserlnm(aTHX_ "SYS$ERROR",  newname);
642                 }
643             }
644 #endif
645
646 #if !defined(WIN32)
647            /* PL_fdpid isn't used on Windows, so avoid this useless work.
648             * XXX Probably the same for a lot of other places. */
649             {
650                 Pid_t pid;
651                 SV *sv;
652
653                 LOCK_FDPID_MUTEX;
654                 sv = *av_fetch(PL_fdpid,fd,TRUE);
655                 SvUPGRADE(sv, SVt_IV);
656                 pid = SvIVX(sv);
657                 SvIV_set(sv, 0);
658                 sv = *av_fetch(PL_fdpid,savefd,TRUE);
659                 SvUPGRADE(sv, SVt_IV);
660                 SvIV_set(sv, pid);
661                 UNLOCK_FDPID_MUTEX;
662             }
663 #endif
664
665             if (was_fdopen) {
666                 /* need to close fp without closing underlying fd */
667                 int ofd = PerlIO_fileno(fp);
668                 int dupfd = PerlLIO_dup(ofd);
669 #if defined(HAS_FCNTL) && defined(F_SETFD)
670                 /* Assume if we have F_SETFD we have F_GETFD */
671                 int coe = fcntl(ofd,F_GETFD);
672 #endif
673                 PerlIO_close(fp);
674                 PerlLIO_dup2(dupfd,ofd);
675 #if defined(HAS_FCNTL) && defined(F_SETFD)
676                 /* The dup trick has lost close-on-exec on ofd */
677                 fcntl(ofd,F_SETFD, coe);
678 #endif
679                 PerlLIO_close(dupfd);
680             }
681             else
682                 PerlIO_close(fp);
683         }
684         fp = saveifp;
685         PerlIO_clearerr(fp);
686         fd = PerlIO_fileno(fp);
687     }
688 #if defined(HAS_FCNTL) && defined(F_SETFD)
689     if (fd >= 0) {
690         const int save_errno = errno;
691         fcntl(fd,F_SETFD,fd > PL_maxsysfd); /* can change errno */
692         errno = save_errno;
693     }
694 #endif
695     IoIFP(io) = fp;
696
697     IoFLAGS(io) &= ~IOf_NOLINE;
698     if (writing) {
699         if (IoTYPE(io) == IoTYPE_SOCKET
700             || (IoTYPE(io) == IoTYPE_WRONLY && fd >= 0 && S_ISCHR(PL_statbuf.st_mode)) ) {
701             char *s = mode;
702             if (*s == IoTYPE_IMPLICIT || *s == IoTYPE_NUMERIC)
703               s++;
704             *s = 'w';
705             if (!(IoOFP(io) = PerlIO_openn(aTHX_ type,s,fd,0,0,NULL,0,svp))) {
706                 PerlIO_close(fp);
707                 IoIFP(io) = Nullfp;
708                 goto say_false;
709             }
710         }
711         else
712             IoOFP(io) = fp;
713     }
714     return TRUE;
715
716 say_false:
717     IoIFP(io) = saveifp;
718     IoOFP(io) = saveofp;
719     IoTYPE(io) = savetype;
720     return FALSE;
721 }
722
723 PerlIO *
724 Perl_nextargv(pTHX_ register GV *gv)
725 {
726     dVAR;
727     register SV *sv;
728 #ifndef FLEXFILENAMES
729     int filedev;
730     int fileino;
731 #endif
732     Uid_t fileuid;
733     Gid_t filegid;
734     IO * const io = GvIOp(gv);
735
736     if (!PL_argvoutgv)
737         PL_argvoutgv = gv_fetchpvs("ARGVOUT",TRUE,SVt_PVIO);
738     if (io && (IoFLAGS(io) & IOf_ARGV) && (IoFLAGS(io) & IOf_START)) {
739         IoFLAGS(io) &= ~IOf_START;
740         if (PL_inplace) {
741             if (!PL_argvout_stack)
742                 PL_argvout_stack = newAV();
743             av_push(PL_argvout_stack, SvREFCNT_inc(PL_defoutgv));
744         }
745     }
746     if (PL_filemode & (S_ISUID|S_ISGID)) {
747         PerlIO_flush(IoIFP(GvIOn(PL_argvoutgv)));  /* chmod must follow last write */
748 #ifdef HAS_FCHMOD
749         if (PL_lastfd != -1)
750             (void)fchmod(PL_lastfd,PL_filemode);
751 #else
752         (void)PerlLIO_chmod(PL_oldname,PL_filemode);
753 #endif
754     }
755     PL_lastfd = -1;
756     PL_filemode = 0;
757     if (!GvAV(gv))
758         return Nullfp;
759     while (av_len(GvAV(gv)) >= 0) {
760         STRLEN oldlen;
761         sv = av_shift(GvAV(gv));
762         SAVEFREESV(sv);
763         sv_setsv(GvSVn(gv),sv);
764         SvSETMAGIC(GvSV(gv));
765         PL_oldname = SvPVx(GvSV(gv), oldlen);
766         if (do_open(gv,PL_oldname,oldlen,PL_inplace!=0,O_RDONLY,0,Nullfp)) {
767             if (PL_inplace) {
768                 TAINT_PROPER("inplace open");
769                 if (oldlen == 1 && *PL_oldname == '-') {
770                     setdefout(gv_fetchpvs("STDOUT",TRUE,SVt_PVIO));
771                     return IoIFP(GvIOp(gv));
772                 }
773 #ifndef FLEXFILENAMES
774                 filedev = PL_statbuf.st_dev;
775                 fileino = PL_statbuf.st_ino;
776 #endif
777                 PL_filemode = PL_statbuf.st_mode;
778                 fileuid = PL_statbuf.st_uid;
779                 filegid = PL_statbuf.st_gid;
780                 if (!S_ISREG(PL_filemode)) {
781                     if (ckWARN_d(WARN_INPLACE)) 
782                         Perl_warner(aTHX_ packWARN(WARN_INPLACE),
783                             "Can't do inplace edit: %s is not a regular file",
784                             PL_oldname );
785                     do_close(gv,FALSE);
786                     continue;
787                 }
788                 if (*PL_inplace) {
789                     const char *star = strchr(PL_inplace, '*');
790                     if (star) {
791                         const char *begin = PL_inplace;
792                         sv_setpvn(sv, "", 0);
793                         do {
794                             sv_catpvn(sv, begin, star - begin);
795                             sv_catpvn(sv, PL_oldname, oldlen);
796                             begin = ++star;
797                         } while ((star = strchr(begin, '*')));
798                         if (*begin)
799                             sv_catpv(sv,begin);
800                     }
801                     else {
802                         sv_catpv(sv,PL_inplace);
803                     }
804 #ifndef FLEXFILENAMES
805                     if ((PerlLIO_stat(SvPVX_const(sv),&PL_statbuf) >= 0
806                          && PL_statbuf.st_dev == filedev
807                          && PL_statbuf.st_ino == fileino)
808 #ifdef DJGPP
809                         || ((_djstat_fail_bits & _STFAIL_TRUENAME)!=0)
810 #endif
811                       )
812                     {
813                         if (ckWARN_d(WARN_INPLACE))     
814                             Perl_warner(aTHX_ packWARN(WARN_INPLACE),
815                               "Can't do inplace edit: %"SVf" would not be unique",
816                               sv);
817                         do_close(gv,FALSE);
818                         continue;
819                     }
820 #endif
821 #ifdef HAS_RENAME
822 #if !defined(DOSISH) && !defined(__CYGWIN__) && !defined(EPOC)
823                     if (PerlLIO_rename(PL_oldname,SvPVX_const(sv)) < 0) {
824                         if (ckWARN_d(WARN_INPLACE))     
825                             Perl_warner(aTHX_ packWARN(WARN_INPLACE),
826                               "Can't rename %s to %"SVf": %s, skipping file",
827                               PL_oldname, sv, Strerror(errno) );
828                         do_close(gv,FALSE);
829                         continue;
830                     }
831 #else
832                     do_close(gv,FALSE);
833                     (void)PerlLIO_unlink(SvPVX_const(sv));
834                     (void)PerlLIO_rename(PL_oldname,SvPVX_const(sv));
835                     do_open(gv,(char*)SvPVX_const(sv),SvCUR(sv),PL_inplace!=0,
836                             O_RDONLY,0,Nullfp);
837 #endif /* DOSISH */
838 #else
839                     (void)UNLINK(SvPVX_const(sv));
840                     if (link(PL_oldname,SvPVX_const(sv)) < 0) {
841                         if (ckWARN_d(WARN_INPLACE))     
842                             Perl_warner(aTHX_ packWARN(WARN_INPLACE),
843                               "Can't rename %s to %"SVf": %s, skipping file",
844                               PL_oldname, sv, Strerror(errno) );
845                         do_close(gv,FALSE);
846                         continue;
847                     }
848                     (void)UNLINK(PL_oldname);
849 #endif
850                 }
851                 else {
852 #if !defined(DOSISH) && !defined(AMIGAOS)
853 #  ifndef VMS  /* Don't delete; use automatic file versioning */
854                     if (UNLINK(PL_oldname) < 0) {
855                         if (ckWARN_d(WARN_INPLACE))     
856                             Perl_warner(aTHX_ packWARN(WARN_INPLACE),
857                               "Can't remove %s: %s, skipping file",
858                               PL_oldname, Strerror(errno) );
859                         do_close(gv,FALSE);
860                         continue;
861                     }
862 #  endif
863 #else
864                     Perl_croak(aTHX_ "Can't do inplace edit without backup");
865 #endif
866                 }
867
868                 sv_setpvn(sv,">",!PL_inplace);
869                 sv_catpvn(sv,PL_oldname,oldlen);
870                 SETERRNO(0,0);          /* in case sprintf set errno */
871 #ifdef VMS
872                 if (!do_open(PL_argvoutgv,(char*)SvPVX_const(sv),SvCUR(sv),
873                              PL_inplace!=0,O_WRONLY|O_CREAT|O_TRUNC,0,Nullfp))
874 #else
875                     if (!do_open(PL_argvoutgv,(char*)SvPVX_const(sv),SvCUR(sv),
876                              PL_inplace!=0,O_WRONLY|O_CREAT|OPEN_EXCL,0666,
877                              Nullfp))
878 #endif
879                 {
880                     if (ckWARN_d(WARN_INPLACE)) 
881                         Perl_warner(aTHX_ packWARN(WARN_INPLACE), "Can't do inplace edit on %s: %s",
882                           PL_oldname, Strerror(errno) );
883                     do_close(gv,FALSE);
884                     continue;
885                 }
886                 setdefout(PL_argvoutgv);
887                 PL_lastfd = PerlIO_fileno(IoIFP(GvIOp(PL_argvoutgv)));
888                 (void)PerlLIO_fstat(PL_lastfd,&PL_statbuf);
889 #ifdef HAS_FCHMOD
890                 (void)fchmod(PL_lastfd,PL_filemode);
891 #else
892 #  if !(defined(WIN32) && defined(__BORLANDC__))
893                 /* Borland runtime creates a readonly file! */
894                 (void)PerlLIO_chmod(PL_oldname,PL_filemode);
895 #  endif
896 #endif
897                 if (fileuid != PL_statbuf.st_uid || filegid != PL_statbuf.st_gid) {
898 #ifdef HAS_FCHOWN
899                     (void)fchown(PL_lastfd,fileuid,filegid);
900 #else
901 #ifdef HAS_CHOWN
902                     (void)PerlLIO_chown(PL_oldname,fileuid,filegid);
903 #endif
904 #endif
905                 }
906             }
907             return IoIFP(GvIOp(gv));
908         }
909         else {
910             if (ckWARN_d(WARN_INPLACE)) {
911                 const int eno = errno;
912                 if (PerlLIO_stat(PL_oldname, &PL_statbuf) >= 0
913                     && !S_ISREG(PL_statbuf.st_mode))    
914                 {
915                     Perl_warner(aTHX_ packWARN(WARN_INPLACE),
916                                 "Can't do inplace edit: %s is not a regular file",
917                                 PL_oldname);
918                 }
919                 else
920                     Perl_warner(aTHX_ packWARN(WARN_INPLACE), "Can't open %s: %s",
921                                 PL_oldname, Strerror(eno));
922             }
923         }
924     }
925     if (io && (IoFLAGS(io) & IOf_ARGV))
926         IoFLAGS(io) |= IOf_START;
927     if (PL_inplace) {
928         (void)do_close(PL_argvoutgv,FALSE);
929         if (io && (IoFLAGS(io) & IOf_ARGV)
930             && PL_argvout_stack && AvFILLp(PL_argvout_stack) >= 0)
931         {
932             GV *oldout = (GV*)av_pop(PL_argvout_stack);
933             setdefout(oldout);
934             SvREFCNT_dec(oldout);
935             return Nullfp;
936         }
937         setdefout(gv_fetchpvs("STDOUT",TRUE,SVt_PVIO));
938     }
939     return Nullfp;
940 }
941
942 /* explicit renamed to avoid C++ conflict    -- kja */
943 bool
944 Perl_do_close(pTHX_ GV *gv, bool not_implicit)
945 {
946     dVAR;
947     bool retval;
948     IO *io;
949
950     if (!gv)
951         gv = PL_argvgv;
952     if (!gv || SvTYPE(gv) != SVt_PVGV) {
953         if (not_implicit)
954             SETERRNO(EBADF,SS_IVCHAN);
955         return FALSE;
956     }
957     io = GvIO(gv);
958     if (!io) {          /* never opened */
959         if (not_implicit) {
960             if (ckWARN(WARN_UNOPENED)) /* no check for closed here */
961                 report_evil_fh(gv, io, PL_op->op_type);
962             SETERRNO(EBADF,SS_IVCHAN);
963         }
964         return FALSE;
965     }
966     retval = io_close(io, not_implicit);
967     if (not_implicit) {
968         IoLINES(io) = 0;
969         IoPAGE(io) = 0;
970         IoLINES_LEFT(io) = IoPAGE_LEN(io);
971     }
972     IoTYPE(io) = IoTYPE_CLOSED;
973     return retval;
974 }
975
976 bool
977 Perl_io_close(pTHX_ IO *io, bool not_implicit)
978 {
979     dVAR;
980     bool retval = FALSE;
981
982     if (IoIFP(io)) {
983         if (IoTYPE(io) == IoTYPE_PIPE) {
984             const int status = PerlProc_pclose(IoIFP(io));
985             if (not_implicit) {
986                 STATUS_NATIVE_CHILD_SET(status);
987                 retval = (STATUS_UNIX == 0);
988             }
989             else {
990                 retval = (status != -1);
991             }
992         }
993         else if (IoTYPE(io) == IoTYPE_STD)
994             retval = TRUE;
995         else {
996             if (IoOFP(io) && IoOFP(io) != IoIFP(io)) {          /* a socket */
997                 const bool prev_err = PerlIO_error(IoOFP(io));
998                 retval = (PerlIO_close(IoOFP(io)) != EOF && !prev_err);
999                 PerlIO_close(IoIFP(io));        /* clear stdio, fd already closed */
1000             }
1001             else {
1002                 const bool prev_err = PerlIO_error(IoIFP(io));
1003                 retval = (PerlIO_close(IoIFP(io)) != EOF && !prev_err);
1004             }
1005         }
1006         IoOFP(io) = IoIFP(io) = Nullfp;
1007     }
1008     else if (not_implicit) {
1009         SETERRNO(EBADF,SS_IVCHAN);
1010     }
1011
1012     return retval;
1013 }
1014
1015 bool
1016 Perl_do_eof(pTHX_ GV *gv)
1017 {
1018     dVAR;
1019     register IO * const io = GvIO(gv);
1020
1021     if (!io)
1022         return TRUE;
1023     else if ((IoTYPE(io) == IoTYPE_WRONLY) && ckWARN(WARN_IO))
1024         report_evil_fh(gv, io, OP_phoney_OUTPUT_ONLY);
1025
1026     while (IoIFP(io)) {
1027         if (PerlIO_has_cntptr(IoIFP(io))) {     /* (the code works without this) */
1028             if (PerlIO_get_cnt(IoIFP(io)) > 0)  /* cheat a little, since */
1029                 return FALSE;                   /* this is the most usual case */
1030         }
1031
1032         {
1033              /* getc and ungetc can stomp on errno */
1034             const int saverrno = errno;
1035             const int ch = PerlIO_getc(IoIFP(io));
1036             if (ch != EOF) {
1037                 (void)PerlIO_ungetc(IoIFP(io),ch);
1038                 errno = saverrno;
1039                 return FALSE;
1040             }
1041             errno = saverrno;
1042         }
1043
1044         if (PerlIO_has_cntptr(IoIFP(io)) && PerlIO_canset_cnt(IoIFP(io))) {
1045             if (PerlIO_get_cnt(IoIFP(io)) < -1)
1046                 PerlIO_set_cnt(IoIFP(io),-1);
1047         }
1048         if (PL_op->op_flags & OPf_SPECIAL) { /* not necessarily a real EOF yet? */
1049             if (gv != PL_argvgv || !nextargv(gv))       /* get another fp handy */
1050                 return TRUE;
1051         }
1052         else
1053             return TRUE;                /* normal fp, definitely end of file */
1054     }
1055     return TRUE;
1056 }
1057
1058 Off_t
1059 Perl_do_tell(pTHX_ GV *gv)
1060 {
1061     dVAR;
1062     register IO *io = NULL;
1063     register PerlIO *fp;
1064
1065     if (gv && (io = GvIO(gv)) && (fp = IoIFP(io))) {
1066 #ifdef ULTRIX_STDIO_BOTCH
1067         if (PerlIO_eof(fp))
1068             (void)PerlIO_seek(fp, 0L, 2);       /* ultrix 1.2 workaround */
1069 #endif
1070         return PerlIO_tell(fp);
1071     }
1072     if (ckWARN2(WARN_UNOPENED,WARN_CLOSED))
1073         report_evil_fh(gv, io, PL_op->op_type);
1074     SETERRNO(EBADF,RMS_IFI);
1075     return (Off_t)-1;
1076 }
1077
1078 bool
1079 Perl_do_seek(pTHX_ GV *gv, Off_t pos, int whence)
1080 {
1081     dVAR;
1082     register IO *io = NULL;
1083     register PerlIO *fp;
1084
1085     if (gv && (io = GvIO(gv)) && (fp = IoIFP(io))) {
1086 #ifdef ULTRIX_STDIO_BOTCH
1087         if (PerlIO_eof(fp))
1088             (void)PerlIO_seek(fp, 0L, 2);       /* ultrix 1.2 workaround */
1089 #endif
1090         return PerlIO_seek(fp, pos, whence) >= 0;
1091     }
1092     if (ckWARN2(WARN_UNOPENED,WARN_CLOSED))
1093         report_evil_fh(gv, io, PL_op->op_type);
1094     SETERRNO(EBADF,RMS_IFI);
1095     return FALSE;
1096 }
1097
1098 Off_t
1099 Perl_do_sysseek(pTHX_ GV *gv, Off_t pos, int whence)
1100 {
1101     dVAR;
1102     register IO *io = NULL;
1103     register PerlIO *fp;
1104
1105     if (gv && (io = GvIO(gv)) && (fp = IoIFP(io)))
1106         return PerlLIO_lseek(PerlIO_fileno(fp), pos, whence);
1107     if (ckWARN2(WARN_UNOPENED,WARN_CLOSED))
1108         report_evil_fh(gv, io, PL_op->op_type);
1109     SETERRNO(EBADF,RMS_IFI);
1110     return (Off_t)-1;
1111 }
1112
1113 int
1114 Perl_mode_from_discipline(pTHX_ SV *discp)
1115 {
1116     int mode = O_BINARY;
1117     if (discp) {
1118         STRLEN len;
1119         const char *s = SvPV_const(discp,len);
1120         while (*s) {
1121             if (*s == ':') {
1122                 switch (s[1]) {
1123                 case 'r':
1124                     if (s[2] == 'a' && s[3] == 'w'
1125                         && (!s[4] || s[4] == ':' || isSPACE(s[4])))
1126                     {
1127                         mode = O_BINARY;
1128                         s += 4;
1129                         len -= 4;
1130                         break;
1131                     }
1132                     /* FALL THROUGH */
1133                 case 'c':
1134                     if (s[2] == 'r' && s[3] == 'l' && s[4] == 'f'
1135                         && (!s[5] || s[5] == ':' || isSPACE(s[5])))
1136                     {
1137                         mode = O_TEXT;
1138                         s += 5;
1139                         len -= 5;
1140                         break;
1141                     }
1142                     /* FALL THROUGH */
1143                 default:
1144                     goto fail_discipline;
1145                 }
1146             }
1147             else if (isSPACE(*s)) {
1148                 ++s;
1149                 --len;
1150             }
1151             else {
1152                 const char *end;
1153 fail_discipline:
1154                 end = strchr(s+1, ':');
1155                 if (!end)
1156                     end = s+len;
1157 #ifndef PERLIO_LAYERS
1158                 Perl_croak(aTHX_ "IO layers (like '%.*s') unavailable", end-s, s);
1159 #else
1160                 len -= end-s;
1161                 s = end;
1162 #endif
1163             }
1164         }
1165     }
1166     return mode;
1167 }
1168
1169 #if !defined(HAS_TRUNCATE) && !defined(HAS_CHSIZE)
1170 I32
1171 my_chsize(int fd, Off_t length)
1172 {
1173 #ifdef F_FREESP
1174         /* code courtesy of William Kucharski */
1175 #define HAS_CHSIZE
1176
1177     struct flock fl;
1178     Stat_t filebuf;
1179
1180     if (PerlLIO_fstat(fd, &filebuf) < 0)
1181         return -1;
1182
1183     if (filebuf.st_size < length) {
1184
1185         /* extend file length */
1186
1187         if ((PerlLIO_lseek(fd, (length - 1), 0)) < 0)
1188             return -1;
1189
1190         /* write a "0" byte */
1191
1192         if ((PerlLIO_write(fd, "", 1)) != 1)
1193             return -1;
1194     }
1195     else {
1196         /* truncate length */
1197
1198         fl.l_whence = 0;
1199         fl.l_len = 0;
1200         fl.l_start = length;
1201         fl.l_type = F_WRLCK;    /* write lock on file space */
1202
1203         /*
1204         * This relies on the UNDOCUMENTED F_FREESP argument to
1205         * fcntl(2), which truncates the file so that it ends at the
1206         * position indicated by fl.l_start.
1207         *
1208         * Will minor miracles never cease?
1209         */
1210
1211         if (fcntl(fd, F_FREESP, &fl) < 0)
1212             return -1;
1213
1214     }
1215     return 0;
1216 #else
1217     Perl_croak_nocontext("truncate not implemented");
1218 #endif /* F_FREESP */
1219     return -1;
1220 }
1221 #endif /* !HAS_TRUNCATE && !HAS_CHSIZE */
1222
1223 bool
1224 Perl_do_print(pTHX_ register SV *sv, PerlIO *fp)
1225 {
1226     dVAR;
1227     register const char *tmps;
1228     STRLEN len;
1229
1230     /* assuming fp is checked earlier */
1231     if (!sv)
1232         return TRUE;
1233     switch (SvTYPE(sv)) {
1234     case SVt_NULL:
1235         if (ckWARN(WARN_UNINITIALIZED))
1236             report_uninit(sv);
1237         return TRUE;
1238     case SVt_IV:
1239         if (SvIOK(sv)) {
1240             SvGETMAGIC(sv);
1241             if (SvIsUV(sv))
1242                 PerlIO_printf(fp, "%"UVuf, (UV)SvUVX(sv));
1243             else
1244                 PerlIO_printf(fp, "%"IVdf, (IV)SvIVX(sv));
1245             return !PerlIO_error(fp);
1246         }
1247         /* FALL THROUGH */
1248     default:
1249         if (PerlIO_isutf8(fp)) {
1250             if (!SvUTF8(sv))
1251                 sv_utf8_upgrade_flags(sv = sv_mortalcopy(sv),
1252                                       SV_GMAGIC|SV_UTF8_NO_ENCODING);
1253         }
1254         else if (DO_UTF8(sv)) {
1255             if (!sv_utf8_downgrade((sv = sv_mortalcopy(sv)), TRUE)
1256                 && ckWARN_d(WARN_UTF8))
1257             {
1258                 Perl_warner(aTHX_ packWARN(WARN_UTF8), "Wide character in print");
1259             }
1260         }
1261         tmps = SvPV_const(sv, len);
1262         break;
1263     }
1264     /* To detect whether the process is about to overstep its
1265      * filesize limit we would need getrlimit().  We could then
1266      * also transparently raise the limit with setrlimit() --
1267      * but only until the system hard limit/the filesystem limit,
1268      * at which we would get EPERM.  Note that when using buffered
1269      * io the write failure can be delayed until the flush/close. --jhi */
1270     if (len && (PerlIO_write(fp,tmps,len) == 0))
1271         return FALSE;
1272     return !PerlIO_error(fp);
1273 }
1274
1275 I32
1276 Perl_my_stat(pTHX)
1277 {
1278     dVAR;
1279     dSP;
1280     IO *io;
1281     GV* gv;
1282
1283     if (PL_op->op_flags & OPf_REF) {
1284         EXTEND(SP,1);
1285         gv = cGVOP_gv;
1286       do_fstat:
1287         io = GvIO(gv);
1288         if (io && IoIFP(io)) {
1289             PL_statgv = gv;
1290             sv_setpvn(PL_statname,"", 0);
1291             PL_laststype = OP_STAT;
1292             return (PL_laststatval = PerlLIO_fstat(PerlIO_fileno(IoIFP(io)), &PL_statcache));
1293         }
1294         else {
1295             if (gv == PL_defgv)
1296                 return PL_laststatval;
1297             if (ckWARN2(WARN_UNOPENED,WARN_CLOSED))
1298                 report_evil_fh(gv, io, PL_op->op_type);
1299             PL_statgv = Nullgv;
1300             sv_setpvn(PL_statname,"", 0);
1301             return (PL_laststatval = -1);
1302         }
1303     }
1304     else if (PL_op->op_private & OPpFT_STACKED) {
1305         return PL_laststatval;
1306     }
1307     else {
1308         SV* const sv = POPs;
1309         const char *s;
1310         STRLEN len;
1311         PUTBACK;
1312         if (SvTYPE(sv) == SVt_PVGV) {
1313             gv = (GV*)sv;
1314             goto do_fstat;
1315         }
1316         else if (SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVGV) {
1317             gv = (GV*)SvRV(sv);
1318             goto do_fstat;
1319         }
1320
1321         s = SvPV_const(sv, len);
1322         PL_statgv = Nullgv;
1323         sv_setpvn(PL_statname, s, len);
1324         s = SvPVX_const(PL_statname);           /* s now NUL-terminated */
1325         PL_laststype = OP_STAT;
1326         PL_laststatval = PerlLIO_stat(s, &PL_statcache);
1327         if (PL_laststatval < 0 && ckWARN(WARN_NEWLINE) && strchr(s, '\n'))
1328             Perl_warner(aTHX_ packWARN(WARN_NEWLINE), PL_warn_nl, "stat");
1329         return PL_laststatval;
1330     }
1331 }
1332
1333
1334 I32
1335 Perl_my_lstat(pTHX)
1336 {
1337     dVAR;
1338     static const char no_prev_lstat[] = "The stat preceding -l _ wasn't an lstat";
1339     dSP;
1340     SV *sv;
1341     if (PL_op->op_flags & OPf_REF) {
1342         EXTEND(SP,1);
1343         if (cGVOP_gv == PL_defgv) {
1344             if (PL_laststype != OP_LSTAT)
1345                 Perl_croak(aTHX_ no_prev_lstat);
1346             return PL_laststatval;
1347         }
1348         if (ckWARN(WARN_IO)) {
1349             Perl_warner(aTHX_ packWARN(WARN_IO), "Use of -l on filehandle %s",
1350                     GvENAME(cGVOP_gv));
1351             return (PL_laststatval = -1);
1352         }
1353     }
1354     else if (PL_laststype != OP_LSTAT
1355             && (PL_op->op_private & OPpFT_STACKED) && ckWARN(WARN_IO))
1356         Perl_croak(aTHX_ no_prev_lstat);
1357
1358     PL_laststype = OP_LSTAT;
1359     PL_statgv = Nullgv;
1360     sv = POPs;
1361     PUTBACK;
1362     if (SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVGV && ckWARN(WARN_IO)) {
1363         Perl_warner(aTHX_ packWARN(WARN_IO), "Use of -l on filehandle %s",
1364                 GvENAME((GV*) SvRV(sv)));
1365         return (PL_laststatval = -1);
1366     }
1367     /* XXX Do really need to be calling SvPV() all these times? */
1368     sv_setpv(PL_statname,SvPV_nolen_const(sv));
1369     PL_laststatval = PerlLIO_lstat(SvPV_nolen_const(sv),&PL_statcache);
1370     if (PL_laststatval < 0 && ckWARN(WARN_NEWLINE) && strchr(SvPV_nolen_const(sv), '\n'))
1371         Perl_warner(aTHX_ packWARN(WARN_NEWLINE), PL_warn_nl, "lstat");
1372     return PL_laststatval;
1373 }
1374
1375 bool
1376 Perl_do_aexec5(pTHX_ SV *really, register SV **mark, register SV **sp,
1377                int fd, int do_report)
1378 {
1379     dVAR;
1380 #if defined(MACOS_TRADITIONAL) || defined(__SYMBIAN32__)
1381     Perl_croak(aTHX_ "exec? I'm not *that* kind of operating system");
1382 #else
1383     if (sp > mark) {
1384         char **a;
1385         const char *tmps = NULL;
1386         Newx(PL_Argv, sp - mark + 1, char*);
1387         a = PL_Argv;
1388
1389         while (++mark <= sp) {
1390             if (*mark)
1391                 *a++ = (char*)SvPV_nolen_const(*mark);
1392             else
1393                 *a++ = "";
1394         }
1395         *a = NULL;
1396         if (really)
1397             tmps = SvPV_nolen_const(really);
1398         if ((!really && *PL_Argv[0] != '/') ||
1399             (really && *tmps != '/'))           /* will execvp use PATH? */
1400             TAINT_ENV();                /* testing IFS here is overkill, probably */
1401         PERL_FPU_PRE_EXEC
1402         if (really && *tmps)
1403             PerlProc_execvp(tmps,EXEC_ARGV_CAST(PL_Argv));
1404         else
1405             PerlProc_execvp(PL_Argv[0],EXEC_ARGV_CAST(PL_Argv));
1406         PERL_FPU_POST_EXEC
1407         if (ckWARN(WARN_EXEC))
1408             Perl_warner(aTHX_ packWARN(WARN_EXEC), "Can't exec \"%s\": %s",
1409                 (really ? tmps : PL_Argv[0]), Strerror(errno));
1410         if (do_report) {
1411             const int e = errno;
1412
1413             PerlLIO_write(fd, (void*)&e, sizeof(int));
1414             PerlLIO_close(fd);
1415         }
1416     }
1417     do_execfree();
1418 #endif
1419     return FALSE;
1420 }
1421
1422 void
1423 Perl_do_execfree(pTHX)
1424 {
1425     dVAR;
1426     Safefree(PL_Argv);
1427     PL_Argv = Null(char **);
1428     Safefree(PL_Cmd);
1429     PL_Cmd = Nullch;
1430 }
1431
1432 #ifdef PERL_DEFAULT_DO_EXEC3_IMPLEMENTATION
1433
1434 bool
1435 Perl_do_exec3(pTHX_ const char *incmd, int fd, int do_report)
1436 {
1437     dVAR;
1438     register char **a;
1439     register char *s;
1440     char *cmd;
1441
1442     /* Make a copy so we can change it */
1443     const int cmdlen = strlen(incmd);
1444     Newx(cmd, cmdlen+1, char);
1445     strncpy(cmd, incmd, cmdlen);
1446     cmd[cmdlen] = 0;
1447
1448     while (*cmd && isSPACE(*cmd))
1449         cmd++;
1450
1451     /* save an extra exec if possible */
1452
1453 #ifdef CSH
1454     {
1455         char flags[PERL_FLAGS_MAX];
1456         if (strnEQ(cmd,PL_cshname,PL_cshlen) &&
1457             strnEQ(cmd+PL_cshlen," -c",3)) {
1458 #ifdef HAS_STRLCPY
1459           strlcpy(flags, "-c", PERL_FLAGS_MAX);
1460 #else
1461           strcpy(flags,"-c");
1462 #endif
1463           s = cmd+PL_cshlen+3;
1464           if (*s == 'f') {
1465               s++;
1466 #ifdef HAS_STRLCPY
1467               strlcat(flags, "f", PERL_FLAGS_MAX);
1468 #else
1469               strcat(flags,"f");
1470 #endif
1471           }
1472           if (*s == ' ')
1473               s++;
1474           if (*s++ == '\'') {
1475               char * const ncmd = s;
1476
1477               while (*s)
1478                   s++;
1479               if (s[-1] == '\n')
1480                   *--s = '\0';
1481               if (s[-1] == '\'') {
1482                   *--s = '\0';
1483                   PERL_FPU_PRE_EXEC
1484                   PerlProc_execl(PL_cshname,"csh", flags, ncmd, (char*)0);
1485                   PERL_FPU_POST_EXEC
1486                   *s = '\'';
1487                   Safefree(cmd);
1488                   return FALSE;
1489               }
1490           }
1491         }
1492     }
1493 #endif /* CSH */
1494
1495     /* see if there are shell metacharacters in it */
1496
1497     if (*cmd == '.' && isSPACE(cmd[1]))
1498         goto doshell;
1499
1500     if (strnEQ(cmd,"exec",4) && isSPACE(cmd[4]))
1501         goto doshell;
1502
1503     for (s = cmd; *s && isALNUM(*s); s++) ;     /* catch VAR=val gizmo */
1504     if (*s == '=')
1505         goto doshell;
1506
1507     for (s = cmd; *s; s++) {
1508         if (*s != ' ' && !isALPHA(*s) &&
1509             strchr("$&*(){}[]'\";\\|?<>~`\n",*s)) {
1510             if (*s == '\n' && !s[1]) {
1511                 *s = '\0';
1512                 break;
1513             }
1514             /* handle the 2>&1 construct at the end */
1515             if (*s == '>' && s[1] == '&' && s[2] == '1'
1516                 && s > cmd + 1 && s[-1] == '2' && isSPACE(s[-2])
1517                 && (!s[3] || isSPACE(s[3])))
1518             {
1519                 const char *t = s + 3;
1520
1521                 while (*t && isSPACE(*t))
1522                     ++t;
1523                 if (!*t && (PerlLIO_dup2(1,2) != -1)) {
1524                     s[-2] = '\0';
1525                     break;
1526                 }
1527             }
1528           doshell:
1529             PERL_FPU_PRE_EXEC
1530             PerlProc_execl(PL_sh_path, "sh", "-c", cmd, (char*)0);
1531             PERL_FPU_POST_EXEC
1532             Safefree(cmd);
1533             return FALSE;
1534         }
1535     }
1536
1537     Newx(PL_Argv, (s - cmd) / 2 + 2, char*);
1538     PL_Cmd = savepvn(cmd, s-cmd);
1539     a = PL_Argv;
1540     for (s = PL_Cmd; *s;) {
1541         while (*s && isSPACE(*s)) s++;
1542         if (*s)
1543             *(a++) = s;
1544         while (*s && !isSPACE(*s)) s++;
1545         if (*s)
1546             *s++ = '\0';
1547     }
1548     *a = NULL;
1549     if (PL_Argv[0]) {
1550         PERL_FPU_PRE_EXEC
1551         PerlProc_execvp(PL_Argv[0],PL_Argv);
1552         PERL_FPU_POST_EXEC
1553         if (errno == ENOEXEC) {         /* for system V NIH syndrome */
1554             do_execfree();
1555             goto doshell;
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, (const void*)&e, sizeof(int));
1563             PerlLIO_close(fd);
1564         }
1565     }
1566     do_execfree();
1567     Safefree(cmd);
1568     return FALSE;
1569 }
1570
1571 #endif /* OS2 || WIN32 */
1572
1573 I32
1574 Perl_apply(pTHX_ I32 type, register SV **mark, register SV **sp)
1575 {
1576     dVAR;
1577     register I32 val;
1578     register I32 tot = 0;
1579     const char *const what = PL_op_name[type];
1580     const char *s;
1581     SV ** const oldmark = mark;
1582
1583     /* Doing this ahead of the switch statement preserves the old behaviour,
1584        where attempting to use kill as a taint test test would fail on
1585        platforms where kill was not defined.  */
1586 #ifndef HAS_KILL
1587     if (type == OP_KILL)
1588         Perl_die(aTHX_ PL_no_func, what);
1589 #endif
1590 #ifndef HAS_CHOWN
1591     if (type == OP_CHOWN)
1592         Perl_die(aTHX_ PL_no_func, what);
1593 #endif
1594
1595
1596 #define APPLY_TAINT_PROPER() \
1597     STMT_START {                                                        \
1598         if (PL_tainted) { TAINT_PROPER(what); }                         \
1599     } STMT_END
1600
1601     /* This is a first heuristic; it doesn't catch tainting magic. */
1602     if (PL_tainting) {
1603         while (++mark <= sp) {
1604             if (SvTAINTED(*mark)) {
1605                 TAINT;
1606                 break;
1607             }
1608         }
1609         mark = oldmark;
1610     }
1611     switch (type) {
1612     case OP_CHMOD:
1613         APPLY_TAINT_PROPER();
1614         if (++mark <= sp) {
1615             val = SvIVx(*mark);
1616             APPLY_TAINT_PROPER();
1617             tot = sp - mark;
1618             while (++mark <= sp) {
1619                 GV* gv;
1620                 if (SvTYPE(*mark) == SVt_PVGV) {
1621                     gv = (GV*)*mark;
1622                 do_fchmod:
1623                     if (GvIO(gv) && IoIFP(GvIOp(gv))) {
1624 #ifdef HAS_FCHMOD
1625                         APPLY_TAINT_PROPER();
1626                         if (fchmod(PerlIO_fileno(IoIFP(GvIOn(gv))), val))
1627                             tot--;
1628 #else
1629                         Perl_die(aTHX_ PL_no_func, "fchmod");
1630 #endif
1631                     }
1632                     else {
1633                         tot--;
1634                     }
1635                 }
1636                 else if (SvROK(*mark) && SvTYPE(SvRV(*mark)) == SVt_PVGV) {
1637                     gv = (GV*)SvRV(*mark);
1638                     goto do_fchmod;
1639                 }
1640                 else {
1641                     const char *name = SvPV_nolen_const(*mark);
1642                     APPLY_TAINT_PROPER();
1643                     if (PerlLIO_chmod(name, val))
1644                         tot--;
1645                 }
1646             }
1647         }
1648         break;
1649 #ifdef HAS_CHOWN
1650     case OP_CHOWN:
1651         APPLY_TAINT_PROPER();
1652         if (sp - mark > 2) {
1653             register I32 val2;
1654             val = SvIVx(*++mark);
1655             val2 = SvIVx(*++mark);
1656             APPLY_TAINT_PROPER();
1657             tot = sp - mark;
1658             while (++mark <= sp) {
1659                 GV* gv;
1660                 if (SvTYPE(*mark) == SVt_PVGV) {
1661                     gv = (GV*)*mark;
1662                 do_fchown:
1663                     if (GvIO(gv) && IoIFP(GvIOp(gv))) {
1664 #ifdef HAS_FCHOWN
1665                         APPLY_TAINT_PROPER();
1666                         if (fchown(PerlIO_fileno(IoIFP(GvIOn(gv))), val, val2))
1667                             tot--;
1668 #else
1669                         Perl_die(aTHX_ PL_no_func, "fchown");
1670 #endif
1671                     }
1672                     else {
1673                         tot--;
1674                     }
1675                 }
1676                 else if (SvROK(*mark) && SvTYPE(SvRV(*mark)) == SVt_PVGV) {
1677                     gv = (GV*)SvRV(*mark);
1678                     goto do_fchown;
1679                 }
1680                 else {
1681                     const char *name = SvPV_nolen_const(*mark);
1682                     APPLY_TAINT_PROPER();
1683                     if (PerlLIO_chown(name, val, val2))
1684                         tot--;
1685                 }
1686             }
1687         }
1688         break;
1689 #endif
1690 /*
1691 XXX Should we make lchown() directly available from perl?
1692 For now, we'll let Configure test for HAS_LCHOWN, but do
1693 nothing in the core.
1694     --AD  5/1998
1695 */
1696 #ifdef HAS_KILL
1697     case OP_KILL:
1698         APPLY_TAINT_PROPER();
1699         if (mark == sp)
1700             break;
1701         s = SvPVx_nolen_const(*++mark);
1702         if (isALPHA(*s)) {
1703             if (*s == 'S' && s[1] == 'I' && s[2] == 'G')
1704                 s += 3;
1705             if ((val = whichsig(s)) < 0)
1706                 Perl_croak(aTHX_ "Unrecognized signal name \"%s\"",s);
1707         }
1708         else
1709             val = SvIVx(*mark);
1710         APPLY_TAINT_PROPER();
1711         tot = sp - mark;
1712 #ifdef VMS
1713         /* kill() doesn't do process groups (job trees?) under VMS */
1714         if (val < 0) val = -val;
1715         if (val == SIGKILL) {
1716 #           include <starlet.h>
1717             /* Use native sys$delprc() to insure that target process is
1718              * deleted; supervisor-mode images don't pay attention to
1719              * CRTL's emulation of Unix-style signals and kill()
1720              */
1721             while (++mark <= sp) {
1722                 I32 proc = SvIVx(*mark);
1723                 register unsigned long int __vmssts;
1724                 APPLY_TAINT_PROPER();
1725                 if (!((__vmssts = sys$delprc(&proc,0)) & 1)) {
1726                     tot--;
1727                     switch (__vmssts) {
1728                         case SS$_NONEXPR:
1729                         case SS$_NOSUCHNODE:
1730                             SETERRNO(ESRCH,__vmssts);
1731                             break;
1732                         case SS$_NOPRIV:
1733                             SETERRNO(EPERM,__vmssts);
1734                             break;
1735                         default:
1736                             SETERRNO(EVMSERR,__vmssts);
1737                     }
1738                 }
1739             }
1740             break;
1741         }
1742 #endif
1743         if (val < 0) {
1744             val = -val;
1745             while (++mark <= sp) {
1746                 const I32 proc = SvIVx(*mark);
1747                 APPLY_TAINT_PROPER();
1748 #ifdef HAS_KILLPG
1749                 if (PerlProc_killpg(proc,val))  /* BSD */
1750 #else
1751                 if (PerlProc_kill(-proc,val))   /* SYSV */
1752 #endif
1753                     tot--;
1754             }
1755         }
1756         else {
1757             while (++mark <= sp) {
1758                 const I32 proc = SvIVx(*mark);
1759                 APPLY_TAINT_PROPER();
1760                 if (PerlProc_kill(proc, val))
1761                     tot--;
1762             }
1763         }
1764         break;
1765 #endif
1766     case OP_UNLINK:
1767         APPLY_TAINT_PROPER();
1768         tot = sp - mark;
1769         while (++mark <= sp) {
1770             s = SvPV_nolen_const(*mark);
1771             APPLY_TAINT_PROPER();
1772             if (PL_euid || PL_unsafe) {
1773                 if (UNLINK(s))
1774                     tot--;
1775             }
1776             else {      /* don't let root wipe out directories without -U */
1777                 if (PerlLIO_lstat(s,&PL_statbuf) < 0 || S_ISDIR(PL_statbuf.st_mode))
1778                     tot--;
1779                 else {
1780                     if (UNLINK(s))
1781                         tot--;
1782                 }
1783             }
1784         }
1785         break;
1786 #if defined(HAS_UTIME) || defined(HAS_FUTIMES)
1787     case OP_UTIME:
1788         APPLY_TAINT_PROPER();
1789         if (sp - mark > 2) {
1790 #if defined(HAS_FUTIMES)
1791             struct timeval utbuf[2];
1792             void *utbufp = utbuf;
1793 #elif defined(I_UTIME) || defined(VMS)
1794             struct utimbuf utbuf;
1795             struct utimbuf *utbufp = &utbuf;
1796 #else
1797             struct {
1798                 Time_t  actime;
1799                 Time_t  modtime;
1800             } utbuf;
1801             void *utbufp = &utbuf;
1802 #endif
1803
1804            SV* const accessed = *++mark;
1805            SV* const modified = *++mark;
1806
1807            /* Be like C, and if both times are undefined, let the C
1808             * library figure out what to do.  This usually means
1809             * "current time". */
1810
1811            if ( accessed == &PL_sv_undef && modified == &PL_sv_undef )
1812                 utbufp = NULL;
1813            else {
1814                 Zero(&utbuf, sizeof utbuf, char);
1815 #ifdef HAS_FUTIMES
1816                 utbuf[0].tv_sec = (long)SvIVx(accessed);  /* time accessed */
1817                 utbuf[0].tv_usec = 0;
1818                 utbuf[1].tv_sec = (long)SvIVx(modified);  /* time modified */
1819                 utbuf[1].tv_usec = 0;
1820 #elif defined(BIG_TIME)
1821                 utbuf.actime = (Time_t)SvNVx(accessed);  /* time accessed */
1822                 utbuf.modtime = (Time_t)SvNVx(modified); /* time modified */
1823 #else
1824                 utbuf.actime = (Time_t)SvIVx(accessed);  /* time accessed */
1825                 utbuf.modtime = (Time_t)SvIVx(modified); /* time modified */
1826 #endif
1827             }
1828             APPLY_TAINT_PROPER();
1829             tot = sp - mark;
1830             while (++mark <= sp) {
1831                 GV* gv;
1832                 if (SvTYPE(*mark) == SVt_PVGV) {
1833                     gv = (GV*)*mark;
1834                 do_futimes:
1835                     if (GvIO(gv) && IoIFP(GvIOp(gv))) {
1836 #ifdef HAS_FUTIMES
1837                         APPLY_TAINT_PROPER();
1838                         if (futimes(PerlIO_fileno(IoIFP(GvIOn(gv))), utbufp))
1839                             tot--;
1840 #else
1841                         Perl_die(aTHX_ PL_no_func, "futimes");
1842 #endif
1843                     }
1844                     else {
1845                         tot--;
1846                     }
1847                 }
1848                 else if (SvROK(*mark) && SvTYPE(SvRV(*mark)) == SVt_PVGV) {
1849                     gv = (GV*)SvRV(*mark);
1850                     goto do_futimes;
1851                 }
1852                 else {
1853                     const char * const name = SvPV_nolen_const(*mark);
1854                     APPLY_TAINT_PROPER();
1855 #ifdef HAS_FUTIMES
1856                     if (utimes(name, utbufp))
1857 #else
1858                     if (PerlLIO_utime(name, utbufp))
1859 #endif
1860                         tot--;
1861                 }
1862
1863             }
1864         }
1865         else
1866             tot = 0;
1867         break;
1868 #endif
1869     }
1870     return tot;
1871
1872 #undef APPLY_TAINT_PROPER
1873 }
1874
1875 /* Do the permissions allow some operation?  Assumes statcache already set. */
1876 #ifndef VMS /* VMS' cando is in vms.c */
1877 bool
1878 Perl_cando(pTHX_ Mode_t mode, bool effective, register const Stat_t *statbufp)
1879 /* effective is a flag, true for EUID, or for checking if the effective gid
1880  *  is in the list of groups returned from getgroups().
1881  */
1882 {
1883     dVAR;
1884 #ifdef DOSISH
1885     /* [Comments and code from Len Reed]
1886      * MS-DOS "user" is similar to UNIX's "superuser," but can't write
1887      * to write-protected files.  The execute permission bit is set
1888      * by the Miscrosoft C library stat() function for the following:
1889      *          .exe files
1890      *          .com files
1891      *          .bat files
1892      *          directories
1893      * All files and directories are readable.
1894      * Directories and special files, e.g. "CON", cannot be
1895      * write-protected.
1896      * [Comment by Tom Dinger -- a directory can have the write-protect
1897      *          bit set in the file system, but DOS permits changes to
1898      *          the directory anyway.  In addition, all bets are off
1899      *          here for networked software, such as Novell and
1900      *          Sun's PC-NFS.]
1901      */
1902
1903      /* Atari stat() does pretty much the same thing. we set x_bit_set_in_stat
1904       * too so it will actually look into the files for magic numbers
1905       */
1906      return (mode & statbufp->st_mode) ? TRUE : FALSE;
1907
1908 #else /* ! DOSISH */
1909     if ((effective ? PL_euid : PL_uid) == 0) {  /* root is special */
1910         if (mode == S_IXUSR) {
1911             if (statbufp->st_mode & 0111 || S_ISDIR(statbufp->st_mode))
1912                 return TRUE;
1913         }
1914         else
1915             return TRUE;                /* root reads and writes anything */
1916         return FALSE;
1917     }
1918     if (statbufp->st_uid == (effective ? PL_euid : PL_uid) ) {
1919         if (statbufp->st_mode & mode)
1920             return TRUE;        /* ok as "user" */
1921     }
1922     else if (ingroup(statbufp->st_gid,effective)) {
1923         if (statbufp->st_mode & mode >> 3)
1924             return TRUE;        /* ok as "group" */
1925     }
1926     else if (statbufp->st_mode & mode >> 6)
1927         return TRUE;    /* ok as "other" */
1928     return FALSE;
1929 #endif /* ! DOSISH */
1930 }
1931 #endif /* ! VMS */
1932
1933 bool
1934 Perl_ingroup(pTHX_ Gid_t testgid, bool effective)
1935 {
1936 #ifdef MACOS_TRADITIONAL
1937     /* This is simply not correct for AppleShare, but fix it yerself. */
1938     return TRUE;
1939 #else
1940     dVAR;
1941     if (testgid == (effective ? PL_egid : PL_gid))
1942         return TRUE;
1943 #ifdef HAS_GETGROUPS
1944     {
1945         Groups_t *gary = NULL;
1946         I32 anum;
1947         bool rc = FALSE;
1948
1949         anum = getgroups(0, gary);
1950         Newx(gary, anum, Groups_t);
1951         anum = getgroups(anum, gary);
1952         while (--anum >= 0)
1953             if (gary[anum] == testgid) {
1954                 rc = TRUE;
1955                 break;
1956             }
1957
1958         Safefree(gary);
1959         return rc;
1960     }
1961 #else
1962     return FALSE;
1963 #endif
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(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  */