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
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.
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.
17 * [p.684 of _The Lord of the Rings_, IV/vi: "The Forbidden Pool"]
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.
26 #define PERL_IN_DOIO_C
29 #if defined(HAS_MSG) || defined(HAS_SEM) || defined(HAS_SHM)
38 # ifndef HAS_SHMAT_PROTOTYPE
39 extern Shmat_t shmat (int, char *, int);
45 # if defined(_MSC_VER) || defined(__MINGW32__)
46 # include <sys/utime.h>
53 # define OPEN_EXCL O_EXCL
58 #define PERL_MODE_MAX 8
59 #define PERL_FLAGS_MAX 10
64 S_openn_setup(pTHX_ GV *gv, char *mode, PerlIO **saveifp, PerlIO **saveofp,
65 int *savefd, char *savetype)
67 IO * const io = GvIOn(gv);
69 PERL_ARGS_ASSERT_OPENN_SETUP;
74 *savetype = IoTYPE_CLOSED;
76 Zero(mode,sizeof(mode),char);
77 PL_forkprocess = 1; /* assume true if no fork */
79 /* If currently open - close before we re-open */
81 if (IoTYPE(io) == IoTYPE_STD) {
82 /* This is a clone of one of STD* handles */
85 const int old_fd = PerlIO_fileno(IoIFP(io));
87 if (old_fd >= 0 && old_fd <= PL_maxsysfd) {
88 /* This is one of the original STD* handles */
91 *savetype = IoTYPE(io);
97 if (IoTYPE(io) == IoTYPE_PIPE)
98 result = PerlProc_pclose(IoIFP(io));
99 else if (IoIFP(io) != IoOFP(io)) {
101 result = PerlIO_close(IoOFP(io));
102 PerlIO_close(IoIFP(io)); /* clear stdio, fd already closed */
105 result = PerlIO_close(IoIFP(io));
108 result = PerlIO_close(IoIFP(io));
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))
119 IoOFP(io) = IoIFP(io) = NULL;
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,
129 PERL_ARGS_ASSERT_DO_OPENN;
132 /* sysopen style args, i.e. integer mode and permissions */
135 Perl_croak(aTHX_ "panic: sysopen with multiple args, num_svs=%ld",
138 return do_open_raw(gv, oname, len, rawmode, rawperm);
140 return do_open6(gv, oname, len, supplied_fp, svp, num_svs);
144 Perl_do_open_raw(pTHX_ GV *gv, const char *oname, STRLEN len,
145 int rawmode, int rawperm)
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);
156 PERL_ARGS_ASSERT_DO_OPEN_RAW;
158 /* For ease of blame back to 5.000, keep the existing indenting. */
160 /* sysopen style args, i.e. integer mode and permissions */
162 const int appendtrunc =
164 #ifdef O_APPEND /* Not fully portable. */
167 #ifdef O_TRUNC /* Not fully portable. */
171 const int modifyingmode = O_WRONLY|O_RDWR|O_CREAT|appendtrunc;
181 It might be (in OS/390 and Mac OS Classic it is)
187 This means that simple & with O_RDWR would look
188 like O_RDONLY is present. Therefore we have to
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");
197 mode[ix++] = IoTYPE_NUMERIC; /* Marker to openn to use numeric "sysopen" */
199 #if defined(USE_64_BIT_RAWIO) && defined(O_LARGEFILE)
200 rawmode |= O_LARGEFILE; /* Transparently largefiley. */
203 IoTYPE(io) = PerlIO_intmode2str(rawmode, &mode[ix], &writing);
205 namesv = newSVpvn_flags(oname, len, SVs_TEMP);
206 fp = PerlIO_openn(aTHX_ NULL, mode, -1, rawmode, rawperm, NULL, 1, &namesv);
208 return openn_cleanup(gv, io, fp, mode, oname, saveifp, saveofp, savefd,
209 savetype, writing, 0, NULL);
213 Perl_do_open6(pTHX_ GV *gv, const char *oname, STRLEN len,
214 PerlIO *supplied_fp, SV **svp, U32 num_svs)
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);
224 bool was_fdopen = FALSE;
227 PERL_ARGS_ASSERT_DO_OPEN6;
229 /* For ease of blame back to 5.000, keep the existing indenting. */
231 /* Regular (non-sys) open */
236 bool in_raw = 0, in_crlf = 0, out_raw = 0, out_crlf = 0;
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);
248 type = savepvn(oname, len);
252 /* Lose leading and trailing white space */
253 while (isSPACE(*type))
255 while (tend > type && isSPACE(tend[-1]))
261 /* New style explicit name, type is just mode and layer info */
263 if (SvROK(*svp) && !strchr(oname,'&')) {
265 Perl_warner(aTHX_ packWARN(WARN_IO),
266 "Can't open a reference");
267 SETERRNO(EINVAL, LIB_INVARG);
271 #endif /* USE_STDIO */
272 p = (SvOK(*svp) || SvGMAGICAL(*svp)) ? SvPV(*svp, nlen) : NULL;
274 if (p && !IS_SAFE_PATHNAME(p, nlen, "open")) {
279 name = p ? savepvn(p, nlen) : savepvs("");
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");
296 if (*type == IoTYPE_PIPE) {
298 if (type[1] != IoTYPE_STD) {
300 Perl_croak(aTHX_ "Unknown open() mode '%.*s'", (int)olen, oname);
306 } while (isSPACE(*type));
312 /* command is missing 19990114 */
313 if (ckWARN(WARN_PIPE))
314 Perl_warner(aTHX_ packWARN(WARN_PIPE), "Missing command in piped open");
319 if (!(*name == '-' && name[1] == '\0') || num_svs)
321 TAINT_PROPER("piped open");
322 if (!num_svs && name[len-1] == '|') {
324 if (ckWARN(WARN_PIPE))
325 Perl_warner(aTHX_ packWARN(WARN_PIPE), "Can't open bidirectional pipe");
334 fp = PerlProc_popen_list(mode, num_svs, svp);
337 fp = PerlProc_popen(name,mode);
341 if (PerlIO_apply_layers(aTHX_ fp, mode, type) != 0) {
348 else if (*type == IoTYPE_WRONLY) {
349 TAINT_PROPER("open");
351 if (*type == IoTYPE_WRONLY) {
352 /* Two IoTYPE_WRONLYs in a row make for an IoTYPE_APPEND. */
353 mode[0] = IoTYPE(io) = IoTYPE_APPEND;
367 dodup = PERLIO_DUP_FD;
373 if (!num_svs && !*type && supplied_fp) {
374 /* "<+&" etc. is used by typemaps */
378 PerlIO *that_fp = NULL;
382 /* diag_listed_as: More than one argument to '%s' open */
383 Perl_croak(aTHX_ "More than one argument to '%c&' open",IoTYPE(io));
385 while (isSPACE(*type))
389 || (SvPOKp(*svp) && looks_like_number(*svp))
391 wanted_fd = SvUV(*svp);
394 else if (isDIGIT(*type)
395 && grok_atoUV(type, &uv, NULL)
403 thatio = sv_2io(*svp);
406 GV * const thatgv = gv_fetchpvn_flags(type, tend - type,
408 thatio = GvIO(thatgv);
412 SETERRNO(EINVAL,SS_IVCHAN);
417 if ((that_fp = IoIFP(thatio))) {
418 /* Flush stdio buffer before dup. --mjd
419 * Unfortunately SEEK_CURing 0 seems to
420 * be optimized away on most platforms;
421 * only Solaris and Linux seem to flush
423 /* On the other hand, do all platforms
424 * take gracefully to flushing a read-only
425 * filehandle? Perhaps we should do
426 * fsetpos(src)+fgetpos(dst)? --nik */
427 PerlIO_flush(that_fp);
428 wanted_fd = PerlIO_fileno(that_fp);
429 /* When dup()ing STDIN, STDOUT or STDERR
430 * explicitly set appropriate access mode */
431 if (that_fp == PerlIO_stdout()
432 || that_fp == PerlIO_stderr())
433 IoTYPE(io) = IoTYPE_WRONLY;
434 else if (that_fp == PerlIO_stdin())
435 IoTYPE(io) = IoTYPE_RDONLY;
436 /* When dup()ing a socket, say result is
438 else if (IoTYPE(thatio) == IoTYPE_SOCKET)
439 IoTYPE(io) = IoTYPE_SOCKET;
442 SETERRNO(EBADF, RMS_IFI);
450 fp = PerlIO_fdupopen(aTHX_ that_fp, NULL, dodup);
454 wanted_fd = PerlLIO_dup(wanted_fd);
457 if (!(fp = PerlIO_openn(aTHX_ type,mode,wanted_fd,0,0,NULL,num_svs,svp))) {
458 if (dodup && wanted_fd >= 0)
459 PerlLIO_close(wanted_fd);
465 while (isSPACE(*type))
467 if (*type == IoTYPE_STD && (!type[1] || isSPACE(type[1]) || type[1] == ':')) {
469 fp = PerlIO_stdout();
470 IoTYPE(io) = IoTYPE_STD;
472 /* diag_listed_as: More than one argument to '%s' open */
473 Perl_croak(aTHX_ "More than one argument to '>%c' open",IoTYPE_STD);
478 fp = PerlIO_openn(aTHX_ type,mode,-1,0,0,NULL,num_svs,svp);
481 SV *namesv = newSVpvn_flags(type, tend - type, SVs_TEMP);
483 fp = PerlIO_openn(aTHX_ type,mode,-1,0,0,NULL,1,&namesv);
487 if (!fp && type && *type && *type != ':' && !isIDFIRST(*type))
488 goto unknown_open_mode;
489 } /* IoTYPE_WRONLY */
490 else if (*type == IoTYPE_RDONLY) {
493 } while (isSPACE(*type));
502 if (*type == IoTYPE_STD && (!type[1] || isSPACE(type[1]) || type[1] == ':')) {
505 IoTYPE(io) = IoTYPE_STD;
507 /* diag_listed_as: More than one argument to '%s' open */
508 Perl_croak(aTHX_ "More than one argument to '<%c' open",IoTYPE_STD);
513 fp = PerlIO_openn(aTHX_ type,mode,-1,0,0,NULL,num_svs,svp);
516 SV *namesv = newSVpvn_flags(type, tend - type, SVs_TEMP);
518 fp = PerlIO_openn(aTHX_ type,mode,-1,0,0,NULL,1,&namesv);
521 if (!fp && type && *type && *type != ':' && !isIDFIRST(*type))
522 goto unknown_open_mode;
523 } /* IoTYPE_RDONLY */
524 else if ((num_svs && /* '-|...' or '...|' */
525 type[0] == IoTYPE_STD && type[1] == IoTYPE_PIPE) ||
526 (!num_svs && tend > type+1 && tend[-1] == IoTYPE_PIPE)) {
528 type += 2; /* skip over '-|' */
532 while (tend > type && isSPACE(tend[-1]))
534 for (; isSPACE(*type); type++)
540 /* command is missing 19990114 */
541 if (ckWARN(WARN_PIPE))
542 Perl_warner(aTHX_ packWARN(WARN_PIPE), "Missing command in piped open");
547 if (!(*name == '-' && name[1] == '\0') || num_svs)
549 TAINT_PROPER("piped open");
558 fp = PerlProc_popen_list(mode,num_svs,svp);
561 fp = PerlProc_popen(name,mode);
563 IoTYPE(io) = IoTYPE_PIPE;
565 while (isSPACE(*type))
568 if (PerlIO_apply_layers(aTHX_ fp, mode, type) != 0) {
575 else { /* layer(Args) */
577 goto unknown_open_mode;
579 IoTYPE(io) = IoTYPE_RDONLY;
580 for (; isSPACE(*name); name++)
589 if (*name == '-' && name[1] == '\0') {
591 IoTYPE(io) = IoTYPE_STD;
595 fp = PerlIO_openn(aTHX_ type,mode,-1,0,0,NULL,num_svs,svp);
598 SV *namesv = newSVpvn_flags(type, tend - type, SVs_TEMP);
600 fp = PerlIO_openn(aTHX_ type,mode,-1,0,0,NULL,1,&namesv);
607 return openn_cleanup(gv, io, fp, mode, oname, saveifp, saveofp, savefd,
608 savetype, writing, was_fdopen, type);
611 /* Yes, this is ugly, but it's private, and I don't see a cleaner way to
612 simplify the two-headed public interface of do_openn. */
614 S_openn_cleanup(pTHX_ GV *gv, IO *io, PerlIO *fp, char *mode, const char *oname,
615 PerlIO *saveifp, PerlIO *saveofp, int savefd, char savetype,
616 int writing, bool was_fdopen, const char *type)
620 PERL_ARGS_ASSERT_OPENN_CLEANUP;
623 if (IoTYPE(io) == IoTYPE_RDONLY && ckWARN(WARN_NEWLINE)
624 && should_warn_nl(oname)
628 GCC_DIAG_IGNORE(-Wformat-nonliteral); /* PL_warn_nl is constant */
629 Perl_warner(aTHX_ packWARN(WARN_NEWLINE), PL_warn_nl, "open");
635 if (ckWARN(WARN_IO)) {
636 if ((IoTYPE(io) == IoTYPE_RDONLY) &&
637 (fp == PerlIO_stdout() || fp == PerlIO_stderr())) {
638 Perl_warner(aTHX_ packWARN(WARN_IO),
639 "Filehandle STD%s reopened as %"HEKf
641 ((fp == PerlIO_stdout()) ? "OUT" : "ERR"),
642 HEKfARG(GvENAME_HEK(gv)));
644 else if ((IoTYPE(io) == IoTYPE_WRONLY) && fp == PerlIO_stdin()) {
645 Perl_warner(aTHX_ packWARN(WARN_IO),
646 "Filehandle STDIN reopened as %"HEKf" only for output",
647 HEKfARG(GvENAME_HEK(gv))
652 fd = PerlIO_fileno(fp);
653 /* Do NOT do: "if (fd < 0) goto say_false;" here. If there is no
654 * fd assume it isn't a socket - this covers PerlIO::scalar -
655 * otherwise unless we "know" the type probe for socket-ness.
657 if (IoTYPE(io) && IoTYPE(io) != IoTYPE_PIPE && IoTYPE(io) != IoTYPE_STD && fd >= 0) {
658 if (PerlLIO_fstat(fd,&PL_statbuf) < 0) {
659 /* If PerlIO claims to have fd we had better be able to fstat() it. */
660 (void) PerlIO_close(fp);
664 if (S_ISSOCK(PL_statbuf.st_mode))
665 IoTYPE(io) = IoTYPE_SOCKET; /* in case a socket was passed in to us */
668 !(PL_statbuf.st_mode & S_IFMT)
669 && IoTYPE(io) != IoTYPE_WRONLY /* Dups of STD* filehandles already have */
670 && IoTYPE(io) != IoTYPE_RDONLY /* type so they aren't marked as sockets */
671 ) { /* on OS's that return 0 on fstat()ed pipe */
673 Sock_size_t buflen = sizeof tmpbuf;
674 if (PerlSock_getsockname(fd, (struct sockaddr *)tmpbuf, &buflen) >= 0
675 || errno != ENOTSOCK)
676 IoTYPE(io) = IoTYPE_SOCKET; /* some OS's return 0 on fstat()ed socket */
677 /* but some return 0 for streams too, sigh */
679 #endif /* HAS_SOCKET */
680 #endif /* !PERL_MICRO */
684 * If this is a standard handle we discard all the layer stuff
685 * and just dup the fd into whatever was on the handle before !
688 if (saveifp) { /* must use old fp? */
689 /* If fd is less that PL_maxsysfd i.e. STDIN..STDERR
690 then dup the new fileno down
693 PerlIO_flush(saveofp); /* emulate PerlIO_close() */
694 if (saveofp != saveifp) { /* was a socket? */
695 PerlIO_close(saveofp);
699 /* Still a small can-of-worms here if (say) PerlIO::scalar
700 is assigned to (say) STDOUT - for now let dup2() fail
701 and provide the error
704 SETERRNO(EBADF,RMS_IFI);
706 } else if (PerlLIO_dup2(fd, savefd) < 0) {
707 (void)PerlIO_close(fp);
711 if (savefd != PerlIO_fileno(PerlIO_stdin())) {
712 char newname[FILENAME_MAX+1];
713 if (PerlIO_getname(fp, newname)) {
714 if (fd == PerlIO_fileno(PerlIO_stdout()))
715 vmssetuserlnm("SYS$OUTPUT", newname);
716 if (fd == PerlIO_fileno(PerlIO_stderr()))
717 vmssetuserlnm("SYS$ERROR", newname);
723 /* PL_fdpid isn't used on Windows, so avoid this useless work.
724 * XXX Probably the same for a lot of other places. */
729 sv = *av_fetch(PL_fdpid,fd,TRUE);
730 SvUPGRADE(sv, SVt_IV);
733 sv = *av_fetch(PL_fdpid,savefd,TRUE);
734 SvUPGRADE(sv, SVt_IV);
740 /* need to close fp without closing underlying fd */
741 int ofd = PerlIO_fileno(fp);
742 int dupfd = ofd >= 0 ? PerlLIO_dup(ofd) : -1;
743 #if defined(HAS_FCNTL) && defined(F_SETFD)
744 /* Assume if we have F_SETFD we have F_GETFD. */
745 /* Get a copy of all the fd flags. */
746 int fd_flags = ofd >= 0 ? fcntl(ofd, F_GETFD) : -1;
749 PerlLIO_close(dupfd);
753 if (ofd < 0 || dupfd < 0) {
755 PerlLIO_close(dupfd);
759 PerlLIO_dup2(dupfd, ofd);
760 #if defined(HAS_FCNTL) && defined(F_SETFD)
761 /* The dup trick has lost close-on-exec on ofd,
762 * and possibly any other flags, so restore them. */
763 fcntl(ofd,F_SETFD, fd_flags);
765 PerlLIO_close(dupfd);
772 fd = PerlIO_fileno(fp);
774 #if defined(HAS_FCNTL) && defined(F_SETFD) && defined(FD_CLOEXEC)
775 if (fd >= 0 && fd > PL_maxsysfd && fcntl(fd, F_SETFD, FD_CLOEXEC) < 0) {
782 IoFLAGS(io) &= ~IOf_NOLINE;
784 if (IoTYPE(io) == IoTYPE_SOCKET
785 || (IoTYPE(io) == IoTYPE_WRONLY && fd >= 0 && S_ISCHR(PL_statbuf.st_mode)) ) {
787 if (*s == IoTYPE_IMPLICIT || *s == IoTYPE_NUMERIC)
790 if (!(IoOFP(io) = PerlIO_openn(aTHX_ type,s,fd,0,0,NULL,0,NULL))) {
803 IoTYPE(io) = savetype;
808 Perl_nextargv(pTHX_ GV *gv, bool nomagicopen)
810 IO * const io = GvIOp(gv);
812 PERL_ARGS_ASSERT_NEXTARGV;
815 PL_argvoutgv = gv_fetchpvs("ARGVOUT", GV_ADD|GV_NOTQUAL, SVt_PVIO);
816 if (io && (IoFLAGS(io) & (IOf_ARGV|IOf_START)) == (IOf_ARGV|IOf_START)) {
817 IoFLAGS(io) &= ~IOf_START;
820 Perl_av_create_and_push(aTHX_ &PL_argvout_stack,
821 SvREFCNT_inc_simple_NN(PL_defoutgv));
824 if (PL_filemode & (S_ISUID|S_ISGID)) {
825 PerlIO_flush(IoIFP(GvIOn(PL_argvoutgv))); /* chmod must follow last write */
828 (void)fchmod(PL_lastfd,PL_filemode);
830 (void)PerlLIO_chmod(PL_oldname,PL_filemode);
837 while (av_tindex(GvAV(gv)) >= 0) {
840 SV *const sv = av_shift(GvAV(gv));
842 SvTAINTED_off(GvSVn(gv)); /* previous tainting irrelevant */
843 sv_setsv(GvSVn(gv),sv);
844 SvSETMAGIC(GvSV(gv));
845 PL_oldname = SvPVx(GvSV(gv), oldlen);
846 if (LIKELY(!PL_inplace)) {
848 ? do_open6(gv, "<", 1, NULL, &GvSV(gv), 1)
849 : do_open6(gv, PL_oldname, oldlen, NULL, NULL, 0)
851 return IoIFP(GvIOp(gv));
855 /* This very long block ends with return IoIFP(GvIOp(gv));
856 Both this block and the block above fall through on open
857 failure to the warning code, and then the while loop above tries
859 if (do_open_raw(gv, PL_oldname, oldlen, O_RDONLY, 0)) {
860 #ifndef FLEXFILENAMES
867 TAINT_PROPER("inplace open");
868 if (oldlen == 1 && *PL_oldname == '-') {
869 setdefout(gv_fetchpvs("STDOUT", GV_ADD|GV_NOTQUAL,
871 return IoIFP(GvIOp(gv));
873 #ifndef FLEXFILENAMES
874 filedev = PL_statbuf.st_dev;
875 fileino = PL_statbuf.st_ino;
877 PL_filemode = PL_statbuf.st_mode;
878 fileuid = PL_statbuf.st_uid;
879 filegid = PL_statbuf.st_gid;
880 if (!S_ISREG(PL_filemode)) {
881 Perl_ck_warner_d(aTHX_ packWARN(WARN_INPLACE),
882 "Can't do inplace edit: %s is not a regular file",
887 if (*PL_inplace && strNE(PL_inplace, "*")) {
888 const char *star = strchr(PL_inplace, '*');
890 const char *begin = PL_inplace;
893 sv_catpvn(sv, begin, star - begin);
894 sv_catpvn(sv, PL_oldname, oldlen);
896 } while ((star = strchr(begin, '*')));
901 sv_catpv(sv,PL_inplace);
903 #ifndef FLEXFILENAMES
904 if ((PerlLIO_stat(SvPVX_const(sv),&PL_statbuf) >= 0
905 && PL_statbuf.st_dev == filedev
906 && PL_statbuf.st_ino == fileino)
908 || ((_djstat_fail_bits & _STFAIL_TRUENAME)!=0)
912 Perl_ck_warner_d(aTHX_ packWARN(WARN_INPLACE),
913 "Can't do inplace edit: %"SVf" would not be unique",
920 #if !defined(DOSISH) && !defined(__CYGWIN__)
921 if (PerlLIO_rename(PL_oldname,SvPVX_const(sv)) < 0) {
922 Perl_ck_warner_d(aTHX_ packWARN(WARN_INPLACE),
923 "Can't rename %s to %"SVf": %s, skipping file",
924 PL_oldname, SVfARG(sv), Strerror(errno));
930 (void)PerlLIO_unlink(SvPVX_const(sv));
931 (void)PerlLIO_rename(PL_oldname,SvPVX_const(sv));
932 do_open_raw(gv, SvPVX_const(sv), SvCUR(sv), O_RDONLY, 0);
935 (void)UNLINK(SvPVX_const(sv));
936 if (link(PL_oldname,SvPVX_const(sv)) < 0) {
937 Perl_ck_warner_d(aTHX_ packWARN(WARN_INPLACE),
938 "Can't rename %s to %"SVf": %s, skipping file",
939 PL_oldname, SVfARG(sv), Strerror(errno) );
943 (void)UNLINK(PL_oldname);
947 #if !defined(DOSISH) && !defined(__amigaos4__)
948 # ifndef VMS /* Don't delete; use automatic file versioning */
949 if (UNLINK(PL_oldname) < 0) {
950 Perl_ck_warner_d(aTHX_ packWARN(WARN_INPLACE),
951 "Can't remove %s: %s, skipping file",
952 PL_oldname, Strerror(errno) );
958 Perl_croak(aTHX_ "Can't do inplace edit without backup");
962 sv_setpvn(sv,PL_oldname,oldlen);
963 SETERRNO(0,0); /* in case sprintf set errno */
964 if (!Perl_do_open_raw(aTHX_ PL_argvoutgv, SvPVX_const(sv),
967 O_WRONLY|O_CREAT|O_TRUNC, 0
969 O_WRONLY|O_CREAT|OPEN_EXCL, 0600
972 Perl_ck_warner_d(aTHX_ packWARN(WARN_INPLACE), "Can't do inplace edit on %s: %s",
973 PL_oldname, Strerror(errno) );
977 setdefout(PL_argvoutgv);
978 PL_lastfd = PerlIO_fileno(IoIFP(GvIOp(PL_argvoutgv)));
979 if (PL_lastfd >= 0) {
980 (void)PerlLIO_fstat(PL_lastfd,&statbuf);
982 (void)fchmod(PL_lastfd,PL_filemode);
984 (void)PerlLIO_chmod(PL_oldname,PL_filemode);
986 if (fileuid != statbuf.st_uid || filegid != statbuf.st_gid) {
987 /* XXX silently ignore failures */
989 PERL_UNUSED_RESULT(fchown(PL_lastfd,fileuid,filegid));
992 PERL_UNUSED_RESULT(PerlLIO_chown(PL_oldname,fileuid,filegid));
997 return IoIFP(GvIOp(gv));
999 } /* successful do_open_raw(), PL_inplace non-NULL */
1001 if (ckWARN_d(WARN_INPLACE)) {
1002 const int eno = errno;
1003 if (PerlLIO_stat(PL_oldname, &statbuf) >= 0
1004 && !S_ISREG(statbuf.st_mode)) {
1005 Perl_warner(aTHX_ packWARN(WARN_INPLACE),
1006 "Can't do inplace edit: %s is not a regular file",
1010 Perl_warner(aTHX_ packWARN(WARN_INPLACE), "Can't open %s: %s",
1011 PL_oldname, Strerror(eno));
1015 if (io && (IoFLAGS(io) & IOf_ARGV))
1016 IoFLAGS(io) |= IOf_START;
1018 (void)do_close(PL_argvoutgv,FALSE);
1019 if (io && (IoFLAGS(io) & IOf_ARGV)
1020 && PL_argvout_stack && AvFILLp(PL_argvout_stack) >= 0)
1022 GV * const oldout = MUTABLE_GV(av_pop(PL_argvout_stack));
1024 SvREFCNT_dec_NN(oldout);
1027 setdefout(gv_fetchpvs("STDOUT", GV_ADD|GV_NOTQUAL, SVt_PVIO));
1032 /* explicit renamed to avoid C++ conflict -- kja */
1034 Perl_do_close(pTHX_ GV *gv, bool not_implicit)
1041 if (!gv || !isGV_with_GP(gv)) {
1043 SETERRNO(EBADF,SS_IVCHAN);
1047 if (!io) { /* never opened */
1050 SETERRNO(EBADF,SS_IVCHAN);
1054 retval = io_close(io, NULL, not_implicit, FALSE);
1058 IoLINES_LEFT(io) = IoPAGE_LEN(io);
1060 IoTYPE(io) = IoTYPE_CLOSED;
1065 Perl_io_close(pTHX_ IO *io, GV *gv, bool not_implicit, bool warn_on_fail)
1067 bool retval = FALSE;
1069 PERL_ARGS_ASSERT_IO_CLOSE;
1072 if (IoTYPE(io) == IoTYPE_PIPE) {
1073 const int status = PerlProc_pclose(IoIFP(io));
1075 STATUS_NATIVE_CHILD_SET(status);
1076 retval = (STATUS_UNIX == 0);
1079 retval = (status != -1);
1082 else if (IoTYPE(io) == IoTYPE_STD)
1085 if (IoOFP(io) && IoOFP(io) != IoIFP(io)) { /* a socket */
1086 const bool prev_err = PerlIO_error(IoOFP(io));
1089 PerlIO_restore_errno(IoOFP(io));
1091 retval = (PerlIO_close(IoOFP(io)) != EOF && !prev_err);
1092 PerlIO_close(IoIFP(io)); /* clear stdio, fd already closed */
1095 const bool prev_err = PerlIO_error(IoIFP(io));
1098 PerlIO_restore_errno(IoIFP(io));
1100 retval = (PerlIO_close(IoIFP(io)) != EOF && !prev_err);
1103 IoOFP(io) = IoIFP(io) = NULL;
1105 if (warn_on_fail && !retval) {
1107 Perl_ck_warner_d(aTHX_ packWARN(WARN_IO),
1108 "Warning: unable to close filehandle %"
1109 HEKf" properly: %"SVf,
1110 HEKfARG(GvNAME_HEK(gv)),
1111 SVfARG(get_sv("!",GV_ADD)));
1113 Perl_ck_warner_d(aTHX_ packWARN(WARN_IO),
1114 "Warning: unable to close filehandle "
1116 SVfARG(get_sv("!",GV_ADD)));
1119 else if (not_implicit) {
1120 SETERRNO(EBADF,SS_IVCHAN);
1127 Perl_do_eof(pTHX_ GV *gv)
1129 IO * const io = GvIO(gv);
1131 PERL_ARGS_ASSERT_DO_EOF;
1135 else if (IoTYPE(io) == IoTYPE_WRONLY)
1136 report_wrongway_fh(gv, '>');
1139 if (PerlIO_has_cntptr(IoIFP(io))) { /* (the code works without this) */
1140 if (PerlIO_get_cnt(IoIFP(io)) > 0) /* cheat a little, since */
1141 return FALSE; /* this is the most usual case */
1145 /* getc and ungetc can stomp on errno */
1147 const int ch = PerlIO_getc(IoIFP(io));
1149 (void)PerlIO_ungetc(IoIFP(io),ch);
1156 if (PerlIO_has_cntptr(IoIFP(io)) && PerlIO_canset_cnt(IoIFP(io))) {
1157 if (PerlIO_get_cnt(IoIFP(io)) < -1)
1158 PerlIO_set_cnt(IoIFP(io),-1);
1160 if (PL_op->op_flags & OPf_SPECIAL) { /* not necessarily a real EOF yet? */
1161 if (gv != PL_argvgv || !nextargv(gv, FALSE)) /* get another fp handy */
1165 return TRUE; /* normal fp, definitely end of file */
1171 Perl_do_tell(pTHX_ GV *gv)
1173 IO *const io = GvIO(gv);
1176 PERL_ARGS_ASSERT_DO_TELL;
1178 if (io && (fp = IoIFP(io))) {
1179 return PerlIO_tell(fp);
1182 SETERRNO(EBADF,RMS_IFI);
1187 Perl_do_seek(pTHX_ GV *gv, Off_t pos, int whence)
1189 IO *const io = GvIO(gv);
1192 if (io && (fp = IoIFP(io))) {
1193 return PerlIO_seek(fp, pos, whence) >= 0;
1196 SETERRNO(EBADF,RMS_IFI);
1201 Perl_do_sysseek(pTHX_ GV *gv, Off_t pos, int whence)
1203 IO *const io = GvIO(gv);
1206 PERL_ARGS_ASSERT_DO_SYSSEEK;
1208 if (io && (fp = IoIFP(io))) {
1209 int fd = PerlIO_fileno(fp);
1210 if (fd < 0 || (whence == SEEK_SET && pos < 0)) {
1211 SETERRNO(EINVAL,LIB_INVARG);
1214 return PerlLIO_lseek(fd, pos, whence);
1218 SETERRNO(EBADF,RMS_IFI);
1223 Perl_mode_from_discipline(pTHX_ const char *s, STRLEN len)
1225 int mode = O_BINARY;
1226 PERL_UNUSED_CONTEXT;
1232 if (s[2] == 'a' && s[3] == 'w'
1233 && (!s[4] || s[4] == ':' || isSPACE(s[4])))
1242 if (s[2] == 'r' && s[3] == 'l' && s[4] == 'f'
1243 && (!s[5] || s[5] == ':' || isSPACE(s[5])))
1252 goto fail_discipline;
1255 else if (isSPACE(*s)) {
1262 end = strchr(s+1, ':');
1265 #ifndef PERLIO_LAYERS
1266 Perl_croak(aTHX_ "IO layers (like '%.*s') unavailable", end-s, s);
1277 #if !defined(HAS_TRUNCATE) && !defined(HAS_CHSIZE)
1279 my_chsize(int fd, Off_t length)
1282 /* code courtesy of William Kucharski */
1287 if (PerlLIO_fstat(fd, &filebuf) < 0)
1290 if (filebuf.st_size < length) {
1292 /* extend file length */
1294 if ((PerlLIO_lseek(fd, (length - 1), 0)) < 0)
1297 /* write a "0" byte */
1299 if ((PerlLIO_write(fd, "", 1)) != 1)
1303 /* truncate length */
1307 fl.l_start = length;
1308 fl.l_type = F_WRLCK; /* write lock on file space */
1311 * This relies on the UNDOCUMENTED F_FREESP argument to
1312 * fcntl(2), which truncates the file so that it ends at the
1313 * position indicated by fl.l_start.
1315 * Will minor miracles never cease?
1318 if (fcntl(fd, F_FREESP, &fl) < 0)
1324 Perl_croak_nocontext("truncate not implemented");
1325 #endif /* F_FREESP */
1328 #endif /* !HAS_TRUNCATE && !HAS_CHSIZE */
1331 Perl_do_print(pTHX_ SV *sv, PerlIO *fp)
1333 PERL_ARGS_ASSERT_DO_PRINT;
1335 /* assuming fp is checked earlier */
1338 if (SvTYPE(sv) == SVt_IV && SvIOK(sv)) {
1339 assert(!SvGMAGICAL(sv));
1341 PerlIO_printf(fp, "%"UVuf, (UV)SvUVX(sv));
1343 PerlIO_printf(fp, "%"IVdf, (IV)SvIVX(sv));
1344 return !PerlIO_error(fp);
1348 /* Do this first to trigger any overloading. */
1349 const char *tmps = SvPV_const(sv, len);
1353 if (PerlIO_isutf8(fp)) { /* If the stream is utf8 ... */
1354 if (!SvUTF8(sv)) { /* Convert to utf8 if necessary */
1355 /* We don't modify the original scalar. */
1356 tmpbuf = bytes_to_utf8((const U8*) tmps, &len);
1357 tmps = (char *) tmpbuf;
1359 else if (ckWARN4_d(WARN_UTF8, WARN_SURROGATE, WARN_NON_UNICODE, WARN_NONCHAR)) {
1360 (void) check_utf8_print((const U8*) tmps, len);
1362 } /* else stream isn't utf8 */
1363 else if (DO_UTF8(sv)) { /* But if is utf8 internally, attempt to
1365 STRLEN tmplen = len;
1367 U8 * const result = bytes_from_utf8((const U8*) tmps, &tmplen, &utf8);
1370 /* Here, succeeded in downgrading from utf8. Set up to below
1371 * output the converted value */
1373 tmps = (char *) tmpbuf;
1376 else { /* Non-utf8 output stream, but string only representable in
1378 assert((char *)result == tmps);
1379 Perl_ck_warner_d(aTHX_ packWARN(WARN_UTF8),
1380 "Wide character in %s",
1381 PL_op ? OP_DESC(PL_op) : "print"
1383 /* Could also check that isn't one of the things to avoid
1384 * in utf8 by using check_utf8_print(), but not doing so,
1385 * since the stream isn't a UTF8 stream */
1388 /* To detect whether the process is about to overstep its
1389 * filesize limit we would need getrlimit(). We could then
1390 * also transparently raise the limit with setrlimit() --
1391 * but only until the system hard limit/the filesystem limit,
1392 * at which we would get EPERM. Note that when using buffered
1393 * io the write failure can be delayed until the flush/close. --jhi */
1394 if (len && (PerlIO_write(fp,tmps,len) == 0))
1397 return happy ? !PerlIO_error(fp) : FALSE;
1402 Perl_my_stat_flags(pTHX_ const U32 flags)
1408 if (PL_op->op_flags & OPf_REF) {
1412 return PL_laststatval;
1415 PL_laststype = OP_STAT;
1416 PL_statgv = gv ? gv : (GV *)io;
1417 sv_setpvs(PL_statname, "");
1420 int fd = PerlIO_fileno(IoIFP(io));
1422 /* E.g. PerlIO::scalar has no real fd. */
1423 return (PL_laststatval = -1);
1425 return (PL_laststatval = PerlLIO_fstat(fd, &PL_statcache));
1427 } else if (IoDIRP(io)) {
1428 return (PL_laststatval = PerlLIO_fstat(my_dirfd(IoDIRP(io)), &PL_statcache));
1431 PL_laststatval = -1;
1435 else if ((PL_op->op_private & (OPpFT_STACKED|OPpFT_AFTER_t))
1437 return PL_laststatval;
1439 SV* const sv = TOPs;
1442 if ((gv = MAYBE_DEREF_GV_flags(sv,flags))) {
1445 else if (SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVIO) {
1446 io = MUTABLE_IO(SvRV(sv));
1448 goto do_fstat_have_io;
1451 s = SvPV_flags_const(sv, len, flags);
1453 sv_setpvn(PL_statname, s, len);
1454 s = SvPVX_const(PL_statname); /* s now NUL-terminated */
1455 PL_laststype = OP_STAT;
1456 PL_laststatval = PerlLIO_stat(s, &PL_statcache);
1457 if (PL_laststatval < 0 && ckWARN(WARN_NEWLINE) && should_warn_nl(s)) {
1458 GCC_DIAG_IGNORE(-Wformat-nonliteral); /* PL_warn_nl is constant */
1459 Perl_warner(aTHX_ packWARN(WARN_NEWLINE), PL_warn_nl, "stat");
1462 return PL_laststatval;
1468 Perl_my_lstat_flags(pTHX_ const U32 flags)
1470 static const char* const no_prev_lstat = "The stat preceding -l _ wasn't an lstat";
1473 SV* const sv = TOPs;
1475 if (PL_op->op_flags & OPf_REF) {
1476 if (cGVOP_gv == PL_defgv) {
1477 if (PL_laststype != OP_LSTAT)
1478 Perl_croak(aTHX_ "%s", no_prev_lstat);
1479 return PL_laststatval;
1481 PL_laststatval = -1;
1482 if (ckWARN(WARN_IO)) {
1483 /* diag_listed_as: Use of -l on filehandle%s */
1484 Perl_warner(aTHX_ packWARN(WARN_IO),
1485 "Use of -l on filehandle %"HEKf,
1486 HEKfARG(GvENAME_HEK(cGVOP_gv)));
1490 if ((PL_op->op_private & (OPpFT_STACKED|OPpFT_AFTER_t))
1492 if (PL_laststype != OP_LSTAT)
1493 Perl_croak(aTHX_ "%s", no_prev_lstat);
1494 return PL_laststatval;
1497 PL_laststype = OP_LSTAT;
1499 if ( ( (SvROK(sv) && ( isGV_with_GP(SvRV(sv))
1500 || (isio = SvTYPE(SvRV(sv)) == SVt_PVIO) )
1504 && ckWARN(WARN_IO)) {
1506 /* diag_listed_as: Use of -l on filehandle%s */
1507 Perl_warner(aTHX_ packWARN(WARN_IO),
1508 "Use of -l on filehandle");
1510 /* diag_listed_as: Use of -l on filehandle%s */
1511 Perl_warner(aTHX_ packWARN(WARN_IO),
1512 "Use of -l on filehandle %"HEKf,
1513 HEKfARG(GvENAME_HEK((const GV *)
1514 (SvROK(sv) ? SvRV(sv) : sv))));
1516 file = SvPV_flags_const_nolen(sv, flags);
1517 sv_setpv(PL_statname,file);
1518 PL_laststatval = PerlLIO_lstat(file,&PL_statcache);
1519 if (PL_laststatval < 0 && ckWARN(WARN_NEWLINE) && should_warn_nl(file)) {
1520 GCC_DIAG_IGNORE(-Wformat-nonliteral); /* PL_warn_nl is constant */
1521 Perl_warner(aTHX_ packWARN(WARN_NEWLINE), PL_warn_nl, "lstat");
1524 return PL_laststatval;
1528 S_exec_failed(pTHX_ const char *cmd, int fd, int do_report)
1530 const int e = errno;
1531 PERL_ARGS_ASSERT_EXEC_FAILED;
1533 if (ckWARN(WARN_EXEC))
1534 Perl_warner(aTHX_ packWARN(WARN_EXEC), "Can't exec \"%s\": %s",
1537 /* XXX silently ignore failures */
1538 PERL_UNUSED_RESULT(PerlLIO_write(fd, (void*)&e, sizeof(int)));
1544 Perl_do_aexec5(pTHX_ SV *really, SV **mark, SV **sp,
1545 int fd, int do_report)
1548 PERL_ARGS_ASSERT_DO_AEXEC5;
1549 #if defined(__SYMBIAN32__) || defined(__LIBCATAMOUNT__)
1550 Perl_croak(aTHX_ "exec? I'm not *that* kind of operating system");
1554 const char *tmps = NULL;
1555 Newx(PL_Argv, sp - mark + 1, const char*);
1558 while (++mark <= sp) {
1560 *a++ = SvPV_nolen_const(*mark);
1566 tmps = SvPV_nolen_const(really);
1567 if ((!really && *PL_Argv[0] != '/') ||
1568 (really && *tmps != '/')) /* will execvp use PATH? */
1569 TAINT_ENV(); /* testing IFS here is overkill, probably */
1571 if (really && *tmps) {
1572 PerlProc_execvp(tmps,EXEC_ARGV_CAST(PL_Argv));
1574 PerlProc_execvp(PL_Argv[0],EXEC_ARGV_CAST(PL_Argv));
1577 S_exec_failed(aTHX_ (really ? tmps : PL_Argv[0]), fd, do_report);
1585 Perl_do_execfree(pTHX)
1593 #ifdef PERL_DEFAULT_DO_EXEC3_IMPLEMENTATION
1596 Perl_do_exec3(pTHX_ const char *incmd, int fd, int do_report)
1603 /* Make a copy so we can change it */
1604 const Size_t cmdlen = strlen(incmd) + 1;
1606 PERL_ARGS_ASSERT_DO_EXEC3;
1608 Newx(buf, cmdlen, char);
1610 memcpy(cmd, incmd, cmdlen);
1612 while (*cmd && isSPACE(*cmd))
1615 /* save an extra exec if possible */
1619 char flags[PERL_FLAGS_MAX];
1620 if (strnEQ(cmd,PL_cshname,PL_cshlen) &&
1621 strnEQ(cmd+PL_cshlen," -c",3)) {
1622 my_strlcpy(flags, "-c", PERL_FLAGS_MAX);
1623 s = cmd+PL_cshlen+3;
1626 my_strlcat(flags, "f", PERL_FLAGS_MAX - 2);
1631 char * const ncmd = s;
1637 if (s[-1] == '\'') {
1640 PerlProc_execl(PL_cshname, "csh", flags, ncmd, (char*)NULL);
1643 S_exec_failed(aTHX_ PL_cshname, fd, do_report);
1652 /* see if there are shell metacharacters in it */
1654 if (*cmd == '.' && isSPACE(cmd[1]))
1657 if (strnEQ(cmd,"exec",4) && isSPACE(cmd[4]))
1661 while (isWORDCHAR(*s))
1662 s++; /* catch VAR=val gizmo */
1666 for (s = cmd; *s; s++) {
1667 if (*s != ' ' && !isALPHA(*s) &&
1668 strchr("$&*(){}[]'\";\\|?<>~`\n",*s)) {
1669 if (*s == '\n' && !s[1]) {
1673 /* handle the 2>&1 construct at the end */
1674 if (*s == '>' && s[1] == '&' && s[2] == '1'
1675 && s > cmd + 1 && s[-1] == '2' && isSPACE(s[-2])
1676 && (!s[3] || isSPACE(s[3])))
1678 const char *t = s + 3;
1680 while (*t && isSPACE(*t))
1682 if (!*t && (PerlLIO_dup2(1,2) != -1)) {
1689 PerlProc_execl(PL_sh_path, "sh", "-c", cmd, (char *)NULL);
1691 S_exec_failed(aTHX_ PL_sh_path, fd, do_report);
1697 Newx(PL_Argv, (s - cmd) / 2 + 2, const char*);
1698 PL_Cmd = savepvn(cmd, s-cmd);
1700 for (s = PL_Cmd; *s;) {
1705 while (*s && !isSPACE(*s))
1713 PerlProc_execvp(PL_Argv[0],EXEC_ARGV_CAST(PL_Argv));
1715 if (errno == ENOEXEC) { /* for system V NIH syndrome */
1719 S_exec_failed(aTHX_ PL_Argv[0], fd, do_report);
1726 #endif /* OS2 || WIN32 */
1729 Perl_apply(pTHX_ I32 type, SV **mark, SV **sp)
1733 const char *const what = PL_op_name[type];
1736 SV ** const oldmark = mark;
1737 bool killgp = FALSE;
1739 PERL_ARGS_ASSERT_APPLY;
1741 PERL_UNUSED_VAR(what); /* may not be used depending on compile options */
1743 /* Doing this ahead of the switch statement preserves the old behaviour,
1744 where attempting to use kill as a taint test test would fail on
1745 platforms where kill was not defined. */
1747 if (type == OP_KILL)
1748 Perl_die(aTHX_ PL_no_func, what);
1751 if (type == OP_CHOWN)
1752 Perl_die(aTHX_ PL_no_func, what);
1756 #define APPLY_TAINT_PROPER() \
1758 if (TAINT_get) { TAINT_PROPER(what); } \
1761 /* This is a first heuristic; it doesn't catch tainting magic. */
1763 while (++mark <= sp) {
1764 if (SvTAINTED(*mark)) {
1773 APPLY_TAINT_PROPER();
1776 APPLY_TAINT_PROPER();
1778 while (++mark <= sp) {
1780 if ((gv = MAYBE_DEREF_GV(*mark))) {
1781 if (GvIO(gv) && IoIFP(GvIOp(gv))) {
1783 int fd = PerlIO_fileno(IoIFP(GvIOn(gv)));
1784 APPLY_TAINT_PROPER();
1786 SETERRNO(EBADF,RMS_IFI);
1788 } else if (fchmod(fd, val))
1791 Perl_die(aTHX_ PL_no_func, "fchmod");
1795 SETERRNO(EBADF,RMS_IFI);
1800 const char *name = SvPV_nomg_const(*mark, len);
1801 APPLY_TAINT_PROPER();
1802 if (!IS_SAFE_PATHNAME(name, len, "chmod") ||
1803 PerlLIO_chmod(name, val)) {
1812 APPLY_TAINT_PROPER();
1813 if (sp - mark > 2) {
1815 val = SvIVx(*++mark);
1816 val2 = SvIVx(*++mark);
1817 APPLY_TAINT_PROPER();
1819 while (++mark <= sp) {
1821 if ((gv = MAYBE_DEREF_GV(*mark))) {
1822 if (GvIO(gv) && IoIFP(GvIOp(gv))) {
1824 int fd = PerlIO_fileno(IoIFP(GvIOn(gv)));
1825 APPLY_TAINT_PROPER();
1827 SETERRNO(EBADF,RMS_IFI);
1830 } else if (val < 0) {
1831 SETERRNO(EINVAL,LIB_INVARG);
1835 } else if (val2 < 0) {
1836 SETERRNO(EINVAL,LIB_INVARG);
1839 } else if (fchown(fd, val, val2))
1842 Perl_die(aTHX_ PL_no_func, "fchown");
1846 SETERRNO(EBADF,RMS_IFI);
1851 const char *name = SvPV_nomg_const(*mark, len);
1852 APPLY_TAINT_PROPER();
1853 if (!IS_SAFE_PATHNAME(name, len, "chown") ||
1854 PerlLIO_chown(name, val, val2)) {
1863 XXX Should we make lchown() directly available from perl?
1864 For now, we'll let Configure test for HAS_LCHOWN, but do
1865 nothing in the core.
1870 APPLY_TAINT_PROPER();
1873 s = SvPVx_const(*++mark, len);
1874 if (*s == '-' && isALPHA(s[1]))
1881 if (*s == 'S' && s[1] == 'I' && s[2] == 'G') {
1885 if ((val = whichsig_pvn(s, len)) < 0)
1886 Perl_croak(aTHX_ "Unrecognized signal name \"%"SVf"\"", SVfARG(*mark));
1897 APPLY_TAINT_PROPER();
1900 while (++mark <= sp) {
1903 if (!(SvNIOK(*mark) || looks_like_number(*mark)))
1904 Perl_croak(aTHX_ "Can't kill a non-numeric process ID");
1905 proc = SvIV_nomg(*mark);
1906 APPLY_TAINT_PROPER();
1908 /* use killpg in preference, as the killpg() wrapper for Win32
1909 * understands process groups, but the kill() wrapper doesn't */
1910 if (killgp ? PerlProc_killpg(proc, val)
1911 : PerlProc_kill(proc, val))
1913 if (PerlProc_kill(killgp ? -proc: proc, val))
1921 APPLY_TAINT_PROPER();
1923 while (++mark <= sp) {
1924 s = SvPV_const(*mark, len);
1925 APPLY_TAINT_PROPER();
1926 if (!IS_SAFE_PATHNAME(s, len, "unlink")) {
1929 else if (PL_unsafe) {
1934 #if defined(__amigaos4__) && defined(NEWLIB)
1937 /* Under AmigaOS4 unlink only 'fails' if the
1938 * filename is invalid. It may not remove the file
1939 * if it's locked, so check if it's still around. */
1940 if ((access(s,F_OK) != -1))
1947 else { /* don't let root wipe out directories without -U */
1949 if (PerlLIO_lstat(s, &statbuf) < 0)
1951 else if (S_ISDIR(statbuf.st_mode)) {
1952 SETERRNO(EISDIR, SS_NOPRIV);
1960 #if defined(__amigaos4__) && defined(NEWLIB)
1963 /* Under AmigaOS4 unlink only 'fails' if the filename is invalid */
1964 /* It may not remove the file if it's Locked, so check if it's still */
1966 if((access(s,F_OK) != -1))
1976 #if defined(HAS_UTIME) || defined(HAS_FUTIMES)
1978 APPLY_TAINT_PROPER();
1979 if (sp - mark > 2) {
1980 #if defined(HAS_FUTIMES)
1981 struct timeval utbuf[2];
1982 void *utbufp = utbuf;
1983 #elif defined(I_UTIME) || defined(VMS)
1984 struct utimbuf utbuf;
1985 struct utimbuf *utbufp = &utbuf;
1991 void *utbufp = &utbuf;
1994 SV* const accessed = *++mark;
1995 SV* const modified = *++mark;
1997 /* Be like C, and if both times are undefined, let the C
1998 * library figure out what to do. This usually means
1999 * "current time". */
2001 if ( accessed == &PL_sv_undef && modified == &PL_sv_undef )
2004 Zero(&utbuf, sizeof utbuf, char);
2006 utbuf[0].tv_sec = (long)SvIV(accessed); /* time accessed */
2007 utbuf[0].tv_usec = 0;
2008 utbuf[1].tv_sec = (long)SvIV(modified); /* time modified */
2009 utbuf[1].tv_usec = 0;
2010 #elif defined(BIG_TIME)
2011 utbuf.actime = (Time_t)SvNV(accessed); /* time accessed */
2012 utbuf.modtime = (Time_t)SvNV(modified); /* time modified */
2014 utbuf.actime = (Time_t)SvIV(accessed); /* time accessed */
2015 utbuf.modtime = (Time_t)SvIV(modified); /* time modified */
2018 APPLY_TAINT_PROPER();
2020 while (++mark <= sp) {
2022 if ((gv = MAYBE_DEREF_GV(*mark))) {
2023 if (GvIO(gv) && IoIFP(GvIOp(gv))) {
2025 int fd = PerlIO_fileno(IoIFP(GvIOn(gv)));
2026 APPLY_TAINT_PROPER();
2028 SETERRNO(EBADF,RMS_IFI);
2030 } else if (futimes(fd, (struct timeval *) utbufp))
2033 Perl_die(aTHX_ PL_no_func, "futimes");
2041 const char * const name = SvPV_nomg_const(*mark, len);
2042 APPLY_TAINT_PROPER();
2043 if (!IS_SAFE_PATHNAME(name, len, "utime")) {
2048 if (utimes(name, (struct timeval *)utbufp))
2050 if (PerlLIO_utime(name, utbufp))
2064 #undef APPLY_TAINT_PROPER
2067 /* Do the permissions allow some operation? Assumes statcache already set. */
2068 #ifndef VMS /* VMS' cando is in vms.c */
2070 Perl_cando(pTHX_ Mode_t mode, bool effective, const Stat_t *statbufp)
2071 /* effective is a flag, true for EUID, or for checking if the effective gid
2072 * is in the list of groups returned from getgroups().
2075 PERL_ARGS_ASSERT_CANDO;
2076 PERL_UNUSED_CONTEXT;
2079 /* [Comments and code from Len Reed]
2080 * MS-DOS "user" is similar to UNIX's "superuser," but can't write
2081 * to write-protected files. The execute permission bit is set
2082 * by the Microsoft C library stat() function for the following:
2087 * All files and directories are readable.
2088 * Directories and special files, e.g. "CON", cannot be
2090 * [Comment by Tom Dinger -- a directory can have the write-protect
2091 * bit set in the file system, but DOS permits changes to
2092 * the directory anyway. In addition, all bets are off
2093 * here for networked software, such as Novell and
2097 /* Atari stat() does pretty much the same thing. we set x_bit_set_in_stat
2098 * too so it will actually look into the files for magic numbers
2100 return (mode & statbufp->st_mode) ? TRUE : FALSE;
2102 #else /* ! DOSISH */
2104 if (ingroup(544,effective)) { /* member of Administrators */
2106 if ((effective ? PerlProc_geteuid() : PerlProc_getuid()) == 0) { /* root is special */
2108 if (mode == S_IXUSR) {
2109 if (statbufp->st_mode & 0111 || S_ISDIR(statbufp->st_mode))
2113 return TRUE; /* root reads and writes anything */
2116 if (statbufp->st_uid == (effective ? PerlProc_geteuid() : PerlProc_getuid()) ) {
2117 if (statbufp->st_mode & mode)
2118 return TRUE; /* ok as "user" */
2120 else if (ingroup(statbufp->st_gid,effective)) {
2121 if (statbufp->st_mode & mode >> 3)
2122 return TRUE; /* ok as "group" */
2124 else if (statbufp->st_mode & mode >> 6)
2125 return TRUE; /* ok as "other" */
2127 #endif /* ! DOSISH */
2132 S_ingroup(pTHX_ Gid_t testgid, bool effective)
2134 #ifndef PERL_IMPLICIT_SYS
2135 /* PERL_IMPLICIT_SYS like Win32: getegid() etc. require the context. */
2136 PERL_UNUSED_CONTEXT;
2138 if (testgid == (effective ? PerlProc_getegid() : PerlProc_getgid()))
2140 #ifdef HAS_GETGROUPS
2142 Groups_t *gary = NULL;
2146 anum = getgroups(0, gary);
2148 Newx(gary, anum, Groups_t);
2149 anum = getgroups(anum, gary);
2151 if (gary[anum] == testgid) {
2165 #if defined(HAS_MSG) || defined(HAS_SEM) || defined(HAS_SHM)
2168 Perl_do_ipcget(pTHX_ I32 optype, SV **mark, SV **sp)
2170 const key_t key = (key_t)SvNVx(*++mark);
2171 SV *nsv = optype == OP_MSGGET ? NULL : *++mark;
2172 const I32 flags = SvIVx(*++mark);
2174 PERL_ARGS_ASSERT_DO_IPCGET;
2175 PERL_UNUSED_ARG(sp);
2182 return msgget(key, flags);
2186 return semget(key, (int) SvIV(nsv), flags);
2190 return shmget(key, (size_t) SvUV(nsv), flags);
2192 #if !defined(HAS_MSG) || !defined(HAS_SEM) || !defined(HAS_SHM)
2194 /* diag_listed_as: msg%s not implemented */
2195 Perl_croak(aTHX_ "%s not implemented", PL_op_desc[optype]);
2198 return -1; /* should never happen */
2202 Perl_do_ipcctl(pTHX_ I32 optype, SV **mark, SV **sp)
2206 const I32 id = SvIVx(*++mark);
2208 const I32 n = (optype == OP_SEMCTL) ? SvIVx(*++mark) : 0;
2210 const I32 cmd = SvIVx(*++mark);
2211 SV * const astr = *++mark;
2212 STRLEN infosize = 0;
2213 I32 getinfo = (cmd == IPC_STAT);
2215 PERL_ARGS_ASSERT_DO_IPCCTL;
2216 PERL_UNUSED_ARG(sp);
2222 if (cmd == IPC_STAT || cmd == IPC_SET)
2223 infosize = sizeof(struct msqid_ds);
2228 if (cmd == IPC_STAT || cmd == IPC_SET)
2229 infosize = sizeof(struct shmid_ds);
2235 if (cmd == IPC_STAT || cmd == IPC_SET)
2236 infosize = sizeof(struct semid_ds);
2237 else if (cmd == GETALL || cmd == SETALL)
2239 struct semid_ds semds;
2241 #ifdef EXTRA_F_IN_SEMUN_BUF
2242 semun.buff = &semds;
2246 getinfo = (cmd == GETALL);
2247 if (Semctl(id, 0, IPC_STAT, semun) == -1)
2249 infosize = semds.sem_nsems * sizeof(short);
2250 /* "short" is technically wrong but much more portable
2251 than guessing about u_?short(_t)? */
2254 /* diag_listed_as: sem%s not implemented */
2255 Perl_croak(aTHX_ "%s not implemented", PL_op_desc[optype]);
2259 #if !defined(HAS_MSG) || !defined(HAS_SEM) || !defined(HAS_SHM)
2261 /* diag_listed_as: shm%s not implemented */
2262 Perl_croak(aTHX_ "%s not implemented", PL_op_desc[optype]);
2270 SvPV_force_nolen(astr);
2271 a = SvGROW(astr, infosize+1);
2276 a = SvPV(astr, len);
2277 if (len != infosize)
2278 Perl_croak(aTHX_ "Bad arg length for %s, is %lu, should be %ld",
2286 const IV i = SvIV(astr);
2287 a = INT2PTR(char *,i); /* ouch */
2294 ret = msgctl(id, cmd, (struct msqid_ds *)a);
2300 union semun unsemds;
2303 unsemds.val = PTR2nat(a);
2306 #ifdef EXTRA_F_IN_SEMUN_BUF
2307 unsemds.buff = (struct semid_ds *)a;
2309 unsemds.buf = (struct semid_ds *)a;
2312 ret = Semctl(id, n, cmd, unsemds);
2314 /* diag_listed_as: sem%s not implemented */
2315 Perl_croak(aTHX_ "%s not implemented", PL_op_desc[optype]);
2322 ret = shmctl(id, cmd, (struct shmid_ds *)a);
2326 if (getinfo && ret >= 0) {
2327 SvCUR_set(astr, infosize);
2328 *SvEND(astr) = '\0';
2335 Perl_do_msgsnd(pTHX_ SV **mark, SV **sp)
2339 const I32 id = SvIVx(*++mark);
2340 SV * const mstr = *++mark;
2341 const I32 flags = SvIVx(*++mark);
2342 const char * const mbuf = SvPV_const(mstr, len);
2343 const I32 msize = len - sizeof(long);
2345 PERL_ARGS_ASSERT_DO_MSGSND;
2346 PERL_UNUSED_ARG(sp);
2349 Perl_croak(aTHX_ "Arg too short for msgsnd");
2351 if (id >= 0 && flags >= 0) {
2352 return msgsnd(id, (struct msgbuf *)mbuf, msize, flags);
2354 SETERRNO(EINVAL,LIB_INVARG);
2358 PERL_UNUSED_ARG(sp);
2359 PERL_UNUSED_ARG(mark);
2360 /* diag_listed_as: msg%s not implemented */
2361 Perl_croak(aTHX_ "msgsnd not implemented");
2367 Perl_do_msgrcv(pTHX_ SV **mark, SV **sp)
2372 I32 msize, flags, ret;
2373 const I32 id = SvIVx(*++mark);
2374 SV * const mstr = *++mark;
2376 PERL_ARGS_ASSERT_DO_MSGRCV;
2377 PERL_UNUSED_ARG(sp);
2379 /* suppress warning when reading into undef var --jhi */
2381 sv_setpvs(mstr, "");
2382 msize = SvIVx(*++mark);
2383 mtype = (long)SvIVx(*++mark);
2384 flags = SvIVx(*++mark);
2385 SvPV_force_nolen(mstr);
2386 mbuf = SvGROW(mstr, sizeof(long)+msize+1);
2389 if (id >= 0 && msize >= 0 && flags >= 0) {
2390 ret = msgrcv(id, (struct msgbuf *)mbuf, msize, mtype, flags);
2392 SETERRNO(EINVAL,LIB_INVARG);
2396 SvCUR_set(mstr, sizeof(long)+ret);
2397 *SvEND(mstr) = '\0';
2398 /* who knows who has been playing with this message? */
2403 PERL_UNUSED_ARG(sp);
2404 PERL_UNUSED_ARG(mark);
2405 /* diag_listed_as: msg%s not implemented */
2406 Perl_croak(aTHX_ "msgrcv not implemented");
2412 Perl_do_semop(pTHX_ SV **mark, SV **sp)
2416 const I32 id = SvIVx(*++mark);
2417 SV * const opstr = *++mark;
2418 const char * const opbuf = SvPV_const(opstr, opsize);
2420 PERL_ARGS_ASSERT_DO_SEMOP;
2421 PERL_UNUSED_ARG(sp);
2423 if (opsize < 3 * SHORTSIZE
2424 || (opsize % (3 * SHORTSIZE))) {
2425 SETERRNO(EINVAL,LIB_INVARG);
2429 /* We can't assume that sizeof(struct sembuf) == 3 * sizeof(short). */
2431 const int nsops = opsize / (3 * sizeof (short));
2433 short * const ops = (short *) opbuf;
2435 struct sembuf *temps, *t;
2438 Newx (temps, nsops, struct sembuf);
2446 result = semop(id, temps, nsops);
2451 /* diag_listed_as: sem%s not implemented */
2452 Perl_croak(aTHX_ "semop not implemented");
2457 Perl_do_shmio(pTHX_ I32 optype, SV **mark, SV **sp)
2461 struct shmid_ds shmds;
2462 const I32 id = SvIVx(*++mark);
2463 SV * const mstr = *++mark;
2464 const I32 mpos = SvIVx(*++mark);
2465 const I32 msize = SvIVx(*++mark);
2467 PERL_ARGS_ASSERT_DO_SHMIO;
2468 PERL_UNUSED_ARG(sp);
2471 if (shmctl(id, IPC_STAT, &shmds) == -1)
2473 if (mpos < 0 || msize < 0
2474 || (size_t)mpos + msize > (size_t)shmds.shm_segsz) {
2475 SETERRNO(EFAULT,SS_ACCVIO); /* can't do as caller requested */
2479 shm = (char *)shmat(id, NULL, (optype == OP_SHMREAD) ? SHM_RDONLY : 0);
2481 SETERRNO(EINVAL,LIB_INVARG);
2484 if (shm == (char *)-1) /* I hate System V IPC, I really do */
2486 if (optype == OP_SHMREAD) {
2488 /* suppress warning when reading into undef var (tchrist 3/Mar/00) */
2490 SvUPGRADE(mstr, SVt_PV);
2492 sv_setpvs(mstr, "");
2494 mbuf = SvGROW(mstr, (STRLEN)msize+1);
2496 Copy(shm + mpos, mbuf, msize, char);
2497 SvCUR_set(mstr, msize);
2498 *SvEND(mstr) = '\0';
2500 /* who knows who has been playing with this shared memory? */
2506 const char *mbuf = SvPV_const(mstr, len);
2507 const I32 n = ((I32)len > msize) ? msize : (I32)len;
2508 Copy(mbuf, shm + mpos, n, char);
2510 memzero(shm + mpos + n, msize - n);
2514 /* diag_listed_as: shm%s not implemented */
2515 Perl_croak(aTHX_ "shm I/O not implemented");
2520 #endif /* SYSV IPC */
2525 =for apidoc start_glob
2527 Function called by C<do_readline> to spawn a glob (or do the glob inside
2528 perl on VMS). This code used to be inline, but now perl uses C<File::Glob>
2529 this glob starter is only used by miniperl during the build process,
2530 or when PERL_EXTERNAL_GLOB is defined.
2531 Moving it away shrinks F<pp_hot.c>; shrinking F<pp_hot.c> helps speed perl up.
2537 Perl_start_glob (pTHX_ SV *tmpglob, IO *io)
2539 SV * const tmpcmd = newSV(0);
2542 const char *s = SvPV(tmpglob, len);
2544 PERL_ARGS_ASSERT_START_GLOB;
2546 if (!IS_SAFE_SYSCALL(s, len, "pattern", "glob"))
2551 #ifdef VMS /* expand the wildcards right here, rather than opening a pipe, */
2552 /* since spawning off a process is a real performance hit */
2559 fp = Perl_vms_start_glob(aTHX_ tmpglob, io);
2564 sv_setpv(tmpcmd, "for a in ");
2565 sv_catsv(tmpcmd, tmpglob);
2566 sv_catpv(tmpcmd, "; do echo \"$a\\0\\c\"; done |");
2569 sv_setpv(tmpcmd, "/dev/dosglob/"); /* File System Extension */
2570 sv_catsv(tmpcmd, tmpglob);
2572 sv_setpv(tmpcmd, "perlglob ");
2573 sv_catsv(tmpcmd, tmpglob);
2574 sv_catpv(tmpcmd, " |");
2579 sv_setpvn(tmpcmd, PL_cshname, PL_cshlen);
2580 sv_catpv(tmpcmd, " -cf 'set nonomatch; glob ");
2581 sv_catsv(tmpcmd, tmpglob);
2582 sv_catpv(tmpcmd, "' 2>/dev/null |");
2584 sv_setpv(tmpcmd, "echo ");
2585 sv_catsv(tmpcmd, tmpglob);
2586 sv_catpv(tmpcmd, "|tr -s ' \t\f\r' '\\n\\n\\n\\n'|");
2588 #endif /* !DOSISH */
2590 GV * const envgv = gv_fetchpvs("ENV", 0, SVt_PVHV);
2591 SV ** const home = hv_fetchs(GvHV(envgv), "HOME", 0);
2592 SV ** const path = hv_fetchs(GvHV(envgv), "PATH", 0);
2593 if (home && *home) SvGETMAGIC(*home);
2594 if (path && *path) SvGETMAGIC(*path);
2595 save_hash(gv_fetchpvs("ENV", 0, SVt_PVHV));
2596 if (home && *home) SvSETMAGIC(*home);
2597 if (path && *path) SvSETMAGIC(*path);
2599 (void)do_open6(PL_last_in_gv, SvPVX_const(tmpcmd), SvCUR(tmpcmd),
2605 if (!fp && ckWARN(WARN_GLOB)) {
2606 Perl_warner(aTHX_ packWARN(WARN_GLOB), "glob failed (can't start child: %s)",
2614 * ex: set ts=8 sts=4 sw=4 et: