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