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