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