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