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