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