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