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