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 Perl_setfd_cloexec(int fd)
67 #if defined(HAS_FCNTL) && defined(F_SETFD) && defined(FD_CLOEXEC)
68 (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
73 Perl_setfd_inhexec(int fd)
76 #if defined(HAS_FCNTL) && defined(F_SETFD) && defined(FD_CLOEXEC)
77 (void) fcntl(fd, F_SETFD, 0);
82 Perl_setfd_cloexec_for_nonsysfd(pTHX_ int fd)
90 Perl_setfd_inhexec_for_sysfd(pTHX_ int fd)
97 Perl_setfd_cloexec_or_inhexec_by_sysfdness(pTHX_ int fd)
100 if(fd <= PL_maxsysfd)
107 #define DO_GENOPEN_THEN_CLOEXEC(GENOPEN_NORMAL, GENSETFD_CLOEXEC) \
109 int res = (GENOPEN_NORMAL); \
110 if(LIKELY(res != -1)) GENSETFD_CLOEXEC; \
113 #if defined(HAS_FCNTL) && defined(F_SETFD) && defined(FD_CLOEXEC) && \
115 enum { CLOEXEC_EXPERIMENT = 0, CLOEXEC_AT_OPEN, CLOEXEC_AFTER_OPEN };
116 # define DO_GENOPEN_EXPERIMENTING_CLOEXEC(strategy, TESTFD, GENOPEN_CLOEXEC, \
117 GENOPEN_NORMAL, GENSETFD_CLOEXEC) \
119 switch (strategy) { \
120 case CLOEXEC_EXPERIMENT: default: { \
121 int res = (GENOPEN_CLOEXEC), eno; \
122 if (LIKELY(res != -1)) { \
123 int fdflags = fcntl((TESTFD), F_GETFD); \
124 if (LIKELY(fdflags != -1) && \
125 LIKELY(fdflags & FD_CLOEXEC)) { \
126 strategy = CLOEXEC_AT_OPEN; \
128 strategy = CLOEXEC_AFTER_OPEN; \
131 } else if (UNLIKELY((eno = errno) == EINVAL || \
133 res = (GENOPEN_NORMAL); \
134 if (LIKELY(res != -1)) { \
135 strategy = CLOEXEC_AFTER_OPEN; \
137 } else if (!LIKELY((eno = errno) == EINVAL || \
139 strategy = CLOEXEC_AFTER_OPEN; \
144 case CLOEXEC_AT_OPEN: \
145 return (GENOPEN_CLOEXEC); \
146 case CLOEXEC_AFTER_OPEN: \
147 DO_GENOPEN_THEN_CLOEXEC(GENOPEN_NORMAL, GENSETFD_CLOEXEC); \
151 # define DO_GENOPEN_EXPERIMENTING_CLOEXEC(strategy, TESTFD, GENOPEN_CLOEXEC, \
152 GENOPEN_NORMAL, GENSETFD_CLOEXEC) \
153 DO_GENOPEN_THEN_CLOEXEC(GENOPEN_NORMAL, GENSETFD_CLOEXEC)
156 #define DO_ONEOPEN_THEN_CLOEXEC(ONEOPEN_NORMAL) \
159 DO_GENOPEN_THEN_CLOEXEC(fd = (ONEOPEN_NORMAL), \
160 setfd_cloexec(fd)); \
162 #define DO_ONEOPEN_EXPERIMENTING_CLOEXEC(strategy, \
163 ONEOPEN_CLOEXEC, ONEOPEN_NORMAL) \
166 DO_GENOPEN_EXPERIMENTING_CLOEXEC(strategy, \
168 fd = (ONEOPEN_CLOEXEC), \
169 fd = (ONEOPEN_NORMAL), setfd_cloexec(fd)); \
172 #define DO_PIPESETFD_CLOEXEC(PIPEFD) \
174 setfd_cloexec((PIPEFD)[0]); \
175 setfd_cloexec((PIPEFD)[1]); \
177 #define DO_PIPEOPEN_THEN_CLOEXEC(PIPEFD, PIPEOPEN_NORMAL) \
178 DO_GENOPEN_THEN_CLOEXEC(PIPEOPEN_NORMAL, DO_PIPESETFD_CLOEXEC(PIPEFD))
179 #define DO_PIPEOPEN_EXPERIMENTING_CLOEXEC(strategy, PIPEFD, PIPEOPEN_CLOEXEC, \
181 DO_GENOPEN_EXPERIMENTING_CLOEXEC(strategy, \
182 (PIPEFD)[0], PIPEOPEN_CLOEXEC, \
183 PIPEOPEN_NORMAL, DO_PIPESETFD_CLOEXEC(PIPEFD))
186 Perl_PerlLIO_dup_cloexec(pTHX_ int oldfd)
188 #if !defined(PERL_IMPLICIT_SYS) && defined(F_DUPFD_CLOEXEC)
190 * struct IPerlLIO doesn't cover fcntl(), and there's no clear way
191 * to extend it, so for the time being this just isn't available on
192 * PERL_IMPLICIT_SYS builds.
194 DO_ONEOPEN_EXPERIMENTING_CLOEXEC(
196 fcntl(oldfd, F_DUPFD_CLOEXEC, 0),
199 DO_ONEOPEN_THEN_CLOEXEC(PerlLIO_dup(oldfd));
204 Perl_PerlLIO_dup2_cloexec(pTHX_ int oldfd, int newfd)
206 #if !defined(PERL_IMPLICIT_SYS) && defined(HAS_DUP3) && defined(O_CLOEXEC)
208 * struct IPerlLIO doesn't cover dup3(), and there's no clear way
209 * to extend it, so for the time being this just isn't available on
210 * PERL_IMPLICIT_SYS builds.
212 DO_ONEOPEN_EXPERIMENTING_CLOEXEC(
214 dup3(oldfd, newfd, O_CLOEXEC),
215 PerlLIO_dup2(oldfd, newfd));
217 DO_ONEOPEN_THEN_CLOEXEC(PerlLIO_dup2(oldfd, newfd));
222 #if (__CHARSET_LIB == 1)
226 static int setccsid(int fd, int ccsid)
231 memset(&attr, 0, sizeof(attr));
232 attr.att_filetagchg = 1;
233 attr.att_filetag.ft_ccsid = ccsid;
234 attr.att_filetag.ft_txtflag = 1;
236 rc = __fchattr(fd, &attr, sizeof(attr));
240 static void updateccsid(int fd, const char* path, int oflag, int perm)
243 if (oflag & O_CREAT) {
244 rc = setccsid(fd, 819);
248 int asciiopen(const char* path, int oflag)
251 int fd = open(path, oflag);
255 updateccsid(fd, path, oflag, -1);
259 int asciiopen3(const char* path, int oflag, int perm)
262 int fd = open(path, oflag, perm);
266 updateccsid(fd, path, oflag, perm);
273 Perl_PerlLIO_open_cloexec(pTHX_ const char *file, int flag)
275 PERL_ARGS_ASSERT_PERLLIO_OPEN_CLOEXEC;
276 #if defined(O_CLOEXEC)
277 DO_ONEOPEN_EXPERIMENTING_CLOEXEC(
279 PerlLIO_open(file, flag | O_CLOEXEC),
280 PerlLIO_open(file, flag));
282 DO_ONEOPEN_THEN_CLOEXEC(PerlLIO_open(file, flag));
287 Perl_PerlLIO_open3_cloexec(pTHX_ const char *file, int flag, int perm)
289 PERL_ARGS_ASSERT_PERLLIO_OPEN3_CLOEXEC;
290 #if defined(O_CLOEXEC)
291 DO_ONEOPEN_EXPERIMENTING_CLOEXEC(
293 PerlLIO_open3(file, flag | O_CLOEXEC, perm),
294 PerlLIO_open3(file, flag, perm));
296 DO_ONEOPEN_THEN_CLOEXEC(PerlLIO_open3(file, flag, perm));
301 #if (__CHARSET_LIB == 1)
302 #define TEMP_CCSID 819
304 static int Internal_Perl_my_mkstemp_cloexec(char *templte)
306 PERL_ARGS_ASSERT_MY_MKSTEMP_CLOEXEC;
307 # if defined(O_CLOEXEC)
308 DO_ONEOPEN_EXPERIMENTING_CLOEXEC(
310 Perl_my_mkostemp(templte, O_CLOEXEC),
311 Perl_my_mkstemp(templte));
313 DO_ONEOPEN_THEN_CLOEXEC(Perl_my_mkstemp(templte));
317 Perl_my_mkstemp_cloexec(char *templte)
319 int tempfd = Internal_Perl_my_mkstemp_cloexec(templte);
320 # if defined(TEMP_CCSID)
321 setccsid(tempfd, TEMP_CCSID);
326 # else /* Below is ! OEMVS */
328 Perl_my_mkstemp_cloexec(char *templte)
330 PERL_ARGS_ASSERT_MY_MKSTEMP_CLOEXEC;
331 # if defined(O_CLOEXEC)
332 DO_ONEOPEN_EXPERIMENTING_CLOEXEC(
334 Perl_my_mkostemp(templte, O_CLOEXEC),
335 Perl_my_mkstemp(templte));
337 DO_ONEOPEN_THEN_CLOEXEC(Perl_my_mkstemp(templte));
343 Perl_my_mkostemp_cloexec(char *templte, int flags)
345 PERL_ARGS_ASSERT_MY_MKOSTEMP_CLOEXEC;
346 #if defined(O_CLOEXEC)
347 DO_ONEOPEN_EXPERIMENTING_CLOEXEC(
349 Perl_my_mkostemp(templte, flags | O_CLOEXEC),
350 Perl_my_mkostemp(templte, flags));
352 DO_ONEOPEN_THEN_CLOEXEC(Perl_my_mkostemp(templte, flags));
358 Perl_PerlProc_pipe_cloexec(pTHX_ int *pipefd)
360 PERL_ARGS_ASSERT_PERLPROC_PIPE_CLOEXEC;
362 * struct IPerlProc doesn't cover pipe2(), and there's no clear way
363 * to extend it, so for the time being this just isn't available on
364 * PERL_IMPLICIT_SYS builds.
366 # if !defined(PERL_IMPLICIT_SYS) && defined(HAS_PIPE2) && defined(O_CLOEXEC)
367 DO_PIPEOPEN_EXPERIMENTING_CLOEXEC(PL_strategy_pipe, pipefd,
368 pipe2(pipefd, O_CLOEXEC),
369 PerlProc_pipe(pipefd));
371 DO_PIPEOPEN_THEN_CLOEXEC(pipefd, PerlProc_pipe(pipefd));
379 Perl_PerlSock_socket_cloexec(pTHX_ int domain, int type, int protocol)
381 # if defined(SOCK_CLOEXEC)
382 DO_ONEOPEN_EXPERIMENTING_CLOEXEC(
384 PerlSock_socket(domain, type | SOCK_CLOEXEC, protocol),
385 PerlSock_socket(domain, type, protocol));
387 DO_ONEOPEN_THEN_CLOEXEC(PerlSock_socket(domain, type, protocol));
392 Perl_PerlSock_accept_cloexec(pTHX_ int listenfd, struct sockaddr *addr,
393 Sock_size_t *addrlen)
395 # if !defined(PERL_IMPLICIT_SYS) && \
396 defined(HAS_ACCEPT4) && defined(SOCK_CLOEXEC)
398 * struct IPerlSock doesn't cover accept4(), and there's no clear
399 * way to extend it, so for the time being this just isn't available
400 * on PERL_IMPLICIT_SYS builds.
402 DO_ONEOPEN_EXPERIMENTING_CLOEXEC(
404 accept4(listenfd, addr, addrlen, SOCK_CLOEXEC),
405 PerlSock_accept(listenfd, addr, addrlen));
407 DO_ONEOPEN_THEN_CLOEXEC(PerlSock_accept(listenfd, addr, addrlen));
413 #if defined (HAS_SOCKETPAIR) || \
414 (defined (HAS_SOCKET) && defined(SOCK_DGRAM) && \
415 defined(AF_INET) && defined(PF_INET))
417 Perl_PerlSock_socketpair_cloexec(pTHX_ int domain, int type, int protocol,
420 PERL_ARGS_ASSERT_PERLSOCK_SOCKETPAIR_CLOEXEC;
422 DO_PIPEOPEN_EXPERIMENTING_CLOEXEC(PL_strategy_socketpair, pairfd,
423 PerlSock_socketpair(domain, type | SOCK_CLOEXEC, protocol, pairfd),
424 PerlSock_socketpair(domain, type, protocol, pairfd));
426 DO_PIPEOPEN_THEN_CLOEXEC(pairfd,
427 PerlSock_socketpair(domain, type, protocol, pairfd));
433 S_openn_setup(pTHX_ GV *gv, char *mode, PerlIO **saveifp, PerlIO **saveofp,
434 int *savefd, char *savetype)
436 IO * const io = GvIOn(gv);
438 PERL_ARGS_ASSERT_OPENN_SETUP;
443 *savetype = IoTYPE_CLOSED;
445 Zero(mode,sizeof(mode),char);
446 PL_forkprocess = 1; /* assume true if no fork */
448 /* If currently open - close before we re-open */
450 if (IoTYPE(io) == IoTYPE_STD) {
451 /* This is a clone of one of STD* handles */
454 const int old_fd = PerlIO_fileno(IoIFP(io));
456 if (inRANGE(old_fd, 0, PL_maxsysfd)) {
457 /* This is one of the original STD* handles */
458 *saveifp = IoIFP(io);
459 *saveofp = IoOFP(io);
460 *savetype = IoTYPE(io);
466 if (IoTYPE(io) == IoTYPE_PIPE)
467 result = PerlProc_pclose(IoIFP(io));
468 else if (IoIFP(io) != IoOFP(io)) {
470 result = PerlIO_close(IoOFP(io));
471 PerlIO_close(IoIFP(io)); /* clear stdio, fd already closed */
474 result = PerlIO_close(IoIFP(io));
477 result = PerlIO_close(IoIFP(io));
479 if (result == EOF && old_fd > PL_maxsysfd) {
480 /* Why is this not Perl_warn*() call ? */
481 PerlIO_printf(Perl_error_log,
482 "Warning: unable to close filehandle %" HEKf
484 HEKfARG(GvENAME_HEK(gv))
489 IoOFP(io) = IoIFP(io) = NULL;
495 Perl_do_openn(pTHX_ GV *gv, const char *oname, I32 len, int as_raw,
496 int rawmode, int rawperm, PerlIO *supplied_fp, SV **svp,
499 PERL_ARGS_ASSERT_DO_OPENN;
502 /* sysopen style args, i.e. integer mode and permissions */
505 Perl_croak(aTHX_ "panic: sysopen with multiple args, num_svs=%ld",
508 return do_open_raw(gv, oname, len, rawmode, rawperm, NULL);
510 return do_open6(gv, oname, len, supplied_fp, svp, num_svs);
514 Perl_do_open_raw(pTHX_ GV *gv, const char *oname, STRLEN len,
515 int rawmode, int rawperm, Stat_t *statbufp)
521 char mode[PERL_MODE_MAX]; /* file mode ("r\0", "rb\0", "ab\0" etc.) */
522 IO * const io = openn_setup(gv, mode, &saveifp, &saveofp, &savefd, &savetype);
526 PERL_ARGS_ASSERT_DO_OPEN_RAW;
528 /* For ease of blame back to 5.000, keep the existing indenting. */
530 /* sysopen style args, i.e. integer mode and permissions */
532 const int appendtrunc =
534 #ifdef O_APPEND /* Not fully portable. */
537 #ifdef O_TRUNC /* Not fully portable. */
541 const int modifyingmode = O_WRONLY|O_RDWR|O_CREAT|appendtrunc;
551 It might be (in OS/390 and Mac OS Classic it is)
557 This means that simple & with O_RDWR would look
558 like O_RDONLY is present. Therefore we have to
561 if ((ismodifying = (rawmode & modifyingmode))) {
562 if ((ismodifying & O_WRONLY) == O_WRONLY ||
563 (ismodifying & O_RDWR) == O_RDWR ||
564 (ismodifying & (O_CREAT|appendtrunc)))
565 TAINT_PROPER("sysopen");
567 mode[ix++] = IoTYPE_NUMERIC; /* Marker to openn to use numeric "sysopen" */
569 #if defined(USE_64_BIT_RAWIO) && defined(O_LARGEFILE)
570 rawmode |= O_LARGEFILE; /* Transparently largefiley. */
573 IoTYPE(io) = PerlIO_intmode2str(rawmode, &mode[ix], &writing);
575 namesv = newSVpvn_flags(oname, len, SVs_TEMP);
576 fp = PerlIO_openn(aTHX_ NULL, mode, -1, rawmode, rawperm, NULL, 1, &namesv);
578 return openn_cleanup(gv, io, fp, mode, oname, saveifp, saveofp, savefd,
579 savetype, writing, 0, NULL, statbufp);
583 Perl_do_open6(pTHX_ GV *gv, const char *oname, STRLEN len,
584 PerlIO *supplied_fp, SV **svp, U32 num_svs)
590 char mode[PERL_MODE_MAX]; /* file mode ("r\0", "rb\0", "ab\0" etc.) */
591 IO * const io = openn_setup(gv, mode, &saveifp, &saveofp, &savefd, &savetype);
594 bool was_fdopen = FALSE;
597 PERL_ARGS_ASSERT_DO_OPEN6;
599 /* For ease of blame back to 5.000, keep the existing indenting. */
601 /* Regular (non-sys) open */
606 bool in_raw = 0, in_crlf = 0, out_raw = 0, out_crlf = 0;
608 /* Collect default raw/crlf info from the op */
609 if (PL_op && PL_op->op_type == OP_OPEN) {
610 /* set up IO layers */
611 const U8 flags = PL_op->op_private;
612 in_raw = (flags & OPpOPEN_IN_RAW);
613 in_crlf = (flags & OPpOPEN_IN_CRLF);
614 out_raw = (flags & OPpOPEN_OUT_RAW);
615 out_crlf = (flags & OPpOPEN_OUT_CRLF);
618 type = savepvn(oname, len);
622 /* Lose leading and trailing white space */
623 while (isSPACE(*type))
625 while (tend > type && isSPACE(tend[-1]))
631 /* New style explicit name, type is just mode and layer info */
633 if (SvROK(*svp) && !memchr(oname, '&', len)) {
635 Perl_warner(aTHX_ packWARN(WARN_IO),
636 "Can't open a reference");
637 SETERRNO(EINVAL, LIB_INVARG);
641 #endif /* USE_STDIO */
642 p = (SvOK(*svp) || SvGMAGICAL(*svp)) ? SvPV(*svp, nlen) : NULL;
644 if (p && !IS_SAFE_PATHNAME(p, nlen, "open")) {
649 name = p ? savepvn(p, nlen) : savepvs("");
658 if ((*type == IoTYPE_RDWR) && /* scary */
659 (*(type+1) == IoTYPE_RDONLY || *(type+1) == IoTYPE_WRONLY) &&
660 ((!num_svs || (tend > type+1 && tend[-1] != IoTYPE_PIPE)))) {
661 TAINT_PROPER("open");
666 if (*type == IoTYPE_PIPE) {
668 if (type[1] != IoTYPE_STD) {
670 Perl_croak(aTHX_ "Unknown open() mode '%.*s'", (int)olen, oname);
676 } while (isSPACE(*type));
682 /* command is missing 19990114 */
683 if (ckWARN(WARN_PIPE))
684 Perl_warner(aTHX_ packWARN(WARN_PIPE), "Missing command in piped open");
689 if (!(*name == '-' && name[1] == '\0') || num_svs)
691 TAINT_PROPER("piped open");
692 if (!num_svs && name[len-1] == '|') {
694 if (ckWARN(WARN_PIPE))
695 Perl_warner(aTHX_ packWARN(WARN_PIPE), "Can't open bidirectional pipe");
704 fp = PerlProc_popen_list(mode, num_svs, svp);
707 fp = PerlProc_popen(name,mode);
711 if (PerlIO_apply_layers(aTHX_ fp, mode, type) != 0) {
718 else if (*type == IoTYPE_WRONLY) {
719 TAINT_PROPER("open");
721 if (*type == IoTYPE_WRONLY) {
722 /* Two IoTYPE_WRONLYs in a row make for an IoTYPE_APPEND. */
723 mode[0] = IoTYPE(io) = IoTYPE_APPEND;
737 dodup = PERLIO_DUP_FD;
743 if (!num_svs && !*type && supplied_fp) {
744 /* "<+&" etc. is used by typemaps */
748 PerlIO *that_fp = NULL;
752 /* diag_listed_as: More than one argument to '%s' open */
753 Perl_croak(aTHX_ "More than one argument to '%c&' open",IoTYPE(io));
755 while (isSPACE(*type))
759 || (SvPOKp(*svp) && looks_like_number(*svp))
761 wanted_fd = SvUV(*svp);
764 else if (isDIGIT(*type)
765 && grok_atoUV(type, &uv, NULL)
773 thatio = sv_2io(*svp);
776 GV * const thatgv = gv_fetchpvn_flags(type, tend - type,
778 thatio = GvIO(thatgv);
782 SETERRNO(EINVAL,SS_IVCHAN);
787 if ((that_fp = IoIFP(thatio))) {
788 /* Flush stdio buffer before dup. --mjd
789 * Unfortunately SEEK_CURing 0 seems to
790 * be optimized away on most platforms;
791 * only Solaris and Linux seem to flush
793 /* On the other hand, do all platforms
794 * take gracefully to flushing a read-only
795 * filehandle? Perhaps we should do
796 * fsetpos(src)+fgetpos(dst)? --nik */
797 PerlIO_flush(that_fp);
798 wanted_fd = PerlIO_fileno(that_fp);
799 /* When dup()ing STDIN, STDOUT or STDERR
800 * explicitly set appropriate access mode */
801 if (that_fp == PerlIO_stdout()
802 || that_fp == PerlIO_stderr())
803 IoTYPE(io) = IoTYPE_WRONLY;
804 else if (that_fp == PerlIO_stdin())
805 IoTYPE(io) = IoTYPE_RDONLY;
806 /* When dup()ing a socket, say result is
808 else if (IoTYPE(thatio) == IoTYPE_SOCKET)
809 IoTYPE(io) = IoTYPE_SOCKET;
812 SETERRNO(EBADF, RMS_IFI);
820 fp = PerlIO_fdupopen(aTHX_ that_fp, NULL, dodup);
824 wanted_fd = PerlLIO_dup_cloexec(wanted_fd);
827 if (!(fp = PerlIO_openn(aTHX_ type,mode,wanted_fd,0,0,NULL,num_svs,svp))) {
828 if (dodup && wanted_fd >= 0)
829 PerlLIO_close(wanted_fd);
835 while (isSPACE(*type))
837 if (*type == IoTYPE_STD && (!type[1] || isSPACE(type[1]) || type[1] == ':')) {
839 fp = PerlIO_stdout();
840 IoTYPE(io) = IoTYPE_STD;
842 /* diag_listed_as: More than one argument to '%s' open */
843 Perl_croak(aTHX_ "More than one argument to '>%c' open",IoTYPE_STD);
848 fp = PerlIO_openn(aTHX_ type,mode,-1,0,0,NULL,num_svs,svp);
851 SV *namesv = newSVpvn_flags(type, tend - type, SVs_TEMP);
853 fp = PerlIO_openn(aTHX_ type,mode,-1,0,0,NULL,1,&namesv);
857 if (!fp && type && *type && *type != ':' && !isIDFIRST(*type))
858 goto unknown_open_mode;
859 } /* IoTYPE_WRONLY */
860 else if (*type == IoTYPE_RDONLY) {
863 } while (isSPACE(*type));
872 if (*type == IoTYPE_STD && (!type[1] || isSPACE(type[1]) || type[1] == ':')) {
875 IoTYPE(io) = IoTYPE_STD;
877 /* diag_listed_as: More than one argument to '%s' open */
878 Perl_croak(aTHX_ "More than one argument to '<%c' open",IoTYPE_STD);
883 fp = PerlIO_openn(aTHX_ type,mode,-1,0,0,NULL,num_svs,svp);
886 SV *namesv = newSVpvn_flags(type, tend - type, SVs_TEMP);
888 fp = PerlIO_openn(aTHX_ type,mode,-1,0,0,NULL,1,&namesv);
891 if (!fp && type && *type && *type != ':' && !isIDFIRST(*type))
892 goto unknown_open_mode;
893 } /* IoTYPE_RDONLY */
894 else if ((num_svs && /* '-|...' or '...|' */
895 type[0] == IoTYPE_STD && type[1] == IoTYPE_PIPE) ||
896 (!num_svs && tend > type+1 && tend[-1] == IoTYPE_PIPE)) {
898 type += 2; /* skip over '-|' */
902 while (tend > type && isSPACE(tend[-1]))
904 for (; isSPACE(*type); type++)
910 /* command is missing 19990114 */
911 if (ckWARN(WARN_PIPE))
912 Perl_warner(aTHX_ packWARN(WARN_PIPE), "Missing command in piped open");
917 if (!(*name == '-' && name[1] == '\0') || num_svs)
919 TAINT_PROPER("piped open");
928 fp = PerlProc_popen_list(mode,num_svs,svp);
931 fp = PerlProc_popen(name,mode);
933 IoTYPE(io) = IoTYPE_PIPE;
935 while (isSPACE(*type))
938 if (PerlIO_apply_layers(aTHX_ fp, mode, type) != 0) {
945 else { /* layer(Args) */
947 goto unknown_open_mode;
949 IoTYPE(io) = IoTYPE_RDONLY;
950 for (; isSPACE(*name); name++)
959 if (*name == '-' && name[1] == '\0') {
961 IoTYPE(io) = IoTYPE_STD;
965 fp = PerlIO_openn(aTHX_ type,mode,-1,0,0,NULL,num_svs,svp);
968 SV *namesv = newSVpvn_flags(type, tend - type, SVs_TEMP);
970 fp = PerlIO_openn(aTHX_ type,mode,-1,0,0,NULL,1,&namesv);
977 return openn_cleanup(gv, io, fp, mode, oname, saveifp, saveofp, savefd,
978 savetype, writing, was_fdopen, type, NULL);
981 /* Yes, this is ugly, but it's private, and I don't see a cleaner way to
982 simplify the two-headed public interface of do_openn. */
984 S_openn_cleanup(pTHX_ GV *gv, IO *io, PerlIO *fp, char *mode, const char *oname,
985 PerlIO *saveifp, PerlIO *saveofp, int savefd, char savetype,
986 int writing, bool was_fdopen, const char *type, Stat_t *statbufp)
991 PERL_ARGS_ASSERT_OPENN_CLEANUP;
993 Zero(&statbuf, 1, Stat_t);
996 if (IoTYPE(io) == IoTYPE_RDONLY && ckWARN(WARN_NEWLINE)
997 && should_warn_nl(oname)
1001 GCC_DIAG_IGNORE_STMT(-Wformat-nonliteral); /* PL_warn_nl is constant */
1002 Perl_warner(aTHX_ packWARN(WARN_NEWLINE), PL_warn_nl, "open");
1003 GCC_DIAG_RESTORE_STMT;
1008 if (ckWARN(WARN_IO)) {
1009 if ((IoTYPE(io) == IoTYPE_RDONLY) &&
1010 (fp == PerlIO_stdout() || fp == PerlIO_stderr())) {
1011 Perl_warner(aTHX_ packWARN(WARN_IO),
1012 "Filehandle STD%s reopened as %" HEKf
1014 ((fp == PerlIO_stdout()) ? "OUT" : "ERR"),
1015 HEKfARG(GvENAME_HEK(gv)));
1017 else if ((IoTYPE(io) == IoTYPE_WRONLY) && fp == PerlIO_stdin()) {
1018 Perl_warner(aTHX_ packWARN(WARN_IO),
1019 "Filehandle STDIN reopened as %" HEKf " only for output",
1020 HEKfARG(GvENAME_HEK(gv))
1025 fd = PerlIO_fileno(fp);
1026 /* Do NOT do: "if (fd < 0) goto say_false;" here. If there is no
1027 * fd assume it isn't a socket - this covers PerlIO::scalar -
1028 * otherwise unless we "know" the type probe for socket-ness.
1030 if (IoTYPE(io) && IoTYPE(io) != IoTYPE_PIPE && IoTYPE(io) != IoTYPE_STD && fd >= 0) {
1031 if (PerlLIO_fstat(fd,&statbuf) < 0) {
1032 /* If PerlIO claims to have fd we had better be able to fstat() it. */
1033 (void) PerlIO_close(fp);
1037 if (S_ISSOCK(statbuf.st_mode))
1038 IoTYPE(io) = IoTYPE_SOCKET; /* in case a socket was passed in to us */
1041 !(statbuf.st_mode & S_IFMT)
1042 && IoTYPE(io) != IoTYPE_WRONLY /* Dups of STD* filehandles already have */
1043 && IoTYPE(io) != IoTYPE_RDONLY /* type so they aren't marked as sockets */
1044 ) { /* on OS's that return 0 on fstat()ed pipe */
1046 Sock_size_t buflen = sizeof tmpbuf;
1047 if (PerlSock_getsockname(fd, (struct sockaddr *)tmpbuf, &buflen) >= 0
1048 || errno != ENOTSOCK)
1049 IoTYPE(io) = IoTYPE_SOCKET; /* some OS's return 0 on fstat()ed socket */
1050 /* but some return 0 for streams too, sigh */
1052 #endif /* HAS_SOCKET */
1053 #endif /* !PERL_MICRO */
1057 * If this is a standard handle we discard all the layer stuff
1058 * and just dup the fd into whatever was on the handle before !
1061 if (saveifp) { /* must use old fp? */
1062 /* If fd is less that PL_maxsysfd i.e. STDIN..STDERR
1063 then dup the new fileno down
1066 PerlIO_flush(saveofp); /* emulate PerlIO_close() */
1067 if (saveofp != saveifp) { /* was a socket? */
1068 PerlIO_close(saveofp);
1072 /* Still a small can-of-worms here if (say) PerlIO::scalar
1073 is assigned to (say) STDOUT - for now let dup2() fail
1074 and provide the error
1077 SETERRNO(EBADF,RMS_IFI);
1079 } else if (PerlLIO_dup2(fd, savefd) < 0) {
1080 (void)PerlIO_close(fp);
1084 if (savefd != PerlIO_fileno(PerlIO_stdin())) {
1085 char newname[FILENAME_MAX+1];
1086 if (PerlIO_getname(fp, newname)) {
1087 if (fd == PerlIO_fileno(PerlIO_stdout()))
1088 vmssetuserlnm("SYS$OUTPUT", newname);
1089 if (fd == PerlIO_fileno(PerlIO_stderr()))
1090 vmssetuserlnm("SYS$ERROR", newname);
1096 /* PL_fdpid isn't used on Windows, so avoid this useless work.
1097 * XXX Probably the same for a lot of other places. */
1102 sv = *av_fetch(PL_fdpid,fd,TRUE);
1103 SvUPGRADE(sv, SVt_IV);
1106 sv = *av_fetch(PL_fdpid,savefd,TRUE);
1107 SvUPGRADE(sv, SVt_IV);
1113 /* need to close fp without closing underlying fd */
1114 int ofd = PerlIO_fileno(fp);
1115 int dupfd = ofd >= 0 ? PerlLIO_dup_cloexec(ofd) : -1;
1116 if (ofd < 0 || dupfd < 0) {
1118 PerlLIO_close(dupfd);
1122 PerlLIO_dup2_cloexec(dupfd, ofd);
1123 setfd_inhexec_for_sysfd(ofd);
1124 PerlLIO_close(dupfd);
1130 PerlIO_clearerr(fp);
1131 fd = PerlIO_fileno(fp);
1135 IoFLAGS(io) &= ~IOf_NOLINE;
1137 if (IoTYPE(io) == IoTYPE_SOCKET
1138 || (IoTYPE(io) == IoTYPE_WRONLY && fd >= 0 && S_ISCHR(statbuf.st_mode)) ) {
1140 if (*s == IoTYPE_IMPLICIT || *s == IoTYPE_NUMERIC)
1143 if (!(IoOFP(io) = PerlIO_openn(aTHX_ type,s,fd,0,0,NULL,0,NULL))) {
1152 *statbufp = statbuf;
1157 IoIFP(io) = saveifp;
1158 IoOFP(io) = saveofp;
1159 IoTYPE(io) = savetype;
1163 /* Open a temp file in the same directory as an original name.
1167 S_openindirtemp(pTHX_ GV *gv, SV *orig_name, SV *temp_out_name) {
1170 const char *p = SvPV_nolen(orig_name);
1173 /* look for the last directory separator */
1174 sep = strrchr(p, '/');
1179 if ((sep2 = strrchr(sep ? sep : p, '\\')))
1185 const char *openp = strchr(p, '[');
1187 sep = strchr(openp, ']');
1189 sep = strchr(p, ':');
1194 sv_setpvn(temp_out_name, p, sep - p + 1);
1195 sv_catpvs(temp_out_name, "XXXXXXXX");
1198 sv_setpvs(temp_out_name, "XXXXXXXX");
1201 int old_umask = umask(0177);
1202 fd = Perl_my_mkstemp_cloexec(SvPVX(temp_out_name));
1209 fp = PerlIO_fdopen(fd, "w+");
1213 return do_openn(gv, "+>&", 3, 0, 0, 0, fp, NULL, 0);
1216 #if defined(HAS_UNLINKAT) && defined(HAS_RENAMEAT) && defined(HAS_FCHMODAT) && \
1217 (defined(HAS_DIRFD) || defined(HAS_DIR_DD_FD)) && !defined(NO_USE_ATFUNCTIONS) && \
1219 # define ARGV_USE_ATFUNCTIONS
1222 /* Win32 doesn't necessarily return useful information
1223 * in st_dev, st_ino.
1226 # define ARGV_USE_STAT_INO
1229 #define ARGVMG_BACKUP_NAME 0
1230 #define ARGVMG_TEMP_NAME 1
1231 #define ARGVMG_ORIG_NAME 2
1232 #define ARGVMG_ORIG_MODE 3
1233 #define ARGVMG_ORIG_PID 4
1235 /* we store the entire stat_t since the ino_t and dev_t values might
1236 not fit in an IV. I could have created a new structure and
1237 transferred them across, but this seemed too much effort for very
1240 We store it even when the *at() functions are available, since
1241 while the C runtime might have definitions for these functions, the
1242 operating system or a specific filesystem might not implement them.
1243 eg. NetBSD 6 implements linkat() but only where the fds are AT_FDCWD.
1245 #ifdef ARGV_USE_STAT_INO
1246 # define ARGVMG_ORIG_CWD_STAT 5
1249 #ifdef ARGV_USE_ATFUNCTIONS
1250 # define ARGVMG_ORIG_DIRP 6
1254 #define NotSupported(e) ((e) == ENOSYS || (e) == ENOTSUP)
1256 #define NotSupported(e) ((e) == ENOSYS)
1260 S_argvout_free(pTHX_ SV *io, MAGIC *mg) {
1261 PERL_UNUSED_ARG(io);
1263 /* note this can be entered once the file has been
1264 successfully deleted too */
1265 assert(IoTYPE(io) != IoTYPE_PIPE);
1267 /* mg_obj can be NULL if a thread is created with the handle open, in which
1268 case we leave any clean up to the parent thread */
1270 #ifdef ARGV_USE_ATFUNCTIONS
1274 dir_psv = av_fetch((AV*)mg->mg_obj, ARGVMG_ORIG_DIRP, FALSE);
1275 assert(dir_psv && *dir_psv && SvIOK(*dir_psv));
1276 dir = INT2PTR(DIR *, SvIV(*dir_psv));
1279 if (PL_phase == PERL_PHASE_DESTRUCT && PL_statusvalue == 0) {
1280 (void)argvout_final(mg, (IO*)io, FALSE);
1284 PerlIO *iop = IoIFP(io);
1286 assert(SvTYPE(mg->mg_obj) == SVt_PVAV);
1288 pid_psv = av_fetch((AV*)mg->mg_obj, ARGVMG_ORIG_PID, FALSE);
1290 assert(pid_psv && *pid_psv);
1292 if (SvIV(*pid_psv) == (IV)PerlProc_getpid()) {
1293 /* if we get here the file hasn't been closed explicitly by the
1294 user and hadn't been closed implicitly by nextargv(), so
1296 SV **temp_psv = av_fetch((AV*)mg->mg_obj, ARGVMG_TEMP_NAME, FALSE);
1297 const char *temp_pv = SvPVX(*temp_psv);
1299 assert(temp_psv && *temp_psv && SvPOK(*temp_psv));
1300 (void)PerlIO_close(iop);
1301 IoIFP(io) = IoOFP(io) = NULL;
1302 #ifdef ARGV_USE_ATFUNCTIONS
1304 if (unlinkat(my_dirfd(dir), temp_pv, 0) < 0 &&
1305 NotSupported(errno))
1306 (void)UNLINK(temp_pv);
1309 (void)UNLINK(temp_pv);
1314 #ifdef ARGV_USE_ATFUNCTIONS
1324 S_argvout_dup(pTHX_ MAGIC *mg, CLONE_PARAMS *param) {
1325 PERL_UNUSED_ARG(param);
1327 /* ideally we could just remove the magic from the SV but we don't get the SV here */
1328 SvREFCNT_dec(mg->mg_obj);
1334 /* Magic of this type has an AV containing the following:
1335 0: name of the backup file (if any)
1336 1: name of the temp output file
1337 2: name of the original file
1338 3: file mode of the original file
1339 4: pid of the process we opened at, to prevent doing the renaming
1340 etc in both the child and the parent after a fork
1342 If we have useful inode/device ids in stat_t we also keep:
1343 5: a stat of the original current working directory
1345 If we have unlinkat(), renameat(), fchmodat(), dirfd() we also keep:
1346 6: the DIR * for the current directory when we open the file, stored as an IV
1349 static const MGVTBL argvout_vtbl =
1354 NULL, /* svt_clear */
1355 S_argvout_free, /* svt_free */
1356 NULL, /* svt_copy */
1357 S_argvout_dup, /* svt_dup */
1358 NULL /* svt_local */
1362 Perl_nextargv(pTHX_ GV *gv, bool nomagicopen)
1364 IO * const io = GvIOp(gv);
1365 SV *const old_out_name = PL_inplace ? newSVsv(GvSV(gv)) : NULL;
1367 PERL_ARGS_ASSERT_NEXTARGV;
1370 SAVEFREESV(old_out_name);
1373 PL_argvoutgv = gv_fetchpvs("ARGVOUT", GV_ADD|GV_NOTQUAL, SVt_PVIO);
1374 if (io && (IoFLAGS(io) & (IOf_ARGV|IOf_START)) == (IOf_ARGV|IOf_START)) {
1375 IoFLAGS(io) &= ~IOf_START;
1377 assert(PL_defoutgv);
1378 Perl_av_create_and_push(aTHX_ &PL_argvout_stack,
1379 SvREFCNT_inc_simple_NN(PL_defoutgv));
1384 IO * const io = GvIOp(PL_argvoutgv);
1385 if (io && IoIFP(io) && old_out_name) {
1386 do_close(PL_argvoutgv, FALSE);
1394 while (av_count(GvAV(gv)) > 0) {
1396 SV *const sv = av_shift(GvAV(gv));
1398 SvTAINTED_off(GvSVn(gv)); /* previous tainting irrelevant */
1399 sv_setsv(GvSVn(gv),sv);
1400 SvSETMAGIC(GvSV(gv));
1401 PL_oldname = SvPVx(GvSV(gv), oldlen);
1402 if (LIKELY(!PL_inplace)) {
1404 ? do_open6(gv, "<", 1, NULL, &GvSV(gv), 1)
1405 : do_open6(gv, PL_oldname, oldlen, NULL, NULL, 0)
1407 return IoIFP(GvIOp(gv));
1412 /* This very long block ends with return IoIFP(GvIOp(gv));
1413 Both this block and the block above fall through on open
1414 failure to the warning code, and then the while loop above tries
1416 if (do_open_raw(gv, PL_oldname, oldlen, O_RDONLY, 0, &statbuf)) {
1417 #ifndef FLEXFILENAMES
1421 #ifdef ARGV_USE_ATFUNCTIONS
1426 AV *magic_av = NULL;
1427 SV *temp_name_sv = NULL;
1430 TAINT_PROPER("inplace open");
1431 if (oldlen == 1 && *PL_oldname == '-') {
1432 setdefout(gv_fetchpvs("STDOUT", GV_ADD|GV_NOTQUAL,
1434 return IoIFP(GvIOp(gv));
1436 #ifndef FLEXFILENAMES
1437 filedev = statbuf.st_dev;
1438 fileino = statbuf.st_ino;
1440 PL_filemode = statbuf.st_mode;
1441 fileuid = statbuf.st_uid;
1442 filegid = statbuf.st_gid;
1443 if (!S_ISREG(PL_filemode)) {
1444 Perl_ck_warner_d(aTHX_ packWARN(WARN_INPLACE),
1445 "Can't do inplace edit: %s is not a regular file",
1451 if (*PL_inplace && strNE(PL_inplace, "*")) {
1452 const char *star = strchr(PL_inplace, '*');
1454 const char *begin = PL_inplace;
1457 sv_catpvn(sv, begin, star - begin);
1458 sv_catpvn(sv, PL_oldname, oldlen);
1460 } while ((star = strchr(begin, '*')));
1465 sv_catpv(sv,PL_inplace);
1467 #ifndef FLEXFILENAMES
1468 if ((PerlLIO_stat(SvPVX_const(sv),&statbuf) >= 0
1469 && statbuf.st_dev == filedev
1470 && statbuf.st_ino == fileino)
1473 Perl_ck_warner_d(aTHX_ packWARN(WARN_INPLACE),
1474 "Can't do inplace edit: %"
1475 SVf " would not be unique",
1480 av_store(magic_av, ARGVMG_BACKUP_NAME, newSVsv(sv));
1483 sv_setpvn(sv,PL_oldname,oldlen);
1484 SETERRNO(0,0); /* in case sprintf set errno */
1485 temp_name_sv = newSV(0);
1486 if (!S_openindirtemp(aTHX_ PL_argvoutgv, GvSV(gv), temp_name_sv)) {
1487 SvREFCNT_dec(temp_name_sv);
1488 /* diag_listed_as: Can't do inplace edit on %s: %s */
1489 Perl_ck_warner_d(aTHX_ packWARN(WARN_INPLACE), "Can't do inplace edit on %s: Cannot make temp name: %s",
1490 PL_oldname, Strerror(errno) );
1491 #ifndef FLEXFILENAMES
1495 SvREFCNT_dec(magic_av);
1498 av_store(magic_av, ARGVMG_TEMP_NAME, temp_name_sv);
1499 av_store(magic_av, ARGVMG_ORIG_NAME, newSVsv(sv));
1500 av_store(magic_av, ARGVMG_ORIG_MODE, newSVuv(PL_filemode));
1501 av_store(magic_av, ARGVMG_ORIG_PID, newSViv((IV)PerlProc_getpid()));
1502 #if defined(ARGV_USE_ATFUNCTIONS)
1503 curdir = opendir(".");
1504 av_store(magic_av, ARGVMG_ORIG_DIRP, newSViv(PTR2IV(curdir)));
1505 #elif defined(ARGV_USE_STAT_INO)
1506 if (PerlLIO_stat(".", &statbuf) >= 0) {
1507 av_store(magic_av, ARGVMG_ORIG_CWD_STAT,
1508 newSVpvn((char *)&statbuf, sizeof(statbuf)));
1511 setdefout(PL_argvoutgv);
1512 sv_setsv(GvSVn(PL_argvoutgv), temp_name_sv);
1513 mg = sv_magicext((SV*)GvIOp(PL_argvoutgv), (SV*)magic_av, PERL_MAGIC_uvar, &argvout_vtbl, NULL, 0);
1514 mg->mg_flags |= MGf_DUP;
1515 SvREFCNT_dec(magic_av);
1516 PL_lastfd = PerlIO_fileno(IoIFP(GvIOp(PL_argvoutgv)));
1517 if (PL_lastfd >= 0) {
1518 (void)PerlLIO_fstat(PL_lastfd,&statbuf);
1520 (void)fchmod(PL_lastfd,PL_filemode);
1522 (void)PerlLIO_chmod(PL_oldname,PL_filemode);
1524 if (fileuid != statbuf.st_uid || filegid != statbuf.st_gid) {
1525 /* XXX silently ignore failures */
1527 PERL_UNUSED_RESULT(fchown(PL_lastfd,fileuid,filegid));
1528 #elif defined(HAS_CHOWN)
1529 PERL_UNUSED_RESULT(PerlLIO_chown(PL_oldname,fileuid,filegid));
1533 return IoIFP(GvIOp(gv));
1535 } /* successful do_open_raw(), PL_inplace non-NULL */
1537 if (ckWARN_d(WARN_INPLACE)) {
1538 const int eno = errno;
1540 if (PerlLIO_stat(PL_oldname, &statbuf) >= 0
1541 && !S_ISREG(statbuf.st_mode)) {
1542 Perl_warner(aTHX_ packWARN(WARN_INPLACE),
1543 "Can't do inplace edit: %s is not a regular file",
1547 Perl_warner(aTHX_ packWARN(WARN_INPLACE), "Can't open %s: %s",
1548 PL_oldname, Strerror(eno));
1552 if (io && (IoFLAGS(io) & IOf_ARGV))
1553 IoFLAGS(io) |= IOf_START;
1555 if (io && (IoFLAGS(io) & IOf_ARGV)
1556 && PL_argvout_stack && AvFILLp(PL_argvout_stack) >= 0)
1558 GV * const oldout = MUTABLE_GV(av_pop(PL_argvout_stack));
1560 SvREFCNT_dec_NN(oldout);
1563 setdefout(gv_fetchpvs("STDOUT", GV_ADD|GV_NOTQUAL, SVt_PVIO));
1568 #ifdef ARGV_USE_ATFUNCTIONS
1569 # if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1571 /* FreeBSD 11 renameat() mis-behaves strangely with absolute paths in cases where the
1572 * equivalent rename() succeeds
1575 S_my_renameat(int olddfd, const char *oldpath, int newdfd, const char *newpath) {
1576 /* this is intended only for use in Perl_do_close() */
1577 assert(olddfd == newdfd);
1578 assert(PERL_FILE_IS_ABSOLUTE(oldpath) == PERL_FILE_IS_ABSOLUTE(newpath));
1579 if (PERL_FILE_IS_ABSOLUTE(oldpath)) {
1580 return PerlLIO_rename(oldpath, newpath);
1583 return renameat(olddfd, oldpath, newdfd, newpath);
1588 # define S_my_renameat(dh1, pv1, dh2, pv2) renameat((dh1), (pv1), (dh2), (pv2))
1589 # endif /* if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) */
1593 S_dir_unchanged(pTHX_ const char *orig_pv, MAGIC *mg) {
1596 #ifdef ARGV_USE_STAT_INO
1597 SV **stat_psv = av_fetch((AV*)mg->mg_obj, ARGVMG_ORIG_CWD_STAT, FALSE);
1598 Stat_t *orig_cwd_stat = stat_psv && *stat_psv ? (Stat_t *)SvPVX(*stat_psv) : NULL;
1600 /* if the path is absolute the possible moving of cwd (which the file
1601 might be in) isn't our problem.
1602 This code tries to be reasonably balanced about detecting a changed
1603 CWD, if we have the information needed to check that curdir has changed, we
1606 if (!PERL_FILE_IS_ABSOLUTE(orig_pv)
1608 && PerlLIO_stat(".", &statbuf) >= 0
1609 && ( statbuf.st_dev != orig_cwd_stat->st_dev
1610 || statbuf.st_ino != orig_cwd_stat->st_ino)) {
1611 Perl_croak(aTHX_ "Cannot complete in-place edit of %s: %s",
1612 orig_pv, "Current directory has changed");
1615 SV **temp_psv = av_fetch((AV*)mg->mg_obj, ARGVMG_TEMP_NAME, FALSE);
1617 /* Some platforms don't have useful st_ino etc, so just
1618 check we can see the work file.
1620 if (!PERL_FILE_IS_ABSOLUTE(orig_pv)
1621 && PerlLIO_stat(SvPVX(*temp_psv), &statbuf) < 0) {
1622 Perl_croak(aTHX_ "Cannot complete in-place edit of %s: %s",
1624 "Work file is missing - did you change directory?");
1631 #define dir_unchanged(orig_psv, mg) \
1632 S_dir_unchanged(aTHX_ (orig_psv), (mg))
1635 S_argvout_final(pTHX_ MAGIC *mg, IO *io, bool is_explict) {
1638 /* ensure args are checked before we start using them */
1639 PERL_ARGS_ASSERT_ARGVOUT_FINAL;
1642 /* handle to an in-place edit work file */
1643 SV **back_psv = av_fetch((AV*)mg->mg_obj, ARGVMG_BACKUP_NAME, FALSE);
1644 SV **temp_psv = av_fetch((AV*)mg->mg_obj, ARGVMG_TEMP_NAME, FALSE);
1645 /* PL_oldname may have been modified by a nested ARGV use at this point */
1646 SV **orig_psv = av_fetch((AV*)mg->mg_obj, ARGVMG_ORIG_NAME, FALSE);
1647 SV **mode_psv = av_fetch((AV*)mg->mg_obj, ARGVMG_ORIG_MODE, FALSE);
1648 SV **pid_psv = av_fetch((AV*)mg->mg_obj, ARGVMG_ORIG_PID, FALSE);
1649 #if defined(ARGV_USE_ATFUNCTIONS)
1650 SV **dir_psv = av_fetch((AV*)mg->mg_obj, ARGVMG_ORIG_DIRP, FALSE);
1657 const char *orig_pv;
1659 assert(temp_psv && *temp_psv);
1660 assert(orig_psv && *orig_psv);
1661 assert(mode_psv && *mode_psv);
1662 assert(pid_psv && *pid_psv);
1663 #ifdef ARGV_USE_ATFUNCTIONS
1664 assert(dir_psv && *dir_psv);
1665 dir = INT2PTR(DIR *, SvIVX(*dir_psv));
1666 dfd = my_dirfd(dir);
1669 orig_pv = SvPVX(*orig_psv);
1670 mode = SvUV(*mode_psv);
1672 if ((mode & (S_ISUID|S_ISGID)) != 0
1673 && (fd = PerlIO_fileno(IoIFP(io))) >= 0) {
1674 (void)PerlIO_flush(IoIFP(io));
1676 (void)fchmod(fd, mode);
1678 (void)PerlLIO_chmod(orig_pv, mode);
1682 retval = io_close(io, NULL, is_explict, FALSE);
1684 if (SvIV(*pid_psv) != (IV)PerlProc_getpid()) {
1685 /* this is a child process, don't duplicate our rename() etc
1691 #if defined(DOSISH) || defined(__CYGWIN__)
1692 if (PL_argvgv && GvIOp(PL_argvgv)
1693 && IoIFP(GvIOp(PL_argvgv))
1694 && (IoFLAGS(GvIOp(PL_argvgv)) & (IOf_ARGV|IOf_START)) == IOf_ARGV) {
1695 do_close(PL_argvgv, FALSE);
1698 #ifndef ARGV_USE_ATFUNCTIONS
1699 if (!dir_unchanged(orig_pv, mg))
1702 if (back_psv && *back_psv) {
1703 #if defined(HAS_LINK) && !defined(DOSISH) && !defined(__CYGWIN__) && defined(HAS_RENAME)
1705 # ifdef ARGV_USE_ATFUNCTIONS
1706 linkat(dfd, orig_pv, dfd, SvPVX(*back_psv), 0) < 0 &&
1707 !(UNLIKELY(NotSupported(errno)) &&
1708 dir_unchanged(orig_pv, mg) &&
1709 link(orig_pv, SvPVX(*back_psv)) == 0)
1711 link(orig_pv, SvPVX(*back_psv)) < 0
1718 # ifdef ARGV_USE_ATFUNCTIONS
1719 S_my_renameat(dfd, orig_pv, dfd, SvPVX(*back_psv)) < 0 &&
1720 !(UNLIKELY(NotSupported(errno)) &&
1721 dir_unchanged(orig_pv, mg) &&
1722 PerlLIO_rename(orig_pv, SvPVX(*back_psv)) == 0)
1724 PerlLIO_rename(orig_pv, SvPVX(*back_psv)) < 0
1728 # ifdef ARGV_USE_ATFUNCTIONS
1729 if (unlinkat(dfd, SvPVX_const(*temp_psv), 0) < 0 &&
1730 UNLIKELY(NotSupported(errno)) &&
1731 dir_unchanged(orig_pv, mg))
1732 (void)UNLINK(SvPVX_const(*temp_psv));
1734 UNLINK(SvPVX(*temp_psv));
1736 Perl_croak(aTHX_ "Can't rename %s to %s: %s, skipping file",
1737 SvPVX(*orig_psv), SvPVX(*back_psv), Strerror(errno));
1739 /* should we warn here? */
1743 (void)UNLINK(SvPVX(*back_psv));
1744 if (link(orig_pv, SvPVX(*back_psv))) {
1746 Perl_croak(aTHX_ "Can't rename %s to %s: %s, skipping file",
1747 SvPVX(*orig_psv), SvPVX(*back_psv), Strerror(errno));
1751 /* we need to use link() to get the temp into place too, and linK()
1752 fails if the new link name exists */
1753 (void)UNLINK(orig_pv);
1757 #if defined(DOSISH) || defined(__CYGWIN__) || !defined(HAS_RENAME)
1763 #if !defined(HAS_RENAME)
1764 link(SvPVX(*temp_psv), orig_pv) < 0
1765 #elif defined(ARGV_USE_ATFUNCTIONS)
1766 S_my_renameat(dfd, SvPVX(*temp_psv), dfd, orig_pv) < 0 &&
1767 !(UNLIKELY(NotSupported(errno)) &&
1768 dir_unchanged(orig_pv, mg) &&
1769 PerlLIO_rename(SvPVX(*temp_psv), orig_pv) == 0)
1771 PerlLIO_rename(SvPVX(*temp_psv), orig_pv) < 0
1775 #ifdef ARGV_USE_ATFUNCTIONS
1776 if (unlinkat(dfd, SvPVX_const(*temp_psv), 0) < 0 &&
1777 NotSupported(errno))
1778 UNLINK(SvPVX(*temp_psv));
1780 UNLINK(SvPVX(*temp_psv));
1782 /* diag_listed_as: Cannot complete in-place edit of %s: %s */
1783 Perl_croak(aTHX_ "Cannot complete in-place edit of %s: failed to rename work file '%s' to '%s': %s",
1784 orig_pv, SvPVX(*temp_psv), orig_pv, Strerror(errno));
1787 UNLINK(SvPVX_const(*temp_psv));
1791 UNLINK(SvPVX(*temp_psv));
1795 #ifdef ARGV_USE_ATFUNCTIONS
1796 if (unlinkat(dfd, SvPVX_const(*temp_psv), 0) &&
1797 NotSupported(errno))
1798 UNLINK(SvPVX_const(*temp_psv));
1801 UNLINK(SvPVX_const(*temp_psv));
1804 Perl_croak(aTHX_ "Failed to close in-place work file %s: %s",
1805 SvPVX(*temp_psv), Strerror(errno));
1815 =for apidoc do_close
1817 Close an I/O stream. This implements Perl L<perlfunc/C<close>>.
1819 C<gv> is the glob associated with the stream.
1821 C<is_explict> is C<true> if this is an explicit close of the stream; C<false>
1822 if it is part of another operation, such as closing a pipe (which involves
1823 implicitly closing both ends).
1825 Returns C<true> if successful; otherwise returns C<false> and sets C<errno> to
1832 Perl_do_close(pTHX_ GV *gv, bool is_explict)
1840 if (!gv || !isGV_with_GP(gv)) {
1842 SETERRNO(EBADF,SS_IVCHAN);
1846 if (!io) { /* never opened */
1849 SETERRNO(EBADF,SS_IVCHAN);
1853 if ((mg = mg_findext((SV*)io, PERL_MAGIC_uvar, &argvout_vtbl))
1855 retval = argvout_final(mg, io, is_explict);
1856 mg_freeext((SV*)io, PERL_MAGIC_uvar, &argvout_vtbl);
1859 retval = io_close(io, NULL, is_explict, FALSE);
1864 IoLINES_LEFT(io) = IoPAGE_LEN(io);
1866 IoTYPE(io) = IoTYPE_CLOSED;
1871 Perl_io_close(pTHX_ IO *io, GV *gv, bool is_explict, bool warn_on_fail)
1873 bool retval = FALSE;
1875 PERL_ARGS_ASSERT_IO_CLOSE;
1878 if (IoTYPE(io) == IoTYPE_PIPE) {
1879 PerlIO *fh = IoIFP(io);
1882 /* my_pclose() can propagate signals which might bypass any code
1883 after the call here if the signal handler throws an exception.
1884 This would leave the handle in the IO object and try to close it again
1885 when the SV is destroyed on unwind or global destruction.
1888 IoOFP(io) = IoIFP(io) = NULL;
1889 status = PerlProc_pclose(fh);
1891 STATUS_NATIVE_CHILD_SET(status);
1892 retval = (STATUS_UNIX == 0);
1895 retval = (status != -1);
1898 else if (IoTYPE(io) == IoTYPE_STD)
1901 if (IoOFP(io) && IoOFP(io) != IoIFP(io)) { /* a socket */
1902 const bool prev_err = PerlIO_error(IoOFP(io));
1905 PerlIO_restore_errno(IoOFP(io));
1907 retval = (PerlIO_close(IoOFP(io)) != EOF && !prev_err);
1908 PerlIO_close(IoIFP(io)); /* clear stdio, fd already closed */
1911 const bool prev_err = PerlIO_error(IoIFP(io));
1914 PerlIO_restore_errno(IoIFP(io));
1916 retval = (PerlIO_close(IoIFP(io)) != EOF && !prev_err);
1919 IoOFP(io) = IoIFP(io) = NULL;
1921 if (warn_on_fail && !retval) {
1923 Perl_ck_warner_d(aTHX_ packWARN(WARN_IO),
1924 "Warning: unable to close filehandle %"
1925 HEKf " properly: %" SVf,
1926 HEKfARG(GvNAME_HEK(gv)),
1927 SVfARG(get_sv("!",GV_ADD)));
1929 Perl_ck_warner_d(aTHX_ packWARN(WARN_IO),
1930 "Warning: unable to close filehandle "
1932 SVfARG(get_sv("!",GV_ADD)));
1935 else if (is_explict) {
1936 SETERRNO(EBADF,SS_IVCHAN);
1943 Perl_do_eof(pTHX_ GV *gv)
1945 IO * const io = GvIO(gv);
1947 PERL_ARGS_ASSERT_DO_EOF;
1951 else if (IoTYPE(io) == IoTYPE_WRONLY)
1952 report_wrongway_fh(gv, '>');
1955 if (PerlIO_has_cntptr(IoIFP(io))) { /* (the code works without this) */
1956 if (PerlIO_get_cnt(IoIFP(io)) > 0) /* cheat a little, since */
1957 return FALSE; /* this is the most usual case */
1961 /* getc and ungetc can stomp on errno */
1963 const int ch = PerlIO_getc(IoIFP(io));
1965 (void)PerlIO_ungetc(IoIFP(io),ch);
1972 if (PerlIO_has_cntptr(IoIFP(io)) && PerlIO_canset_cnt(IoIFP(io))) {
1973 if (PerlIO_get_cnt(IoIFP(io)) < -1)
1974 PerlIO_set_cnt(IoIFP(io),-1);
1976 if (PL_op->op_flags & OPf_SPECIAL) { /* not necessarily a real EOF yet? */
1977 if (gv != PL_argvgv || !nextargv(gv, FALSE)) /* get another fp handy */
1981 return TRUE; /* normal fp, definitely end of file */
1987 Perl_do_tell(pTHX_ GV *gv)
1989 IO *const io = GvIO(gv);
1992 PERL_ARGS_ASSERT_DO_TELL;
1994 if (io && (fp = IoIFP(io))) {
1995 return PerlIO_tell(fp);
1998 SETERRNO(EBADF,RMS_IFI);
2003 Perl_do_seek(pTHX_ GV *gv, Off_t pos, int whence)
2005 IO *const io = GvIO(gv);
2008 if (io && (fp = IoIFP(io))) {
2009 return PerlIO_seek(fp, pos, whence) >= 0;
2012 SETERRNO(EBADF,RMS_IFI);
2017 Perl_do_sysseek(pTHX_ GV *gv, Off_t pos, int whence)
2019 IO *const io = GvIO(gv);
2022 PERL_ARGS_ASSERT_DO_SYSSEEK;
2024 if (io && (fp = IoIFP(io))) {
2025 int fd = PerlIO_fileno(fp);
2026 if (fd < 0 || (whence == SEEK_SET && pos < 0)) {
2027 SETERRNO(EINVAL,LIB_INVARG);
2030 return PerlLIO_lseek(fd, pos, whence);
2034 SETERRNO(EBADF,RMS_IFI);
2039 Perl_mode_from_discipline(pTHX_ const char *s, STRLEN len)
2041 int mode = O_BINARY;
2042 PERL_UNUSED_CONTEXT;
2048 if (s[2] == 'a' && s[3] == 'w'
2049 && (!s[4] || s[4] == ':' || isSPACE(s[4])))
2058 if (s[2] == 'r' && s[3] == 'l' && s[4] == 'f'
2059 && (!s[5] || s[5] == ':' || isSPACE(s[5])))
2068 goto fail_discipline;
2071 else if (isSPACE(*s)) {
2078 end = (char *) memchr(s+1, ':', len);
2081 #ifndef PERLIO_LAYERS
2082 Perl_croak(aTHX_ "IO layers (like '%.*s') unavailable", end-s, s);
2094 =for apidoc my_chsize
2096 The C library L<chsize(3)> if available, or a Perl implementation of it.
2101 #if !defined(HAS_TRUNCATE) && !defined(HAS_CHSIZE)
2103 my_chsize(int fd, Off_t length)
2106 /* code courtesy of William Kucharski */
2111 if (PerlLIO_fstat(fd, &filebuf) < 0)
2114 if (filebuf.st_size < length) {
2116 /* extend file length */
2118 if ((PerlLIO_lseek(fd, (length - 1), 0)) < 0)
2121 /* write a "0" byte */
2123 if ((PerlLIO_write(fd, "", 1)) != 1)
2127 /* truncate length */
2131 fl.l_start = length;
2132 fl.l_type = F_WRLCK; /* write lock on file space */
2135 * This relies on the UNDOCUMENTED F_FREESP argument to
2136 * fcntl(2), which truncates the file so that it ends at the
2137 * position indicated by fl.l_start.
2139 * Will minor miracles never cease?
2142 if (fcntl(fd, F_FREESP, &fl) < 0)
2148 Perl_croak_nocontext("truncate not implemented");
2149 # endif /* F_FREESP */
2152 #endif /* !HAS_TRUNCATE && !HAS_CHSIZE */
2155 Perl_do_print(pTHX_ SV *sv, PerlIO *fp)
2157 PERL_ARGS_ASSERT_DO_PRINT;
2159 /* assuming fp is checked earlier */
2162 if (SvTYPE(sv) == SVt_IV && SvIOK(sv)) {
2163 assert(!SvGMAGICAL(sv));
2165 PerlIO_printf(fp, "%" UVuf, (UV)SvUVX(sv));
2167 PerlIO_printf(fp, "%" IVdf, (IV)SvIVX(sv));
2168 return !PerlIO_error(fp);
2172 /* Do this first to trigger any overloading. */
2173 const char *tmps = SvPV_const(sv, len);
2177 if (PerlIO_isutf8(fp)) { /* If the stream is utf8 ... */
2178 if (!SvUTF8(sv)) { /* Convert to utf8 if necessary */
2179 /* We don't modify the original scalar. */
2180 tmpbuf = bytes_to_utf8((const U8*) tmps, &len);
2181 tmps = (char *) tmpbuf;
2183 else if (ckWARN4_d(WARN_UTF8, WARN_SURROGATE, WARN_NON_UNICODE, WARN_NONCHAR)) {
2184 (void) check_utf8_print((const U8*) tmps, len);
2186 } /* else stream isn't utf8 */
2187 else if (DO_UTF8(sv)) { /* But if is utf8 internally, attempt to
2189 STRLEN tmplen = len;
2191 U8 * const result = bytes_from_utf8((const U8*) tmps, &tmplen, &utf8);
2194 /* Here, succeeded in downgrading from utf8. Set up to below
2195 * output the converted value */
2197 tmps = (char *) tmpbuf;
2200 else { /* Non-utf8 output stream, but string only representable in
2202 assert((char *)result == tmps);
2203 Perl_ck_warner_d(aTHX_ packWARN(WARN_UTF8),
2204 "Wide character in %s",
2205 PL_op ? OP_DESC(PL_op) : "print"
2207 /* Could also check that isn't one of the things to avoid
2208 * in utf8 by using check_utf8_print(), but not doing so,
2209 * since the stream isn't a UTF8 stream */
2212 /* To detect whether the process is about to overstep its
2213 * filesize limit we would need getrlimit(). We could then
2214 * also transparently raise the limit with setrlimit() --
2215 * but only until the system hard limit/the filesystem limit,
2216 * at which we would get EPERM. Note that when using buffered
2217 * io the write failure can be delayed until the flush/close. --jhi */
2218 if (len && (PerlIO_write(fp,tmps,len) == 0))
2221 return happy ? !PerlIO_error(fp) : FALSE;
2226 Perl_my_stat_flags(pTHX_ const U32 flags)
2232 if (PL_op->op_flags & OPf_REF) {
2235 if (gv == PL_defgv) {
2236 if (PL_laststatval < 0)
2237 SETERRNO(EBADF,RMS_IFI);
2238 return PL_laststatval;
2242 PL_laststype = OP_STAT;
2243 PL_statgv = gv ? gv : (GV *)io;
2244 SvPVCLEAR(PL_statname);
2247 int fd = PerlIO_fileno(IoIFP(io));
2249 /* E.g. PerlIO::scalar has no real fd. */
2250 SETERRNO(EBADF,RMS_IFI);
2251 return (PL_laststatval = -1);
2253 return (PL_laststatval = PerlLIO_fstat(fd, &PL_statcache));
2255 } else if (IoDIRP(io)) {
2256 return (PL_laststatval = PerlLIO_fstat(my_dirfd(IoDIRP(io)), &PL_statcache));
2259 PL_laststatval = -1;
2261 SETERRNO(EBADF,RMS_IFI);
2264 else if ((PL_op->op_private & (OPpFT_STACKED|OPpFT_AFTER_t))
2266 return PL_laststatval;
2268 SV* const sv = TOPs;
2271 if ((gv = MAYBE_DEREF_GV_flags(sv,flags))) {
2274 else if (SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVIO) {
2275 io = MUTABLE_IO(SvRV(sv));
2277 goto do_fstat_have_io;
2280 s = SvPV_flags_const(sv, len, flags);
2282 sv_setpvn(PL_statname, s, len);
2283 d = SvPVX_const(PL_statname); /* s now NUL-terminated */
2284 PL_laststype = OP_STAT;
2285 if (!IS_SAFE_PATHNAME(s, len, OP_NAME(PL_op))) {
2286 PL_laststatval = -1;
2289 PL_laststatval = PerlLIO_stat(d, &PL_statcache);
2291 if (PL_laststatval < 0 && ckWARN(WARN_NEWLINE) && should_warn_nl(s)) {
2292 GCC_DIAG_IGNORE_STMT(-Wformat-nonliteral); /* PL_warn_nl is constant */
2293 Perl_warner(aTHX_ packWARN(WARN_NEWLINE), PL_warn_nl, "stat");
2294 GCC_DIAG_RESTORE_STMT;
2296 return PL_laststatval;
2302 Perl_my_lstat_flags(pTHX_ const U32 flags)
2304 static const char* const no_prev_lstat = "The stat preceding -l _ wasn't an lstat";
2308 SV* const sv = TOPs;
2310 if (PL_op->op_flags & OPf_REF) {
2311 if (cGVOP_gv == PL_defgv) {
2312 if (PL_laststype != OP_LSTAT)
2313 Perl_croak(aTHX_ "%s", no_prev_lstat);
2314 if (PL_laststatval < 0)
2315 SETERRNO(EBADF,RMS_IFI);
2316 return PL_laststatval;
2318 PL_laststatval = -1;
2319 if (ckWARN(WARN_IO)) {
2320 /* diag_listed_as: Use of -l on filehandle%s */
2321 Perl_warner(aTHX_ packWARN(WARN_IO),
2322 "Use of -l on filehandle %" HEKf,
2323 HEKfARG(GvENAME_HEK(cGVOP_gv)));
2325 SETERRNO(EBADF,RMS_IFI);
2328 if ((PL_op->op_private & (OPpFT_STACKED|OPpFT_AFTER_t))
2330 if (PL_laststype != OP_LSTAT)
2331 Perl_croak(aTHX_ "%s", no_prev_lstat);
2332 return PL_laststatval;
2335 PL_laststype = OP_LSTAT;
2337 if ( ( (SvROK(sv) && ( isGV_with_GP(SvRV(sv))
2338 || (isio = SvTYPE(SvRV(sv)) == SVt_PVIO) )
2342 && ckWARN(WARN_IO)) {
2344 /* diag_listed_as: Use of -l on filehandle%s */
2345 Perl_warner(aTHX_ packWARN(WARN_IO),
2346 "Use of -l on filehandle");
2348 /* diag_listed_as: Use of -l on filehandle%s */
2349 Perl_warner(aTHX_ packWARN(WARN_IO),
2350 "Use of -l on filehandle %" HEKf,
2351 HEKfARG(GvENAME_HEK((const GV *)
2352 (SvROK(sv) ? SvRV(sv) : sv))));
2354 file = SvPV_flags_const(sv, len, flags);
2355 sv_setpv(PL_statname,file);
2356 if (!IS_SAFE_PATHNAME(file, len, OP_NAME(PL_op))) {
2357 PL_laststatval = -1;
2360 PL_laststatval = PerlLIO_lstat(file,&PL_statcache);
2362 if (PL_laststatval < 0 && ckWARN(WARN_NEWLINE) && should_warn_nl(file)) {
2363 GCC_DIAG_IGNORE_STMT(-Wformat-nonliteral); /* PL_warn_nl is constant */
2364 Perl_warner(aTHX_ packWARN(WARN_NEWLINE), PL_warn_nl, "lstat");
2365 GCC_DIAG_RESTORE_STMT;
2367 return PL_laststatval;
2371 S_exec_failed(pTHX_ const char *cmd, int fd, int do_report)
2373 const int e = errno;
2374 PERL_ARGS_ASSERT_EXEC_FAILED;
2376 if (ckWARN(WARN_EXEC))
2377 Perl_warner(aTHX_ packWARN(WARN_EXEC), "Can't exec \"%s\": %s",
2380 /* XXX silently ignore failures */
2381 PERL_UNUSED_RESULT(PerlLIO_write(fd, (void*)&e, sizeof(int)));
2387 Perl_do_aexec5(pTHX_ SV *really, SV **mark, SV **sp,
2388 int fd, int do_report)
2390 PERL_ARGS_ASSERT_DO_AEXEC5;
2391 #if defined(__LIBCATAMOUNT__)
2392 Perl_croak(aTHX_ "exec? I'm not *that* kind of operating system");
2397 const char **argv, **a;
2398 const char *tmps = NULL;
2399 Newx(argv, sp - mark + 1, const char*);
2403 while (++mark <= sp) {
2405 char *arg = savepv(SvPV_nolen_const(*mark));
2413 tmps = savepv(SvPV_nolen_const(really));
2416 if ((!really && argv[0] && *argv[0] != '/') ||
2417 (really && *tmps != '/')) /* will execvp use PATH? */
2418 TAINT_ENV(); /* testing IFS here is overkill, probably */
2420 if (really && *tmps) {
2421 PerlProc_execvp(tmps,EXEC_ARGV_CAST(argv));
2422 } else if (argv[0]) {
2423 PerlProc_execvp(argv[0],EXEC_ARGV_CAST(argv));
2425 SETERRNO(ENOENT,RMS_FNF);
2428 S_exec_failed(aTHX_ (really ? tmps : argv[0] ? argv[0] : ""), fd, do_report);
2435 #ifdef PERL_DEFAULT_DO_EXEC3_IMPLEMENTATION
2438 Perl_do_exec3(pTHX_ const char *incmd, int fd, int do_report)
2440 const char **argv, **a;
2444 /* Make a copy so we can change it */
2445 const Size_t cmdlen = strlen(incmd) + 1;
2447 PERL_ARGS_ASSERT_DO_EXEC3;
2450 Newx(buf, cmdlen, char);
2453 memcpy(cmd, incmd, cmdlen);
2455 while (*cmd && isSPACE(*cmd))
2458 /* save an extra exec if possible */
2462 char flags[PERL_FLAGS_MAX];
2463 if (strnEQ(cmd,PL_cshname,PL_cshlen) &&
2464 strBEGINs(cmd+PL_cshlen," -c")) {
2465 my_strlcpy(flags, "-c", PERL_FLAGS_MAX);
2466 s = cmd+PL_cshlen+3;
2469 my_strlcat(flags, "f", PERL_FLAGS_MAX - 2);
2474 char * const ncmd = s;
2480 if (s[-1] == '\'') {
2483 PerlProc_execl(PL_cshname, "csh", flags, ncmd, (char*)NULL);
2486 S_exec_failed(aTHX_ PL_cshname, fd, do_report);
2494 /* see if there are shell metacharacters in it */
2496 if (*cmd == '.' && isSPACE(cmd[1]))
2499 if (strBEGINs(cmd,"exec") && isSPACE(cmd[4]))
2503 while (isWORDCHAR(*s))
2504 s++; /* catch VAR=val gizmo */
2508 for (s = cmd; *s; s++) {
2509 if (*s != ' ' && !isALPHA(*s) &&
2510 memCHRs("$&*(){}[]'\";\\|?<>~`\n",*s)) {
2511 if (*s == '\n' && !s[1]) {
2515 /* handle the 2>&1 construct at the end */
2516 if (*s == '>' && s[1] == '&' && s[2] == '1'
2517 && s > cmd + 1 && s[-1] == '2' && isSPACE(s[-2])
2518 && (!s[3] || isSPACE(s[3])))
2520 const char *t = s + 3;
2522 while (*t && isSPACE(*t))
2524 if (!*t && (PerlLIO_dup2(1,2) != -1)) {
2531 PerlProc_execl(PL_sh_path, "sh", "-c", cmd, (char *)NULL);
2533 S_exec_failed(aTHX_ PL_sh_path, fd, do_report);
2538 Newx(argv, (s - cmd) / 2 + 2, const char*);
2540 cmd = savepvn(cmd, s-cmd);
2543 for (s = cmd; *s;) {
2548 while (*s && !isSPACE(*s))
2556 PerlProc_execvp(argv[0],EXEC_ARGV_CAST(argv));
2558 if (errno == ENOEXEC) /* for system V NIH syndrome */
2560 S_exec_failed(aTHX_ argv[0], fd, do_report);
2567 #endif /* OS2 || WIN32 */
2570 Perl_apply(pTHX_ I32 type, SV **mark, SV **sp)
2574 const char *const what = PL_op_name[type];
2577 SV ** const oldmark = mark;
2578 bool killgp = FALSE;
2580 PERL_ARGS_ASSERT_APPLY;
2582 PERL_UNUSED_VAR(what); /* may not be used depending on compile options */
2584 /* Doing this ahead of the switch statement preserves the old behaviour,
2585 where attempting to use kill as a taint test would fail on
2586 platforms where kill was not defined. */
2588 if (type == OP_KILL)
2589 Perl_die(aTHX_ PL_no_func, what);
2592 if (type == OP_CHOWN)
2593 Perl_die(aTHX_ PL_no_func, what);
2597 #define APPLY_TAINT_PROPER() \
2599 if (TAINT_get) { TAINT_PROPER(what); } \
2602 /* This is a first heuristic; it doesn't catch tainting magic. */
2604 while (++mark <= sp) {
2605 if (SvTAINTED(*mark)) {
2614 APPLY_TAINT_PROPER();
2617 APPLY_TAINT_PROPER();
2619 while (++mark <= sp) {
2621 if ((gv = MAYBE_DEREF_GV(*mark))) {
2622 if (GvIO(gv) && IoIFP(GvIOp(gv))) {
2624 int fd = PerlIO_fileno(IoIFP(GvIOn(gv)));
2625 APPLY_TAINT_PROPER();
2627 SETERRNO(EBADF,RMS_IFI);
2629 } else if (fchmod(fd, val))
2632 Perl_die(aTHX_ PL_no_func, "fchmod");
2636 SETERRNO(EBADF,RMS_IFI);
2641 const char *name = SvPV_nomg_const(*mark, len);
2642 APPLY_TAINT_PROPER();
2643 if (!IS_SAFE_PATHNAME(name, len, "chmod") ||
2644 PerlLIO_chmod(name, val)) {
2653 APPLY_TAINT_PROPER();
2654 if (sp - mark > 2) {
2656 val = SvIVx(*++mark);
2657 val2 = SvIVx(*++mark);
2658 APPLY_TAINT_PROPER();
2660 while (++mark <= sp) {
2662 if ((gv = MAYBE_DEREF_GV(*mark))) {
2663 if (GvIO(gv) && IoIFP(GvIOp(gv))) {
2665 int fd = PerlIO_fileno(IoIFP(GvIOn(gv)));
2666 APPLY_TAINT_PROPER();
2668 SETERRNO(EBADF,RMS_IFI);
2670 } else if (fchown(fd, val, val2))
2673 Perl_die(aTHX_ PL_no_func, "fchown");
2677 SETERRNO(EBADF,RMS_IFI);
2682 const char *name = SvPV_nomg_const(*mark, len);
2683 APPLY_TAINT_PROPER();
2684 if (!IS_SAFE_PATHNAME(name, len, "chown") ||
2685 PerlLIO_chown(name, val, val2)) {
2694 XXX Should we make lchown() directly available from perl?
2695 For now, we'll let Configure test for HAS_LCHOWN, but do
2696 nothing in the core.
2701 APPLY_TAINT_PROPER();
2704 s = SvPVx_const(*++mark, len);
2705 if (*s == '-' && isALPHA(s[1]))
2712 if (*s == 'S' && s[1] == 'I' && s[2] == 'G') {
2716 if ((val = whichsig_pvn(s, len)) < 0)
2717 Perl_croak(aTHX_ "Unrecognized signal name \"%" SVf "\"",
2729 APPLY_TAINT_PROPER();
2732 while (++mark <= sp) {
2735 if (!(SvNIOK(*mark) || looks_like_number(*mark)))
2736 Perl_croak(aTHX_ "Can't kill a non-numeric process ID");
2737 proc = SvIV_nomg(*mark);
2738 APPLY_TAINT_PROPER();
2740 /* use killpg in preference, as the killpg() wrapper for Win32
2741 * understands process groups, but the kill() wrapper doesn't */
2742 if (killgp ? PerlProc_killpg(proc, val)
2743 : PerlProc_kill(proc, val))
2745 if (PerlProc_kill(killgp ? -proc: proc, val))
2753 APPLY_TAINT_PROPER();
2755 while (++mark <= sp) {
2756 s = SvPV_const(*mark, len);
2757 APPLY_TAINT_PROPER();
2758 if (!IS_SAFE_PATHNAME(s, len, "unlink")) {
2761 else if (PL_unsafe) {
2766 #if defined(__amigaos4__) && defined(NEWLIB)
2769 /* Under AmigaOS4 unlink only 'fails' if the
2770 * filename is invalid. It may not remove the file
2771 * if it's locked, so check if it's still around. */
2772 if ((access(s,F_OK) != -1))
2779 else { /* don't let root wipe out directories without -U */
2781 if (PerlLIO_lstat(s, &statbuf) < 0)
2783 else if (S_ISDIR(statbuf.st_mode)) {
2784 SETERRNO(EISDIR, SS_NOPRIV);
2792 #if defined(__amigaos4__) && defined(NEWLIB)
2795 /* Under AmigaOS4 unlink only 'fails' if the filename is invalid */
2796 /* It may not remove the file if it's Locked, so check if it's still */
2798 if((access(s,F_OK) != -1))
2808 #if defined(HAS_UTIME) || defined(HAS_FUTIMES)
2810 APPLY_TAINT_PROPER();
2811 if (sp - mark > 2) {
2812 #if defined(HAS_FUTIMES)
2813 struct timeval utbuf[2];
2814 void *utbufp = utbuf;
2815 #elif defined(I_UTIME) || defined(VMS)
2816 struct utimbuf utbuf;
2817 struct utimbuf *utbufp = &utbuf;
2823 void *utbufp = &utbuf;
2826 SV* const accessed = *++mark;
2827 SV* const modified = *++mark;
2829 /* Be like C, and if both times are undefined, let the C
2830 * library figure out what to do. This usually means
2831 * "current time". */
2833 if ( accessed == &PL_sv_undef && modified == &PL_sv_undef )
2836 Zero(&utbuf, sizeof utbuf, char);
2838 utbuf[0].tv_sec = (long)SvIV(accessed); /* time accessed */
2839 utbuf[0].tv_usec = 0;
2840 utbuf[1].tv_sec = (long)SvIV(modified); /* time modified */
2841 utbuf[1].tv_usec = 0;
2842 #elif defined(BIG_TIME)
2843 utbuf.actime = (Time_t)SvNV(accessed); /* time accessed */
2844 utbuf.modtime = (Time_t)SvNV(modified); /* time modified */
2846 utbuf.actime = (Time_t)SvIV(accessed); /* time accessed */
2847 utbuf.modtime = (Time_t)SvIV(modified); /* time modified */
2850 APPLY_TAINT_PROPER();
2852 while (++mark <= sp) {
2854 if ((gv = MAYBE_DEREF_GV(*mark))) {
2855 if (GvIO(gv) && IoIFP(GvIOp(gv))) {
2857 int fd = PerlIO_fileno(IoIFP(GvIOn(gv)));
2858 APPLY_TAINT_PROPER();
2860 SETERRNO(EBADF,RMS_IFI);
2862 } else if (futimes(fd, (struct timeval *) utbufp))
2865 Perl_die(aTHX_ PL_no_func, "futimes");
2869 SETERRNO(EBADF,RMS_IFI);
2874 const char * const name = SvPV_nomg_const(*mark, len);
2875 APPLY_TAINT_PROPER();
2876 if (!IS_SAFE_PATHNAME(name, len, "utime")) {
2881 if (utimes(name, (struct timeval *)utbufp))
2883 if (PerlLIO_utime(name, utbufp))
2897 #undef APPLY_TAINT_PROPER
2900 /* Do the permissions in *statbufp allow some operation? */
2901 #ifndef VMS /* VMS' cando is in vms.c */
2903 Perl_cando(pTHX_ Mode_t mode, bool effective, const Stat_t *statbufp)
2904 /* effective is a flag, true for EUID, or for checking if the effective gid
2905 * is in the list of groups returned from getgroups().
2908 PERL_ARGS_ASSERT_CANDO;
2909 PERL_UNUSED_CONTEXT;
2912 /* [Comments and code from Len Reed]
2913 * MS-DOS "user" is similar to UNIX's "superuser," but can't write
2914 * to write-protected files. The execute permission bit is set
2915 * by the Microsoft C library stat() function for the following:
2920 * All files and directories are readable.
2921 * Directories and special files, e.g. "CON", cannot be
2923 * [Comment by Tom Dinger -- a directory can have the write-protect
2924 * bit set in the file system, but DOS permits changes to
2925 * the directory anyway. In addition, all bets are off
2926 * here for networked software, such as Novell and
2930 /* Atari stat() does pretty much the same thing. we set x_bit_set_in_stat
2931 * too so it will actually look into the files for magic numbers
2933 return cBOOL(mode & statbufp->st_mode);
2935 #else /* ! DOSISH */
2937 if (ingroup(544,effective)) { /* member of Administrators */
2939 if ((effective ? PerlProc_geteuid() : PerlProc_getuid()) == 0) { /* root is special */
2941 if (mode == S_IXUSR) {
2942 if (statbufp->st_mode & 0111 || S_ISDIR(statbufp->st_mode))
2946 return TRUE; /* root reads and writes anything */
2949 if (statbufp->st_uid == (effective ? PerlProc_geteuid() : PerlProc_getuid()) ) {
2950 if (statbufp->st_mode & mode)
2951 return TRUE; /* ok as "user" */
2953 else if (ingroup(statbufp->st_gid,effective)) {
2954 if (statbufp->st_mode & mode >> 3)
2955 return TRUE; /* ok as "group" */
2957 else if (statbufp->st_mode & mode >> 6)
2958 return TRUE; /* ok as "other" */
2960 #endif /* ! DOSISH */
2965 S_ingroup(pTHX_ Gid_t testgid, bool effective)
2967 #ifndef PERL_IMPLICIT_SYS
2968 /* PERL_IMPLICIT_SYS like Win32: getegid() etc. require the context. */
2969 PERL_UNUSED_CONTEXT;
2971 if (testgid == (effective ? PerlProc_getegid() : PerlProc_getgid()))
2973 #ifdef HAS_GETGROUPS
2975 Groups_t *gary = NULL;
2979 anum = getgroups(0, gary);
2981 Newx(gary, anum, Groups_t);
2982 anum = getgroups(anum, gary);
2984 if (gary[anum] == testgid) {
2998 #if defined(HAS_MSG) || defined(HAS_SEM) || defined(HAS_SHM)
3001 Perl_do_ipcget(pTHX_ I32 optype, SV **mark, SV **sp)
3003 const key_t key = (key_t)SvNVx(*++mark);
3004 SV *nsv = optype == OP_MSGGET ? NULL : *++mark;
3005 const I32 flags = SvIVx(*++mark);
3007 PERL_ARGS_ASSERT_DO_IPCGET;
3008 PERL_UNUSED_ARG(sp);
3015 return msgget(key, flags);
3019 return semget(key, (int) SvIV(nsv), flags);
3023 return shmget(key, (size_t) SvUV(nsv), flags);
3025 #if !defined(HAS_MSG) || !defined(HAS_SEM) || !defined(HAS_SHM)
3027 /* diag_listed_as: msg%s not implemented */
3028 Perl_croak(aTHX_ "%s not implemented", PL_op_desc[optype]);
3031 return -1; /* should never happen */
3035 Perl_do_ipcctl(pTHX_ I32 optype, SV **mark, SV **sp)
3039 const I32 id = SvIVx(*++mark);
3041 const I32 n = (optype == OP_SEMCTL) ? SvIVx(*++mark) : 0;
3043 const I32 cmd = SvIVx(*++mark);
3044 SV * const astr = *++mark;
3045 STRLEN infosize = 0;
3046 I32 getinfo = (cmd == IPC_STAT);
3048 PERL_ARGS_ASSERT_DO_IPCCTL;
3049 PERL_UNUSED_ARG(sp);
3055 if (cmd == IPC_STAT || cmd == IPC_SET)
3056 infosize = sizeof(struct msqid_ds);
3061 if (cmd == IPC_STAT || cmd == IPC_SET)
3062 infosize = sizeof(struct shmid_ds);
3068 if (cmd == IPC_STAT || cmd == IPC_SET)
3069 infosize = sizeof(struct semid_ds);
3070 else if (cmd == GETALL || cmd == SETALL)
3072 struct semid_ds semds;
3074 #ifdef EXTRA_F_IN_SEMUN_BUF
3075 semun.buff = &semds;
3079 getinfo = (cmd == GETALL);
3080 if (Semctl(id, 0, IPC_STAT, semun) == -1)
3082 infosize = semds.sem_nsems * sizeof(short);
3083 /* "short" is technically wrong but much more portable
3084 than guessing about u_?short(_t)? */
3087 /* diag_listed_as: sem%s not implemented */
3088 Perl_croak(aTHX_ "%s not implemented", PL_op_desc[optype]);
3092 #if !defined(HAS_MSG) || !defined(HAS_SEM) || !defined(HAS_SHM)
3094 /* diag_listed_as: shm%s not implemented */
3095 Perl_croak(aTHX_ "%s not implemented", PL_op_desc[optype]);
3103 /* we're not using the value here, so don't SvPVanything */
3104 SvUPGRADE(astr, SVt_PV);
3106 if (SvTHINKFIRST(astr))
3107 sv_force_normal_flags(astr, 0);
3108 a = SvGROW(astr, infosize+1);
3113 a = SvPVbyte(astr, len);
3114 if (len != infosize)
3115 Perl_croak(aTHX_ "Bad arg length for %s, is %lu, should be %ld",
3123 /* We historically treat this as a pointer if we don't otherwise recognize
3124 the op, but for many ops the value is simply ignored anyway, so
3125 don't warn on undef.
3129 const IV i = SvIV_nomg(astr);
3130 a = INT2PTR(char *,i); /* ouch */
3141 ret = msgctl(id, cmd, (struct msqid_ds *)a);
3147 union semun unsemds;
3150 unsemds.val = PTR2nat(a);
3153 #ifdef EXTRA_F_IN_SEMUN_BUF
3154 unsemds.buff = (struct semid_ds *)a;
3156 unsemds.buf = (struct semid_ds *)a;
3159 ret = Semctl(id, n, cmd, unsemds);
3161 /* diag_listed_as: sem%s not implemented */
3162 Perl_croak(aTHX_ "%s not implemented", PL_op_desc[optype]);
3169 ret = shmctl(id, cmd, (struct shmid_ds *)a);
3173 if (getinfo && ret >= 0) {
3174 SvCUR_set(astr, infosize);
3175 *SvEND(astr) = '\0';
3183 Perl_do_msgsnd(pTHX_ SV **mark, SV **sp)
3187 const I32 id = SvIVx(*++mark);
3188 SV * const mstr = *++mark;
3189 const I32 flags = SvIVx(*++mark);
3190 const char * const mbuf = SvPVbyte(mstr, len);
3191 const I32 msize = len - sizeof(long);
3193 PERL_ARGS_ASSERT_DO_MSGSND;
3194 PERL_UNUSED_ARG(sp);
3197 Perl_croak(aTHX_ "Arg too short for msgsnd");
3199 if (id >= 0 && flags >= 0) {
3200 return msgsnd(id, (struct msgbuf *)mbuf, msize, flags);
3202 SETERRNO(EINVAL,LIB_INVARG);
3206 PERL_UNUSED_ARG(sp);
3207 PERL_UNUSED_ARG(mark);
3208 /* diag_listed_as: msg%s not implemented */
3209 Perl_croak(aTHX_ "msgsnd not implemented");
3215 Perl_do_msgrcv(pTHX_ SV **mark, SV **sp)
3220 I32 msize, flags, ret;
3221 const I32 id = SvIVx(*++mark);
3222 SV * const mstr = *++mark;
3224 PERL_ARGS_ASSERT_DO_MSGRCV;
3225 PERL_UNUSED_ARG(sp);
3227 /* suppress warning when reading into undef var --jhi */
3230 msize = SvIVx(*++mark);
3231 mtype = (long)SvIVx(*++mark);
3232 flags = SvIVx(*++mark);
3233 SvPV_force_nolen(mstr);
3234 mbuf = SvGROW(mstr, sizeof(long)+msize+1);
3237 if (id >= 0 && msize >= 0 && flags >= 0) {
3238 ret = msgrcv(id, (struct msgbuf *)mbuf, msize, mtype, flags);
3240 SETERRNO(EINVAL,LIB_INVARG);
3244 SvCUR_set(mstr, sizeof(long)+ret);
3246 *SvEND(mstr) = '\0';
3247 /* who knows who has been playing with this message? */
3252 PERL_UNUSED_ARG(sp);
3253 PERL_UNUSED_ARG(mark);
3254 /* diag_listed_as: msg%s not implemented */
3255 Perl_croak(aTHX_ "msgrcv not implemented");
3261 Perl_do_semop(pTHX_ SV **mark, SV **sp)
3265 const I32 id = SvIVx(*++mark);
3266 SV * const opstr = *++mark;
3267 const char * const opbuf = SvPVbyte(opstr, opsize);
3269 PERL_ARGS_ASSERT_DO_SEMOP;
3270 PERL_UNUSED_ARG(sp);
3272 if (opsize < 3 * SHORTSIZE
3273 || (opsize % (3 * SHORTSIZE))) {
3274 SETERRNO(EINVAL,LIB_INVARG);
3278 /* We can't assume that sizeof(struct sembuf) == 3 * sizeof(short). */
3280 const int nsops = opsize / (3 * sizeof (short));
3282 short * const ops = (short *) opbuf;
3284 struct sembuf *temps, *t;
3287 Newx (temps, nsops, struct sembuf);
3295 result = semop(id, temps, nsops);
3300 /* diag_listed_as: sem%s not implemented */
3301 Perl_croak(aTHX_ "semop not implemented");
3306 Perl_do_shmio(pTHX_ I32 optype, SV **mark, SV **sp)
3310 struct shmid_ds shmds;
3311 const I32 id = SvIVx(*++mark);
3312 SV * const mstr = *++mark;
3313 const I32 mpos = SvIVx(*++mark);
3314 const I32 msize = SvIVx(*++mark);
3316 PERL_ARGS_ASSERT_DO_SHMIO;
3317 PERL_UNUSED_ARG(sp);
3320 if (shmctl(id, IPC_STAT, &shmds) == -1)
3322 if (mpos < 0 || msize < 0
3323 || (size_t)mpos + msize > (size_t)shmds.shm_segsz) {
3324 SETERRNO(EFAULT,SS_ACCVIO); /* can't do as caller requested */
3328 shm = (char *)shmat(id, NULL, (optype == OP_SHMREAD) ? SHM_RDONLY : 0);
3330 SETERRNO(EINVAL,LIB_INVARG);
3333 if (shm == (char *)-1) /* I hate System V IPC, I really do */
3335 if (optype == OP_SHMREAD) {
3337 /* suppress warning when reading into undef var (tchrist 3/Mar/00) */
3339 SvUPGRADE(mstr, SVt_PV);
3343 mbuf = SvGROW(mstr, (STRLEN)msize+1);
3345 Copy(shm + mpos, mbuf, msize, char);
3346 SvCUR_set(mstr, msize);
3347 *SvEND(mstr) = '\0';
3349 /* who knows who has been playing with this shared memory? */
3355 const char *mbuf = SvPVbyte(mstr, len);
3356 const I32 n = ((I32)len > msize) ? msize : (I32)len;
3357 Copy(mbuf, shm + mpos, n, char);
3359 memzero(shm + mpos + n, msize - n);
3363 /* diag_listed_as: shm%s not implemented */
3364 Perl_croak(aTHX_ "shm I/O not implemented");
3369 #endif /* SYSV IPC */
3372 =for apidoc start_glob
3374 Function called by C<do_readline> to spawn a glob (or do the glob inside
3375 perl on VMS). This code used to be inline, but now perl uses C<File::Glob>
3376 this glob starter is only used by miniperl during the build process,
3377 or when PERL_EXTERNAL_GLOB is defined.
3378 Moving it away shrinks F<pp_hot.c>; shrinking F<pp_hot.c> helps speed perl up.
3384 Perl_start_glob (pTHX_ SV *tmpglob, IO *io)
3386 SV * const tmpcmd = newSV(0);
3389 const char *s = SvPV(tmpglob, len);
3391 PERL_ARGS_ASSERT_START_GLOB;
3393 if (!IS_SAFE_SYSCALL(s, len, "pattern", "glob"))
3398 #ifdef VMS /* expand the wildcards right here, rather than opening a pipe, */
3399 /* since spawning off a process is a real performance hit */
3406 fp = Perl_vms_start_glob(aTHX_ tmpglob, io);
3411 sv_setpv(tmpcmd, "for a in ");
3412 sv_catsv(tmpcmd, tmpglob);
3413 sv_catpvs(tmpcmd, "; do echo \"$a\\0\\c\"; done |");
3415 sv_setpv(tmpcmd, "perlglob ");
3416 sv_catsv(tmpcmd, tmpglob);
3417 sv_catpvs(tmpcmd, " |");
3420 sv_setpvn(tmpcmd, PL_cshname, PL_cshlen);
3421 sv_catpvs(tmpcmd, " -cf 'set nonomatch; glob ");
3422 sv_catsv(tmpcmd, tmpglob);
3423 sv_catpvs(tmpcmd, "' 2>/dev/null |");
3425 sv_setpv(tmpcmd, "echo ");
3426 sv_catsv(tmpcmd, tmpglob);
3427 sv_catpvs(tmpcmd, "|tr -s ' \t\f\r' '\\n\\n\\n\\n'|");
3428 # endif /* !DOSISH && !CSH */
3430 SV ** const svp = hv_fetchs(GvHVn(PL_envgv), "LS_COLORS", 0);
3432 save_helem_flags(GvHV(PL_envgv),
3433 newSVpvs_flags("LS_COLORS", SVs_TEMP), svp,
3436 (void)do_open6(PL_last_in_gv, SvPVX_const(tmpcmd), SvCUR(tmpcmd),
3442 if (!fp && ckWARN(WARN_GLOB)) {
3443 Perl_warner(aTHX_ packWARN(WARN_GLOB), "glob failed (can't start child: %s)",
3451 * ex: set ts=8 sts=4 sw=4 et: