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