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