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