3 * Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003,
4 * 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 * But only a short way ahead its floor and the walls on either side were
13 * cloven by a great fissure, out of which the red glare came, now leaping
14 * up, now dying down into darkness; and all the while far below there was
15 * a rumour and a trouble as of great engines throbbing and labouring.
17 * [p.945 of _The Lord of the Rings_, VI/iii: "Mount Doom"]
20 /* This file contains system pp ("push/pop") functions that
21 * execute the opcodes that make up a perl program. A typical pp function
22 * expects to find its arguments on the stack, and usually pushes its
23 * results onto the stack, hence the 'pp' terminology. Each OP structure
24 * contains a pointer to the relevant pp_foo() function.
26 * By 'system', we mean ops which interact with the OS, such as pp_open().
30 #define PERL_IN_PP_SYS_C
35 /* Shadow password support for solaris - pdo@cs.umd.edu
36 * Not just Solaris: at least HP-UX, IRIX, Linux.
37 * The API is from SysV.
39 * There are at least two more shadow interfaces,
40 * see the comments in pp_gpwent().
44 /* There is a MAXINT coming from <shadow.h> <- <hpsecurity.h> <- <values.h>
45 * and another MAXINT from "perl.h" <- <sys/param.h>. */
52 # include <sys/resource.h>
57 # include <sys/select.h>
61 /* XXX Configure test needed.
62 h_errno might not be a simple 'int', especially for multi-threaded
63 applications, see "extern int errno in perl.h". Creating such
64 a test requires taking into account the differences between
65 compiling multithreaded and singlethreaded ($ccflags et al).
66 HOST_NOT_FOUND is typically defined in <netdb.h>.
68 #if defined(HOST_NOT_FOUND) && !defined(h_errno) && !defined(__CYGWIN__)
76 struct passwd *getpwnam (char *);
77 struct passwd *getpwuid (Uid_t);
81 struct passwd *getpwent (void);
82 # elif defined (VMS) && defined (my_getpwent)
83 struct passwd *Perl_my_getpwent (pTHX);
92 struct group *getgrnam (char *);
93 struct group *getgrgid (Gid_t);
97 struct group *getgrent (void);
103 # if defined(_MSC_VER) || defined(__MINGW32__)
104 # include <sys/utime.h>
111 # ifdef my_chsize /* Probably #defined to Perl_my_chsize in embed.h */
114 # define my_chsize PerlLIO_chsize
115 #elif defined(HAS_TRUNCATE)
116 # define my_chsize PerlLIO_chsize
118 I32 my_chsize(int fd, Off_t length);
123 #else /* no flock() */
125 /* fcntl.h might not have been included, even if it exists, because
126 the current Configure only sets I_FCNTL if it's needed to pick up
127 the *_OK constants. Make sure it has been included before testing
128 the fcntl() locking constants. */
129 # if defined(HAS_FCNTL) && !defined(I_FCNTL)
133 # if defined(HAS_FCNTL) && defined(FCNTL_CAN_LOCK)
134 # define FLOCK fcntl_emulate_flock
135 # define FCNTL_EMULATE_FLOCK
136 # elif defined(HAS_LOCKF)
137 # define FLOCK lockf_emulate_flock
138 # define LOCKF_EMULATE_FLOCK
142 static int FLOCK (int, int);
145 * These are the flock() constants. Since this sytems doesn't have
146 * flock(), the values of the constants are probably not available.
160 # endif /* emulating flock() */
162 #endif /* no flock() */
165 static const char zero_but_true[ZBTLEN + 1] = "0 but true";
167 #if defined(I_SYS_ACCESS) && !defined(R_OK)
168 # include <sys/access.h>
174 /* Missing protos on LynxOS */
175 void sethostent(int);
176 void endhostent(void);
178 void endnetent(void);
179 void setprotoent(int);
180 void endprotoent(void);
181 void setservent(int);
182 void endservent(void);
186 # include "amigaos4/amigaio.h"
189 #undef PERL_EFF_ACCESS /* EFFective uid/gid ACCESS */
191 /* F_OK unused: if stat() cannot find it... */
193 #if !defined(PERL_EFF_ACCESS) && defined(HAS_ACCESS) && defined(EFF_ONLY_OK) && !defined(NO_EFF_ONLY_OK)
194 /* Digital UNIX (when the EFF_ONLY_OK gets fixed), UnixWare */
195 # define PERL_EFF_ACCESS(p,f) (access((p), (f) | EFF_ONLY_OK))
198 #if !defined(PERL_EFF_ACCESS) && defined(HAS_EACCESS)
199 # ifdef I_SYS_SECURITY
200 # include <sys/security.h>
204 # define PERL_EFF_ACCESS(p,f) (eaccess((p), (f), ACC_SELF))
207 # define PERL_EFF_ACCESS(p,f) (eaccess((p), (f)))
211 #if !defined(PERL_EFF_ACCESS) && defined(HAS_ACCESSX) && defined(ACC_SELF)
212 /* AIX's accessx() doesn't declare its argument const, unlike every other platform */
213 # define PERL_EFF_ACCESS(p,f) (accessx((char*)(p), (f), ACC_SELF))
217 #if !defined(PERL_EFF_ACCESS) && defined(HAS_ACCESS) \
218 && (defined(HAS_SETREUID) || defined(HAS_SETRESUID) \
219 || defined(HAS_SETREGID) || defined(HAS_SETRESGID))
222 S_emulate_eaccess(pTHX_ const char* path, Mode_t mode)
224 const Uid_t ruid = getuid();
225 const Uid_t euid = geteuid();
226 const Gid_t rgid = getgid();
227 const Gid_t egid = getegid();
230 #if !defined(HAS_SETREUID) && !defined(HAS_SETRESUID)
231 Perl_croak(aTHX_ "switching effective uid is not implemented");
234 if (setreuid(euid, ruid))
235 # elif defined(HAS_SETRESUID)
236 if (setresuid(euid, ruid, (Uid_t)-1))
238 /* diag_listed_as: entering effective %s failed */
239 Perl_croak(aTHX_ "entering effective uid failed");
242 #if !defined(HAS_SETREGID) && !defined(HAS_SETRESGID)
243 Perl_croak(aTHX_ "switching effective gid is not implemented");
246 if (setregid(egid, rgid))
247 # elif defined(HAS_SETRESGID)
248 if (setresgid(egid, rgid, (Gid_t)-1))
250 /* diag_listed_as: entering effective %s failed */
251 Perl_croak(aTHX_ "entering effective gid failed");
254 res = access(path, mode);
257 if (setreuid(ruid, euid))
258 #elif defined(HAS_SETRESUID)
259 if (setresuid(ruid, euid, (Uid_t)-1))
261 /* diag_listed_as: leaving effective %s failed */
262 Perl_croak(aTHX_ "leaving effective uid failed");
265 if (setregid(rgid, egid))
266 #elif defined(HAS_SETRESGID)
267 if (setresgid(rgid, egid, (Gid_t)-1))
269 /* diag_listed_as: leaving effective %s failed */
270 Perl_croak(aTHX_ "leaving effective gid failed");
274 # define PERL_EFF_ACCESS(p,f) (S_emulate_eaccess(aTHX_ (p), (f)))
281 const char * const tmps = POPpconstx;
282 const U8 gimme = GIMME_V;
283 const char *mode = "r";
286 if (PL_op->op_private & OPpOPEN_IN_RAW)
288 else if (PL_op->op_private & OPpOPEN_IN_CRLF)
290 fp = PerlProc_popen(tmps, mode);
292 const char * const type = Perl_PerlIO_context_layers(aTHX_ NULL);
294 PerlIO_apply_layers(aTHX_ fp,mode,type);
296 if (gimme == G_VOID) {
298 while (PerlIO_read(fp, tmpbuf, sizeof tmpbuf) > 0)
301 else if (gimme == G_SCALAR) {
302 ENTER_with_name("backtick");
304 PL_rs = &PL_sv_undef;
305 SvPVCLEAR(TARG); /* note that this preserves previous buffer */
306 while (sv_gets(TARG, fp, SvCUR(TARG)) != NULL)
308 LEAVE_with_name("backtick");
314 SV * const sv = newSV(79);
315 if (sv_gets(sv, fp, 0) == NULL) {
320 if (SvLEN(sv) - SvCUR(sv) > 20) {
321 SvPV_shrink_to_cur(sv);
326 STATUS_NATIVE_CHILD_SET(PerlProc_pclose(fp));
327 TAINT; /* "I believe that this is not gratuitous!" */
330 STATUS_NATIVE_CHILD_SET(-1);
331 if (gimme == G_SCALAR)
342 GV * const gv = (PL_op->op_flags & OPf_SPECIAL) ? NULL : (GV *)POPs;
346 /* make a copy of the pattern if it is gmagical, to ensure that magic
347 * is called once and only once */
348 if (SvGMAGICAL(TOPs)) TOPs = sv_2mortal(newSVsv(TOPs));
350 tryAMAGICunTARGETlist(iter_amg, (PL_op->op_flags & OPf_SPECIAL));
352 if (PL_op->op_flags & OPf_SPECIAL) {
353 /* call Perl-level glob function instead. Stack args are:
355 * and following OPs should be: gv(CORE::GLOBAL::glob), entersub
364 /* Note that we only ever get here if File::Glob fails to load
365 * without at the same time croaking, for some reason, or if
366 * perl was built with PERL_EXTERNAL_GLOB */
368 ENTER_with_name("glob");
373 * The external globbing program may use things we can't control,
374 * so for security reasons we must assume the worst.
377 taint_proper(PL_no_security, "glob");
381 SAVESPTR(PL_last_in_gv); /* We don't want this to be permanent. */
384 SAVESPTR(PL_rs); /* This is not permanent, either. */
385 PL_rs = newSVpvs_flags("\000", SVs_TEMP);
388 *SvPVX(PL_rs) = '\n';
392 result = do_readline();
393 LEAVE_with_name("glob");
399 PL_last_in_gv = cGVOP_gv;
400 return do_readline();
410 do_join(TARG, &PL_sv_no, MARK, SP);
414 else if (SP == MARK) {
421 if (SvGMAGICAL(exsv)) exsv = sv_mortalcopy(exsv);
424 if (SvROK(exsv) || (SvPV_const(exsv, len), len)) {
425 /* well-formed exception supplied */
428 SV * const errsv = ERRSV;
431 if (SvGMAGICAL(errsv)) {
432 exsv = sv_newmortal();
433 sv_setsv_nomg(exsv, errsv);
437 else if (SvPOKp(errsv) ? SvCUR(errsv) : SvNIOKp(errsv)) {
438 exsv = sv_newmortal();
439 sv_setsv_nomg(exsv, errsv);
440 sv_catpvs(exsv, "\t...caught");
443 exsv = newSVpvs_flags("Warning: something's wrong", SVs_TEMP);
446 if (SvROK(exsv) && !PL_warnhook)
447 Perl_warn(aTHX_ "%" SVf, SVfARG(exsv));
459 VMSISH_HUSHED || (PL_curcop->op_private & OPpHUSH_VMSISH);
461 if (SP - MARK != 1) {
463 do_join(TARG, &PL_sv_no, MARK, SP);
471 if (SvROK(exsv) || (SvPV_const(exsv, len), len)) {
472 /* well-formed exception supplied */
475 SV * const errsv = ERRSV;
479 if (sv_isobject(exsv)) {
480 HV * const stash = SvSTASH(SvRV(exsv));
481 GV * const gv = gv_fetchmethod(stash, "PROPAGATE");
483 SV * const file = sv_2mortal(newSVpv(CopFILE(PL_curcop),0));
484 SV * const line = sv_2mortal(newSVuv(CopLINE(PL_curcop)));
491 call_sv(MUTABLE_SV(GvCV(gv)),
492 G_SCALAR|G_EVAL|G_KEEPERR);
493 exsv = sv_mortalcopy(*PL_stack_sp--);
497 else if (SvOK(errsv) && (SvPV_nomg(errsv,len), len)) {
498 exsv = sv_mortalcopy(errsv);
499 sv_catpvs(exsv, "\t...propagated");
502 exsv = newSVpvs_flags("Died", SVs_TEMP);
506 NOT_REACHED; /* NOTREACHED */
507 return NULL; /* avoid missing return from non-void function warning */
513 Perl_tied_method(pTHX_ SV *methname, SV **sp, SV *const sv,
514 const MAGIC *const mg, const U32 flags, U32 argc, ...)
520 PERL_ARGS_ASSERT_TIED_METHOD;
522 /* Ensure that our flag bits do not overlap. */
523 STATIC_ASSERT_STMT((TIED_METHOD_MORTALIZE_NOT_NEEDED & G_WANT) == 0);
524 STATIC_ASSERT_STMT((TIED_METHOD_ARGUMENTS_ON_STACK & G_WANT) == 0);
525 STATIC_ASSERT_STMT((TIED_METHOD_SAY & G_WANT) == 0);
527 PUTBACK; /* sp is at *foot* of args, so this pops args from old stack */
528 PUSHSTACKi(PERLSI_MAGIC);
529 /* extend for object + args. If argc might wrap/truncate when cast
530 * to SSize_t and incremented, set to -1, which will trigger a panic in
532 * The weird way this is written is because g++ is dumb enough to
533 * warn "comparison is always false" on something like:
535 * sizeof(a) >= sizeof(b) && a >= B_t_MAX -1
537 * (where the LH condition is false)
540 (argc > (sizeof(argc) >= sizeof(SSize_t) ? SSize_t_MAX - 1 : argc))
541 ? -1 : (SSize_t)argc + 1;
542 EXTEND(SP, extend_size);
544 PUSHs(SvTIED_obj(sv, mg));
545 if (flags & TIED_METHOD_ARGUMENTS_ON_STACK) {
546 Copy(orig_sp + 2, sp + 1, argc, SV*); /* copy args to new stack */
550 const U32 mortalize_not_needed
551 = flags & TIED_METHOD_MORTALIZE_NOT_NEEDED;
553 va_start(args, argc);
555 SV *const arg = va_arg(args, SV *);
556 if(mortalize_not_needed)
565 ENTER_with_name("call_tied_method");
566 if (flags & TIED_METHOD_SAY) {
567 /* local $\ = "\n" */
568 SAVEGENERICSV(PL_ors_sv);
569 PL_ors_sv = newSVpvs("\n");
571 ret_args = call_sv(methname, (flags & G_WANT)|G_METHOD_NAMED);
576 if (ret_args) { /* copy results back to original stack */
577 EXTEND(sp, ret_args);
578 Copy(orig_sp - ret_args + 1, sp + 1, ret_args, SV*);
582 LEAVE_with_name("call_tied_method");
586 #define tied_method0(a,b,c,d) \
587 Perl_tied_method(aTHX_ a,b,c,d,G_SCALAR,0)
588 #define tied_method1(a,b,c,d,e) \
589 Perl_tied_method(aTHX_ a,b,c,d,G_SCALAR,1,e)
590 #define tied_method2(a,b,c,d,e,f) \
591 Perl_tied_method(aTHX_ a,b,c,d,G_SCALAR,2,e,f)
604 GV * const gv = MUTABLE_GV(*++MARK);
606 if (!isGV(gv) && !(SvTYPE(gv) == SVt_PVLV && isGV_with_GP(gv)))
607 DIE(aTHX_ PL_no_usym, "filehandle");
609 if ((io = GvIOp(gv))) {
611 IoFLAGS(GvIOp(gv)) &= ~IOf_UNTAINT;
614 Perl_croak(aTHX_ "Cannot open %" HEKf " as a filehandle: it is already open as a dirhandle",
615 HEKfARG(GvENAME_HEK(gv)));
617 mg = SvTIED_mg((const SV *)io, PERL_MAGIC_tiedscalar);
619 /* Method's args are same as ours ... */
620 /* ... except handle is replaced by the object */
621 return Perl_tied_method(aTHX_ SV_CONST(OPEN), mark - 1, MUTABLE_SV(io), mg,
622 G_SCALAR | TIED_METHOD_ARGUMENTS_ON_STACK,
634 tmps = SvPV_const(sv, len);
635 ok = do_open6(gv, tmps, len, NULL, MARK+1, (SP-MARK));
638 PUSHi( (I32)PL_forkprocess );
639 else if (PL_forkprocess == 0) /* we are a new child */
649 /* pp_coreargs pushes a NULL to indicate no args passed to
652 MAXARG == 0 || (!TOPs && !POPs) ? PL_defoutgv : MUTABLE_GV(POPs);
658 IO * const io = GvIO(gv);
660 const MAGIC * const mg = SvTIED_mg((const SV *)io, PERL_MAGIC_tiedscalar);
662 return tied_method0(SV_CONST(CLOSE), SP, MUTABLE_SV(io), mg);
666 PUSHs(boolSV(do_close(gv, TRUE)));
678 GV * const wgv = MUTABLE_GV(POPs);
679 GV * const rgv = MUTABLE_GV(POPs);
683 do_close(rgv, FALSE);
687 do_close(wgv, FALSE);
689 if (PerlProc_pipe_cloexec(fd) < 0)
692 IoIFP(rstio) = PerlIO_fdopen(fd[0], "r" PIPE_OPEN_MODE);
693 IoOFP(wstio) = PerlIO_fdopen(fd[1], "w" PIPE_OPEN_MODE);
694 IoOFP(rstio) = IoIFP(rstio);
695 IoIFP(wstio) = IoOFP(wstio);
696 IoTYPE(rstio) = IoTYPE_RDONLY;
697 IoTYPE(wstio) = IoTYPE_WRONLY;
699 if (!IoIFP(rstio) || !IoOFP(wstio)) {
701 PerlIO_close(IoIFP(rstio));
703 PerlLIO_close(fd[0]);
705 PerlIO_close(IoOFP(wstio));
707 PerlLIO_close(fd[1]);
715 DIE(aTHX_ PL_no_func, "pipe");
729 gv = MUTABLE_GV(POPs);
733 && (mg = SvTIED_mg((const SV *)io, PERL_MAGIC_tiedscalar)))
735 return tied_method0(SV_CONST(FILENO), SP, MUTABLE_SV(io), mg);
738 if (io && IoDIRP(io)) {
739 #if defined(HAS_DIRFD) || defined(HAS_DIR_DD_FD)
740 PUSHi(my_dirfd(IoDIRP(io)));
742 #elif defined(ENOTSUP)
743 errno = ENOTSUP; /* Operation not supported */
745 #elif defined(EOPNOTSUPP)
746 errno = EOPNOTSUPP; /* Operation not supported on socket */
749 errno = EINVAL; /* Invalid argument */
754 if (!io || !(fp = IoIFP(io))) {
755 /* Can't do this because people seem to do things like
756 defined(fileno($foo)) to check whether $foo is a valid fh.
763 PUSHi(PerlIO_fileno(fp));
774 if (MAXARG < 1 || (!TOPs && !POPs)) {
775 anum = PerlLIO_umask(022);
776 /* setting it to 022 between the two calls to umask avoids
777 * to have a window where the umask is set to 0 -- meaning
778 * that another thread could create world-writeable files. */
780 (void)PerlLIO_umask(anum);
783 anum = PerlLIO_umask(POPi);
784 TAINT_PROPER("umask");
787 /* Only DIE if trying to restrict permissions on "user" (self).
788 * Otherwise it's harmless and more useful to just return undef
789 * since 'group' and 'other' concepts probably don't exist here. */
790 if (MAXARG >= 1 && (TOPs||POPs) && (POPi & 0700))
791 DIE(aTHX_ "umask not implemented");
792 XPUSHs(&PL_sv_undef);
811 gv = MUTABLE_GV(POPs);
815 const MAGIC * const mg = SvTIED_mg((const SV *)io, PERL_MAGIC_tiedscalar);
817 /* This takes advantage of the implementation of the varargs
818 function, which I don't think that the optimiser will be able to
819 figure out. Although, as it's a static function, in theory it
821 return Perl_tied_method(aTHX_ SV_CONST(BINMODE), SP, MUTABLE_SV(io), mg,
822 G_SCALAR|TIED_METHOD_MORTALIZE_NOT_NEEDED,
823 discp ? 1 : 0, discp);
827 if (!io || !(fp = IoIFP(io))) {
829 SETERRNO(EBADF,RMS_IFI);
836 const char *d = NULL;
839 d = SvPV_const(discp, len);
840 mode = mode_from_discipline(d, len);
841 if (PerlIO_binmode(aTHX_ fp, IoTYPE(io), mode, d)) {
842 if (IoOFP(io) && IoOFP(io) != IoIFP(io)) {
843 if (!PerlIO_binmode(aTHX_ IoOFP(io), IoTYPE(io), mode, d)) {
864 const I32 markoff = MARK - PL_stack_base;
865 const char *methname;
866 int how = PERL_MAGIC_tied;
870 switch(SvTYPE(varsv)) {
874 methname = "TIEHASH";
875 if (HvLAZYDEL(varsv) && (entry = HvEITER_get((HV *)varsv))) {
876 HvLAZYDEL_off(varsv);
877 hv_free_ent(NULL, entry);
879 HvEITER_set(MUTABLE_HV(varsv), 0);
880 HvRITER_set(MUTABLE_HV(varsv), -1);
884 methname = "TIEARRAY";
885 if (!AvREAL(varsv)) {
887 Perl_croak(aTHX_ "Cannot tie unreifiable array");
888 av_clear((AV *)varsv);
895 if (isGV_with_GP(varsv) && !SvFAKE(varsv)) {
896 methname = "TIEHANDLE";
897 how = PERL_MAGIC_tiedscalar;
898 /* For tied filehandles, we apply tiedscalar magic to the IO
899 slot of the GP rather than the GV itself. AMS 20010812 */
901 GvIOp(varsv) = newIO();
902 varsv = MUTABLE_SV(GvIOp(varsv));
905 if (SvTYPE(varsv) == SVt_PVLV && LvTYPE(varsv) == 'y') {
906 vivify_defelem(varsv);
907 varsv = LvTARG(varsv);
911 methname = "TIESCALAR";
912 how = PERL_MAGIC_tiedscalar;
916 if (sv_isobject(*MARK)) { /* Calls GET magic. */
917 ENTER_with_name("call_TIE");
918 PUSHSTACKi(PERLSI_MAGIC);
920 EXTEND(SP,(I32)items);
924 call_method(methname, G_SCALAR);
927 /* Can't use call_method here, else this: fileno FOO; tie @a, "FOO"
928 * will attempt to invoke IO::File::TIEARRAY, with (best case) the
929 * wrong error message, and worse case, supreme action at a distance.
930 * (Sorry obfuscation writers. You're not going to be given this one.)
932 stash = gv_stashsv(*MARK, 0);
935 DIE(aTHX_ "Can't locate object method %" PVf_QUOTEDPREFIX
936 " via package %" SVf_QUOTEDPREFIX,
937 methname, SVfARG(*MARK));
938 else if (isGV(*MARK)) {
939 /* If the glob doesn't name an existing package, using
940 * SVfARG(*MARK) would yield "*Foo::Bar" or *main::Foo. So
941 * generate the name for the error message explicitly. */
942 SV *stashname = sv_newmortal();
943 gv_fullname4(stashname, (GV *) *MARK, NULL, FALSE);
944 DIE(aTHX_ "Can't locate object method %" PVf_QUOTEDPREFIX
945 " via package %" SVf_QUOTEDPREFIX,
946 methname, SVfARG(stashname));
949 SV *stashname = !SvPOK(*MARK) ? &PL_sv_no
950 : SvCUR(*MARK) ? *MARK
951 : newSVpvs_flags("main", SVs_TEMP);
952 DIE(aTHX_ "Can't locate object method %" PVf_QUOTEDPREFIX
953 " via package %" SVf_QUOTEDPREFIX
954 " (perhaps you forgot to load %" SVf_QUOTEDPREFIX "?)",
955 methname, SVfARG(stashname), SVfARG(stashname));
958 else if (!(gv = gv_fetchmethod(stash, methname))) {
959 /* The effective name can only be NULL for stashes that have
960 * been deleted from the symbol table, which this one can't
961 * be, since we just looked it up by name.
963 DIE(aTHX_ "Can't locate object method %" PVf_QUOTEDPREFIX
964 " via package %" HEKf_QUOTEDPREFIX ,
965 methname, HvENAME_HEK_NN(stash));
967 ENTER_with_name("call_TIE");
968 PUSHSTACKi(PERLSI_MAGIC);
970 EXTEND(SP,(I32)items);
974 call_sv(MUTABLE_SV(GvCV(gv)), G_SCALAR);
980 if (sv_isobject(sv)) {
981 sv_unmagic(varsv, how);
982 /* Croak if a self-tie on an aggregate is attempted. */
983 if (varsv == SvRV(sv) &&
984 (SvTYPE(varsv) == SVt_PVAV ||
985 SvTYPE(varsv) == SVt_PVHV))
987 "Self-ties of arrays and hashes are not supported");
988 sv_magic(varsv, (SvRV(sv) == varsv ? NULL : sv), how, NULL, 0);
990 LEAVE_with_name("call_TIE");
991 SP = PL_stack_base + markoff;
997 /* also used for: pp_dbmclose() */
1004 const char how = (SvTYPE(sv) == SVt_PVHV || SvTYPE(sv) == SVt_PVAV)
1005 ? PERL_MAGIC_tied : PERL_MAGIC_tiedscalar;
1007 if (isGV_with_GP(sv) && !SvFAKE(sv) && !(sv = MUTABLE_SV(GvIOp(sv))))
1010 if (SvTYPE(sv) == SVt_PVLV && LvTYPE(sv) == 'y' &&
1011 !(sv = defelem_target(sv, NULL))) RETPUSHUNDEF;
1013 if ((mg = SvTIED_mg(sv, how))) {
1014 SV * const obj = SvRV(SvTIED_obj(sv, mg));
1015 if (obj && SvSTASH(obj)) {
1016 GV * const gv = gv_fetchmethod_autoload(SvSTASH(obj), "UNTIE", FALSE);
1018 if (gv && isGV(gv) && (cv = GvCV(gv))) {
1020 PUSHs(SvTIED_obj(MUTABLE_SV(gv), mg));
1021 mXPUSHi(SvREFCNT(obj) - 1);
1023 ENTER_with_name("call_UNTIE");
1024 call_sv(MUTABLE_SV(cv), G_VOID);
1025 LEAVE_with_name("call_UNTIE");
1028 else if (mg && SvREFCNT(obj) > 1) {
1029 Perl_ck_warner(aTHX_ packWARN(WARN_UNTIE),
1030 "untie attempted while %" UVuf " inner references still exist",
1031 (UV)SvREFCNT(obj) - 1 ) ;
1035 sv_unmagic(sv, how) ;
1037 if (SvTYPE(sv) == SVt_PVHV) {
1038 /* If the tied hash was partway through iteration, free the iterator and
1039 * any key that it is pointing to. */
1041 if (HvLAZYDEL(sv) && (entry = HvEITER_get((HV *)sv))) {
1043 hv_free_ent(NULL, entry);
1044 HvEITER_set(MUTABLE_HV(sv), 0);
1056 const char how = (SvTYPE(sv) == SVt_PVHV || SvTYPE(sv) == SVt_PVAV)
1057 ? PERL_MAGIC_tied : PERL_MAGIC_tiedscalar;
1059 if (isGV_with_GP(sv) && !SvFAKE(sv) && !(sv = MUTABLE_SV(GvIOp(sv))))
1062 if (SvTYPE(sv) == SVt_PVLV && LvTYPE(sv) == 'y' &&
1063 !(sv = defelem_target(sv, NULL))) goto ret_undef;
1065 if ((mg = SvTIED_mg(sv, how))) {
1066 SETs(SvTIED_obj(sv, mg));
1067 return NORMAL; /* PUTBACK not needed, pp_tied never moves SP */
1081 HV * const hv = MUTABLE_HV(POPs);
1082 SV * const sv = newSVpvs_flags("AnyDBM_File", SVs_TEMP);
1083 stash = gv_stashsv(sv, 0);
1084 if (!stash || !(gv = gv_fetchmethod(stash, "TIEHASH"))) {
1086 require_pv("AnyDBM_File.pm");
1088 if (!stash || !(gv = gv_fetchmethod(stash, "TIEHASH")))
1089 DIE(aTHX_ "No dbm on this machine");
1099 mPUSHu(O_RDWR|O_CREAT);
1103 if (!SvOK(right)) right = &PL_sv_no;
1107 call_sv(MUTABLE_SV(GvCV(gv)), G_SCALAR);
1110 if (!sv_isobject(TOPs)) {
1118 call_sv(MUTABLE_SV(GvCV(gv)), G_SCALAR);
1120 if (sv_isobject(TOPs))
1125 sv_unmagic(MUTABLE_SV(hv), PERL_MAGIC_tied);
1126 sv_magic(MUTABLE_SV(hv), TOPs, PERL_MAGIC_tied, NULL, 0);
1143 struct timeval timebuf;
1144 struct timeval *tbuf = &timebuf;
1148 #if BYTEORDER != 0x1234 && BYTEORDER != 0x12345678
1153 # if BYTEORDER & 0xf0000
1154 # define ORDERBYTE (0x88888888 - BYTEORDER)
1156 # define ORDERBYTE (0x4444 - BYTEORDER)
1162 for (i = 1; i <= 3; i++) {
1163 SV * const sv = svs[i] = SP[i];
1167 if (SvREADONLY(sv)) {
1168 if (!(SvPOK(sv) && SvCUR(sv) == 0))
1169 Perl_croak_no_modify();
1171 else if (SvIsCOW(sv)) sv_force_normal_flags(sv, 0);
1173 if (SvUTF8(sv)) sv_utf8_downgrade(sv, FALSE);
1177 Perl_ck_warner(aTHX_ packWARN(WARN_MISC),
1178 "Non-string passed as bitmask");
1179 if (SvGAMAGIC(sv)) {
1180 svs[i] = sv_newmortal();
1181 sv_copypv_nomg(svs[i], sv);
1184 SvPV_force_nomg_nolen(sv); /* force string conversion */
1191 /* little endians can use vecs directly */
1192 #if BYTEORDER != 0x1234 && BYTEORDER != 0x12345678
1199 masksize = NFDBITS / NBBY;
1201 masksize = sizeof(long); /* documented int, everyone seems to use long */
1203 Zero(&fd_sets[0], 4, char*);
1206 # if SELECT_MIN_BITS == 1
1207 growsize = sizeof(fd_set);
1209 # if defined(__GLIBC__) && defined(__FD_SETSIZE)
1210 # undef SELECT_MIN_BITS
1211 # define SELECT_MIN_BITS __FD_SETSIZE
1213 /* If SELECT_MIN_BITS is greater than one we most probably will want
1214 * to align the sizes with SELECT_MIN_BITS/8 because for example
1215 * in many little-endian (Intel, Alpha) systems (Linux, OS/2, Digital
1216 * UNIX, Solaris, Darwin) the smallest quantum select() operates
1217 * on (sets/tests/clears bits) is 32 bits. */
1218 growsize = maxlen + (SELECT_MIN_BITS/8 - (maxlen % (SELECT_MIN_BITS/8)));
1224 value = SvNV_nomg(sv);
1227 timebuf.tv_sec = (long)value;
1228 value -= (NV)timebuf.tv_sec;
1229 timebuf.tv_usec = (long)(value * 1000000.0);
1234 for (i = 1; i <= 3; i++) {
1236 if (!SvOK(sv) || SvCUR(sv) == 0) {
1243 Sv_Grow(sv, growsize);
1247 while (++j <= growsize) {
1251 #if BYTEORDER != 0x1234 && BYTEORDER != 0x12345678
1253 Newx(fd_sets[i], growsize, char);
1254 for (offset = 0; offset < growsize; offset += masksize) {
1255 for (j = 0, k=ORDERBYTE; j < masksize; j++, (k >>= 4))
1256 fd_sets[i][j+offset] = s[(k % masksize) + offset];
1259 fd_sets[i] = SvPVX(sv);
1263 #ifdef PERL_IRIX5_SELECT_TIMEVAL_VOID_CAST
1264 /* Can't make just the (void*) conditional because that would be
1265 * cpp #if within cpp macro, and not all compilers like that. */
1266 nfound = PerlSock_select(
1268 (Select_fd_set_t) fd_sets[1],
1269 (Select_fd_set_t) fd_sets[2],
1270 (Select_fd_set_t) fd_sets[3],
1271 (void*) tbuf); /* Workaround for compiler bug. */
1273 nfound = PerlSock_select(
1275 (Select_fd_set_t) fd_sets[1],
1276 (Select_fd_set_t) fd_sets[2],
1277 (Select_fd_set_t) fd_sets[3],
1280 for (i = 1; i <= 3; i++) {
1283 #if BYTEORDER != 0x1234 && BYTEORDER != 0x12345678
1285 for (offset = 0; offset < growsize; offset += masksize) {
1286 for (j = 0, k=ORDERBYTE; j < masksize; j++, (k >>= 4))
1287 s[(k % masksize) + offset] = fd_sets[i][j+offset];
1289 Safefree(fd_sets[i]);
1292 SvSetMagicSV(SP[i], sv);
1299 if (GIMME_V == G_LIST && tbuf) {
1300 value = (NV)(timebuf.tv_sec) +
1301 (NV)(timebuf.tv_usec) / 1000000.0;
1306 DIE(aTHX_ "select not implemented");
1312 =for apidoc_section $GV
1314 =for apidoc setdefout
1316 Sets C<PL_defoutgv>, the default file handle for output, to the passed in
1317 typeglob. As C<PL_defoutgv> "owns" a reference on its typeglob, the reference
1318 count of the passed in typeglob is increased by one, and the reference count
1319 of the typeglob that C<PL_defoutgv> points to is decreased by one.
1321 =for apidoc AmnU||PL_defoutgv
1323 See C<L</setdefout>>.
1329 Perl_setdefout(pTHX_ GV *gv)
1331 GV *oldgv = PL_defoutgv;
1333 PERL_ARGS_ASSERT_SETDEFOUT;
1335 SvREFCNT_inc_simple_void_NN(gv);
1337 SvREFCNT_dec(oldgv);
1344 GV * const newdefout = (PL_op->op_private > 0) ? (MUTABLE_GV(POPs)) : NULL;
1345 GV * egv = GvEGVx(PL_defoutgv);
1350 hv = isGV_with_GP(egv) ? GvSTASH(egv) : NULL;
1351 gvp = hv && HvENAME(hv)
1352 ? (GV**)hv_fetch(hv, GvNAME(egv), HEK_UTF8(GvNAME_HEK(egv)) ? -GvNAMELEN(egv) : GvNAMELEN(egv), FALSE)
1354 if (gvp && *gvp == egv) {
1355 gv_efullname4(TARG, PL_defoutgv, NULL, TRUE);
1359 mXPUSHs(newRV(MUTABLE_SV(egv)));
1363 if (!GvIO(newdefout))
1364 gv_IOadd(newdefout);
1365 setdefout(newdefout);
1374 /* pp_coreargs pushes a NULL to indicate no args passed to
1377 MAXARG==0 || (!TOPs && !POPs) ? PL_stdingv : MUTABLE_GV(POPs);
1378 IO *const io = GvIO(gv);
1384 const MAGIC * const mg = SvTIED_mg((const SV *)io, PERL_MAGIC_tiedscalar);
1386 const U8 gimme = GIMME_V;
1387 Perl_tied_method(aTHX_ SV_CONST(GETC), SP, MUTABLE_SV(io), mg, gimme, 0);
1388 if (gimme == G_SCALAR) {
1390 SvSetMagicSV_nosteal(TARG, TOPs);
1395 if (!gv || do_eof(gv)) { /* make sure we have fp with something */
1396 if (!io || (!IoIFP(io) && IoTYPE(io) != IoTYPE_WRONLY))
1398 SETERRNO(EBADF,RMS_IFI);
1402 sv_setpvs(TARG, " ");
1403 *SvPVX(TARG) = PerlIO_getc(IoIFP(GvIOp(gv))); /* should never be EOF */
1404 if (PerlIO_isutf8(IoIFP(GvIOp(gv)))) {
1405 /* Find out how many bytes the char needs */
1406 Size_t len = UTF8SKIP(SvPVX_const(TARG));
1409 len = PerlIO_read(IoIFP(GvIOp(gv)),SvPVX(TARG)+1,len-1);
1410 SvCUR_set(TARG,1+len);
1414 else SvUTF8_off(TARG);
1420 S_doform(pTHX_ CV *cv, GV *gv, OP *retop)
1423 const U8 gimme = GIMME_V;
1425 PERL_ARGS_ASSERT_DOFORM;
1428 cv = MUTABLE_CV(sv_2mortal(MUTABLE_SV(cv_clone(cv))));
1430 cx = cx_pushblock(CXt_FORMAT, gimme, PL_stack_sp, PL_savestack_ix);
1431 cx_pushformat(cx, cv, retop, gv);
1432 if (CvDEPTH(cv) >= 2)
1433 pad_push(CvPADLIST(cv), CvDEPTH(cv));
1434 PAD_SET_CUR_NOSAVE(CvPADLIST(cv), CvDEPTH(cv));
1436 setdefout(gv); /* locally select filehandle so $% et al work */
1453 gv = MUTABLE_GV(POPs);
1470 SV * const tmpsv = sv_newmortal();
1471 gv_efullname4(tmpsv, fgv, NULL, FALSE);
1472 DIE(aTHX_ "Undefined format \"%" SVf "\" called", SVfARG(tmpsv));
1474 IoFLAGS(io) &= ~IOf_DIDTOP;
1475 RETURNOP(doform(cv,gv,PL_op->op_next));
1481 GV * const gv = CX_CUR()->blk_format.gv;
1482 IO * const io = GvIOp(gv);
1487 bool is_return = cBOOL(PL_op->op_type == OP_RETURN);
1489 if (is_return || !io || !(ofp = IoOFP(io)))
1492 DEBUG_f(PerlIO_printf(Perl_debug_log, "left=%ld, todo=%ld\n",
1493 (long)IoLINES_LEFT(io), (long)FmLINES(PL_formtarget)));
1495 if (IoLINES_LEFT(io) < FmLINES(PL_formtarget) &&
1496 PL_formtarget != PL_toptarget)
1500 if (!IoTOP_GV(io)) {
1503 if (!IoTOP_NAME(io)) {
1505 if (!IoFMT_NAME(io))
1506 IoFMT_NAME(io) = savepv(GvNAME(gv));
1507 topname = sv_2mortal(Perl_newSVpvf(aTHX_ "%" HEKf "_TOP",
1508 HEKfARG(GvNAME_HEK(gv))));
1509 topgv = gv_fetchsv(topname, 0, SVt_PVFM);
1510 if ((topgv && GvFORM(topgv)) ||
1511 !gv_fetchpvs("top", GV_NOTQUAL, SVt_PVFM))
1512 IoTOP_NAME(io) = savesvpv(topname);
1514 IoTOP_NAME(io) = savepvs("top");
1516 topgv = gv_fetchpv(IoTOP_NAME(io), 0, SVt_PVFM);
1517 if (!topgv || !GvFORM(topgv)) {
1518 IoLINES_LEFT(io) = IoPAGE_LEN(io);
1521 IoTOP_GV(io) = topgv;
1523 if (IoFLAGS(io) & IOf_DIDTOP) { /* Oh dear. It still doesn't fit. */
1524 I32 lines = IoLINES_LEFT(io);
1525 const char *s = SvPVX_const(PL_formtarget);
1526 const char *e = SvEND(PL_formtarget);
1527 if (lines <= 0) /* Yow, header didn't even fit!!! */
1529 while (lines-- > 0) {
1530 s = (char *) memchr(s, '\n', e - s);
1536 const STRLEN save = SvCUR(PL_formtarget);
1537 SvCUR_set(PL_formtarget, s - SvPVX_const(PL_formtarget));
1538 do_print(PL_formtarget, ofp);
1539 SvCUR_set(PL_formtarget, save);
1540 sv_chop(PL_formtarget, s);
1541 FmLINES(PL_formtarget) -= IoLINES_LEFT(io);
1544 if (IoLINES_LEFT(io) >= 0 && IoPAGE(io) > 0)
1545 do_print(GvSV(gv_fetchpvs("\f", GV_ADD, SVt_PV)), ofp);
1546 IoLINES_LEFT(io) = IoPAGE_LEN(io);
1548 PL_formtarget = PL_toptarget;
1549 IoFLAGS(io) |= IOf_DIDTOP;
1551 assert(fgv); /* IoTOP_GV(io) should have been set above */
1554 SV * const sv = sv_newmortal();
1555 gv_efullname4(sv, fgv, NULL, FALSE);
1556 DIE(aTHX_ "Undefined top format \"%" SVf "\" called", SVfARG(sv));
1558 return doform(cv, gv, PL_op);
1563 assert(CxTYPE(cx) == CXt_FORMAT);
1564 SP = PL_stack_base + cx->blk_oldsp; /* ignore retval of formline */
1568 retop = cx->blk_sub.retop;
1574 /* XXX the semantics of doing 'return' in a format aren't documented.
1575 * Currently we ignore any args to 'return' and just return
1576 * a single undef in both scalar and list contexts
1578 PUSHs(&PL_sv_undef);
1579 else if (!io || !(fp = IoOFP(io))) {
1580 if (io && IoIFP(io))
1581 report_wrongway_fh(gv, '<');
1587 if ((IoLINES_LEFT(io) -= FmLINES(PL_formtarget)) < 0) {
1588 Perl_ck_warner(aTHX_ packWARN(WARN_IO), "page overflow");
1590 if (!do_print(PL_formtarget, fp))
1593 FmLINES(PL_formtarget) = 0;
1594 SvCUR_set(PL_formtarget, 0);
1595 *SvEND(PL_formtarget) = '\0';
1596 if (IoFLAGS(io) & IOf_FLUSH)
1597 (void)PerlIO_flush(fp);
1601 PL_formtarget = PL_bodytarget;
1607 dSP; dMARK; dORIGMARK;
1611 = (PL_op->op_flags & OPf_STACKED) ? MUTABLE_GV(*++MARK) : PL_defoutgv;
1612 IO *const io = GvIO(gv);
1614 /* Treat empty list as "" */
1615 if (MARK == SP) XPUSHs(&PL_sv_no);
1618 const MAGIC * const mg = SvTIED_mg((const SV *)io, PERL_MAGIC_tiedscalar);
1620 if (MARK == ORIGMARK) {
1623 Move(MARK, MARK + 1, (SP - MARK) + 1, SV*);
1626 return Perl_tied_method(aTHX_ SV_CONST(PRINTF), mark - 1, MUTABLE_SV(io),
1628 G_SCALAR | TIED_METHOD_ARGUMENTS_ON_STACK,
1635 SETERRNO(EBADF,RMS_IFI);
1638 else if (!(fp = IoOFP(io))) {
1640 report_wrongway_fh(gv, '<');
1641 else if (ckWARN(WARN_CLOSED))
1643 SETERRNO(EBADF,IoIFP(io)?RMS_FAC:RMS_IFI);
1647 SV *sv = sv_newmortal();
1648 do_sprintf(sv, SP - MARK, MARK + 1);
1649 if (!do_print(sv, fp))
1652 if (IoFLAGS(io) & IOf_FLUSH)
1653 if (PerlIO_flush(fp) == EOF)
1662 PUSHs(&PL_sv_undef);
1669 const int perm = (MAXARG > 3 && (TOPs || POPs)) ? POPi : 0666;
1670 const int mode = POPi;
1671 SV * const sv = POPs;
1672 GV * const gv = MUTABLE_GV(POPs);
1675 /* Need TIEHANDLE method ? */
1676 const char * const tmps = SvPV_const(sv, len);
1677 if (do_open_raw(gv, tmps, len, mode, perm, NULL)) {
1678 IoLINES(GvIOp(gv)) = 0;
1682 PUSHs(&PL_sv_undef);
1688 /* also used for: pp_read() and pp_recv() (where supported) */
1692 dSP; dMARK; dORIGMARK; dTARGET;
1706 bool charstart = FALSE;
1707 STRLEN charskip = 0;
1709 GV * const gv = MUTABLE_GV(*++MARK);
1712 if ((PL_op->op_type == OP_READ || PL_op->op_type == OP_SYSREAD)
1713 && gv && (io = GvIO(gv)) )
1715 const MAGIC *const mg = SvTIED_mg((const SV *)io, PERL_MAGIC_tiedscalar);
1717 return Perl_tied_method(aTHX_ SV_CONST(READ), mark - 1, MUTABLE_SV(io), mg,
1718 G_SCALAR | TIED_METHOD_ARGUMENTS_ON_STACK,
1728 length = SvIVx(*++MARK);
1730 DIE(aTHX_ "Negative length");
1733 offset = SvIVx(*++MARK);
1737 if (!io || !IoIFP(io)) {
1739 SETERRNO(EBADF,RMS_IFI);
1743 /* Note that fd can here validly be -1, don't check it yet. */
1744 fd = PerlIO_fileno(IoIFP(io));
1746 if ((fp_utf8 = PerlIO_isutf8(IoIFP(io))) && !IN_BYTES) {
1747 if (PL_op->op_type == OP_SYSREAD || PL_op->op_type == OP_RECV) {
1749 "%s() isn't allowed on :utf8 handles",
1752 buffer = SvPVutf8_force(bufsv, blen);
1753 /* UTF-8 may not have been set if they are all low bytes */
1758 buffer = SvPV_force(bufsv, blen);
1759 buffer_utf8 = DO_UTF8(bufsv);
1761 if (DO_UTF8(bufsv)) {
1762 blen = sv_len_utf8_nomg(bufsv);
1771 if (PL_op->op_type == OP_RECV) {
1772 Sock_size_t bufsize;
1773 char namebuf[MAXPATHLEN];
1775 SETERRNO(EBADF,SS_IVCHAN);
1778 #if (defined(VMS_DO_SOCKETS) && defined(DECCRTL_SOCKETS)) || defined(__QNXNTO__)
1779 bufsize = sizeof (struct sockaddr_in);
1781 bufsize = sizeof namebuf;
1783 #ifdef OS2 /* At least Warp3+IAK: only the first byte of bufsize set */
1787 buffer = SvGROW(bufsv, (STRLEN)(length+1));
1788 /* 'offset' means 'flags' here */
1789 count = PerlSock_recvfrom(fd, buffer, length, offset,
1790 (struct sockaddr *)namebuf, &bufsize);
1793 /* MSG_TRUNC can give oversized count; quietly lose it */
1796 SvCUR_set(bufsv, count);
1797 *SvEND(bufsv) = '\0';
1798 (void)SvPOK_only(bufsv);
1802 /* This should not be marked tainted if the fp is marked clean */
1803 if (!(IoFLAGS(io) & IOf_UNTAINT))
1804 SvTAINTED_on(bufsv);
1806 #if defined(__CYGWIN__)
1807 /* recvfrom() on cygwin doesn't set bufsize at all for
1808 connected sockets, leaving us with trash in the returned
1809 name, so use the same test as the Win32 code to check if it
1810 wasn't set, and set it [perl #118843] */
1811 if (bufsize == sizeof namebuf)
1814 sv_setpvn(TARG, namebuf, bufsize);
1820 if (-offset > (SSize_t)blen)
1821 DIE(aTHX_ "Offset outside string");
1824 if (DO_UTF8(bufsv)) {
1825 /* convert offset-as-chars to offset-as-bytes */
1826 if (offset >= (SSize_t)blen)
1827 offset += SvCUR(bufsv) - blen;
1829 offset = utf8_hop((U8 *)buffer,offset) - (U8 *) buffer;
1833 /* Reestablish the fd in case it shifted from underneath us. */
1834 fd = PerlIO_fileno(IoIFP(io));
1836 orig_size = SvCUR(bufsv);
1837 /* Allocating length + offset + 1 isn't perfect in the case of reading
1838 bytes from a byte file handle into a UTF8 buffer, but it won't harm us
1840 (should be 2 * length + offset + 1, or possibly something longer if
1841 IN_ENCODING Is true) */
1842 buffer = SvGROW(bufsv, (STRLEN)(length+offset+1));
1843 if (offset > 0 && offset > (SSize_t)orig_size) { /* Zero any newly allocated space */
1844 Zero(buffer+orig_size, offset-orig_size, char);
1846 buffer = buffer + offset;
1848 read_target = bufsv;
1850 /* Best to read the bytes into a new SV, upgrade that to UTF8, then
1851 concatenate it to the current buffer. */
1853 /* Truncate the existing buffer to the start of where we will be
1855 SvCUR_set(bufsv, offset);
1857 read_target = sv_newmortal();
1858 SvUPGRADE(read_target, SVt_PV);
1859 buffer = SvGROW(read_target, (STRLEN)(length + 1));
1862 if (PL_op->op_type == OP_SYSREAD) {
1863 #ifdef PERL_SOCK_SYSREAD_IS_RECV
1864 if (IoTYPE(io) == IoTYPE_SOCKET) {
1866 SETERRNO(EBADF,SS_IVCHAN);
1870 count = PerlSock_recv(fd, buffer, length, 0);
1876 SETERRNO(EBADF,RMS_IFI);
1880 count = PerlLIO_read(fd, buffer, length);
1885 count = PerlIO_read(IoIFP(io), buffer, length);
1886 /* PerlIO_read() - like fread() returns 0 on both error and EOF */
1887 if (count == 0 && PerlIO_error(IoIFP(io)))
1891 if (IoTYPE(io) == IoTYPE_WRONLY)
1892 report_wrongway_fh(gv, '>');
1895 SvCUR_set(read_target, count+(buffer - SvPVX_const(read_target)));
1896 *SvEND(read_target) = '\0';
1897 (void)SvPOK_only(read_target);
1898 if (fp_utf8 && !IN_BYTES) {
1899 /* Look at utf8 we got back and count the characters */
1900 const char *bend = buffer + count;
1901 while (buffer < bend) {
1903 skip = UTF8SKIP(buffer);
1906 if (buffer - charskip + skip > bend) {
1907 /* partial character - try for rest of it */
1908 length = skip - (bend-buffer);
1909 offset = bend - SvPVX_const(bufsv);
1921 /* If we have not 'got' the number of _characters_ we 'wanted' get some more
1922 provided amount read (count) was what was requested (length)
1924 if (got < wanted && count == length) {
1925 length = wanted - got;
1926 offset = bend - SvPVX_const(bufsv);
1929 /* return value is character count */
1933 else if (buffer_utf8) {
1934 /* Let svcatsv upgrade the bytes we read in to utf8.
1935 The buffer is a mortal so will be freed soon. */
1936 sv_catsv_nomg(bufsv, read_target);
1939 /* This should not be marked tainted if the fp is marked clean */
1940 if (!(IoFLAGS(io) & IOf_UNTAINT))
1941 SvTAINTED_on(bufsv);
1952 /* also used for: pp_send() where defined */
1956 dSP; dMARK; dORIGMARK; dTARGET;
1961 const int op_type = PL_op->op_type;
1964 GV *const gv = MUTABLE_GV(*++MARK);
1965 IO *const io = GvIO(gv);
1968 if (op_type == OP_SYSWRITE && io) {
1969 const MAGIC * const mg = SvTIED_mg((const SV *)io, PERL_MAGIC_tiedscalar);
1971 if (MARK == SP - 1) {
1973 mXPUSHi(sv_len(sv));
1977 return Perl_tied_method(aTHX_ SV_CONST(WRITE), mark - 1, MUTABLE_SV(io), mg,
1978 G_SCALAR | TIED_METHOD_ARGUMENTS_ON_STACK,
1988 if (!io || !IoIFP(io) || IoTYPE(io) == IoTYPE_RDONLY) {
1990 if (io && IoIFP(io))
1991 report_wrongway_fh(gv, '<');
1994 SETERRNO(EBADF,RMS_IFI);
1997 fd = PerlIO_fileno(IoIFP(io));
1999 SETERRNO(EBADF,SS_IVCHAN);
2004 /* Do this first to trigger any overloading. */
2005 buffer = SvPV_const(bufsv, blen);
2006 doing_utf8 = DO_UTF8(bufsv);
2008 if (PerlIO_isutf8(IoIFP(io))) {
2010 "%s() isn't allowed on :utf8 handles",
2013 else if (doing_utf8) {
2014 STRLEN tmplen = blen;
2015 U8 * const result = bytes_from_utf8((const U8*) buffer, &tmplen, &doing_utf8);
2018 buffer = (char *) tmpbuf;
2022 assert((char *)result == buffer);
2023 Perl_croak(aTHX_ "Wide character in %s", OP_DESC(PL_op));
2028 if (op_type == OP_SEND) {
2029 const int flags = SvIVx(*++MARK);
2032 char * const sockbuf = SvPVx(*++MARK, mlen);
2033 retval = PerlSock_sendto(fd, buffer, blen,
2034 flags, (struct sockaddr *)sockbuf, mlen);
2037 retval = PerlSock_send(fd, buffer, blen, flags);
2043 Size_t length = 0; /* This length is in characters. */
2049 #if Size_t_size > IVSIZE
2050 length = (Size_t)SvNVx(*++MARK);
2052 length = (Size_t)SvIVx(*++MARK);
2054 if ((SSize_t)length < 0) {
2056 DIE(aTHX_ "Negative length");
2061 offset = SvIVx(*++MARK);
2063 if (-offset > (IV)blen) {
2065 DIE(aTHX_ "Offset outside string");
2068 } else if (offset > (IV)blen) {
2070 DIE(aTHX_ "Offset outside string");
2074 if (length > blen - offset)
2075 length = blen - offset;
2076 buffer = buffer+offset;
2078 #ifdef PERL_SOCK_SYSWRITE_IS_SEND
2079 if (IoTYPE(io) == IoTYPE_SOCKET) {
2080 retval = PerlSock_send(fd, buffer, length, 0);
2085 /* See the note at doio.c:do_print about filesize limits. --jhi */
2086 retval = PerlLIO_write(fd, buffer, length);
2095 #if Size_t_size > IVSIZE
2115 * in Perl 5.12 and later, the additional parameter is a bitmask:
2118 * 2 = eof() <- ARGV magic
2120 * I'll rely on the compiler's trace flow analysis to decide whether to
2121 * actually assign this out here, or punt it into the only block where it is
2122 * used. Doing it out here is DRY on the condition logic.
2127 gv = PL_last_in_gv = MUTABLE_GV(POPs); /* eof(FH) */
2133 if (PL_op->op_flags & OPf_SPECIAL) {
2134 gv = PL_last_in_gv = GvEGVx(PL_argvgv); /* eof() - ARGV magic */
2138 gv = PL_last_in_gv; /* eof */
2146 if ((io = GvIO(gv)) && (mg = SvTIED_mg((const SV *)io, PERL_MAGIC_tiedscalar))) {
2147 return tied_method1(SV_CONST(EOF), SP, MUTABLE_SV(io), mg, newSVuv(which));
2150 if (!MAXARG && (PL_op->op_flags & OPf_SPECIAL)) { /* eof() */
2151 if (io && !IoIFP(io)) {
2152 if ((IoFLAGS(io) & IOf_START) && av_count(GvAVn(gv)) == 0) {
2155 IoFLAGS(io) &= ~IOf_START;
2156 do_open6(gv, "-", 1, NULL, NULL, 0);
2164 *svp = newSVpvs("-");
2166 else if (!nextargv(gv, FALSE))
2171 PUSHs(boolSV(do_eof(gv)));
2181 if (MAXARG != 0 && (TOPs || POPs))
2182 PL_last_in_gv = MUTABLE_GV(POPs);
2189 const MAGIC * const mg = SvTIED_mg((const SV *)io, PERL_MAGIC_tiedscalar);
2191 return tied_method0(SV_CONST(TELL), SP, MUTABLE_SV(io), mg);
2196 SETERRNO(EBADF,RMS_IFI);
2201 #if LSEEKSIZE > IVSIZE
2202 PUSHn( (NV)do_tell(gv) );
2204 PUSHi( (IV)do_tell(gv) );
2210 /* also used for: pp_seek() */
2215 const int whence = POPi;
2216 #if LSEEKSIZE > IVSIZE
2217 const Off_t offset = (Off_t)SvNVx(POPs);
2219 const Off_t offset = (Off_t)SvIVx(POPs);
2222 GV * const gv = PL_last_in_gv = MUTABLE_GV(POPs);
2223 IO *const io = GvIO(gv);
2226 const MAGIC * const mg = SvTIED_mg((const SV *)io, PERL_MAGIC_tiedscalar);
2228 #if LSEEKSIZE > IVSIZE
2229 SV *const offset_sv = newSVnv((NV) offset);
2231 SV *const offset_sv = newSViv(offset);
2234 return tied_method2(SV_CONST(SEEK), SP, MUTABLE_SV(io), mg, offset_sv,
2239 if (PL_op->op_type == OP_SEEK)
2240 PUSHs(boolSV(do_seek(gv, offset, whence)));
2242 const Off_t sought = do_sysseek(gv, offset, whence);
2244 PUSHs(&PL_sv_undef);
2246 SV* const sv = sought ?
2247 #if LSEEKSIZE > IVSIZE
2252 : newSVpvn(zero_but_true, ZBTLEN);
2262 /* There seems to be no consensus on the length type of truncate()
2263 * and ftruncate(), both off_t and size_t have supporters. In
2264 * general one would think that when using large files, off_t is
2265 * at least as wide as size_t, so using an off_t should be okay. */
2266 /* XXX Configure probe for the length type of *truncate() needed XXX */
2269 #if Off_t_size > IVSIZE
2274 /* Checking for length < 0 is problematic as the type might or
2275 * might not be signed: if it is not, clever compilers will moan. */
2276 /* XXX Configure probe for the signedness of the length type of *truncate() needed? XXX */
2279 SV * const sv = POPs;
2284 if (PL_op->op_flags & OPf_SPECIAL
2285 ? (tmpgv = gv_fetchsv(sv, 0, SVt_PVIO), 1)
2286 : cBOOL(tmpgv = MAYBE_DEREF_GV(sv)) )
2294 TAINT_PROPER("truncate");
2295 if (!(fp = IoIFP(io))) {
2299 int fd = PerlIO_fileno(fp);
2301 SETERRNO(EBADF,RMS_IFI);
2305 SETERRNO(EINVAL, LIB_INVARG);
2310 if (ftruncate(fd, len) < 0)
2312 if (my_chsize(fd, len) < 0)
2320 else if (SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVIO) {
2321 io = MUTABLE_IO(SvRV(sv)); /* *main::FRED{IO} for example */
2322 goto do_ftruncate_io;
2325 const char * const name = SvPV_nomg_const_nolen(sv);
2326 TAINT_PROPER("truncate");
2328 if (truncate(name, len) < 0)
2335 #if defined(USE_64_BIT_RAWIO) && defined(O_LARGEFILE)
2336 mode |= O_LARGEFILE; /* Transparently largefiley. */
2339 /* On open(), the Win32 CRT tries to seek around text
2340 * files using 32-bit offsets, which causes the open()
2341 * to fail on large files, so open in binary mode.
2345 tmpfd = PerlLIO_open_cloexec(name, mode);
2350 if (my_chsize(tmpfd, len) < 0)
2352 PerlLIO_close(tmpfd);
2361 SETERRNO(EBADF,RMS_IFI);
2367 /* also used for: pp_fcntl() */
2372 SV * const argsv = POPs;
2373 const unsigned int func = POPu;
2375 GV * const gv = MUTABLE_GV(POPs);
2376 IO * const io = GvIOn(gv);
2382 SETERRNO(EBADF,RMS_IFI); /* well, sort of... */
2386 if (SvPOK(argsv) || !SvNIOK(argsv)) {
2389 s = SvPV_force(argsv, len);
2390 need = IOCPARM_LEN(func);
2392 s = Sv_Grow(argsv, need + 1);
2393 SvCUR_set(argsv, need);
2396 s[SvCUR(argsv)] = 17; /* a little sanity check here */
2399 retval = SvIV(argsv);
2400 s = INT2PTR(char*,retval); /* ouch */
2403 optype = PL_op->op_type;
2404 TAINT_PROPER(PL_op_desc[optype]);
2406 if (optype == OP_IOCTL)
2408 retval = PerlLIO_ioctl(PerlIO_fileno(IoIFP(io)), func, s);
2410 DIE(aTHX_ "ioctl is not implemented");
2414 DIE(aTHX_ "fcntl is not implemented");
2415 #elif defined(OS2) && defined(__EMX__)
2416 retval = fcntl(PerlIO_fileno(IoIFP(io)), func, (int)s);
2418 retval = fcntl(PerlIO_fileno(IoIFP(io)), func, s);
2421 #if defined(HAS_IOCTL) || defined(HAS_FCNTL)
2423 if (s[SvCUR(argsv)] != 17)
2424 DIE(aTHX_ "Possible memory corruption: %s overflowed 3rd argument",
2426 s[SvCUR(argsv)] = 0; /* put our null back */
2427 SvSETMAGIC(argsv); /* Assume it has changed */
2436 PUSHp(zero_but_true, ZBTLEN);
2447 const int argtype = POPi;
2448 GV * const gv = MUTABLE_GV(POPs);
2449 IO *const io = GvIO(gv);
2450 PerlIO *const fp = io ? IoIFP(io) : NULL;
2452 /* XXX Looks to me like io is always NULL at this point */
2454 (void)PerlIO_flush(fp);
2455 value = (I32)(PerlLIO_flock(PerlIO_fileno(fp), argtype) >= 0);
2460 SETERRNO(EBADF,RMS_IFI);
2465 DIE(aTHX_ PL_no_func, "flock");
2476 const int protocol = POPi;
2477 const int type = POPi;
2478 const int domain = POPi;
2479 GV * const gv = MUTABLE_GV(POPs);
2480 IO * const io = GvIOn(gv);
2484 do_close(gv, FALSE);
2486 TAINT_PROPER("socket");
2487 fd = PerlSock_socket_cloexec(domain, type, protocol);
2491 IoIFP(io) = PerlIO_fdopen(fd, "r" SOCKET_OPEN_MODE); /* stdio gets confused about sockets */
2492 IoOFP(io) = PerlIO_fdopen(fd, "w" SOCKET_OPEN_MODE);
2493 IoTYPE(io) = IoTYPE_SOCKET;
2494 if (!IoIFP(io) || !IoOFP(io)) {
2495 if (IoIFP(io)) PerlIO_close(IoIFP(io));
2496 if (IoOFP(io)) PerlIO_close(IoOFP(io));
2497 if (!IoIFP(io) && !IoOFP(io)) PerlLIO_close(fd);
2507 #if defined (HAS_SOCKETPAIR) || (defined (HAS_SOCKET) && defined(SOCK_DGRAM) && defined(AF_INET) && defined(PF_INET))
2510 const int protocol = POPi;
2511 const int type = POPi;
2512 const int domain = POPi;
2514 GV * const gv2 = MUTABLE_GV(POPs);
2515 IO * const io2 = GvIOn(gv2);
2516 GV * const gv1 = MUTABLE_GV(POPs);
2517 IO * const io1 = GvIOn(gv1);
2520 do_close(gv1, FALSE);
2522 do_close(gv2, FALSE);
2524 TAINT_PROPER("socketpair");
2525 if (PerlSock_socketpair_cloexec(domain, type, protocol, fd) < 0)
2527 IoIFP(io1) = PerlIO_fdopen(fd[0], "r" SOCKET_OPEN_MODE);
2528 IoOFP(io1) = PerlIO_fdopen(fd[0], "w" SOCKET_OPEN_MODE);
2529 IoTYPE(io1) = IoTYPE_SOCKET;
2530 IoIFP(io2) = PerlIO_fdopen(fd[1], "r" SOCKET_OPEN_MODE);
2531 IoOFP(io2) = PerlIO_fdopen(fd[1], "w" SOCKET_OPEN_MODE);
2532 IoTYPE(io2) = IoTYPE_SOCKET;
2533 if (!IoIFP(io1) || !IoOFP(io1) || !IoIFP(io2) || !IoOFP(io2)) {
2534 if (IoIFP(io1)) PerlIO_close(IoIFP(io1));
2535 if (IoOFP(io1)) PerlIO_close(IoOFP(io1));
2536 if (!IoIFP(io1) && !IoOFP(io1)) PerlLIO_close(fd[0]);
2537 if (IoIFP(io2)) PerlIO_close(IoIFP(io2));
2538 if (IoOFP(io2)) PerlIO_close(IoOFP(io2));
2539 if (!IoIFP(io2) && !IoOFP(io2)) PerlLIO_close(fd[1]);
2545 DIE(aTHX_ PL_no_sock_func, "socketpair");
2551 /* also used for: pp_connect() */
2556 SV * const addrsv = POPs;
2557 /* OK, so on what platform does bind modify addr? */
2559 GV * const gv = MUTABLE_GV(POPs);
2560 IO * const io = GvIOn(gv);
2567 fd = PerlIO_fileno(IoIFP(io));
2571 addr = SvPV_const(addrsv, len);
2572 op_type = PL_op->op_type;
2573 TAINT_PROPER(PL_op_desc[op_type]);
2574 if ((op_type == OP_BIND
2575 ? PerlSock_bind(fd, (struct sockaddr *)addr, len)
2576 : PerlSock_connect(fd, (struct sockaddr *)addr, len))
2584 SETERRNO(EBADF,SS_IVCHAN);
2591 const int backlog = POPi;
2592 GV * const gv = MUTABLE_GV(POPs);
2593 IO * const io = GvIOn(gv);
2598 if (PerlSock_listen(PerlIO_fileno(IoIFP(io)), backlog) >= 0)
2605 SETERRNO(EBADF,SS_IVCHAN);
2613 char namebuf[MAXPATHLEN];
2614 #if (defined(VMS_DO_SOCKETS) && defined(DECCRTL_SOCKETS)) || defined(__QNXNTO__)
2615 Sock_size_t len = sizeof (struct sockaddr_in);
2617 Sock_size_t len = sizeof namebuf;
2619 GV * const ggv = MUTABLE_GV(POPs);
2620 GV * const ngv = MUTABLE_GV(POPs);
2623 IO * const gstio = GvIO(ggv);
2624 if (!gstio || !IoIFP(gstio))
2628 fd = PerlSock_accept_cloexec(PerlIO_fileno(IoIFP(gstio)), (struct sockaddr *) namebuf, &len);
2631 /* Some platforms indicate zero length when an AF_UNIX client is
2632 * not bound. Simulate a non-zero-length sockaddr structure in
2634 namebuf[0] = 0; /* sun_len */
2635 namebuf[1] = AF_UNIX; /* sun_family */
2643 do_close(ngv, FALSE);
2644 IoIFP(nstio) = PerlIO_fdopen(fd, "r" SOCKET_OPEN_MODE);
2645 IoOFP(nstio) = PerlIO_fdopen(fd, "w" SOCKET_OPEN_MODE);
2646 IoTYPE(nstio) = IoTYPE_SOCKET;
2647 if (!IoIFP(nstio) || !IoOFP(nstio)) {
2648 if (IoIFP(nstio)) PerlIO_close(IoIFP(nstio));
2649 if (IoOFP(nstio)) PerlIO_close(IoOFP(nstio));
2650 if (!IoIFP(nstio) && !IoOFP(nstio)) PerlLIO_close(fd);
2654 #ifdef __SCO_VERSION__
2655 len = sizeof (struct sockaddr_in); /* OpenUNIX 8 somehow truncates info */
2658 PUSHp(namebuf, len);
2662 report_evil_fh(ggv);
2663 SETERRNO(EBADF,SS_IVCHAN);
2673 const int how = POPi;
2674 GV * const gv = MUTABLE_GV(POPs);
2675 IO * const io = GvIOn(gv);
2680 PUSHi( PerlSock_shutdown(PerlIO_fileno(IoIFP(io)), how) >= 0 );
2685 SETERRNO(EBADF,SS_IVCHAN);
2690 /* also used for: pp_gsockopt() */
2695 const int optype = PL_op->op_type;
2696 SV * const sv = (optype == OP_GSOCKOPT) ? sv_2mortal(newSV(257)) : POPs;
2697 const unsigned int optname = (unsigned int) POPi;
2698 const unsigned int lvl = (unsigned int) POPi;
2699 GV * const gv = MUTABLE_GV(POPs);
2700 IO * const io = GvIOn(gv);
2707 fd = PerlIO_fileno(IoIFP(io));
2712 /* Note: there used to be an explicit SvGROW(sv,257) here, but
2713 * this is redundant given the sv initialization ternary above */
2714 (void)SvPOK_only(sv);
2718 if (PerlSock_getsockopt(fd, lvl, optname, SvPVX(sv), &len) < 0)
2721 /* XXX Configure test: does getsockopt set the length properly? */
2733 if (SvPOK(sv) && !SvIsBOOL(sv)) { /* sv is originally a string */
2735 buf = SvPVbyte_nomg(sv, l);
2739 aint = (int)SvIV_nomg(sv);
2740 buf = (const char *) &aint;
2743 if (PerlSock_setsockopt(fd, lvl, optname, buf, len) < 0)
2753 SETERRNO(EBADF,SS_IVCHAN);
2760 /* also used for: pp_getsockname() */
2765 const int optype = PL_op->op_type;
2766 GV * const gv = MUTABLE_GV(POPs);
2767 IO * const io = GvIOn(gv);
2775 #ifdef HAS_SOCKADDR_STORAGE
2776 len = sizeof(struct sockaddr_storage);
2780 sv = sv_2mortal(newSV(len+1));
2781 (void)SvPOK_only(sv);
2784 fd = PerlIO_fileno(IoIFP(io));
2788 case OP_GETSOCKNAME:
2789 if (PerlSock_getsockname(fd, (struct sockaddr *)SvPVX(sv), &len) < 0)
2792 case OP_GETPEERNAME:
2793 if (PerlSock_getpeername(fd, (struct sockaddr *)SvPVX(sv), &len) < 0)
2795 #if defined(VMS_DO_SOCKETS) && defined (DECCRTL_SOCKETS)
2797 static const char nowhere[] = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
2798 /* If the call succeeded, make sure we don't have a zeroed port/addr */
2799 if (((struct sockaddr *)SvPVX_const(sv))->sa_family == AF_INET &&
2800 !memcmp(SvPVX_const(sv) + sizeof(u_short), nowhere,
2801 sizeof(u_short) + sizeof(struct in_addr))) {
2808 #ifdef BOGUS_GETNAME_RETURN
2809 /* Interactive Unix, getpeername() and getsockname()
2810 does not return valid namelen */
2811 if (len == BOGUS_GETNAME_RETURN)
2812 len = sizeof(struct sockaddr);
2821 SETERRNO(EBADF,SS_IVCHAN);
2830 /* also used for: pp_lstat() */
2841 if (PL_op->op_flags & OPf_REF ? (gv = cGVOP_gv, 1)
2842 : cBOOL((sv=POPs, gv = MAYBE_DEREF_GV(sv))))
2844 if (PL_op->op_type == OP_LSTAT) {
2845 if (gv != PL_defgv) {
2846 do_fstat_warning_check:
2847 Perl_ck_warner(aTHX_ packWARN(WARN_IO),
2848 "lstat() on filehandle%s%" SVf,
2851 ? newSVhek_mortal(GvENAME_HEK(gv))
2853 } else if (PL_laststype != OP_LSTAT)
2854 /* diag_listed_as: The stat preceding %s wasn't an lstat */
2855 Perl_croak(aTHX_ "The stat preceding lstat() wasn't an lstat");
2858 if (gv == PL_defgv) {
2859 if (PL_laststatval < 0)
2860 SETERRNO(EBADF,RMS_IFI);
2863 PL_laststype = OP_STAT;
2864 PL_statgv = gv ? gv : (GV *)io;
2865 SvPVCLEAR(PL_statname);
2871 int fd = PerlIO_fileno(IoIFP(io));
2874 PL_laststatval = -1;
2875 SETERRNO(EBADF,RMS_IFI);
2877 PL_laststatval = PerlLIO_fstat(fd, &PL_statcache);
2879 } else if (IoDIRP(io)) {
2881 PerlLIO_fstat(my_dirfd(IoDIRP(io)), &PL_statcache);
2884 PL_laststatval = -1;
2885 SETERRNO(EBADF,RMS_IFI);
2889 PL_laststatval = -1;
2890 SETERRNO(EBADF,RMS_IFI);
2894 if (PL_laststatval < 0) {
2902 if (SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVIO) {
2903 io = MUTABLE_IO(SvRV(sv));
2904 if (PL_op->op_type == OP_LSTAT)
2905 goto do_fstat_warning_check;
2906 goto do_fstat_have_io;
2908 SvTAINTED_off(PL_statname); /* previous tainting irrelevant */
2909 temp = SvPV_nomg_const(sv, len);
2910 sv_setpv(PL_statname, temp);
2912 PL_laststype = PL_op->op_type;
2913 file = SvPV_nolen_const(PL_statname);
2914 if (!IS_SAFE_PATHNAME(temp, len, OP_NAME(PL_op))) {
2915 PL_laststatval = -1;
2917 else if (PL_op->op_type == OP_LSTAT)
2918 PL_laststatval = PerlLIO_lstat(file, &PL_statcache);
2920 PL_laststatval = PerlLIO_stat(file, &PL_statcache);
2921 if (PL_laststatval < 0) {
2922 if (ckWARN(WARN_NEWLINE) && should_warn_nl(file)) {
2923 /* PL_warn_nl is constant */
2924 GCC_DIAG_IGNORE_STMT(-Wformat-nonliteral);
2925 Perl_warner(aTHX_ packWARN(WARN_NEWLINE), PL_warn_nl, "stat");
2926 GCC_DIAG_RESTORE_STMT;
2933 if (gimme != G_LIST) {
2934 if (gimme != G_VOID)
2935 XPUSHs(boolSV(max));
2941 #if ST_DEV_SIZE < IVSIZE || (ST_DEV_SIZE == IVSIZE && ST_DEV_SIGN < 0)
2942 mPUSHi(PL_statcache.st_dev);
2943 #elif ST_DEV_SIZE == IVSIZE
2944 mPUSHu(PL_statcache.st_dev);
2946 # if ST_DEV_SIGN < 0
2947 if (LIKELY((IV)PL_statcache.st_dev == PL_statcache.st_dev)) {
2948 mPUSHi((IV)PL_statcache.st_dev);
2951 if (LIKELY((UV)PL_statcache.st_dev == PL_statcache.st_dev)) {
2952 mPUSHu((UV)PL_statcache.st_dev);
2956 char buf[sizeof(PL_statcache.st_dev)*3+1];
2957 /* sv_catpvf() casts 'j' size values down to IV, so it
2958 isn't suitable for use here.
2960 # if defined(I_INTTYPES) && defined(HAS_SNPRINTF)
2961 # if ST_DEV_SIGN < 0
2962 int size = snprintf(buf, sizeof(buf), "%" PRIdMAX, (intmax_t)PL_statcache.st_dev);
2964 int size = snprintf(buf, sizeof(buf), "%" PRIuMAX, (uintmax_t)PL_statcache.st_dev);
2966 STATIC_ASSERT_STMT(sizeof(intmax_t) >= sizeof(PL_statcache.st_dev));
2969 # error extraordinarily large st_dev but no inttypes.h or no snprintf
2975 * We try to represent st_ino as a native IV or UV where
2976 * possible, but fall back to a decimal string where
2977 * necessary. The code to generate these decimal strings
2978 * is quite obtuse, because (a) we're portable to non-POSIX
2979 * platforms where st_ino might be signed; (b) we didn't
2980 * necessarily detect at Configure time whether st_ino is
2981 * signed; (c) we're portable to non-POSIX platforms where
2982 * ino_t isn't defined, so have no name for the type of
2983 * st_ino; and (d) sprintf() doesn't necessarily support
2984 * integers as large as st_ino.
2988 CLANG_DIAG_IGNORE_STMT(-Wtautological-compare);
2989 GCC_DIAG_IGNORE_STMT(-Wtype-limits);
2990 neg = PL_statcache.st_ino < 0;
2991 GCC_DIAG_RESTORE_STMT;
2992 CLANG_DIAG_RESTORE_STMT;
2994 s.st_ino = (IV)PL_statcache.st_ino;
2995 if (LIKELY(s.st_ino == PL_statcache.st_ino)) {
2998 char buf[sizeof(s.st_ino)*3+1], *p;
2999 s.st_ino = PL_statcache.st_ino;
3000 for (p = buf + sizeof(buf); p != buf+1; ) {
3002 t.st_ino = s.st_ino / 10;
3003 *--p = '0' + (int)(t.st_ino*10 - s.st_ino);
3004 s.st_ino = t.st_ino;
3009 mPUSHp(p, buf+sizeof(buf) - p);
3012 s.st_ino = (UV)PL_statcache.st_ino;
3013 if (LIKELY(s.st_ino == PL_statcache.st_ino)) {
3016 char buf[sizeof(s.st_ino)*3], *p;
3017 s.st_ino = PL_statcache.st_ino;
3018 for (p = buf + sizeof(buf); p != buf; ) {
3020 t.st_ino = s.st_ino / 10;
3021 *--p = '0' + (int)(s.st_ino - t.st_ino*10);
3022 s.st_ino = t.st_ino;
3026 mPUSHp(p, buf+sizeof(buf) - p);
3030 mPUSHu(PL_statcache.st_mode);
3031 mPUSHu(PL_statcache.st_nlink);
3033 sv_setuid(PUSHmortal, PL_statcache.st_uid);
3034 sv_setgid(PUSHmortal, PL_statcache.st_gid);
3036 #ifdef USE_STAT_RDEV
3037 mPUSHi(PL_statcache.st_rdev);
3039 PUSHs(newSVpvs_flags("", SVs_TEMP));
3041 #if Off_t_size > IVSIZE
3042 mPUSHn(PL_statcache.st_size);
3044 mPUSHi(PL_statcache.st_size);
3047 mPUSHn(PL_statcache.st_atime);
3048 mPUSHn(PL_statcache.st_mtime);
3049 mPUSHn(PL_statcache.st_ctime);
3051 mPUSHi(PL_statcache.st_atime);
3052 mPUSHi(PL_statcache.st_mtime);
3053 mPUSHi(PL_statcache.st_ctime);
3055 #ifdef USE_STAT_BLOCKS
3056 mPUSHu(PL_statcache.st_blksize);
3057 mPUSHu(PL_statcache.st_blocks);
3059 PUSHs(newSVpvs_flags("", SVs_TEMP));
3060 PUSHs(newSVpvs_flags("", SVs_TEMP));
3066 /* All filetest ops avoid manipulating the perl stack pointer in their main
3067 bodies (since commit d2c4d2d1e22d3125), and return using either
3068 S_ft_return_false() or S_ft_return_true(). These two helper functions are
3069 the only two which manipulate the perl stack. To ensure that no stack
3070 manipulation macros are used, the filetest ops avoid defining a local copy
3071 of the stack pointer with dSP. */
3073 /* If the next filetest is stacked up with this one
3074 (PL_op->op_private & OPpFT_STACKING), we leave
3075 the original argument on the stack for success,
3076 and skip the stacked operators on failure.
3077 The next few macros/functions take care of this.
3081 S_ft_return_false(pTHX_ SV *ret) {
3085 if (PL_op->op_flags & OPf_REF) XPUSHs(ret);
3089 if (PL_op->op_private & OPpFT_STACKING) {
3090 while (next && OP_IS_FILETEST(next->op_type)
3091 && next->op_private & OPpFT_STACKED)
3092 next = next->op_next;
3097 PERL_STATIC_INLINE OP *
3098 S_ft_return_true(pTHX_ SV *ret) {
3100 if (PL_op->op_flags & OPf_REF)
3101 XPUSHs(PL_op->op_private & OPpFT_STACKING ? (SV *)cGVOP_gv : (ret));
3102 else if (!(PL_op->op_private & OPpFT_STACKING))
3108 #define FT_RETURNNO return S_ft_return_false(aTHX_ &PL_sv_no)
3109 #define FT_RETURNUNDEF return S_ft_return_false(aTHX_ &PL_sv_undef)
3110 #define FT_RETURNYES return S_ft_return_true(aTHX_ &PL_sv_yes)
3112 #define tryAMAGICftest_MG(chr) STMT_START { \
3113 if ( (SvFLAGS(*PL_stack_sp) & (SVf_ROK|SVs_GMG)) \
3114 && PL_op->op_flags & OPf_KIDS) { \
3115 OP *next = S_try_amagic_ftest(aTHX_ chr); \
3116 if (next) return next; \
3121 S_try_amagic_ftest(pTHX_ char chr) {
3122 SV *const arg = *PL_stack_sp;
3125 if (!(PL_op->op_private & OPpFT_STACKED)) SvGETMAGIC(arg);
3129 const char tmpchr = chr;
3130 SV * const tmpsv = amagic_call(arg,
3131 newSVpvn_flags(&tmpchr, 1, SVs_TEMP),
3132 ftest_amg, AMGf_unary);
3137 return SvTRUE(tmpsv)
3138 ? S_ft_return_true(aTHX_ tmpsv) : S_ft_return_false(aTHX_ tmpsv);
3144 /* also used for: pp_fteexec() pp_fteread() pp_ftewrite() pp_ftrexec()
3150 /* Not const, because things tweak this below. Not bool, because there's
3151 no guarantee that OPpFT_ACCESS is <= CHAR_MAX */
3152 #if defined(HAS_ACCESS) || defined (PERL_EFF_ACCESS)
3153 I32 use_access = PL_op->op_private & OPpFT_ACCESS;
3154 /* Giving some sort of initial value silences compilers. */
3156 int access_mode = R_OK;
3158 int access_mode = 0;
3161 /* access_mode is never used, but leaving use_access in makes the
3162 conditional compiling below much clearer. */
3165 Mode_t stat_mode = S_IRUSR;
3167 bool effective = FALSE;
3170 switch (PL_op->op_type) {
3171 case OP_FTRREAD: opchar = 'R'; break;
3172 case OP_FTRWRITE: opchar = 'W'; break;
3173 case OP_FTREXEC: opchar = 'X'; break;
3174 case OP_FTEREAD: opchar = 'r'; break;
3175 case OP_FTEWRITE: opchar = 'w'; break;
3176 case OP_FTEEXEC: opchar = 'x'; break;
3178 tryAMAGICftest_MG(opchar);
3180 switch (PL_op->op_type) {
3182 #if !(defined(HAS_ACCESS) && defined(R_OK))
3188 #if defined(HAS_ACCESS) && defined(W_OK)
3193 stat_mode = S_IWUSR;
3197 #if defined(HAS_ACCESS) && defined(X_OK)
3202 stat_mode = S_IXUSR;
3206 #ifdef PERL_EFF_ACCESS
3209 stat_mode = S_IWUSR;
3213 #ifndef PERL_EFF_ACCESS
3220 #ifdef PERL_EFF_ACCESS
3225 stat_mode = S_IXUSR;
3231 #if defined(HAS_ACCESS) || defined (PERL_EFF_ACCESS)
3233 const char *name = SvPV(*PL_stack_sp, len);
3234 if (!IS_SAFE_PATHNAME(name, len, OP_NAME(PL_op))) {
3237 else if (effective) {
3238 # ifdef PERL_EFF_ACCESS
3239 result = PERL_EFF_ACCESS(name, access_mode);
3241 DIE(aTHX_ "panic: attempt to call PERL_EFF_ACCESS in %s",
3247 result = access(name, access_mode);
3249 DIE(aTHX_ "panic: attempt to call access() in %s", OP_NAME(PL_op));
3260 result = my_stat_flags(0);
3263 if (cando(stat_mode, effective, &PL_statcache))
3269 /* also used for: pp_ftatime() pp_ftctime() pp_ftmtime() pp_ftsize() */
3274 const int op_type = PL_op->op_type;
3278 case OP_FTIS: opchar = 'e'; break;
3279 case OP_FTSIZE: opchar = 's'; break;
3280 case OP_FTMTIME: opchar = 'M'; break;
3281 case OP_FTCTIME: opchar = 'C'; break;
3282 case OP_FTATIME: opchar = 'A'; break;
3284 tryAMAGICftest_MG(opchar);
3286 result = my_stat_flags(0);
3289 if (op_type == OP_FTIS)
3292 /* You can't dTARGET inside OP_FTIS, because you'll get
3293 "panic: pad_sv po" - the op is not flagged to have a target. */
3297 #if Off_t_size > IVSIZE
3298 sv_setnv(TARG, (NV)PL_statcache.st_size);
3300 sv_setiv(TARG, (IV)PL_statcache.st_size);
3305 ((NV)PL_basetime - PL_statcache.st_mtime) / 86400.0 );
3309 ((NV)PL_basetime - PL_statcache.st_atime) / 86400.0 );
3313 ((NV)PL_basetime - PL_statcache.st_ctime) / 86400.0 );
3317 return SvTRUE_nomg_NN(TARG)
3318 ? S_ft_return_true(aTHX_ TARG) : S_ft_return_false(aTHX_ TARG);
3323 /* also used for: pp_ftblk() pp_ftchr() pp_ftdir() pp_fteowned()
3324 * pp_ftfile() pp_ftpipe() pp_ftsgid() pp_ftsock()
3325 * pp_ftsuid() pp_ftsvtx() pp_ftzero() */
3332 switch (PL_op->op_type) {
3333 case OP_FTROWNED: opchar = 'O'; break;
3334 case OP_FTEOWNED: opchar = 'o'; break;
3335 case OP_FTZERO: opchar = 'z'; break;
3336 case OP_FTSOCK: opchar = 'S'; break;
3337 case OP_FTCHR: opchar = 'c'; break;
3338 case OP_FTBLK: opchar = 'b'; break;
3339 case OP_FTFILE: opchar = 'f'; break;
3340 case OP_FTDIR: opchar = 'd'; break;
3341 case OP_FTPIPE: opchar = 'p'; break;
3342 case OP_FTSUID: opchar = 'u'; break;
3343 case OP_FTSGID: opchar = 'g'; break;
3344 case OP_FTSVTX: opchar = 'k'; break;
3346 tryAMAGICftest_MG(opchar);
3348 result = my_stat_flags(0);
3351 switch (PL_op->op_type) {
3353 if (PL_statcache.st_uid == PerlProc_getuid())
3357 if (PL_statcache.st_uid == PerlProc_geteuid())
3361 if (PL_statcache.st_size == 0)
3365 if (S_ISSOCK(PL_statcache.st_mode))
3369 if (S_ISCHR(PL_statcache.st_mode))
3373 if (S_ISBLK(PL_statcache.st_mode))
3377 if (S_ISREG(PL_statcache.st_mode))
3381 if (S_ISDIR(PL_statcache.st_mode))
3385 if (S_ISFIFO(PL_statcache.st_mode))
3390 if (PL_statcache.st_mode & S_ISUID)
3396 if (PL_statcache.st_mode & S_ISGID)
3402 if (PL_statcache.st_mode & S_ISVTX)
3414 tryAMAGICftest_MG('l');
3415 result = my_lstat_flags(0);
3419 if (S_ISLNK(PL_statcache.st_mode))
3432 tryAMAGICftest_MG('t');
3434 if (PL_op->op_flags & OPf_REF)
3437 SV *tmpsv = *PL_stack_sp;
3438 if (!(gv = MAYBE_DEREF_GV_nomg(tmpsv))) {
3439 name = SvPV_nomg(tmpsv, namelen);
3440 gv = gv_fetchpvn_flags(name, namelen, SvUTF8(tmpsv), SVt_PVIO);
3444 if (GvIO(gv) && IoIFP(GvIOp(gv)))
3445 fd = PerlIO_fileno(IoIFP(GvIOp(gv)));
3446 else if (name && isDIGIT(*name) && grok_atoUV(name, &uv, NULL) && uv <= PERL_INT_MAX)
3451 SETERRNO(EBADF,RMS_IFI);
3454 if (PerlLIO_isatty(fd))
3460 /* also used for: pp_ftbinary() */
3473 const U8 * first_variant;
3475 tryAMAGICftest_MG(PL_op->op_type == OP_FTTEXT ? 'T' : 'B');
3477 if (PL_op->op_flags & OPf_REF)
3479 else if ((PL_op->op_private & (OPpFT_STACKED|OPpFT_AFTER_t))
3484 gv = MAYBE_DEREF_GV_nomg(sv);
3488 if (gv == PL_defgv) {
3490 io = SvTYPE(PL_statgv) == SVt_PVIO
3494 goto really_filename;
3499 SvPVCLEAR(PL_statname);
3500 io = GvIO(PL_statgv);
3502 PL_laststatval = -1;
3503 PL_laststype = OP_STAT;
3504 if (io && IoIFP(io)) {
3506 if (! PerlIO_has_base(IoIFP(io)))
3507 DIE(aTHX_ "-T and -B not implemented on filehandles");
3508 fd = PerlIO_fileno(IoIFP(io));
3510 SETERRNO(EBADF,RMS_IFI);
3513 PL_laststatval = PerlLIO_fstat(fd, &PL_statcache);
3514 if (PL_laststatval < 0)
3516 if (S_ISDIR(PL_statcache.st_mode)) { /* handle NFS glitch */
3517 if (PL_op->op_type == OP_FTTEXT)
3522 if (PerlIO_get_cnt(IoIFP(io)) <= 0) {
3523 i = PerlIO_getc(IoIFP(io));
3525 (void)PerlIO_ungetc(IoIFP(io),i);
3527 /* null file is anything */
3530 len = PerlIO_get_bufsiz(IoIFP(io));
3531 s = (STDCHAR *) PerlIO_get_base(IoIFP(io));
3532 /* sfio can have large buffers - limit to 512 */
3537 SETERRNO(EBADF,RMS_IFI);
3539 SETERRNO(EBADF,RMS_IFI);
3550 temp = SvPV_nomg_const(sv, temp_len);
3551 sv_setpv(PL_statname, temp);
3552 if (!IS_SAFE_PATHNAME(temp, temp_len, OP_NAME(PL_op))) {
3553 PL_laststatval = -1;
3554 PL_laststype = OP_STAT;
3558 file = SvPVX_const(PL_statname);
3560 if (!(fp = PerlIO_open(file, "r"))) {
3562 PL_laststatval = -1;
3563 PL_laststype = OP_STAT;
3565 if (ckWARN(WARN_NEWLINE) && should_warn_nl(file)) {
3566 /* PL_warn_nl is constant */
3567 GCC_DIAG_IGNORE_STMT(-Wformat-nonliteral);
3568 Perl_warner(aTHX_ packWARN(WARN_NEWLINE), PL_warn_nl, "open");
3569 GCC_DIAG_RESTORE_STMT;
3573 PL_laststype = OP_STAT;
3574 fd = PerlIO_fileno(fp);
3576 (void)PerlIO_close(fp);
3577 SETERRNO(EBADF,RMS_IFI);
3580 PL_laststatval = PerlLIO_fstat(fd, &PL_statcache);
3581 if (PL_laststatval < 0) {
3583 (void)PerlIO_close(fp);
3587 PerlIO_binmode(aTHX_ fp, '<', O_BINARY, NULL);
3588 len = PerlIO_read(fp, tbuf, sizeof(tbuf));
3589 (void)PerlIO_close(fp);
3591 if (S_ISDIR(PL_statcache.st_mode) && PL_op->op_type == OP_FTTEXT)
3592 FT_RETURNNO; /* special case NFS directories */
3593 FT_RETURNYES; /* null file is anything */
3598 /* now scan s to look for textiness */
3600 #if defined(DOSISH) || defined(USEMYBINMODE)
3601 /* ignore trailing ^Z on short files */
3602 if (len && len < (I32)sizeof(tbuf) && tbuf[len-1] == 26)
3607 if (! is_utf8_invariant_string_loc((U8 *) s, len, &first_variant)) {
3609 /* Here contains a variant under UTF-8 . See if the entire string is
3611 if (is_utf8_fixed_width_buf_flags(first_variant,
3612 len - ((char *) first_variant - (char *) s),
3615 if (PL_op->op_type == OP_FTTEXT) {
3624 /* Here, is not UTF-8 or is entirely ASCII. Look through the buffer for
3625 * things that wouldn't be in ASCII text or rich ASCII text. Count these
3627 for (i = 0; i < len; i++, s++) {
3628 if (!*s) { /* null never allowed in text */
3632 #ifdef USE_LOCALE_CTYPE
3633 if (IN_LC_RUNTIME(LC_CTYPE)) {
3634 if ( isPRINT_LC(*s) || isSPACE_LC(*s)) {
3641 /* VT occurs so rarely in text, that we consider it odd */
3642 || (isSPACE_A(*s) && *s != VT_NATIVE)
3644 /* But there is a fair amount of backspaces and escapes in
3647 || *s == ESC_NATIVE)
3654 if ((odd * 3 > len) == (PL_op->op_type == OP_FTTEXT)) /* allow 1/3 odd */
3665 const char *tmps = NULL;
3669 SV * const sv = POPs;
3670 if (PL_op->op_flags & OPf_SPECIAL) {
3671 gv = gv_fetchsv(sv, 0, SVt_PVIO);
3673 if (ckWARN(WARN_UNOPENED)) {
3674 Perl_warner(aTHX_ packWARN(WARN_UNOPENED),
3675 "chdir() on unopened filehandle %" SVf, sv);
3677 SETERRNO(EBADF,RMS_IFI);
3679 TAINT_PROPER("chdir");
3683 else if (!(gv = MAYBE_DEREF_GV(sv)))
3684 tmps = SvPV_nomg_const_nolen(sv);
3687 HV * const table = GvHVn(PL_envgv);
3691 if ( (svp = hv_fetchs(table, "HOME", FALSE))
3692 || (svp = hv_fetchs(table, "LOGDIR", FALSE))
3694 || (svp = hv_fetchs(table, "SYS$LOGIN", FALSE))
3698 tmps = SvPV_nolen_const(*svp);
3702 SETERRNO(EINVAL, LIB_INVARG);
3703 TAINT_PROPER("chdir");
3708 TAINT_PROPER("chdir");
3711 IO* const io = GvIO(gv);
3714 PUSHi(fchdir(my_dirfd(IoDIRP(io))) >= 0);
3715 } else if (IoIFP(io)) {
3716 int fd = PerlIO_fileno(IoIFP(io));
3720 PUSHi(fchdir(fd) >= 0);
3730 DIE(aTHX_ PL_no_func, "fchdir");
3734 PUSHi( PerlDir_chdir(tmps) >= 0 );
3736 /* Clear the DEFAULT element of ENV so we'll get the new value
3738 hv_delete(GvHVn(PL_envgv),"DEFAULT",7,G_DISCARD);
3745 SETERRNO(EBADF,RMS_IFI);
3752 /* also used for: pp_chmod() pp_kill() pp_unlink() pp_utime() */
3756 dSP; dMARK; dTARGET;
3757 const I32 value = (I32)apply(PL_op->op_type, MARK, SP);
3768 char * const tmps = POPpx;
3769 TAINT_PROPER("chroot");
3770 PUSHi( chroot(tmps) >= 0 );
3773 DIE(aTHX_ PL_no_func, "chroot");
3784 const char * const tmps2 = POPpconstx;
3785 const char * const tmps = SvPV_nolen_const(TOPs);
3786 TAINT_PROPER("rename");
3788 anum = PerlLIO_rename(tmps, tmps2);
3790 if (!(anum = PerlLIO_stat(tmps, &statbuf))) {
3791 if (same_dirent(tmps2, tmps)) /* can always rename to same name */
3794 if (PerlProc_geteuid() || PerlLIO_stat(tmps2, &statbuf) < 0 || !S_ISDIR(statbuf.st_mode))
3795 (void)UNLINK(tmps2);
3796 if (!(anum = link(tmps, tmps2)))
3797 anum = UNLINK(tmps);
3806 /* also used for: pp_symlink() */
3808 #if defined(HAS_LINK) || defined(HAS_SYMLINK)
3812 const int op_type = PL_op->op_type;
3816 if (op_type == OP_LINK)
3817 DIE(aTHX_ PL_no_func, "link");
3819 # ifndef HAS_SYMLINK
3820 if (op_type == OP_SYMLINK)
3821 DIE(aTHX_ PL_no_func, "symlink");
3825 const char * const tmps2 = POPpconstx;
3826 const char * const tmps = SvPV_nolen_const(TOPs);
3827 TAINT_PROPER(PL_op_desc[op_type]);
3829 # if defined(HAS_LINK) && defined(HAS_SYMLINK)
3830 /* Both present - need to choose which. */
3831 (op_type == OP_LINK) ?
3832 PerlLIO_link(tmps, tmps2) : PerlLIO_symlink(tmps, tmps2);
3833 # elif defined(HAS_LINK)
3834 /* Only have link, so calls to pp_symlink will have DIE()d above. */
3835 PerlLIO_link(tmps, tmps2);
3836 # elif defined(HAS_SYMLINK)
3837 /* Only have symlink, so calls to pp_link will have DIE()d above. */
3838 PerlLIO_symlink(tmps, tmps2);
3842 SETi( result >= 0 );
3847 /* also used for: pp_symlink() */
3852 DIE(aTHX_ PL_no_func, PL_op_desc[PL_op->op_type]);
3862 char buf[MAXPATHLEN];
3867 /* NOTE: if the length returned by readlink() is sizeof(buf) - 1,
3868 * it is impossible to know whether the result was truncated. */
3869 len = PerlLIO_readlink(tmps, buf, sizeof(buf) - 1);
3877 RETSETUNDEF; /* just pretend it's a normal file */
3881 #if !defined(HAS_MKDIR) || !defined(HAS_RMDIR)
3883 S_dooneliner(pTHX_ const char *cmd, const char *filename)
3885 char * const save_filename = filename;
3890 Size_t size = strlen(cmd) + (strlen(filename) * 2) + 10;
3892 PERL_ARGS_ASSERT_DOONELINER;
3894 Newx(cmdline, size, char);
3895 my_strlcpy(cmdline, cmd, size);
3896 my_strlcat(cmdline, " ", size);
3897 for (s = cmdline + strlen(cmdline); *filename; ) {
3901 if (s - cmdline < size)
3902 my_strlcpy(s, " 2>&1", size - (s - cmdline));
3903 myfp = PerlProc_popen(cmdline, "r");
3907 SV * const tmpsv = sv_newmortal();
3908 /* Need to save/restore 'PL_rs' ?? */
3909 s = sv_gets(tmpsv, myfp, 0);
3910 (void)PerlProc_pclose(myfp);
3914 #ifdef HAS_SYS_ERRLIST
3919 /* you don't see this */
3920 const char * const errmsg = Strerror(e) ;
3923 if (instr(s, errmsg)) {
3930 #define EACCES EPERM
3932 if (instr(s, "cannot make"))
3933 SETERRNO(EEXIST,RMS_FEX);
3934 else if (instr(s, "existing file"))
3935 SETERRNO(EEXIST,RMS_FEX);
3936 else if (instr(s, "ile exists"))
3937 SETERRNO(EEXIST,RMS_FEX);
3938 else if (instr(s, "non-exist"))
3939 SETERRNO(ENOENT,RMS_FNF);
3940 else if (instr(s, "does not exist"))
3941 SETERRNO(ENOENT,RMS_FNF);
3942 else if (instr(s, "not empty"))
3943 SETERRNO(EBUSY,SS_DEVOFFLINE);
3944 else if (instr(s, "cannot access"))
3945 SETERRNO(EACCES,RMS_PRV);
3947 SETERRNO(EPERM,RMS_PRV);
3950 else { /* some mkdirs return no failure indication */
3952 anum = (PerlLIO_stat(save_filename, &statbuf) >= 0);
3953 if (PL_op->op_type == OP_RMDIR)
3958 SETERRNO(EACCES,RMS_PRV); /* a guess */
3967 /* This macro removes trailing slashes from a directory name.
3968 * Different operating and file systems take differently to
3969 * trailing slashes. According to POSIX 1003.1 1996 Edition
3970 * any number of trailing slashes should be allowed.
3971 * Thusly we snip them away so that even non-conforming
3972 * systems are happy.
3973 * We should probably do this "filtering" for all
3974 * the functions that expect (potentially) directory names:
3975 * -d, chdir(), chmod(), chown(), chroot(), fcntl()?,
3976 * (mkdir()), opendir(), rename(), rmdir(), stat(). --jhi */
3978 #define TRIMSLASHES(tmps,len,copy) (tmps) = SvPV_const(TOPs, (len)); \
3979 if ((len) > 1 && (tmps)[(len)-1] == '/') { \
3982 } while ((len) > 1 && (tmps)[(len)-1] == '/'); \
3983 (tmps) = savepvn((tmps), (len)); \
3993 const unsigned int mode = (MAXARG > 1 && (TOPs||((void)POPs,0))) ? POPu : 0777;
3995 TRIMSLASHES(tmps,len,copy);
3997 TAINT_PROPER("mkdir");
3999 SETi( PerlDir_mkdir(tmps, mode) >= 0 );
4003 SETi( dooneliner("mkdir", tmps) );
4004 oldumask = PerlLIO_umask(0);
4005 PerlLIO_umask(oldumask);
4006 PerlLIO_chmod(tmps, (mode & ~oldumask) & 0777);
4021 TRIMSLASHES(tmps,len,copy);
4022 TAINT_PROPER("rmdir");
4024 SETi( PerlDir_rmdir(tmps) >= 0 );
4026 SETi( dooneliner("rmdir", tmps) );
4033 /* Directory calls. */
4037 #if defined(Direntry_t) && defined(HAS_READDIR)
4039 const char * const dirname = POPpconstx;
4040 GV * const gv = MUTABLE_GV(POPs);
4041 IO * const io = GvIOn(gv);
4043 if ((IoIFP(io) || IoOFP(io)))
4044 Perl_croak(aTHX_ "Cannot open %" HEKf " as a dirhandle: it is already open as a filehandle",
4045 HEKfARG(GvENAME_HEK(gv)));
4047 PerlDir_close(IoDIRP(io));
4048 if (!(IoDIRP(io) = PerlDir_open(dirname)))
4054 SETERRNO(EBADF,RMS_DIR);
4057 DIE(aTHX_ PL_no_dir_func, "opendir");
4063 #if !defined(Direntry_t) || !defined(HAS_READDIR)
4064 DIE(aTHX_ PL_no_dir_func, "readdir");
4066 #if !defined(I_DIRENT) && !defined(VMS)
4067 Direntry_t *readdir (DIR *);
4072 const U8 gimme = GIMME_V;
4073 GV * const gv = MUTABLE_GV(POPs);
4074 const Direntry_t *dp;
4075 IO * const io = GvIOn(gv);
4078 Perl_ck_warner(aTHX_ packWARN(WARN_IO),
4079 "readdir() attempted on invalid dirhandle %" HEKf,
4080 HEKfARG(GvENAME_HEK(gv)));
4085 dp = (Direntry_t *)PerlDir_read(IoDIRP(io));
4089 sv = newSVpvn(dp->d_name, dp->d_namlen);
4091 sv = newSVpv(dp->d_name, 0);
4093 if (!(IoFLAGS(io) & IOf_UNTAINT))
4096 } while (gimme == G_LIST);
4098 if (!dp && gimme != G_LIST)
4105 SETERRNO(EBADF,RMS_ISI);
4106 if (gimme == G_LIST)
4115 #if defined(HAS_TELLDIR) || defined(telldir)
4117 /* XXX does _anyone_ need this? --AD 2/20/1998 */
4118 /* XXX netbsd still seemed to.
4119 XXX HAS_TELLDIR_PROTO is new style, NEED_TELLDIR_PROTO is old style.
4120 --JHI 1999-Feb-02 */
4121 # if !defined(HAS_TELLDIR_PROTO) || defined(NEED_TELLDIR_PROTO)
4122 long telldir (DIR *);
4124 GV * const gv = MUTABLE_GV(POPs);
4125 IO * const io = GvIOn(gv);
4128 Perl_ck_warner(aTHX_ packWARN(WARN_IO),
4129 "telldir() attempted on invalid dirhandle %" HEKf,
4130 HEKfARG(GvENAME_HEK(gv)));
4134 PUSHi( PerlDir_tell(IoDIRP(io)) );
4138 SETERRNO(EBADF,RMS_ISI);
4141 DIE(aTHX_ PL_no_dir_func, "telldir");
4147 #if defined(HAS_SEEKDIR) || defined(seekdir)
4149 const long along = POPl;
4150 GV * const gv = MUTABLE_GV(POPs);
4151 IO * const io = GvIOn(gv);
4154 Perl_ck_warner(aTHX_ packWARN(WARN_IO),
4155 "seekdir() attempted on invalid dirhandle %" HEKf,
4156 HEKfARG(GvENAME_HEK(gv)));
4159 (void)PerlDir_seek(IoDIRP(io), along);
4164 SETERRNO(EBADF,RMS_ISI);
4167 DIE(aTHX_ PL_no_dir_func, "seekdir");
4173 #if defined(HAS_REWINDDIR) || defined(rewinddir)
4175 GV * const gv = MUTABLE_GV(POPs);
4176 IO * const io = GvIOn(gv);
4179 Perl_ck_warner(aTHX_ packWARN(WARN_IO),
4180 "rewinddir() attempted on invalid dirhandle %" HEKf,
4181 HEKfARG(GvENAME_HEK(gv)));
4184 (void)PerlDir_rewind(IoDIRP(io));
4188 SETERRNO(EBADF,RMS_ISI);
4191 DIE(aTHX_ PL_no_dir_func, "rewinddir");
4197 #if defined(Direntry_t) && defined(HAS_READDIR)
4199 GV * const gv = MUTABLE_GV(POPs);
4200 IO * const io = GvIOn(gv);
4203 Perl_ck_warner(aTHX_ packWARN(WARN_IO),
4204 "closedir() attempted on invalid dirhandle %" HEKf,
4205 HEKfARG(GvENAME_HEK(gv)));
4208 #ifdef VOID_CLOSEDIR
4209 PerlDir_close(IoDIRP(io));
4211 if (PerlDir_close(IoDIRP(io)) < 0) {
4212 IoDIRP(io) = 0; /* Don't try to close again--coredumps on SysV */
4221 SETERRNO(EBADF,RMS_IFI);
4224 DIE(aTHX_ PL_no_dir_func, "closedir");
4228 /* Process control. */
4235 #ifdef HAS_SIGPROCMASK
4236 sigset_t oldmask, newmask;
4241 PERL_FLUSHALL_FOR_CHILD;
4242 #ifdef HAS_SIGPROCMASK
4243 sigfillset(&newmask);
4244 sigprocmask(SIG_SETMASK, &newmask, &oldmask);
4246 childpid = PerlProc_fork();
4247 if (childpid == 0) {
4251 for (sig = 1; sig < SIG_SIZE; sig++)
4252 PL_psig_pend[sig] = 0;
4254 #ifdef HAS_SIGPROCMASK
4257 sigprocmask(SIG_SETMASK, &oldmask, NULL);
4264 #ifdef PERL_USES_PL_PIDSTATUS
4265 hv_clear(PL_pidstatus); /* no kids, so don't wait for 'em */
4267 PERL_SRAND_OVERRIDE_NEXT_CHILD();
4269 PERL_SRAND_OVERRIDE_NEXT_PARENT();
4273 #elif (defined(USE_ITHREADS) && defined(PERL_IMPLICIT_SYS)) || defined(__amigaos4__)
4278 PERL_FLUSHALL_FOR_CHILD;
4279 childpid = PerlProc_fork();
4282 else if (childpid) {
4283 /* we are in the parent */
4284 PERL_SRAND_OVERRIDE_NEXT_PARENT();
4287 /* This is part of the logic supporting the env var
4288 * PERL_RAND_SEED which causes use of rand() without an
4289 * explicit srand() to use a deterministic seed. This logic is
4290 * intended to give most forked children of a process a
4291 * deterministic but different srand seed.
4293 PERL_SRAND_OVERRIDE_NEXT_CHILD();
4298 DIE(aTHX_ PL_no_func, "fork");
4304 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32)) && !defined(__LIBCATAMOUNT__)
4309 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
4310 childpid = wait4pid(-1, &argflags, 0);
4312 while ((childpid = wait4pid(-1, &argflags, 0)) == -1 &&
4317 # if defined(USE_ITHREADS) && defined(PERL_IMPLICIT_SYS)
4318 /* 0 and -1 are both error returns (the former applies to WNOHANG case) */
4319 STATUS_NATIVE_CHILD_SET((childpid && childpid != -1) ? argflags : -1);
4321 STATUS_NATIVE_CHILD_SET((childpid > 0) ? argflags : -1);
4326 DIE(aTHX_ PL_no_func, "wait");
4332 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32)) && !defined(__LIBCATAMOUNT__)
4334 const int optype = POPi;
4335 const Pid_t pid = TOPi;
4339 result = amigaos_waitpid(aTHX_ optype, pid, &argflags);
4340 STATUS_NATIVE_CHILD_SET((result >= 0) ? argflags : -1);
4341 result = result == 0 ? pid : -1;
4345 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
4346 result = wait4pid(pid, &argflags, optype);
4348 while ((result = wait4pid(pid, &argflags, optype)) == -1 &&
4353 # if defined(USE_ITHREADS) && defined(PERL_IMPLICIT_SYS)
4354 /* 0 and -1 are both error returns (the former applies to WNOHANG case) */
4355 STATUS_NATIVE_CHILD_SET((result && result != -1) ? argflags : -1);
4357 STATUS_NATIVE_CHILD_SET((result > 0) ? argflags : -1);
4359 # endif /* __amigaos4__ */
4363 DIE(aTHX_ PL_no_func, "waitpid");
4369 dSP; dMARK; dORIGMARK; dTARGET;
4370 #if defined(__LIBCATAMOUNT__)
4371 PL_statusvalue = -1;
4376 # ifdef __amigaos4__
4382 while (++MARK <= SP) {
4383 SV *origsv = *MARK, *copysv;
4387 #if defined(WIN32) || defined(__VMS)
4389 * Because of a nasty platform-specific variation on the meaning
4390 * of arguments to this op, we must preserve numeric arguments
4391 * as numeric, not just retain the string value.
4393 if (SvNIOK(origsv) || SvNIOKp(origsv)) {
4394 copysv = newSV_type(SVt_PVNV);
4396 if (SvPOK(origsv) || SvPOKp(origsv)) {
4397 pv = SvPV_nomg(origsv, len);
4398 sv_setpvn_fresh(copysv, pv, len);
4401 if (SvIOK(origsv) || SvIOKp(origsv))
4402 SvIV_set(copysv, SvIVX(origsv));
4403 if (SvNOK(origsv) || SvNOKp(origsv))
4404 SvNV_set(copysv, SvNVX(origsv));
4405 SvFLAGS(copysv) |= SvFLAGS(origsv) &
4406 (SVf_IOK|SVf_NOK|SVf_POK|SVp_IOK|SVp_NOK|SVp_POK|
4407 SVf_UTF8|SVf_IVisUV);
4411 pv = SvPV_nomg(origsv, len);
4412 copysv = newSVpvn_flags(pv, len,
4413 (SvFLAGS(origsv) & SVf_UTF8) | SVs_TEMP);
4421 TAINT_PROPER("system");
4423 PERL_FLUSHALL_FOR_CHILD;
4424 #if (defined(HAS_FORK) || defined(__amigaos4__)) && !defined(VMS) && !defined(OS2) || defined(PERL_MICRO)
4427 struct UserData userdata;
4434 bool child_success = FALSE;
4435 #ifdef HAS_SIGPROCMASK
4436 sigset_t newset, oldset;
4439 if (PerlProc_pipe_cloexec(pp) >= 0)
4442 amigaos_fork_set_userdata(aTHX_
4448 pthread_create(&proc,NULL,amigaos_system_child,(void *)&userdata);
4449 child_success = proc > 0;
4451 #ifdef HAS_SIGPROCMASK
4452 sigemptyset(&newset);
4453 sigaddset(&newset, SIGCHLD);
4454 sigprocmask(SIG_BLOCK, &newset, &oldset);
4456 while ((childpid = PerlProc_fork()) == -1) {
4457 if (errno != EAGAIN) {
4462 PerlLIO_close(pp[0]);
4463 PerlLIO_close(pp[1]);
4465 #ifdef HAS_SIGPROCMASK
4466 sigprocmask(SIG_SETMASK, &oldset, NULL);
4472 child_success = childpid > 0;
4474 if (child_success) {
4475 Sigsave_t ihand,qhand; /* place to save signals during system() */
4478 #ifndef __amigaos4__
4480 PerlLIO_close(pp[1]);
4483 rsignal_save(SIGINT, (Sighandler_t) SIG_IGN, &ihand);
4484 rsignal_save(SIGQUIT, (Sighandler_t) SIG_IGN, &qhand);
4487 result = pthread_join(proc, (void **)&status);
4490 result = wait4pid(childpid, &status, 0);
4491 } while (result == -1 && errno == EINTR);
4494 #ifdef HAS_SIGPROCMASK
4495 sigprocmask(SIG_SETMASK, &oldset, NULL);
4497 (void)rsignal_restore(SIGINT, &ihand);
4498 (void)rsignal_restore(SIGQUIT, &qhand);
4500 STATUS_NATIVE_CHILD_SET(result == -1 ? -1 : status);
4506 while (n < sizeof(int)) {
4507 const SSize_t n1 = PerlLIO_read(pp[0],
4508 (void*)(((char*)&errkid)+n),
4514 PerlLIO_close(pp[0]);
4515 if (n) { /* Error */
4516 if (n != sizeof(int))
4517 DIE(aTHX_ "panic: kid popen errno read, n=%u", n);
4518 errno = errkid; /* Propagate errno from kid */
4520 /* The pipe always has something in it
4521 * so n alone is not enough. */
4525 STATUS_NATIVE_CHILD_SET(-1);
4529 XPUSHi(STATUS_CURRENT);
4532 #ifndef __amigaos4__
4533 #ifdef HAS_SIGPROCMASK
4534 sigprocmask(SIG_SETMASK, &oldset, NULL);
4537 PerlLIO_close(pp[0]);
4538 if (PL_op->op_flags & OPf_STACKED) {
4539 SV * const really = *++MARK;
4540 value = (I32)do_aexec5(really, MARK, SP, pp[1], did_pipes);
4542 else if (SP - MARK != 1)
4543 value = (I32)do_aexec5(NULL, MARK, SP, pp[1], did_pipes);
4545 value = (I32)do_exec3(SvPVx_nolen(sv_mortalcopy(*SP)), pp[1], did_pipes);
4547 #endif /* __amigaos4__ */
4550 #else /* ! FORK or VMS or OS/2 */
4553 if (PL_op->op_flags & OPf_STACKED) {
4554 SV * const really = *++MARK;
4555 # if defined(WIN32) || defined(OS2) || defined(__VMS)
4556 value = (I32)do_aspawn(really, MARK, SP);
4558 value = (I32)do_aspawn(really, (void **)MARK, (void **)SP);
4561 else if (SP - MARK != 1) {
4562 # if defined(WIN32) || defined(OS2) || defined(__VMS)
4563 value = (I32)do_aspawn(NULL, MARK, SP);
4565 value = (I32)do_aspawn(NULL, (void **)MARK, (void **)SP);
4569 value = (I32)do_spawn(SvPVx_nolen(sv_mortalcopy(*SP)));
4571 if (PL_statusvalue == -1) /* hint that value must be returned as is */
4573 STATUS_NATIVE_CHILD_SET(value);
4575 XPUSHi(result ? value : STATUS_CURRENT);
4576 #endif /* !FORK or VMS or OS/2 */
4583 dSP; dMARK; dORIGMARK; dTARGET;
4588 while (++MARK <= SP) {
4589 (void)SvPV_nolen_const(*MARK); /* stringify for taint check */
4594 TAINT_PROPER("exec");
4597 PERL_FLUSHALL_FOR_CHILD;
4598 if (PL_op->op_flags & OPf_STACKED) {
4599 SV * const really = *++MARK;
4600 value = (I32)do_aexec(really, MARK, SP);
4602 else if (SP - MARK != 1)
4604 value = (I32)vms_do_aexec(NULL, MARK, SP);
4606 value = (I32)do_aexec(NULL, MARK, SP);
4610 value = (I32)vms_do_exec(SvPVx_nolen(sv_mortalcopy(*SP)));
4612 value = (I32)do_exec(SvPVx_nolen(sv_mortalcopy(*SP)));
4624 XPUSHi( getppid() );
4627 DIE(aTHX_ PL_no_func, "getppid");
4637 (MAXARG < 1) ? 0 : TOPs ? SvIVx(POPs) : ((void)POPs, 0);
4640 pgrp = (I32)BSD_GETPGRP(pid);
4642 if (pid != 0 && pid != PerlProc_getpid())
4643 DIE(aTHX_ "POSIX getpgrp can't take an argument");
4649 DIE(aTHX_ PL_no_func, "getpgrp");
4659 pgrp = MAXARG == 2 && (TOPs||POPs) ? POPi : 0;
4660 if (MAXARG > 0) pid = TOPs ? TOPi : 0;
4667 TAINT_PROPER("setpgrp");
4669 SETi( BSD_SETPGRP(pid, pgrp) >= 0 );
4671 if ((pgrp != 0 && pgrp != PerlProc_getpid())
4672 || (pid != 0 && pid != PerlProc_getpid()))
4674 DIE(aTHX_ "setpgrp can't take arguments");
4676 SETi( setpgrp() >= 0 );
4677 #endif /* USE_BSDPGRP */
4680 DIE(aTHX_ PL_no_func, "setpgrp");
4685 * The glibc headers typedef __priority_which_t to an enum under C, but
4686 * under C++, it keeps it as int. -Wc++-compat doesn't know this, so we
4687 * need to explicitly cast it to shut up the warning.
4689 #if defined(__GLIBC__) && ((__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3) || (__GLIBC__ > 2))
4690 # define PRIORITY_WHICH_T(which) (__priority_which_t)which
4692 # define PRIORITY_WHICH_T(which) which
4697 #ifdef HAS_GETPRIORITY
4699 const int who = POPi;
4700 const int which = TOPi;
4701 SETi( getpriority(PRIORITY_WHICH_T(which), who) );
4704 DIE(aTHX_ PL_no_func, "getpriority");
4710 #ifdef HAS_SETPRIORITY
4712 const int niceval = POPi;
4713 const int who = POPi;
4714 const int which = TOPi;
4715 TAINT_PROPER("setpriority");
4716 SETi( setpriority(PRIORITY_WHICH_T(which), who, niceval) >= 0 );
4719 DIE(aTHX_ PL_no_func, "setpriority");
4723 #undef PRIORITY_WHICH_T
4731 XPUSHn( (NV)time(NULL) );
4733 XPUSHu( (UV)time(NULL) );
4742 struct tms timesbuf;
4745 (void)PerlProc_times(×buf);
4747 mPUSHn(((NV)timesbuf.tms_utime)/(NV)PL_clocktick);
4748 if (GIMME_V == G_LIST) {
4749 mPUSHn(((NV)timesbuf.tms_stime)/(NV)PL_clocktick);
4750 mPUSHn(((NV)timesbuf.tms_cutime)/(NV)PL_clocktick);
4751 mPUSHn(((NV)timesbuf.tms_cstime)/(NV)PL_clocktick);
4754 #elif defined(PERL_MICRO)
4758 if (GIMME_V == G_LIST) {
4765 DIE(aTHX_ "times not implemented");
4766 #endif /* HAS_TIMES */
4769 /* The 32 bit int year limits the times we can represent to these
4770 boundaries with a few days wiggle room to account for time zone
4773 /* Sat Jan 3 00:00:00 -2147481748 */
4774 #define TIME_LOWER_BOUND -67768100567755200.0
4775 /* Sun Dec 29 12:00:00 2147483647 */
4776 #define TIME_UPPER_BOUND 67767976233316800.0
4779 /* also used for: pp_localtime() */
4787 const char *opname = PL_op->op_type == OP_LOCALTIME ? "localtime" : "gmtime";
4788 static const char * const dayname[] =
4789 {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
4790 static const char * const monname[] =
4791 {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
4792 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
4794 if (MAXARG < 1 || (!TOPs && ((void)POPs, 1))) {
4797 when = (Time64_T)now;
4800 NV input = Perl_floor(POPn);
4801 const bool pl_isnan = Perl_isnan(input);
4802 when = (Time64_T)input;
4803 if (UNLIKELY(pl_isnan || when != input)) {
4804 /* diag_listed_as: gmtime(%f) too large */
4805 Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
4806 "%s(%.0" NVff ") too large", opname, input);
4814 if ( TIME_LOWER_BOUND > when ) {
4815 /* diag_listed_as: gmtime(%f) too small */
4816 Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
4817 "%s(%.0" NVff ") too small", opname, when);
4820 else if( when > TIME_UPPER_BOUND ) {
4821 /* diag_listed_as: gmtime(%f) too small */
4822 Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
4823 "%s(%.0" NVff ") too large", opname, when);
4827 if (PL_op->op_type == OP_LOCALTIME)
4828 err = Perl_localtime64_r(&when, &tmbuf);
4830 err = Perl_gmtime64_r(&when, &tmbuf);
4834 /* diag_listed_as: gmtime(%f) failed */
4835 /* XXX %lld broken for quads */
4837 Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
4838 "%s(%.0" NVff ") failed", opname, when);
4841 if (GIMME_V != G_LIST) { /* scalar context */
4848 Perl_sv_setpvf_mg(aTHX_ TARG, "%s %s %2d %02d:%02d:%02d %" IVdf,
4849 dayname[tmbuf.tm_wday],
4850 monname[tmbuf.tm_mon],
4855 (IV)tmbuf.tm_year + 1900);
4858 else { /* list context */
4864 mPUSHi(tmbuf.tm_sec);
4865 mPUSHi(tmbuf.tm_min);
4866 mPUSHi(tmbuf.tm_hour);
4867 mPUSHi(tmbuf.tm_mday);
4868 mPUSHi(tmbuf.tm_mon);
4869 mPUSHn(tmbuf.tm_year);
4870 mPUSHi(tmbuf.tm_wday);
4871 mPUSHi(tmbuf.tm_yday);
4872 mPUSHi(tmbuf.tm_isdst);
4881 /* alarm() takes an unsigned int number of seconds, and return the
4882 * unsigned int number of seconds remaining in the previous alarm
4883 * (alarms don't stack). Therefore negative return values are not
4887 /* Note that while the C library function alarm() as such has
4888 * no errors defined (or in other words, properly behaving client
4889 * code shouldn't expect any), alarm() being obsoleted by
4890 * setitimer() and often being implemented in terms of
4891 * setitimer(), can fail. */
4892 /* diag_listed_as: %s() with negative argument */
4893 Perl_ck_warner_d(aTHX_ packWARN(WARN_MISC),
4894 "alarm() with negative argument");
4895 SETERRNO(EINVAL, LIB_INVARG);
4899 unsigned int retval = alarm(anum);
4900 if ((int)retval < 0) /* Strictly speaking "cannot happen". */
4906 DIE(aTHX_ PL_no_func, "alarm");
4916 (void)time(&lasttime);
4917 if (MAXARG < 1 || (!TOPs && !POPs))
4920 const I32 duration = POPi;
4922 /* diag_listed_as: %s() with negative argument */
4923 Perl_ck_warner_d(aTHX_ packWARN(WARN_MISC),
4924 "sleep() with negative argument");
4925 SETERRNO(EINVAL, LIB_INVARG);
4926 XPUSHs(&PL_sv_zero);
4929 PerlProc_sleep((unsigned int)duration);
4933 XPUSHu((UV)(when - lasttime));
4937 /* Shared memory. */
4938 /* Merged with some message passing. */
4940 /* also used for: pp_msgrcv() pp_msgsnd() pp_semop() pp_shmread() */
4944 #if defined(HAS_MSG) || defined(HAS_SEM) || defined(HAS_SHM)
4945 dSP; dMARK; dTARGET;
4946 const int op_type = PL_op->op_type;
4951 value = (I32)(do_msgsnd(MARK, SP) >= 0);
4954 value = (I32)(do_msgrcv(MARK, SP) >= 0);
4957 value = (I32)(do_semop(MARK, SP) >= 0);
4960 value = (I32)(do_shmio(op_type, MARK, SP) >= 0);
4968 return Perl_pp_semget(aTHX);
4974 /* also used for: pp_msgget() pp_shmget() */
4978 #if defined(HAS_MSG) || defined(HAS_SEM) || defined(HAS_SHM)
4979 dSP; dMARK; dTARGET;
4980 const int anum = do_ipcget(PL_op->op_type, MARK, SP);
4987 DIE(aTHX_ "System V IPC is not implemented on this machine");
4991 /* also used for: pp_msgctl() pp_shmctl() */
4995 #if defined(HAS_MSG) || defined(HAS_SEM) || defined(HAS_SHM)
4996 dSP; dMARK; dTARGET;
4997 const int anum = do_ipcctl(PL_op->op_type, MARK, SP);
5005 PUSHp(zero_but_true, ZBTLEN);
5009 return Perl_pp_semget(aTHX);
5013 /* I can't const this further without getting warnings about the types of
5014 various arrays passed in from structures. */
5016 S_space_join_names_mortal(pTHX_ char *const *array)
5020 if (array && *array) {
5021 target = newSVpvs_flags("", SVs_TEMP);
5023 sv_catpv(target, *array);
5026 sv_catpvs(target, " ");
5029 target = sv_mortalcopy(&PL_sv_no);
5034 /* Get system info. */
5036 /* also used for: pp_ghbyaddr() pp_ghbyname() */
5040 #if defined(HAS_GETHOSTBYNAME) || defined(HAS_GETHOSTBYADDR) || defined(HAS_GETHOSTENT)
5042 I32 which = PL_op->op_type;
5045 #ifndef HAS_GETHOST_PROTOS /* XXX Do we need individual probes? */
5046 struct hostent *gethostbyaddr(Netdb_host_t, Netdb_hlen_t, int);
5047 struct hostent *gethostbyname(Netdb_name_t);
5048 struct hostent *gethostent(void);
5050 struct hostent *hent = NULL;
5054 if (which == OP_GHBYNAME) {
5055 #ifdef HAS_GETHOSTBYNAME
5056 const char* const name = POPpbytex;
5057 hent = PerlSock_gethostbyname(name);
5059 DIE(aTHX_ PL_no_sock_func, "gethostbyname");
5062 else if (which == OP_GHBYADDR) {
5063 #ifdef HAS_GETHOSTBYADDR
5064 const int addrtype = POPi;
5065 SV * const addrsv = POPs;
5067 const char *addr = (char *)SvPVbyte(addrsv, addrlen);
5069 hent = PerlSock_gethostbyaddr(addr, (Netdb_hlen_t) addrlen, addrtype);
5071 DIE(aTHX_ PL_no_sock_func, "gethostbyaddr");
5075 #ifdef HAS_GETHOSTENT
5076 hent = PerlSock_gethostent();
5078 DIE(aTHX_ PL_no_sock_func, "gethostent");
5081 #ifdef HOST_NOT_FOUND
5083 #ifdef USE_REENTRANT_API
5084 # ifdef USE_GETHOSTENT_ERRNO
5085 h_errno = PL_reentrant_buffer->_gethostent_errno;
5088 STATUS_UNIX_SET(h_errno);
5092 if (GIMME_V != G_LIST) {
5093 PUSHs(sv = sv_newmortal());
5095 if (which == OP_GHBYNAME) {
5097 sv_upgrade(sv, SVt_PV);
5098 sv_setpvn_fresh(sv, hent->h_addr, hent->h_length);
5102 sv_setpv(sv, (char*)hent->h_name);
5108 mPUSHs(newSVpv((char*)hent->h_name, 0));
5109 PUSHs(space_join_names_mortal(hent->h_aliases));
5110 mPUSHi(hent->h_addrtype);
5111 len = hent->h_length;
5114 for (elem = hent->h_addr_list; elem && *elem; elem++) {
5115 mXPUSHp(*elem, len);
5119 mPUSHp(hent->h_addr, len);
5121 PUSHs(sv_mortalcopy(&PL_sv_no));
5126 DIE(aTHX_ PL_no_sock_func, PL_op_desc[PL_op->op_type]);
5130 /* also used for: pp_gnbyaddr() pp_gnbyname() */
5134 #if defined(HAS_GETNETBYNAME) || defined(HAS_GETNETBYADDR) || defined(HAS_GETNETENT)
5136 I32 which = PL_op->op_type;
5138 #ifndef HAS_GETNET_PROTOS /* XXX Do we need individual probes? */
5139 struct netent *getnetbyaddr(Netdb_net_t, int);
5140 struct netent *getnetbyname(Netdb_name_t);
5141 struct netent *getnetent(void);
5143 struct netent *nent;
5145 if (which == OP_GNBYNAME){
5146 #ifdef HAS_GETNETBYNAME
5147 const char * const name = POPpbytex;
5148 nent = PerlSock_getnetbyname(name);
5150 DIE(aTHX_ PL_no_sock_func, "getnetbyname");
5153 else if (which == OP_GNBYADDR) {
5154 #ifdef HAS_GETNETBYADDR
5155 const int addrtype = POPi;
5156 const Netdb_net_t addr = (Netdb_net_t) (U32)POPu;
5157 nent = PerlSock_getnetbyaddr(addr, addrtype);
5159 DIE(aTHX_ PL_no_sock_func, "getnetbyaddr");
5163 #ifdef HAS_GETNETENT
5164 nent = PerlSock_getnetent();
5166 DIE(aTHX_ PL_no_sock_func, "getnetent");
5169 #ifdef HOST_NOT_FOUND
5171 #ifdef USE_REENTRANT_API
5172 # ifdef USE_GETNETENT_ERRNO
5173 h_errno = PL_reentrant_buffer->_getnetent_errno;
5176 STATUS_UNIX_SET(h_errno);
5181 if (GIMME_V != G_LIST) {
5182 PUSHs(sv = sv_newmortal());
5184 if (which == OP_GNBYNAME)
5185 sv_setiv(sv, (IV)nent->n_net);
5187 sv_setpv(sv, nent->n_name);
5193 mPUSHs(newSVpv(nent->n_name, 0));
5194 PUSHs(space_join_names_mortal(nent->n_aliases));
5195 mPUSHi(nent->n_addrtype);
5196 mPUSHi(nent->n_net);
5201 DIE(aTHX_ PL_no_sock_func, PL_op_desc[PL_op->op_type]);
5206 /* also used for: pp_gpbyname() pp_gpbynumber() */
5210 #if defined(HAS_GETPROTOBYNAME) || defined(HAS_GETPROTOBYNUMBER) || defined(HAS_GETPROTOENT)
5212 I32 which = PL_op->op_type;
5214 #ifndef HAS_GETPROTO_PROTOS /* XXX Do we need individual probes? */
5215 struct protoent *getprotobyname(Netdb_name_t);
5216 struct protoent *getprotobynumber(int);
5217 struct protoent *getprotoent(void);
5219 struct protoent *pent;
5221 if (which == OP_GPBYNAME) {
5222 #ifdef HAS_GETPROTOBYNAME
5223 const char* const name = POPpbytex;
5224 pent = PerlSock_getprotobyname(name);
5226 DIE(aTHX_ PL_no_sock_func, "getprotobyname");
5229 else if (which == OP_GPBYNUMBER) {
5230 #ifdef HAS_GETPROTOBYNUMBER
5231 const int number = POPi;
5232 pent = PerlSock_getprotobynumber(number);
5234 DIE(aTHX_ PL_no_sock_func, "getprotobynumber");
5238 #ifdef HAS_GETPROTOENT
5239 pent = PerlSock_getprotoent();
5241 DIE(aTHX_ PL_no_sock_func, "getprotoent");
5245 if (GIMME_V != G_LIST) {
5246 PUSHs(sv = sv_newmortal());
5248 if (which == OP_GPBYNAME)
5249 sv_setiv(sv, (IV)pent->p_proto);
5251 sv_setpv(sv, pent->p_name);
5257 mPUSHs(newSVpv(pent->p_name, 0));
5258 PUSHs(space_join_names_mortal(pent->p_aliases));
5259 mPUSHi(pent->p_proto);
5264 DIE(aTHX_ PL_no_sock_func, PL_op_desc[PL_op->op_type]);
5269 /* also used for: pp_gsbyname() pp_gsbyport() */
5273 #if defined(HAS_GETSERVBYNAME) || defined(HAS_GETSERVBYPORT) || defined(HAS_GETSERVENT)
5275 I32 which = PL_op->op_type;
5277 #ifndef HAS_GETSERV_PROTOS /* XXX Do we need individual probes? */
5278 struct servent *getservbyname(Netdb_name_t, Netdb_name_t);
5279 struct servent *getservbyport(int, Netdb_name_t);
5280 struct servent *getservent(void);
5282 struct servent *sent;
5284 if (which == OP_GSBYNAME) {
5285 #ifdef HAS_GETSERVBYNAME
5286 const char * const proto = POPpbytex;
5287 const char * const name = POPpbytex;
5288 sent = PerlSock_getservbyname(name, (proto && !*proto) ? NULL : proto);
5290 DIE(aTHX_ PL_no_sock_func, "getservbyname");
5293 else if (which == OP_GSBYPORT) {
5294 #ifdef HAS_GETSERVBYPORT
5295 const char * const proto = POPpbytex;
5296 unsigned short port = (unsigned short)POPu;
5297 port = PerlSock_htons(port);
5298 sent = PerlSock_getservbyport(port, (proto && !*proto) ? NULL : proto);
5300 DIE(aTHX_ PL_no_sock_func, "getservbyport");
5304 #ifdef HAS_GETSERVENT
5305 sent = PerlSock_getservent();
5307 DIE(aTHX_ PL_no_sock_func, "getservent");
5311 if (GIMME_V != G_LIST) {
5312 PUSHs(sv = sv_newmortal());
5314 if (which == OP_GSBYNAME) {
5315 sv_setiv(sv, (IV)PerlSock_ntohs(sent->s_port));
5318 sv_setpv(sv, sent->s_name);
5324 mPUSHs(newSVpv(sent->s_name, 0));
5325 PUSHs(space_join_names_mortal(sent->s_aliases));
5326 mPUSHi(PerlSock_ntohs(sent->s_port));
5327 mPUSHs(newSVpv(sent->s_proto, 0));
5332 DIE(aTHX_ PL_no_sock_func, PL_op_desc[PL_op->op_type]);
5337 /* also used for: pp_snetent() pp_sprotoent() pp_sservent() */
5342 const int stayopen = TOPi;
5343 switch(PL_op->op_type) {
5345 #ifdef HAS_SETHOSTENT
5346 PerlSock_sethostent(stayopen);
5348 DIE(aTHX_ PL_no_sock_func, PL_op_desc[PL_op->op_type]);
5352 #ifdef HAS_SETNETENT
5353 PerlSock_setnetent(stayopen);
5355 DIE(aTHX_ PL_no_sock_func, PL_op_desc[PL_op->op_type]);
5359 #ifdef HAS_SETPROTOENT
5360 PerlSock_setprotoent(stayopen);
5362 DIE(aTHX_ PL_no_sock_func, PL_op_desc[PL_op->op_type]);
5366 #ifdef HAS_SETSERVENT
5367 PerlSock_setservent(stayopen);
5369 DIE(aTHX_ PL_no_sock_func, PL_op_desc[PL_op->op_type]);
5377 /* also used for: pp_egrent() pp_enetent() pp_eprotoent() pp_epwent()
5378 * pp_eservent() pp_sgrent() pp_spwent() */
5383 switch(PL_op->op_type) {
5385 #ifdef HAS_ENDHOSTENT
5386 PerlSock_endhostent();
5388 DIE(aTHX_ PL_no_sock_func, PL_op_desc[PL_op->op_type]);
5392 #ifdef HAS_ENDNETENT
5393 PerlSock_endnetent();
5395 DIE(aTHX_ PL_no_sock_func, PL_op_desc[PL_op->op_type]);
5399 #ifdef HAS_ENDPROTOENT
5400 PerlSock_endprotoent();
5402 DIE(aTHX_ PL_no_sock_func, PL_op_desc[PL_op->op_type]);
5406 #ifdef HAS_ENDSERVENT
5407 PerlSock_endservent();
5409 DIE(aTHX_ PL_no_sock_func, PL_op_desc[PL_op->op_type]);
5413 #if defined(HAS_GROUP) && defined(HAS_SETGRENT)
5416 DIE(aTHX_ PL_no_func, PL_op_desc[PL_op->op_type]);
5420 #if defined(HAS_GROUP) && defined(HAS_ENDGRENT)
5423 DIE(aTHX_ PL_no_func, PL_op_desc[PL_op->op_type]);
5427 #if defined(HAS_PASSWD) && defined(HAS_SETPWENT)
5430 DIE(aTHX_ PL_no_func, PL_op_desc[PL_op->op_type]);
5434 #if defined(HAS_PASSWD) && defined(HAS_ENDPWENT)
5437 DIE(aTHX_ PL_no_func, PL_op_desc[PL_op->op_type]);
5446 /* also used for: pp_gpwnam() pp_gpwuid() */
5452 I32 which = PL_op->op_type;
5454 struct passwd *pwent = NULL;
5456 * We currently support only the SysV getsp* shadow password interface.
5457 * The interface is declared in <shadow.h> and often one needs to link
5458 * with -lsecurity or some such.
5459 * This interface is used at least by Solaris, HP-UX, IRIX, and Linux.
5462 * AIX getpwnam() is clever enough to return the encrypted password
5463 * only if the caller (euid?) is root.
5465 * There are at least three other shadow password APIs. Many platforms
5466 * seem to contain more than one interface for accessing the shadow
5467 * password databases, possibly for compatibility reasons.
5468 * The getsp*() is by far he simplest one, the other two interfaces
5469 * are much more complicated, but also very similar to each other.
5474 * struct pr_passwd *getprpw*();
5475 * The password is in
5476 * char getprpw*(...).ufld.fd_encrypt[]
5477 * Mention HAS_GETPRPWNAM here so that Configure probes for it.
5482 * struct es_passwd *getespw*();
5483 * The password is in
5484 * char *(getespw*(...).ufld.fd_encrypt)
5485 * Mention HAS_GETESPWNAM here so that Configure probes for it.
5488 * struct userpw *getuserpw();
5489 * The password is in
5490 * char *(getuserpw(...)).spw_upw_passwd
5491 * (but the de facto standard getpwnam() should work okay)
5493 * Mention I_PROT here so that Configure probes for it.
5495 * In HP-UX for getprpw*() the manual page claims that one should include
5496 * <hpsecurity.h> instead of <sys/security.h>, but that is not needed
5497 * if one includes <shadow.h> as that includes <hpsecurity.h>,
5498 * and pp_sys.c already includes <shadow.h> if there is such.
5500 * Note that <sys/security.h> is already probed for, but currently
5501 * it is only included in special cases.
5503 * In Digital UNIX/Tru64 if using the getespw*() (which seems to be
5504 * the preferred interface, even though also the getprpw*() interface
5505 * is available) one needs to link with -lsecurity -ldb -laud -lm.
5506 * One also needs to call set_auth_parameters() in main() before
5507 * doing anything else, whether one is using getespw*() or getprpw*().
5509 * Note that accessing the shadow databases can be magnitudes
5510 * slower than accessing the standard databases.
5515 # if defined(__CYGWIN__) && defined(USE_REENTRANT_API)
5516 /* Cygwin 1.5.3-1 has buggy getpwnam_r() and getpwuid_r():
5517 * the pw_comment is left uninitialized. */
5518 PL_reentrant_buffer->_pwent_struct.pw_comment = NULL;
5524 const char* const name = POPpbytex;
5525 pwent = getpwnam(name);
5531 pwent = getpwuid(uid);
5535 # ifdef HAS_GETPWENT
5537 #ifdef POSIX_BC /* In some cases pw_passwd has invalid addresses */
5538 if (pwent) pwent = getpwnam(pwent->pw_name);
5541 DIE(aTHX_ PL_no_func, "getpwent");
5547 if (GIMME_V != G_LIST) {
5548 PUSHs(sv = sv_newmortal());
5550 if (which == OP_GPWNAM)
5551 sv_setuid(sv, pwent->pw_uid);
5553 sv_setpv(sv, pwent->pw_name);
5559 mPUSHs(newSVpv(pwent->pw_name, 0));
5563 /* If we have getspnam(), we try to dig up the shadow
5564 * password. If we are underprivileged, the shadow
5565 * interface will set the errno to EACCES or similar,
5566 * and return a null pointer. If this happens, we will
5567 * use the dummy password (usually "*" or "x") from the
5568 * standard password database.
5570 * In theory we could skip the shadow call completely
5571 * if euid != 0 but in practice we cannot know which
5572 * security measures are guarding the shadow databases
5573 * on a random platform.
5575 * Resist the urge to use additional shadow interfaces.
5576 * Divert the urge to writing an extension instead.
5579 /* Some AIX setups falsely(?) detect some getspnam(), which
5580 * has a different API than the Solaris/IRIX one. */
5581 # if defined(HAS_GETSPNAM) && !defined(_AIX)
5584 const struct spwd * const spwent = getspnam(pwent->pw_name);
5585 /* Save and restore errno so that
5586 * underprivileged attempts seem
5587 * to have never made the unsuccessful
5588 * attempt to retrieve the shadow password. */
5590 if (spwent && spwent->sp_pwdp)
5591 sv_setpv(sv, spwent->sp_pwdp);
5595 if (!SvPOK(sv)) /* Use the standard password, then. */
5596 sv_setpv(sv, pwent->pw_passwd);
5599 /* passwd is tainted because user himself can diddle with it.
5600 * admittedly not much and in a very limited way, but nevertheless. */
5603 sv_setuid(PUSHmortal, pwent->pw_uid);
5604 sv_setgid(PUSHmortal, pwent->pw_gid);
5606 /* pw_change, pw_quota, and pw_age are mutually exclusive--
5607 * because of the poor interface of the Perl getpw*(),
5608 * not because there's some standard/convention saying so.
5609 * A better interface would have been to return a hash,
5610 * but we are accursed by our history, alas. --jhi. */
5612 mPUSHi(pwent->pw_change);
5613 # elif defined(PWQUOTA)
5614 mPUSHi(pwent->pw_quota);
5615 # elif defined(PWAGE)
5616 mPUSHs(newSVpv(pwent->pw_age, 0));
5618 /* I think that you can never get this compiled, but just in case. */
5619 PUSHs(sv_mortalcopy(&PL_sv_no));
5622 /* pw_class and pw_comment are mutually exclusive--.
5623 * see the above note for pw_change, pw_quota, and pw_age. */
5625 mPUSHs(newSVpv(pwent->pw_class, 0));
5626 # elif defined(PWCOMMENT)
5627 mPUSHs(newSVpv(pwent->pw_comment, 0));
5629 /* I think that you can never get this compiled, but just in case. */
5630 PUSHs(sv_mortalcopy(&PL_sv_no));
5634 PUSHs(sv = newSVpvn_flags(pwent->pw_gecos,
5635 pwent->pw_gecos == NULL ? 0 : strlen(pwent->pw_gecos),
5638 PUSHs(sv = sv_mortalcopy(&PL_sv_no));
5640 /* pw_gecos is tainted because user himself can diddle with it. */
5643 mPUSHs(newSVpv(pwent->pw_dir, 0));
5645 PUSHs(sv = newSVpvn_flags(pwent->pw_shell,
5646 pwent->pw_shell == NULL ? 0 : strlen(pwent->pw_shell),
5648 /* pw_shell is tainted because user himself can diddle with it. */
5652 mPUSHi(pwent->pw_expire);
5657 DIE(aTHX_ PL_no_func, PL_op_desc[PL_op->op_type]);
5662 /* also used for: pp_ggrgid() pp_ggrnam() */
5668 const I32 which = PL_op->op_type;
5669 const struct group *grent;
5671 if (which == OP_GGRNAM) {
5672 const char* const name = POPpbytex;
5673 grent = (const struct group *)getgrnam(name);
5675 else if (which == OP_GGRGID) {
5677 const Gid_t gid = POPu;
5678 #elif Gid_t_sign == -1
5679 const Gid_t gid = POPi;
5681 # error "Unexpected Gid_t_sign"
5683 grent = (const struct group *)getgrgid(gid);
5687 grent = (struct group *)getgrent();
5689 DIE(aTHX_ PL_no_func, "getgrent");
5693 if (GIMME_V != G_LIST) {
5694 SV * const sv = sv_newmortal();
5698 if (which == OP_GGRNAM)
5699 sv_setgid(sv, grent->gr_gid);
5701 sv_setpv(sv, grent->gr_name);
5707 mPUSHs(newSVpv(grent->gr_name, 0));
5710 mPUSHs(newSVpv(grent->gr_passwd, 0));
5712 PUSHs(sv_mortalcopy(&PL_sv_no));
5715 sv_setgid(PUSHmortal, grent->gr_gid);
5717 #if !(defined(_CRAYMPP) && defined(USE_REENTRANT_API))
5718 /* In UNICOS/mk (_CRAYMPP) the multithreading
5719 * versions (getgrnam_r, getgrgid_r)
5720 * seem to return an illegal pointer
5721 * as the group members list, gr_mem.
5722 * getgrent() doesn't even have a _r version
5723 * but the gr_mem is poisonous anyway.
5724 * So yes, you cannot get the list of group
5725 * members if building multithreaded in UNICOS/mk. */
5726 PUSHs(space_join_names_mortal(grent->gr_mem));
5732 DIE(aTHX_ PL_no_func, PL_op_desc[PL_op->op_type]);
5742 if (!(tmps = PerlProc_getlogin()))
5744 sv_setpv_mg(TARG, tmps);
5748 DIE(aTHX_ PL_no_func, "getlogin");
5752 /* Miscellaneous. */
5757 dSP; dMARK; dORIGMARK; dTARGET;
5758 I32 items = SP - MARK;
5759 unsigned long a[20];
5764 while (++MARK <= SP) {
5765 if (SvTAINTED(*MARK)) {
5771 TAINT_PROPER("syscall");
5774 /* This probably won't work on machines where sizeof(long) != sizeof(int)
5775 * or where sizeof(long) != sizeof(char*). But such machines will
5776 * not likely have syscall implemented either, so who cares?
5778 while (++MARK <= SP) {
5779 if (SvNIOK(*MARK) || !i)
5780 a[i++] = SvIV(*MARK);
5781 else if (*MARK == &PL_sv_undef)
5784 a[i++] = (unsigned long)SvPV_force_nolen(*MARK);
5790 DIE(aTHX_ "Too many args to syscall");
5792 DIE(aTHX_ "Too few args to syscall");
5794 retval = syscall(a[0]);
5797 retval = syscall(a[0],a[1]);
5800 retval = syscall(a[0],a[1],a[2]);
5803 retval = syscall(a[0],a[1],a[2],a[3]);
5806 retval = syscall(a[0],a[1],a[2],a[3],a[4]);
5809 retval = syscall(a[0],a[1],a[2],a[3],a[4],a[5]);
5812 retval = syscall(a[0],a[1],a[2],a[3],a[4],a[5],a[6]);
5815 retval = syscall(a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7]);
5822 DIE(aTHX_ PL_no_func, "syscall");
5826 #ifdef FCNTL_EMULATE_FLOCK
5828 /* XXX Emulate flock() with fcntl().
5829 What's really needed is a good file locking module.
5833 fcntl_emulate_flock(int fd, int operation)
5838 switch (operation & ~LOCK_NB) {
5840 flock.l_type = F_RDLCK;
5843 flock.l_type = F_WRLCK;
5846 flock.l_type = F_UNLCK;
5852 flock.l_whence = SEEK_SET;
5853 flock.l_start = flock.l_len = (Off_t)0;
5855 res = fcntl(fd, (operation & LOCK_NB) ? F_SETLK : F_SETLKW, &flock);
5856 if (res == -1 && ((errno == EAGAIN) || (errno == EACCES)))
5857 errno = EWOULDBLOCK;
5861 #endif /* FCNTL_EMULATE_FLOCK */
5863 #ifdef LOCKF_EMULATE_FLOCK
5865 /* XXX Emulate flock() with lockf(). This is just to increase
5866 portability of scripts. The calls are not completely
5867 interchangeable. What's really needed is a good file
5871 /* The lockf() constants might have been defined in <unistd.h>.
5872 Unfortunately, <unistd.h> causes troubles on some mixed
5873 (BSD/POSIX) systems, such as SunOS 4.1.3.
5875 Further, the lockf() constants aren't POSIX, so they might not be
5876 visible if we're compiling with _POSIX_SOURCE defined. Thus, we'll
5877 just stick in the SVID values and be done with it. Sigh.
5881 # define F_ULOCK 0 /* Unlock a previously locked region */
5884 # define F_LOCK 1 /* Lock a region for exclusive use */
5887 # define F_TLOCK 2 /* Test and lock a region for exclusive use */
5890 # define F_TEST 3 /* Test a region for other processes locks */
5894 lockf_emulate_flock(int fd, int operation)
5900 /* flock locks entire file so for lockf we need to do the same */
5901 pos = PerlLIO_lseek(fd, (Off_t)0, SEEK_CUR); /* get pos to restore later */
5902 if (pos > 0) /* is seekable and needs to be repositioned */
5903 if (PerlLIO_lseek(fd, (Off_t)0, SEEK_SET) < 0)
5904 pos = -1; /* seek failed, so don't seek back afterwards */
5907 switch (operation) {
5909 /* LOCK_SH - get a shared lock */
5911 /* LOCK_EX - get an exclusive lock */
5913 i = lockf (fd, F_LOCK, 0);
5916 /* LOCK_SH|LOCK_NB - get a non-blocking shared lock */
5917 case LOCK_SH|LOCK_NB:
5918 /* LOCK_EX|LOCK_NB - get a non-blocking exclusive lock */
5919 case LOCK_EX|LOCK_NB:
5920 i = lockf (fd, F_TLOCK, 0);
5922 if ((errno == EAGAIN) || (errno == EACCES))
5923 errno = EWOULDBLOCK;
5926 /* LOCK_UN - unlock (non-blocking is a no-op) */
5928 case LOCK_UN|LOCK_NB:
5929 i = lockf (fd, F_ULOCK, 0);
5932 /* Default - can't decipher operation */
5939 if (pos > 0) /* need to restore position of the handle */
5940 PerlLIO_lseek(fd, pos, SEEK_SET); /* ignore error here */
5945 #endif /* LOCKF_EMULATE_FLOCK */
5948 * ex: set ts=8 sts=4 sw=4 et: