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