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