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