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