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