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