3 * Copyright (c) 1991-2002, Larry Wall
5 * You may distribute under the terms of either the GNU General Public
6 * License or the Artistic License, as specified in the README file.
11 * "Very useful, no doubt, that was to Saruman; yet it seems that he was
12 * not content." --Gandalf
16 #define PERL_IN_UTIL_C
20 #if !defined(NSIG) || defined(M_UNIX) || defined(M_XENIX)
25 # define SIG_ERR ((Sighandler_t) -1)
30 # include <sys/wait.h>
35 # include <sys/select.h>
41 #if defined(HAS_FCNTL) && defined(F_SETFD) && !defined(FD_CLOEXEC)
42 # define FD_CLOEXEC 1 /* NeXT needs this */
45 /* NOTE: Do not call the next three routines directly. Use the macros
46 * in handy.h, so that we can easily redefine everything to do tracking of
47 * allocated hunks back to the original New to track down any memory leaks.
48 * XXX This advice seems to be widely ignored :-( --AD August 1996.
51 /* paranoid version of system's malloc() */
54 Perl_safesysmalloc(MEM_SIZE size)
60 PerlIO_printf(Perl_error_log,
61 "Allocation too large: %lx\n", size) FLUSH;
64 #endif /* HAS_64K_LIMIT */
67 Perl_croak_nocontext("panic: malloc");
69 ptr = (Malloc_t)PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
70 PERL_ALLOC_CHECK(ptr);
71 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) malloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
77 PerlIO_puts(Perl_error_log,PL_no_mem) FLUSH;
84 /* paranoid version of system's realloc() */
87 Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
91 #if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) && !defined(PERL_MICRO)
92 Malloc_t PerlMem_realloc();
93 #endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
97 PerlIO_printf(Perl_error_log,
98 "Reallocation too large: %lx\n", size) FLUSH;
101 #endif /* HAS_64K_LIMIT */
108 return safesysmalloc(size);
111 Perl_croak_nocontext("panic: realloc");
113 ptr = (Malloc_t)PerlMem_realloc(where,size);
114 PERL_ALLOC_CHECK(ptr);
116 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) rfree\n",PTR2UV(where),(long)PL_an++));
117 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) realloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
124 PerlIO_puts(Perl_error_log,PL_no_mem) FLUSH;
131 /* safe version of system's free() */
134 Perl_safesysfree(Malloc_t where)
136 #ifdef PERL_IMPLICIT_SYS
139 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) free\n",PTR2UV(where),(long)PL_an++));
146 /* safe version of system's calloc() */
149 Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
155 if (size * count > 0xffff) {
156 PerlIO_printf(Perl_error_log,
157 "Allocation too large: %lx\n", size * count) FLUSH;
160 #endif /* HAS_64K_LIMIT */
162 if ((long)size < 0 || (long)count < 0)
163 Perl_croak_nocontext("panic: calloc");
166 ptr = (Malloc_t)PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
167 PERL_ALLOC_CHECK(ptr);
168 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) calloc %ld x %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)count,(long)size));
170 memset((void*)ptr, 0, size);
176 PerlIO_puts(Perl_error_log,PL_no_mem) FLUSH;
183 /* These must be defined when not using Perl's malloc for binary
188 Malloc_t Perl_malloc (MEM_SIZE nbytes)
191 return (Malloc_t)PerlMem_malloc(nbytes);
194 Malloc_t Perl_calloc (MEM_SIZE elements, MEM_SIZE size)
197 return (Malloc_t)PerlMem_calloc(elements, size);
200 Malloc_t Perl_realloc (Malloc_t where, MEM_SIZE nbytes)
203 return (Malloc_t)PerlMem_realloc(where, nbytes);
206 Free_t Perl_mfree (Malloc_t where)
214 /* copy a string up to some (non-backslashed) delimiter, if any */
217 Perl_delimcpy(pTHX_ register char *to, register char *toend, register char *from, register char *fromend, register int delim, I32 *retlen)
220 for (tolen = 0; from < fromend; from++, tolen++) {
222 if (from[1] == delim)
231 else if (*from == delim)
242 /* return ptr to little string in big string, NULL if not found */
243 /* This routine was donated by Corey Satten. */
246 Perl_instr(pTHX_ register const char *big, register const char *little)
248 register const char *s, *x;
259 for (x=big,s=little; *s; /**/ ) {
268 return (char*)(big-1);
273 /* same as instr but allow embedded nulls */
276 Perl_ninstr(pTHX_ register const char *big, register const char *bigend, const char *little, const char *lend)
278 register const char *s, *x;
279 register I32 first = *little;
280 register const char *littleend = lend;
282 if (!first && little >= littleend)
284 if (bigend - big < littleend - little)
286 bigend -= littleend - little++;
287 while (big <= bigend) {
290 for (x=big,s=little; s < littleend; /**/ ) {
297 return (char*)(big-1);
302 /* reverse of the above--find last substring */
305 Perl_rninstr(pTHX_ register const char *big, const char *bigend, const char *little, const char *lend)
307 register const char *bigbeg;
308 register const char *s, *x;
309 register I32 first = *little;
310 register const char *littleend = lend;
312 if (!first && little >= littleend)
313 return (char*)bigend;
315 big = bigend - (littleend - little++);
316 while (big >= bigbeg) {
319 for (x=big+2,s=little; s < littleend; /**/ ) {
326 return (char*)(big+1);
331 #define FBM_TABLE_OFFSET 2 /* Number of bytes between EOS and table*/
333 /* As a space optimization, we do not compile tables for strings of length
334 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
335 special-cased in fbm_instr().
337 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
340 =head1 Miscellaneous Functions
342 =for apidoc fbm_compile
344 Analyses the string in order to make fast searches on it using fbm_instr()
345 -- the Boyer-Moore algorithm.
351 Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
360 if (flags & FBMcf_TAIL)
361 sv_catpvn(sv, "\n", 1); /* Taken into account in fbm_instr() */
362 s = (U8*)SvPV_force(sv, len);
363 (void)SvUPGRADE(sv, SVt_PVBM);
364 if (len == 0) /* TAIL might be on a zero-length string. */
374 Sv_Grow(sv, len + 256 + FBM_TABLE_OFFSET);
375 table = (unsigned char*)(SvPVX(sv) + len + FBM_TABLE_OFFSET);
376 s = table - 1 - FBM_TABLE_OFFSET; /* last char */
377 memset((void*)table, mlen, 256);
378 table[-1] = (U8)flags;
380 sb = s - mlen + 1; /* first char (maybe) */
382 if (table[*s] == mlen)
387 sv_magic(sv, Nullsv, PERL_MAGIC_bm, Nullch, 0); /* deep magic */
390 s = (unsigned char*)(SvPVX(sv)); /* deeper magic */
391 for (i = 0; i < len; i++) {
392 if (PL_freq[s[i]] < frequency) {
394 frequency = PL_freq[s[i]];
397 BmRARE(sv) = s[rarest];
398 BmPREVIOUS(sv) = (U16)rarest;
399 BmUSEFUL(sv) = 100; /* Initial value */
400 if (flags & FBMcf_TAIL)
402 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %d\n",
403 BmRARE(sv),BmPREVIOUS(sv)));
406 /* If SvTAIL(littlestr), it has a fake '\n' at end. */
407 /* If SvTAIL is actually due to \Z or \z, this gives false positives
411 =for apidoc fbm_instr
413 Returns the location of the SV in the string delimited by C<str> and
414 C<strend>. It returns C<Nullch> if the string can't be found. The C<sv>
415 does not have to be fbm_compiled, but the search will not be as fast
422 Perl_fbm_instr(pTHX_ unsigned char *big, register unsigned char *bigend, SV *littlestr, U32 flags)
424 register unsigned char *s;
426 register unsigned char *little = (unsigned char *)SvPV(littlestr,l);
427 register STRLEN littlelen = l;
428 register I32 multiline = flags & FBMrf_MULTILINE;
430 if ((STRLEN)(bigend - big) < littlelen) {
431 if ( SvTAIL(littlestr)
432 && ((STRLEN)(bigend - big) == littlelen - 1)
434 || (*big == *little &&
435 memEQ((char *)big, (char *)little, littlelen - 1))))
440 if (littlelen <= 2) { /* Special-cased */
442 if (littlelen == 1) {
443 if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
444 /* Know that bigend != big. */
445 if (bigend[-1] == '\n')
446 return (char *)(bigend - 1);
447 return (char *) bigend;
455 if (SvTAIL(littlestr))
456 return (char *) bigend;
460 return (char*)big; /* Cannot be SvTAIL! */
463 if (SvTAIL(littlestr) && !multiline) {
464 if (bigend[-1] == '\n' && bigend[-2] == *little)
465 return (char*)bigend - 2;
466 if (bigend[-1] == *little)
467 return (char*)bigend - 1;
471 /* This should be better than FBM if c1 == c2, and almost
472 as good otherwise: maybe better since we do less indirection.
473 And we save a lot of memory by caching no table. */
474 register unsigned char c1 = little[0];
475 register unsigned char c2 = little[1];
480 while (s <= bigend) {
490 goto check_1char_anchor;
501 goto check_1char_anchor;
504 while (s <= bigend) {
509 goto check_1char_anchor;
518 check_1char_anchor: /* One char and anchor! */
519 if (SvTAIL(littlestr) && (*bigend == *little))
520 return (char *)bigend; /* bigend is already decremented. */
523 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
524 s = bigend - littlelen;
525 if (s >= big && bigend[-1] == '\n' && *s == *little
526 /* Automatically of length > 2 */
527 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
529 return (char*)s; /* how sweet it is */
532 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
534 return (char*)s + 1; /* how sweet it is */
538 if (SvTYPE(littlestr) != SVt_PVBM || !SvVALID(littlestr)) {
539 char *b = ninstr((char*)big,(char*)bigend,
540 (char*)little, (char*)little + littlelen);
542 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
543 /* Chop \n from littlestr: */
544 s = bigend - littlelen + 1;
546 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
555 { /* Do actual FBM. */
556 register unsigned char *table = little + littlelen + FBM_TABLE_OFFSET;
557 register unsigned char *oldlittle;
559 if (littlelen > (STRLEN)(bigend - big))
561 --littlelen; /* Last char found by table lookup */
564 little += littlelen; /* last char */
571 if ((tmp = table[*s])) {
572 if ((s += tmp) < bigend)
576 else { /* less expensive than calling strncmp() */
577 register unsigned char *olds = s;
582 if (*--s == *--little)
584 s = olds + 1; /* here we pay the price for failure */
586 if (s < bigend) /* fake up continue to outer loop */
594 if ( s == bigend && (table[-1] & FBMcf_TAIL)
595 && memEQ((char *)(bigend - littlelen),
596 (char *)(oldlittle - littlelen), littlelen) )
597 return (char*)bigend - littlelen;
602 /* start_shift, end_shift are positive quantities which give offsets
603 of ends of some substring of bigstr.
604 If `last' we want the last occurrence.
605 old_posp is the way of communication between consequent calls if
606 the next call needs to find the .
607 The initial *old_posp should be -1.
609 Note that we take into account SvTAIL, so one can get extra
610 optimizations if _ALL flag is set.
613 /* If SvTAIL is actually due to \Z or \z, this gives false positives
614 if PL_multiline. In fact if !PL_multiline the authoritative answer
615 is not supported yet. */
618 Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
620 register unsigned char *s, *x;
621 register unsigned char *big;
623 register I32 previous;
625 register unsigned char *little;
626 register I32 stop_pos;
627 register unsigned char *littleend;
631 ? (pos = PL_screamfirst[BmRARE(littlestr)]) < 0
632 : (((pos = *old_posp), pos += PL_screamnext[pos]) == 0)) {
634 if ( BmRARE(littlestr) == '\n'
635 && BmPREVIOUS(littlestr) == SvCUR(littlestr) - 1) {
636 little = (unsigned char *)(SvPVX(littlestr));
637 littleend = little + SvCUR(littlestr);
644 little = (unsigned char *)(SvPVX(littlestr));
645 littleend = little + SvCUR(littlestr);
647 /* The value of pos we can start at: */
648 previous = BmPREVIOUS(littlestr);
649 big = (unsigned char *)(SvPVX(bigstr));
650 /* The value of pos we can stop at: */
651 stop_pos = SvCUR(bigstr) - end_shift - (SvCUR(littlestr) - 1 - previous);
652 if (previous + start_shift > stop_pos) {
654 stop_pos does not include SvTAIL in the count, so this check is incorrect
655 (I think) - see [ID 20010618.006] and t/op/study.t. HVDS 2001/06/19
658 if (previous + start_shift == stop_pos + 1) /* A fake '\n'? */
663 while (pos < previous + start_shift) {
664 if (!(pos += PL_screamnext[pos]))
669 if (pos >= stop_pos) break;
670 if (big[pos] != first)
672 for (x=big+pos+1,s=little; s < littleend; /**/ ) {
678 if (s == littleend) {
680 if (!last) return (char *)(big+pos);
683 } while ( pos += PL_screamnext[pos] );
685 return (char *)(big+(*old_posp));
687 if (!SvTAIL(littlestr) || (end_shift > 0))
689 /* Ignore the trailing "\n". This code is not microoptimized */
690 big = (unsigned char *)(SvPVX(bigstr) + SvCUR(bigstr));
691 stop_pos = littleend - little; /* Actual littlestr len */
696 && ((stop_pos == 1) ||
697 memEQ((char *)(big + 1), (char *)little, stop_pos - 1)))
703 Perl_ibcmp(pTHX_ const char *s1, const char *s2, register I32 len)
705 register U8 *a = (U8 *)s1;
706 register U8 *b = (U8 *)s2;
708 if (*a != *b && *a != PL_fold[*b])
716 Perl_ibcmp_locale(pTHX_ const char *s1, const char *s2, register I32 len)
718 register U8 *a = (U8 *)s1;
719 register U8 *b = (U8 *)s2;
721 if (*a != *b && *a != PL_fold_locale[*b])
728 /* copy a string to a safe spot */
731 =head1 Memory Management
735 Perl's version of C<strdup()>. Returns a pointer to a newly allocated
736 string which is a duplicate of C<pv>. The size of the string is
737 determined by C<strlen()>. The memory allocated for the new string can
738 be freed with the C<Safefree()> function.
744 Perl_savepv(pTHX_ const char *pv)
746 register char *newaddr = Nullch;
748 New(902,newaddr,strlen(pv)+1,char);
749 (void)strcpy(newaddr,pv);
754 /* same thing but with a known length */
759 Perl's version of what C<strndup()> would be if it existed. Returns a
760 pointer to a newly allocated string which is a duplicate of the first
761 C<len> bytes from C<pv>. The memory allocated for the new string can be
762 freed with the C<Safefree()> function.
768 Perl_savepvn(pTHX_ const char *pv, register I32 len)
770 register char *newaddr;
772 New(903,newaddr,len+1,char);
773 /* Give a meaning to NULL pointer mainly for the use in sv_magic() */
775 Copy(pv,newaddr,len,char); /* might not be null terminated */
776 newaddr[len] = '\0'; /* is now */
779 Zero(newaddr,len+1,char);
785 =for apidoc savesharedpv
787 A version of C<savepv()> which allocates the duplicate string in memory
788 which is shared between threads.
793 Perl_savesharedpv(pTHX_ const char *pv)
795 register char *newaddr = Nullch;
797 newaddr = (char*)PerlMemShared_malloc(strlen(pv)+1);
798 (void)strcpy(newaddr,pv);
805 /* the SV for Perl_form() and mess() is not kept in an arena */
814 return sv_2mortal(newSVpvn("",0));
819 /* Create as PVMG now, to avoid any upgrading later */
821 Newz(905, any, 1, XPVMG);
822 SvFLAGS(sv) = SVt_PVMG;
823 SvANY(sv) = (void*)any;
824 SvREFCNT(sv) = 1 << 30; /* practically infinite */
829 #if defined(PERL_IMPLICIT_CONTEXT)
831 Perl_form_nocontext(const char* pat, ...)
837 retval = vform(pat, &args);
841 #endif /* PERL_IMPLICIT_CONTEXT */
844 =head1 Miscellaneous Functions
847 Takes a sprintf-style format pattern and conventional
848 (non-SV) arguments and returns the formatted string.
850 (char *) Perl_form(pTHX_ const char* pat, ...)
852 can be used any place a string (char *) is required:
854 char * s = Perl_form("%d.%d",major,minor);
856 Uses a single private buffer so if you want to format several strings you
857 must explicitly copy the earlier strings away (and free the copies when you
864 Perl_form(pTHX_ const char* pat, ...)
869 retval = vform(pat, &args);
875 Perl_vform(pTHX_ const char *pat, va_list *args)
877 SV *sv = mess_alloc();
878 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
882 #if defined(PERL_IMPLICIT_CONTEXT)
884 Perl_mess_nocontext(const char *pat, ...)
890 retval = vmess(pat, &args);
894 #endif /* PERL_IMPLICIT_CONTEXT */
897 Perl_mess(pTHX_ const char *pat, ...)
902 retval = vmess(pat, &args);
908 S_closest_cop(pTHX_ COP *cop, OP *o)
910 /* Look for PL_op starting from o. cop is the last COP we've seen. */
912 if (!o || o == PL_op) return cop;
914 if (o->op_flags & OPf_KIDS) {
916 for (kid = cUNOPo->op_first; kid; kid = kid->op_sibling)
920 /* If the OP_NEXTSTATE has been optimised away we can still use it
921 * the get the file and line number. */
923 if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
926 /* Keep searching, and return when we've found something. */
928 new_cop = closest_cop(cop, kid);
929 if (new_cop) return new_cop;
939 Perl_vmess(pTHX_ const char *pat, va_list *args)
941 SV *sv = mess_alloc();
942 static char dgd[] = " during global destruction.\n";
945 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
946 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
949 * Try and find the file and line for PL_op. This will usually be
950 * PL_curcop, but it might be a cop that has been optimised away. We
951 * can try to find such a cop by searching through the optree starting
952 * from the sibling of PL_curcop.
955 cop = closest_cop(PL_curcop, PL_curcop->op_sibling);
956 if (!cop) cop = PL_curcop;
959 Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
960 OutCopFILE(cop), (IV)CopLINE(cop));
961 if (GvIO(PL_last_in_gv) && IoLINES(GvIOp(PL_last_in_gv))) {
962 bool line_mode = (RsSIMPLE(PL_rs) &&
963 SvCUR(PL_rs) == 1 && *SvPVX(PL_rs) == '\n');
964 Perl_sv_catpvf(aTHX_ sv, ", <%s> %s %"IVdf,
965 PL_last_in_gv == PL_argvgv ?
966 "" : GvNAME(PL_last_in_gv),
967 line_mode ? "line" : "chunk",
968 (IV)IoLINES(GvIOp(PL_last_in_gv)));
970 sv_catpv(sv, PL_dirty ? dgd : ".\n");
976 Perl_vdie(pTHX_ const char* pat, va_list *args)
979 int was_in_eval = PL_in_eval;
986 DEBUG_S(PerlIO_printf(Perl_debug_log,
987 "%p: die: curstack = %p, mainstack = %p\n",
988 thr, PL_curstack, PL_mainstack));
991 msv = vmess(pat, args);
992 if (PL_errors && SvCUR(PL_errors)) {
993 sv_catsv(PL_errors, msv);
994 message = SvPV(PL_errors, msglen);
995 SvCUR_set(PL_errors, 0);
998 message = SvPV(msv,msglen);
1005 DEBUG_S(PerlIO_printf(Perl_debug_log,
1006 "%p: die: message = %s\ndiehook = %p\n",
1007 thr, message, PL_diehook));
1009 /* sv_2cv might call Perl_croak() */
1010 SV *olddiehook = PL_diehook;
1012 SAVESPTR(PL_diehook);
1013 PL_diehook = Nullsv;
1014 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1016 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1023 msg = newSVpvn(message, msglen);
1031 PUSHSTACKi(PERLSI_DIEHOOK);
1035 call_sv((SV*)cv, G_DISCARD);
1041 PL_restartop = die_where(message, msglen);
1042 DEBUG_S(PerlIO_printf(Perl_debug_log,
1043 "%p: die: restartop = %p, was_in_eval = %d, top_env = %p\n",
1044 thr, PL_restartop, was_in_eval, PL_top_env));
1045 if ((!PL_restartop && was_in_eval) || PL_top_env->je_prev)
1047 return PL_restartop;
1050 #if defined(PERL_IMPLICIT_CONTEXT)
1052 Perl_die_nocontext(const char* pat, ...)
1057 va_start(args, pat);
1058 o = vdie(pat, &args);
1062 #endif /* PERL_IMPLICIT_CONTEXT */
1065 Perl_die(pTHX_ const char* pat, ...)
1069 va_start(args, pat);
1070 o = vdie(pat, &args);
1076 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1086 msv = vmess(pat, args);
1087 if (PL_errors && SvCUR(PL_errors)) {
1088 sv_catsv(PL_errors, msv);
1089 message = SvPV(PL_errors, msglen);
1090 SvCUR_set(PL_errors, 0);
1093 message = SvPV(msv,msglen);
1100 DEBUG_S(PerlIO_printf(Perl_debug_log, "croak: 0x%"UVxf" %s",
1101 PTR2UV(thr), message));
1104 /* sv_2cv might call Perl_croak() */
1105 SV *olddiehook = PL_diehook;
1107 SAVESPTR(PL_diehook);
1108 PL_diehook = Nullsv;
1109 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1111 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1118 msg = newSVpvn(message, msglen);
1126 PUSHSTACKi(PERLSI_DIEHOOK);
1130 call_sv((SV*)cv, G_DISCARD);
1136 PL_restartop = die_where(message, msglen);
1140 message = SvPVx(ERRSV, msglen);
1144 /* SFIO can really mess with your errno */
1147 PerlIO *serr = Perl_error_log;
1149 PERL_WRITE_MSG_TO_CONSOLE(serr, message, msglen);
1150 (void)PerlIO_flush(serr);
1158 #if defined(PERL_IMPLICIT_CONTEXT)
1160 Perl_croak_nocontext(const char *pat, ...)
1164 va_start(args, pat);
1169 #endif /* PERL_IMPLICIT_CONTEXT */
1172 =head1 Warning and Dieing
1176 This is the XSUB-writer's interface to Perl's C<die> function.
1177 Normally use this function the same way you use the C C<printf>
1178 function. See C<warn>.
1180 If you want to throw an exception object, assign the object to
1181 C<$@> and then pass C<Nullch> to croak():
1183 errsv = get_sv("@", TRUE);
1184 sv_setsv(errsv, exception_object);
1191 Perl_croak(pTHX_ const char *pat, ...)
1194 va_start(args, pat);
1201 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1212 msv = vmess(pat, args);
1213 message = SvPV(msv, msglen);
1216 /* sv_2cv might call Perl_warn() */
1217 SV *oldwarnhook = PL_warnhook;
1219 SAVESPTR(PL_warnhook);
1220 PL_warnhook = Nullsv;
1221 cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1223 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1229 msg = newSVpvn(message, msglen);
1233 PUSHSTACKi(PERLSI_WARNHOOK);
1237 call_sv((SV*)cv, G_DISCARD);
1244 /* if STDERR is tied, use it instead */
1245 if (PL_stderrgv && (io = GvIOp(PL_stderrgv))
1246 && (mg = SvTIED_mg((SV*)io, PERL_MAGIC_tiedscalar))) {
1249 XPUSHs(SvTIED_obj((SV*)io, mg));
1250 XPUSHs(sv_2mortal(newSVpvn(message, msglen)));
1252 call_method("PRINT", G_SCALAR);
1258 PerlIO *serr = Perl_error_log;
1260 PERL_WRITE_MSG_TO_CONSOLE(serr, message, msglen);
1261 (void)PerlIO_flush(serr);
1265 #if defined(PERL_IMPLICIT_CONTEXT)
1267 Perl_warn_nocontext(const char *pat, ...)
1271 va_start(args, pat);
1275 #endif /* PERL_IMPLICIT_CONTEXT */
1280 This is the XSUB-writer's interface to Perl's C<warn> function. Use this
1281 function the same way you use the C C<printf> function. See
1288 Perl_warn(pTHX_ const char *pat, ...)
1291 va_start(args, pat);
1296 #if defined(PERL_IMPLICIT_CONTEXT)
1298 Perl_warner_nocontext(U32 err, const char *pat, ...)
1302 va_start(args, pat);
1303 vwarner(err, pat, &args);
1306 #endif /* PERL_IMPLICIT_CONTEXT */
1309 Perl_warner(pTHX_ U32 err, const char* pat,...)
1312 va_start(args, pat);
1313 vwarner(err, pat, &args);
1318 Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1327 msv = vmess(pat, args);
1328 message = SvPV(msv, msglen);
1332 /* sv_2cv might call Perl_croak() */
1333 SV *olddiehook = PL_diehook;
1335 SAVESPTR(PL_diehook);
1336 PL_diehook = Nullsv;
1337 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1339 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1345 msg = newSVpvn(message, msglen);
1349 PUSHSTACKi(PERLSI_DIEHOOK);
1353 call_sv((SV*)cv, G_DISCARD);
1359 PL_restartop = die_where(message, msglen);
1363 PerlIO *serr = Perl_error_log;
1364 PERL_WRITE_MSG_TO_CONSOLE(serr, message, msglen);
1365 (void)PerlIO_flush(serr);
1371 /* sv_2cv might call Perl_warn() */
1372 SV *oldwarnhook = PL_warnhook;
1374 SAVESPTR(PL_warnhook);
1375 PL_warnhook = Nullsv;
1376 cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1378 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1384 msg = newSVpvn(message, msglen);
1388 PUSHSTACKi(PERLSI_WARNHOOK);
1392 call_sv((SV*)cv, G_DISCARD);
1399 PerlIO *serr = Perl_error_log;
1400 PERL_WRITE_MSG_TO_CONSOLE(serr, message, msglen);
1401 (void)PerlIO_flush(serr);
1406 /* since we've already done strlen() for both nam and val
1407 * we can use that info to make things faster than
1408 * sprintf(s, "%s=%s", nam, val)
1410 #define my_setenv_format(s, nam, nlen, val, vlen) \
1411 Copy(nam, s, nlen, char); \
1413 Copy(val, s+(nlen+1), vlen, char); \
1414 *(s+(nlen+1+vlen)) = '\0'
1416 #ifdef USE_ENVIRON_ARRAY
1417 /* VMS' my_setenv() is in vms.c */
1418 #if !defined(WIN32) && !defined(NETWARE)
1420 Perl_my_setenv(pTHX_ char *nam, char *val)
1423 /* only parent thread can modify process environment */
1424 if (PL_curinterp == aTHX)
1427 #ifndef PERL_USE_SAFE_PUTENV
1428 /* most putenv()s leak, so we manipulate environ directly */
1429 register I32 i=setenv_getix(nam); /* where does it go? */
1432 if (environ == PL_origenviron) { /* need we copy environment? */
1438 for (max = i; environ[max]; max++) ;
1439 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
1440 for (j=0; j<max; j++) { /* copy environment */
1441 int len = strlen(environ[j]);
1442 tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
1443 Copy(environ[j], tmpenv[j], len+1, char);
1445 tmpenv[max] = Nullch;
1446 environ = tmpenv; /* tell exec where it is now */
1449 safesysfree(environ[i]);
1450 while (environ[i]) {
1451 environ[i] = environ[i+1];
1456 if (!environ[i]) { /* does not exist yet */
1457 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
1458 environ[i+1] = Nullch; /* make sure it's null terminated */
1461 safesysfree(environ[i]);
1465 environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
1466 /* all that work just for this */
1467 my_setenv_format(environ[i], nam, nlen, val, vlen);
1469 #else /* PERL_USE_SAFE_PUTENV */
1470 # if defined(__CYGWIN__) || defined( EPOC)
1471 setenv(nam, val, 1);
1474 int nlen = strlen(nam), vlen;
1479 new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1480 /* all that work just for this */
1481 my_setenv_format(new_env, nam, nlen, val, vlen);
1482 (void)putenv(new_env);
1483 # endif /* __CYGWIN__ */
1484 #endif /* PERL_USE_SAFE_PUTENV */
1488 #else /* WIN32 || NETWARE */
1491 Perl_my_setenv(pTHX_ char *nam,char *val)
1493 register char *envstr;
1494 int nlen = strlen(nam), vlen;
1500 New(904, envstr, nlen+vlen+2, char);
1501 my_setenv_format(envstr, nam, nlen, val, vlen);
1502 (void)PerlEnv_putenv(envstr);
1506 #endif /* WIN32 || NETWARE */
1509 Perl_setenv_getix(pTHX_ char *nam)
1511 register I32 i, len = strlen(nam);
1513 for (i = 0; environ[i]; i++) {
1516 strnicmp(environ[i],nam,len) == 0
1518 strnEQ(environ[i],nam,len)
1520 && environ[i][len] == '=')
1521 break; /* strnEQ must come first to avoid */
1522 } /* potential SEGV's */
1526 #endif /* !VMS && !EPOC*/
1528 #ifdef UNLINK_ALL_VERSIONS
1530 Perl_unlnk(pTHX_ char *f) /* unlink all versions of a file */
1534 for (i = 0; PerlLIO_unlink(f) >= 0; i++) ;
1539 /* this is a drop-in replacement for bcopy() */
1540 #if (!defined(HAS_MEMCPY) && !defined(HAS_BCOPY)) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY) && !defined(HAS_SAFE_BCOPY))
1542 Perl_my_bcopy(register const char *from,register char *to,register I32 len)
1546 if (from - to >= 0) {
1554 *(--to) = *(--from);
1560 /* this is a drop-in replacement for memset() */
1563 Perl_my_memset(register char *loc, register I32 ch, register I32 len)
1573 /* this is a drop-in replacement for bzero() */
1574 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
1576 Perl_my_bzero(register char *loc, register I32 len)
1586 /* this is a drop-in replacement for memcmp() */
1587 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
1589 Perl_my_memcmp(const char *s1, const char *s2, register I32 len)
1591 register U8 *a = (U8 *)s1;
1592 register U8 *b = (U8 *)s2;
1596 if (tmp = *a++ - *b++)
1601 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
1605 #ifdef USE_CHAR_VSPRINTF
1610 vsprintf(char *dest, const char *pat, char *args)
1614 fakebuf._ptr = dest;
1615 fakebuf._cnt = 32767;
1619 fakebuf._flag = _IOWRT|_IOSTRG;
1620 _doprnt(pat, args, &fakebuf); /* what a kludge */
1621 (void)putc('\0', &fakebuf);
1622 #ifdef USE_CHAR_VSPRINTF
1625 return 0; /* perl doesn't use return value */
1629 #endif /* HAS_VPRINTF */
1632 #if BYTEORDER != 0x4321
1634 Perl_my_swap(pTHX_ short s)
1636 #if (BYTEORDER & 1) == 0
1639 result = ((s & 255) << 8) + ((s >> 8) & 255);
1647 Perl_my_htonl(pTHX_ long l)
1651 char c[sizeof(long)];
1654 #if BYTEORDER == 0x1234
1655 u.c[0] = (l >> 24) & 255;
1656 u.c[1] = (l >> 16) & 255;
1657 u.c[2] = (l >> 8) & 255;
1661 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1662 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
1667 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1668 u.c[o & 0xf] = (l >> s) & 255;
1676 Perl_my_ntohl(pTHX_ long l)
1680 char c[sizeof(long)];
1683 #if BYTEORDER == 0x1234
1684 u.c[0] = (l >> 24) & 255;
1685 u.c[1] = (l >> 16) & 255;
1686 u.c[2] = (l >> 8) & 255;
1690 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1691 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
1698 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1699 l |= (u.c[o & 0xf] & 255) << s;
1706 #endif /* BYTEORDER != 0x4321 */
1710 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
1711 * If these functions are defined,
1712 * the BYTEORDER is neither 0x1234 nor 0x4321.
1713 * However, this is not assumed.
1717 #define HTOV(name,type) \
1719 name (register type n) \
1723 char c[sizeof(type)]; \
1727 for (i = 0, s = 0; i < sizeof(u.c); i++, s += 8) { \
1728 u.c[i] = (n >> s) & 0xFF; \
1733 #define VTOH(name,type) \
1735 name (register type n) \
1739 char c[sizeof(type)]; \
1745 for (i = 0, s = 0; i < sizeof(u.c); i++, s += 8) { \
1746 n += (u.c[i] & 0xFF) << s; \
1751 #if defined(HAS_HTOVS) && !defined(htovs)
1754 #if defined(HAS_HTOVL) && !defined(htovl)
1757 #if defined(HAS_VTOHS) && !defined(vtohs)
1760 #if defined(HAS_VTOHL) && !defined(vtohl)
1765 Perl_my_popen_list(pTHX_ char *mode, int n, SV **args)
1767 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(OS2) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL) && !defined(NETWARE)
1769 register I32 This, that;
1775 PERL_FLUSHALL_FOR_CHILD;
1776 This = (*mode == 'w');
1780 taint_proper("Insecure %s%s", "EXEC");
1782 if (PerlProc_pipe(p) < 0)
1784 /* Try for another pipe pair for error return */
1785 if (PerlProc_pipe(pp) >= 0)
1787 while ((pid = PerlProc_fork()) < 0) {
1788 if (errno != EAGAIN) {
1789 PerlLIO_close(p[This]);
1790 PerlLIO_close(p[that]);
1792 PerlLIO_close(pp[0]);
1793 PerlLIO_close(pp[1]);
1805 /* Close parent's end of error status pipe (if any) */
1807 PerlLIO_close(pp[0]);
1808 #if defined(HAS_FCNTL) && defined(F_SETFD)
1809 /* Close error pipe automatically if exec works */
1810 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
1813 /* Now dup our end of _the_ pipe to right position */
1814 if (p[THIS] != (*mode == 'r')) {
1815 PerlLIO_dup2(p[THIS], *mode == 'r');
1816 PerlLIO_close(p[THIS]);
1817 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
1818 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
1821 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
1822 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
1823 /* No automatic close - do it by hand */
1830 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
1836 do_aexec5(Nullsv, args-1, args-1+n, pp[1], did_pipes);
1842 do_execfree(); /* free any memory malloced by child on fork */
1844 PerlLIO_close(pp[1]);
1845 /* Keep the lower of the two fd numbers */
1846 if (p[that] < p[This]) {
1847 PerlLIO_dup2(p[This], p[that]);
1848 PerlLIO_close(p[This]);
1852 PerlLIO_close(p[that]); /* close child's end of pipe */
1855 sv = *av_fetch(PL_fdpid,p[This],TRUE);
1857 (void)SvUPGRADE(sv,SVt_IV);
1859 PL_forkprocess = pid;
1860 /* If we managed to get status pipe check for exec fail */
1861 if (did_pipes && pid > 0) {
1865 while (n < sizeof(int)) {
1866 n1 = PerlLIO_read(pp[0],
1867 (void*)(((char*)&errkid)+n),
1873 PerlLIO_close(pp[0]);
1875 if (n) { /* Error */
1877 PerlLIO_close(p[This]);
1878 if (n != sizeof(int))
1879 Perl_croak(aTHX_ "panic: kid popen errno read");
1881 pid2 = wait4pid(pid, &status, 0);
1882 } while (pid2 == -1 && errno == EINTR);
1883 errno = errkid; /* Propagate errno from kid */
1888 PerlLIO_close(pp[0]);
1889 return PerlIO_fdopen(p[This], mode);
1891 Perl_croak(aTHX_ "List form of piped open not implemented");
1892 return (PerlIO *) NULL;
1896 /* VMS' my_popen() is in VMS.c, same with OS/2. */
1897 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
1899 Perl_my_popen(pTHX_ char *cmd, char *mode)
1902 register I32 This, that;
1905 I32 doexec = strNE(cmd,"-");
1909 PERL_FLUSHALL_FOR_CHILD;
1912 return my_syspopen(aTHX_ cmd,mode);
1915 This = (*mode == 'w');
1917 if (doexec && PL_tainting) {
1919 taint_proper("Insecure %s%s", "EXEC");
1921 if (PerlProc_pipe(p) < 0)
1923 if (doexec && PerlProc_pipe(pp) >= 0)
1925 while ((pid = PerlProc_fork()) < 0) {
1926 if (errno != EAGAIN) {
1927 PerlLIO_close(p[This]);
1928 PerlLIO_close(p[that]);
1930 PerlLIO_close(pp[0]);
1931 PerlLIO_close(pp[1]);
1934 Perl_croak(aTHX_ "Can't fork");
1947 PerlLIO_close(pp[0]);
1948 #if defined(HAS_FCNTL) && defined(F_SETFD)
1949 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
1952 if (p[THIS] != (*mode == 'r')) {
1953 PerlLIO_dup2(p[THIS], *mode == 'r');
1954 PerlLIO_close(p[THIS]);
1955 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
1956 PerlLIO_close(p[THAT]);
1959 PerlLIO_close(p[THAT]);
1962 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
1971 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
1976 /* may or may not use the shell */
1977 do_exec3(cmd, pp[1], did_pipes);
1980 #endif /* defined OS2 */
1982 if ((tmpgv = gv_fetchpv("$",TRUE, SVt_PV))) {
1983 SvREADONLY_off(GvSV(tmpgv));
1984 sv_setiv(GvSV(tmpgv), PerlProc_getpid());
1985 SvREADONLY_on(GvSV(tmpgv));
1987 #ifdef THREADS_HAVE_PIDS
1988 PL_ppid = (IV)getppid();
1991 hv_clear(PL_pidstatus); /* we have no children */
1996 do_execfree(); /* free any memory malloced by child on vfork */
1998 PerlLIO_close(pp[1]);
1999 if (p[that] < p[This]) {
2000 PerlLIO_dup2(p[This], p[that]);
2001 PerlLIO_close(p[This]);
2005 PerlLIO_close(p[that]);
2008 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2010 (void)SvUPGRADE(sv,SVt_IV);
2012 PL_forkprocess = pid;
2013 if (did_pipes && pid > 0) {
2017 while (n < sizeof(int)) {
2018 n1 = PerlLIO_read(pp[0],
2019 (void*)(((char*)&errkid)+n),
2025 PerlLIO_close(pp[0]);
2027 if (n) { /* Error */
2029 PerlLIO_close(p[This]);
2030 if (n != sizeof(int))
2031 Perl_croak(aTHX_ "panic: kid popen errno read");
2033 pid2 = wait4pid(pid, &status, 0);
2034 } while (pid2 == -1 && errno == EINTR);
2035 errno = errkid; /* Propagate errno from kid */
2040 PerlLIO_close(pp[0]);
2041 return PerlIO_fdopen(p[This], mode);
2044 #if defined(atarist) || defined(EPOC)
2047 Perl_my_popen(pTHX_ char *cmd, char *mode)
2049 PERL_FLUSHALL_FOR_CHILD;
2050 /* Call system's popen() to get a FILE *, then import it.
2051 used 0 for 2nd parameter to PerlIO_importFILE;
2054 return PerlIO_importFILE(popen(cmd, mode), 0);
2058 FILE *djgpp_popen();
2060 Perl_my_popen(pTHX_ char *cmd, char *mode)
2062 PERL_FLUSHALL_FOR_CHILD;
2063 /* Call system's popen() to get a FILE *, then import it.
2064 used 0 for 2nd parameter to PerlIO_importFILE;
2067 return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2072 #endif /* !DOSISH */
2074 /* this is called in parent before the fork() */
2076 Perl_atfork_lock(void)
2078 #if defined(USE_ITHREADS)
2079 /* locks must be held in locking order (if any) */
2081 MUTEX_LOCK(&PL_malloc_mutex);
2087 /* this is called in both parent and child after the fork() */
2089 Perl_atfork_unlock(void)
2091 #if defined(USE_ITHREADS)
2092 /* locks must be released in same order as in atfork_lock() */
2094 MUTEX_UNLOCK(&PL_malloc_mutex);
2103 #if defined(HAS_FORK)
2105 #if defined(USE_ITHREADS) && !defined(HAS_PTHREAD_ATFORK)
2110 /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2111 * handlers elsewhere in the code */
2116 /* this "canna happen" since nothing should be calling here if !HAS_FORK */
2117 Perl_croak_nocontext("fork() not available");
2119 #endif /* HAS_FORK */
2124 Perl_dump_fds(pTHX_ char *s)
2129 PerlIO_printf(Perl_debug_log,"%s", s);
2130 for (fd = 0; fd < 32; fd++) {
2131 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
2132 PerlIO_printf(Perl_debug_log," %d",fd);
2134 PerlIO_printf(Perl_debug_log,"\n");
2136 #endif /* DUMP_FDS */
2140 dup2(int oldfd, int newfd)
2142 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2145 PerlLIO_close(newfd);
2146 return fcntl(oldfd, F_DUPFD, newfd);
2148 #define DUP2_MAX_FDS 256
2149 int fdtmp[DUP2_MAX_FDS];
2155 PerlLIO_close(newfd);
2156 /* good enough for low fd's... */
2157 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2158 if (fdx >= DUP2_MAX_FDS) {
2166 PerlLIO_close(fdtmp[--fdx]);
2173 #ifdef HAS_SIGACTION
2175 #ifdef MACOS_TRADITIONAL
2176 /* We don't want restart behavior on MacOS */
2181 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2183 struct sigaction act, oact;
2186 /* only "parent" interpreter can diddle signals */
2187 if (PL_curinterp != aTHX)
2191 act.sa_handler = handler;
2192 sigemptyset(&act.sa_mask);
2195 #if defined(PERL_OLD_SIGNALS)
2196 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2200 if (signo == SIGCHLD && handler == (Sighandler_t)SIG_IGN)
2201 act.sa_flags |= SA_NOCLDWAIT;
2203 if (sigaction(signo, &act, &oact) == -1)
2206 return oact.sa_handler;
2210 Perl_rsignal_state(pTHX_ int signo)
2212 struct sigaction oact;
2214 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2217 return oact.sa_handler;
2221 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2223 struct sigaction act;
2226 /* only "parent" interpreter can diddle signals */
2227 if (PL_curinterp != aTHX)
2231 act.sa_handler = handler;
2232 sigemptyset(&act.sa_mask);
2235 #if defined(PERL_OLD_SIGNALS)
2236 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2240 if (signo == SIGCHLD && handler == (Sighandler_t)SIG_IGN)
2241 act.sa_flags |= SA_NOCLDWAIT;
2243 return sigaction(signo, &act, save);
2247 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2250 /* only "parent" interpreter can diddle signals */
2251 if (PL_curinterp != aTHX)
2255 return sigaction(signo, save, (struct sigaction *)NULL);
2258 #else /* !HAS_SIGACTION */
2261 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2263 #if defined(USE_ITHREADS) && !defined(WIN32)
2264 /* only "parent" interpreter can diddle signals */
2265 if (PL_curinterp != aTHX)
2269 return PerlProc_signal(signo, handler);
2272 static int sig_trapped; /* XXX signals are process-wide anyway, so we
2273 ignore the implications of this for threading */
2283 Perl_rsignal_state(pTHX_ int signo)
2285 Sighandler_t oldsig;
2287 #if defined(USE_ITHREADS) && !defined(WIN32)
2288 /* only "parent" interpreter can diddle signals */
2289 if (PL_curinterp != aTHX)
2294 oldsig = PerlProc_signal(signo, sig_trap);
2295 PerlProc_signal(signo, oldsig);
2297 PerlProc_kill(PerlProc_getpid(), signo);
2302 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2304 #if defined(USE_ITHREADS) && !defined(WIN32)
2305 /* only "parent" interpreter can diddle signals */
2306 if (PL_curinterp != aTHX)
2309 *save = PerlProc_signal(signo, handler);
2310 return (*save == SIG_ERR) ? -1 : 0;
2314 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2316 #if defined(USE_ITHREADS) && !defined(WIN32)
2317 /* only "parent" interpreter can diddle signals */
2318 if (PL_curinterp != aTHX)
2321 return (PerlProc_signal(signo, *save) == SIG_ERR) ? -1 : 0;
2324 #endif /* !HAS_SIGACTION */
2325 #endif /* !PERL_MICRO */
2327 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
2328 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
2330 Perl_my_pclose(pTHX_ PerlIO *ptr)
2332 Sigsave_t hstat, istat, qstat;
2338 int saved_errno = 0;
2340 int saved_vaxc_errno;
2343 int saved_win32_errno;
2347 svp = av_fetch(PL_fdpid,PerlIO_fileno(ptr),TRUE);
2349 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
2351 *svp = &PL_sv_undef;
2353 if (pid == -1) { /* Opened by popen. */
2354 return my_syspclose(ptr);
2357 if ((close_failed = (PerlIO_close(ptr) == EOF))) {
2358 saved_errno = errno;
2360 saved_vaxc_errno = vaxc$errno;
2363 saved_win32_errno = GetLastError();
2367 if(PerlProc_kill(pid, 0) < 0) { return(pid); } /* HOM 12/23/91 */
2370 rsignal_save(SIGHUP, SIG_IGN, &hstat);
2371 rsignal_save(SIGINT, SIG_IGN, &istat);
2372 rsignal_save(SIGQUIT, SIG_IGN, &qstat);
2375 pid2 = wait4pid(pid, &status, 0);
2376 } while (pid2 == -1 && errno == EINTR);
2378 rsignal_restore(SIGHUP, &hstat);
2379 rsignal_restore(SIGINT, &istat);
2380 rsignal_restore(SIGQUIT, &qstat);
2383 SETERRNO(saved_errno, saved_vaxc_errno);
2386 return(pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status));
2388 #endif /* !DOSISH */
2390 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(MACOS_TRADITIONAL)
2392 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
2397 #if !defined(HAS_WAITPID) && !defined(HAS_WAIT4) || defined(HAS_WAITPID_RUNTIME)
2401 char spid[TYPE_CHARS(int)];
2404 sprintf(spid, "%"IVdf, (IV)pid);
2405 svp = hv_fetch(PL_pidstatus,spid,strlen(spid),FALSE);
2406 if (svp && *svp != &PL_sv_undef) {
2407 *statusp = SvIVX(*svp);
2408 (void)hv_delete(PL_pidstatus,spid,strlen(spid),G_DISCARD);
2415 hv_iterinit(PL_pidstatus);
2416 if ((entry = hv_iternext(PL_pidstatus))) {
2418 char spid[TYPE_CHARS(int)];
2420 pid = atoi(hv_iterkey(entry,(I32*)statusp));
2421 sv = hv_iterval(PL_pidstatus,entry);
2422 *statusp = SvIVX(sv);
2423 sprintf(spid, "%"IVdf, (IV)pid);
2424 (void)hv_delete(PL_pidstatus,spid,strlen(spid),G_DISCARD);
2431 # ifdef HAS_WAITPID_RUNTIME
2432 if (!HAS_WAITPID_RUNTIME)
2435 result = PerlProc_waitpid(pid,statusp,flags);
2438 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
2439 result = wait4((pid==-1)?0:pid,statusp,flags,Null(struct rusage *));
2442 #if !defined(HAS_WAITPID) && !defined(HAS_WAIT4) || defined(HAS_WAITPID_RUNTIME)
2446 Perl_croak(aTHX_ "Can't do waitpid with flags");
2448 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
2449 pidgone(result,*statusp);
2456 if (result < 0 && errno == EINTR) {
2461 #endif /* !DOSISH || OS2 || WIN32 || NETWARE */
2465 Perl_pidgone(pTHX_ Pid_t pid, int status)
2468 char spid[TYPE_CHARS(int)];
2470 sprintf(spid, "%"IVdf, (IV)pid);
2471 sv = *hv_fetch(PL_pidstatus,spid,strlen(spid),TRUE);
2472 (void)SvUPGRADE(sv,SVt_IV);
2477 #if defined(atarist) || defined(OS2) || defined(EPOC)
2480 int /* Cannot prototype with I32
2482 my_syspclose(PerlIO *ptr)
2485 Perl_my_pclose(pTHX_ PerlIO *ptr)
2488 /* Needs work for PerlIO ! */
2489 FILE *f = PerlIO_findFILE(ptr);
2490 I32 result = pclose(f);
2491 PerlIO_releaseFILE(ptr,f);
2499 Perl_my_pclose(pTHX_ PerlIO *ptr)
2501 /* Needs work for PerlIO ! */
2502 FILE *f = PerlIO_findFILE(ptr);
2503 I32 result = djgpp_pclose(f);
2504 result = (result << 8) & 0xff00;
2505 PerlIO_releaseFILE(ptr,f);
2511 Perl_repeatcpy(pTHX_ register char *to, register const char *from, I32 len, register I32 count)
2514 register const char *frombase = from;
2517 register const char c = *from;
2522 while (count-- > 0) {
2523 for (todo = len; todo > 0; todo--) {
2532 Perl_same_dirent(pTHX_ char *a, char *b)
2534 char *fa = strrchr(a,'/');
2535 char *fb = strrchr(b,'/');
2538 SV *tmpsv = sv_newmortal();
2551 sv_setpv(tmpsv, ".");
2553 sv_setpvn(tmpsv, a, fa - a);
2554 if (PerlLIO_stat(SvPVX(tmpsv), &tmpstatbuf1) < 0)
2557 sv_setpv(tmpsv, ".");
2559 sv_setpvn(tmpsv, b, fb - b);
2560 if (PerlLIO_stat(SvPVX(tmpsv), &tmpstatbuf2) < 0)
2562 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
2563 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
2565 #endif /* !HAS_RENAME */
2568 Perl_find_script(pTHX_ char *scriptname, bool dosearch, char **search_ext, I32 flags)
2570 char *xfound = Nullch;
2571 char *xfailed = Nullch;
2572 char tmpbuf[MAXPATHLEN];
2576 #if defined(DOSISH) && !defined(OS2) && !defined(atarist)
2577 # define SEARCH_EXTS ".bat", ".cmd", NULL
2578 # define MAX_EXT_LEN 4
2581 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
2582 # define MAX_EXT_LEN 4
2585 # define SEARCH_EXTS ".pl", ".com", NULL
2586 # define MAX_EXT_LEN 4
2588 /* additional extensions to try in each dir if scriptname not found */
2590 char *exts[] = { SEARCH_EXTS };
2591 char **ext = search_ext ? search_ext : exts;
2592 int extidx = 0, i = 0;
2593 char *curext = Nullch;
2595 # define MAX_EXT_LEN 0
2599 * If dosearch is true and if scriptname does not contain path
2600 * delimiters, search the PATH for scriptname.
2602 * If SEARCH_EXTS is also defined, will look for each
2603 * scriptname{SEARCH_EXTS} whenever scriptname is not found
2604 * while searching the PATH.
2606 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
2607 * proceeds as follows:
2608 * If DOSISH or VMSISH:
2609 * + look for ./scriptname{,.foo,.bar}
2610 * + search the PATH for scriptname{,.foo,.bar}
2613 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
2614 * this will not look in '.' if it's not in the PATH)
2619 # ifdef ALWAYS_DEFTYPES
2620 len = strlen(scriptname);
2621 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
2622 int hasdir, idx = 0, deftypes = 1;
2625 hasdir = !dosearch || (strpbrk(scriptname,":[</") != Nullch) ;
2628 int hasdir, idx = 0, deftypes = 1;
2631 hasdir = (strpbrk(scriptname,":[</") != Nullch) ;
2633 /* The first time through, just add SEARCH_EXTS to whatever we
2634 * already have, so we can check for default file types. */
2636 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
2642 if ((strlen(tmpbuf) + strlen(scriptname)
2643 + MAX_EXT_LEN) >= sizeof tmpbuf)
2644 continue; /* don't search dir with too-long name */
2645 strcat(tmpbuf, scriptname);
2649 if (strEQ(scriptname, "-"))
2651 if (dosearch) { /* Look in '.' first. */
2652 char *cur = scriptname;
2654 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
2656 if (strEQ(ext[i++],curext)) {
2657 extidx = -1; /* already has an ext */
2662 DEBUG_p(PerlIO_printf(Perl_debug_log,
2663 "Looking for %s\n",cur));
2664 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
2665 && !S_ISDIR(PL_statbuf.st_mode)) {
2673 if (cur == scriptname) {
2674 len = strlen(scriptname);
2675 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
2677 cur = strcpy(tmpbuf, scriptname);
2679 } while (extidx >= 0 && ext[extidx] /* try an extension? */
2680 && strcpy(tmpbuf+len, ext[extidx++]));
2685 #ifdef MACOS_TRADITIONAL
2686 if (dosearch && !strchr(scriptname, ':') &&
2687 (s = PerlEnv_getenv("Commands")))
2689 if (dosearch && !strchr(scriptname, '/')
2691 && !strchr(scriptname, '\\')
2693 && (s = PerlEnv_getenv("PATH")))
2698 PL_bufend = s + strlen(s);
2699 while (s < PL_bufend) {
2700 #ifdef MACOS_TRADITIONAL
2701 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
2705 #if defined(atarist) || defined(DOSISH)
2710 && *s != ';'; len++, s++) {
2711 if (len < sizeof tmpbuf)
2714 if (len < sizeof tmpbuf)
2716 #else /* ! (atarist || DOSISH) */
2717 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
2720 #endif /* ! (atarist || DOSISH) */
2721 #endif /* MACOS_TRADITIONAL */
2724 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
2725 continue; /* don't search dir with too-long name */
2726 #ifdef MACOS_TRADITIONAL
2727 if (len && tmpbuf[len - 1] != ':')
2728 tmpbuf[len++] = ':';
2731 #if defined(atarist) || defined(__MINT__) || defined(DOSISH)
2732 && tmpbuf[len - 1] != '/'
2733 && tmpbuf[len - 1] != '\\'
2736 tmpbuf[len++] = '/';
2737 if (len == 2 && tmpbuf[0] == '.')
2740 (void)strcpy(tmpbuf + len, scriptname);
2744 len = strlen(tmpbuf);
2745 if (extidx > 0) /* reset after previous loop */
2749 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
2750 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
2751 if (S_ISDIR(PL_statbuf.st_mode)) {
2755 } while ( retval < 0 /* not there */
2756 && extidx>=0 && ext[extidx] /* try an extension? */
2757 && strcpy(tmpbuf+len, ext[extidx++])
2762 if (S_ISREG(PL_statbuf.st_mode)
2763 && cando(S_IRUSR,TRUE,&PL_statbuf)
2764 #if !defined(DOSISH) && !defined(MACOS_TRADITIONAL)
2765 && cando(S_IXUSR,TRUE,&PL_statbuf)
2769 xfound = tmpbuf; /* bingo! */
2773 xfailed = savepv(tmpbuf);
2776 if (!xfound && !seen_dot && !xfailed &&
2777 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
2778 || S_ISDIR(PL_statbuf.st_mode)))
2780 seen_dot = 1; /* Disable message. */
2782 if (flags & 1) { /* do or die? */
2783 Perl_croak(aTHX_ "Can't %s %s%s%s",
2784 (xfailed ? "execute" : "find"),
2785 (xfailed ? xfailed : scriptname),
2786 (xfailed ? "" : " on PATH"),
2787 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
2789 scriptname = Nullch;
2793 scriptname = xfound;
2795 return (scriptname ? savepv(scriptname) : Nullch);
2798 #ifndef PERL_GET_CONTEXT_DEFINED
2801 Perl_get_context(void)
2803 #if defined(USE_ITHREADS)
2804 # ifdef OLD_PTHREADS_API
2806 if (pthread_getspecific(PL_thr_key, &t))
2807 Perl_croak_nocontext("panic: pthread_getspecific");
2810 # ifdef I_MACH_CTHREADS
2811 return (void*)cthread_data(cthread_self());
2813 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
2822 Perl_set_context(void *t)
2824 #if defined(USE_ITHREADS)
2825 # ifdef I_MACH_CTHREADS
2826 cthread_set_data(cthread_self(), t);
2828 if (pthread_setspecific(PL_thr_key, t))
2829 Perl_croak_nocontext("panic: pthread_setspecific");
2834 #endif /* !PERL_GET_CONTEXT_DEFINED */
2836 #ifdef PERL_GLOBAL_STRUCT
2845 Perl_get_op_names(pTHX)
2851 Perl_get_op_descs(pTHX)
2857 Perl_get_no_modify(pTHX)
2859 return (char*)PL_no_modify;
2863 Perl_get_opargs(pTHX)
2869 Perl_get_ppaddr(pTHX)
2871 return (PPADDR_t*)PL_ppaddr;
2874 #ifndef HAS_GETENV_LEN
2876 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
2878 char *env_trans = PerlEnv_getenv(env_elem);
2880 *len = strlen(env_trans);
2887 Perl_get_vtbl(pTHX_ int vtbl_id)
2889 MGVTBL* result = Null(MGVTBL*);
2893 result = &PL_vtbl_sv;
2896 result = &PL_vtbl_env;
2898 case want_vtbl_envelem:
2899 result = &PL_vtbl_envelem;
2902 result = &PL_vtbl_sig;
2904 case want_vtbl_sigelem:
2905 result = &PL_vtbl_sigelem;
2907 case want_vtbl_pack:
2908 result = &PL_vtbl_pack;
2910 case want_vtbl_packelem:
2911 result = &PL_vtbl_packelem;
2913 case want_vtbl_dbline:
2914 result = &PL_vtbl_dbline;
2917 result = &PL_vtbl_isa;
2919 case want_vtbl_isaelem:
2920 result = &PL_vtbl_isaelem;
2922 case want_vtbl_arylen:
2923 result = &PL_vtbl_arylen;
2925 case want_vtbl_glob:
2926 result = &PL_vtbl_glob;
2928 case want_vtbl_mglob:
2929 result = &PL_vtbl_mglob;
2931 case want_vtbl_nkeys:
2932 result = &PL_vtbl_nkeys;
2934 case want_vtbl_taint:
2935 result = &PL_vtbl_taint;
2937 case want_vtbl_substr:
2938 result = &PL_vtbl_substr;
2941 result = &PL_vtbl_vec;
2944 result = &PL_vtbl_pos;
2947 result = &PL_vtbl_bm;
2950 result = &PL_vtbl_fm;
2952 case want_vtbl_uvar:
2953 result = &PL_vtbl_uvar;
2955 case want_vtbl_defelem:
2956 result = &PL_vtbl_defelem;
2958 case want_vtbl_regexp:
2959 result = &PL_vtbl_regexp;
2961 case want_vtbl_regdata:
2962 result = &PL_vtbl_regdata;
2964 case want_vtbl_regdatum:
2965 result = &PL_vtbl_regdatum;
2967 #ifdef USE_LOCALE_COLLATE
2968 case want_vtbl_collxfrm:
2969 result = &PL_vtbl_collxfrm;
2972 case want_vtbl_amagic:
2973 result = &PL_vtbl_amagic;
2975 case want_vtbl_amagicelem:
2976 result = &PL_vtbl_amagicelem;
2978 case want_vtbl_backref:
2979 result = &PL_vtbl_backref;
2981 case want_vtbl_utf8:
2982 result = &PL_vtbl_utf8;
2989 Perl_my_fflush_all(pTHX)
2991 #if defined(USE_PERLIO) || defined(FFLUSH_NULL) || defined(USE_SFIO)
2992 return PerlIO_flush(NULL);
2994 # if defined(HAS__FWALK)
2995 extern int fflush(FILE *);
2996 /* undocumented, unprototyped, but very useful BSDism */
2997 extern void _fwalk(int (*)(FILE *));
3001 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3003 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3004 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3006 # if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3007 open_max = sysconf(_SC_OPEN_MAX);
3010 open_max = FOPEN_MAX;
3013 open_max = OPEN_MAX;
3024 for (i = 0; i < open_max; i++)
3025 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3026 STDIO_STREAM_ARRAY[i]._file < open_max &&
3027 STDIO_STREAM_ARRAY[i]._flag)
3028 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3032 SETERRNO(EBADF,RMS_IFI);
3039 Perl_report_evil_fh(pTHX_ GV *gv, IO *io, I32 op)
3042 op == OP_READLINE ? "readline" : /* "<HANDLE>" not nice */
3043 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
3045 char *pars = OP_IS_FILETEST(op) ? "" : "()";
3046 char *type = OP_IS_SOCKET(op)
3047 || (gv && io && IoTYPE(io) == IoTYPE_SOCKET)
3048 ? "socket" : "filehandle";
3051 if (gv && isGV(gv)) {
3055 if (op == OP_phoney_OUTPUT_ONLY || op == OP_phoney_INPUT_ONLY) {
3056 if (ckWARN(WARN_IO)) {
3057 const char *direction = (op == OP_phoney_INPUT_ONLY) ? "in" : "out";
3059 Perl_warner(aTHX_ packWARN(WARN_IO),
3060 "Filehandle %s opened only for %sput",
3063 Perl_warner(aTHX_ packWARN(WARN_IO),
3064 "Filehandle opened only for %sput", direction);
3071 if (gv && io && IoTYPE(io) == IoTYPE_CLOSED) {
3073 warn_type = WARN_CLOSED;
3077 warn_type = WARN_UNOPENED;
3080 if (ckWARN(warn_type)) {
3081 if (name && *name) {
3082 Perl_warner(aTHX_ packWARN(warn_type),
3083 "%s%s on %s %s %s", func, pars, vile, type, name);
3084 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3086 aTHX_ packWARN(warn_type),
3087 "\t(Are you trying to call %s%s on dirhandle %s?)\n",
3092 Perl_warner(aTHX_ packWARN(warn_type),
3093 "%s%s on %s %s", func, pars, vile, type);
3094 if (gv && io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3096 aTHX_ packWARN(warn_type),
3097 "\t(Are you trying to call %s%s on dirhandle?)\n",
3106 /* in ASCII order, not that it matters */
3107 static const char controllablechars[] = "?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_";
3110 Perl_ebcdic_control(pTHX_ int ch)
3118 if ((ctlp = strchr(controllablechars, ch)) == 0) {
3119 Perl_die(aTHX_ "unrecognised control character '%c'\n", ch);
3122 if (ctlp == controllablechars)
3123 return('\177'); /* DEL */
3125 return((unsigned char)(ctlp - controllablechars - 1));
3126 } else { /* Want uncontrol */
3127 if (ch == '\177' || ch == -1)
3129 else if (ch == '\157')
3131 else if (ch == '\174')
3133 else if (ch == '^') /* '\137' in 1047, '\260' in 819 */
3135 else if (ch == '\155')
3137 else if (0 < ch && ch < (sizeof(controllablechars) - 1))
3138 return(controllablechars[ch+1]);
3140 Perl_die(aTHX_ "invalid control request: '\\%03o'\n", ch & 0xFF);
3145 /* To workaround core dumps from the uninitialised tm_zone we get the
3146 * system to give us a reasonable struct to copy. This fix means that
3147 * strftime uses the tm_zone and tm_gmtoff values returned by
3148 * localtime(time()). That should give the desired result most of the
3149 * time. But probably not always!
3151 * This does not address tzname aspects of NETaa14816.
3156 # ifndef STRUCT_TM_HASZONE
3157 # define STRUCT_TM_HASZONE
3161 #ifdef STRUCT_TM_HASZONE /* Backward compat */
3162 # ifndef HAS_TM_TM_ZONE
3163 # define HAS_TM_TM_ZONE
3168 Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
3170 #ifdef HAS_TM_TM_ZONE
3173 Copy(localtime(&now), ptm, 1, struct tm);
3178 * mini_mktime - normalise struct tm values without the localtime()
3179 * semantics (and overhead) of mktime().
3182 Perl_mini_mktime(pTHX_ struct tm *ptm)
3186 int month, mday, year, jday;
3187 int odd_cent, odd_year;
3189 #define DAYS_PER_YEAR 365
3190 #define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
3191 #define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
3192 #define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
3193 #define SECS_PER_HOUR (60*60)
3194 #define SECS_PER_DAY (24*SECS_PER_HOUR)
3195 /* parentheses deliberately absent on these two, otherwise they don't work */
3196 #define MONTH_TO_DAYS 153/5
3197 #define DAYS_TO_MONTH 5/153
3198 /* offset to bias by March (month 4) 1st between month/mday & year finding */
3199 #define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
3200 /* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
3201 #define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
3204 * Year/day algorithm notes:
3206 * With a suitable offset for numeric value of the month, one can find
3207 * an offset into the year by considering months to have 30.6 (153/5) days,
3208 * using integer arithmetic (i.e., with truncation). To avoid too much
3209 * messing about with leap days, we consider January and February to be
3210 * the 13th and 14th month of the previous year. After that transformation,
3211 * we need the month index we use to be high by 1 from 'normal human' usage,
3212 * so the month index values we use run from 4 through 15.
3214 * Given that, and the rules for the Gregorian calendar (leap years are those
3215 * divisible by 4 unless also divisible by 100, when they must be divisible
3216 * by 400 instead), we can simply calculate the number of days since some
3217 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
3218 * the days we derive from our month index, and adding in the day of the
3219 * month. The value used here is not adjusted for the actual origin which
3220 * it normally would use (1 January A.D. 1), since we're not exposing it.
3221 * We're only building the value so we can turn around and get the
3222 * normalised values for the year, month, day-of-month, and day-of-year.
3224 * For going backward, we need to bias the value we're using so that we find
3225 * the right year value. (Basically, we don't want the contribution of
3226 * March 1st to the number to apply while deriving the year). Having done
3227 * that, we 'count up' the contribution to the year number by accounting for
3228 * full quadracenturies (400-year periods) with their extra leap days, plus
3229 * the contribution from full centuries (to avoid counting in the lost leap
3230 * days), plus the contribution from full quad-years (to count in the normal
3231 * leap days), plus the leftover contribution from any non-leap years.
3232 * At this point, if we were working with an actual leap day, we'll have 0
3233 * days left over. This is also true for March 1st, however. So, we have
3234 * to special-case that result, and (earlier) keep track of the 'odd'
3235 * century and year contributions. If we got 4 extra centuries in a qcent,
3236 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
3237 * Otherwise, we add back in the earlier bias we removed (the 123 from
3238 * figuring in March 1st), find the month index (integer division by 30.6),
3239 * and the remainder is the day-of-month. We then have to convert back to
3240 * 'real' months (including fixing January and February from being 14/15 in
3241 * the previous year to being in the proper year). After that, to get
3242 * tm_yday, we work with the normalised year and get a new yearday value for
3243 * January 1st, which we subtract from the yearday value we had earlier,
3244 * representing the date we've re-built. This is done from January 1
3245 * because tm_yday is 0-origin.
3247 * Since POSIX time routines are only guaranteed to work for times since the
3248 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
3249 * applies Gregorian calendar rules even to dates before the 16th century
3250 * doesn't bother me. Besides, you'd need cultural context for a given
3251 * date to know whether it was Julian or Gregorian calendar, and that's
3252 * outside the scope for this routine. Since we convert back based on the
3253 * same rules we used to build the yearday, you'll only get strange results
3254 * for input which needed normalising, or for the 'odd' century years which
3255 * were leap years in the Julian calander but not in the Gregorian one.
3256 * I can live with that.
3258 * This algorithm also fails to handle years before A.D. 1 gracefully, but
3259 * that's still outside the scope for POSIX time manipulation, so I don't
3263 year = 1900 + ptm->tm_year;
3264 month = ptm->tm_mon;
3265 mday = ptm->tm_mday;
3266 /* allow given yday with no month & mday to dominate the result */
3267 if (ptm->tm_yday >= 0 && mday <= 0 && month <= 0) {
3270 jday = 1 + ptm->tm_yday;
3279 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
3280 yearday += month*MONTH_TO_DAYS + mday + jday;
3282 * Note that we don't know when leap-seconds were or will be,
3283 * so we have to trust the user if we get something which looks
3284 * like a sensible leap-second. Wild values for seconds will
3285 * be rationalised, however.
3287 if ((unsigned) ptm->tm_sec <= 60) {
3294 secs += 60 * ptm->tm_min;
3295 secs += SECS_PER_HOUR * ptm->tm_hour;
3297 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
3298 /* got negative remainder, but need positive time */
3299 /* back off an extra day to compensate */
3300 yearday += (secs/SECS_PER_DAY)-1;
3301 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
3304 yearday += (secs/SECS_PER_DAY);
3305 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
3308 else if (secs >= SECS_PER_DAY) {
3309 yearday += (secs/SECS_PER_DAY);
3310 secs %= SECS_PER_DAY;
3312 ptm->tm_hour = secs/SECS_PER_HOUR;
3313 secs %= SECS_PER_HOUR;
3314 ptm->tm_min = secs/60;
3316 ptm->tm_sec += secs;
3317 /* done with time of day effects */
3319 * The algorithm for yearday has (so far) left it high by 428.
3320 * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
3321 * bias it by 123 while trying to figure out what year it
3322 * really represents. Even with this tweak, the reverse
3323 * translation fails for years before A.D. 0001.
3324 * It would still fail for Feb 29, but we catch that one below.
3326 jday = yearday; /* save for later fixup vis-a-vis Jan 1 */
3327 yearday -= YEAR_ADJUST;
3328 year = (yearday / DAYS_PER_QCENT) * 400;
3329 yearday %= DAYS_PER_QCENT;
3330 odd_cent = yearday / DAYS_PER_CENT;
3331 year += odd_cent * 100;
3332 yearday %= DAYS_PER_CENT;
3333 year += (yearday / DAYS_PER_QYEAR) * 4;
3334 yearday %= DAYS_PER_QYEAR;
3335 odd_year = yearday / DAYS_PER_YEAR;
3337 yearday %= DAYS_PER_YEAR;
3338 if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
3343 yearday += YEAR_ADJUST; /* recover March 1st crock */
3344 month = yearday*DAYS_TO_MONTH;
3345 yearday -= month*MONTH_TO_DAYS;
3346 /* recover other leap-year adjustment */
3355 ptm->tm_year = year - 1900;
3357 ptm->tm_mday = yearday;
3358 ptm->tm_mon = month;
3362 ptm->tm_mon = month - 1;
3364 /* re-build yearday based on Jan 1 to get tm_yday */
3366 yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
3367 yearday += 14*MONTH_TO_DAYS + 1;
3368 ptm->tm_yday = jday - yearday;
3369 /* fix tm_wday if not overridden by caller */
3370 if ((unsigned)ptm->tm_wday > 6)
3371 ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
3375 Perl_my_strftime(pTHX_ char *fmt, int sec, int min, int hour, int mday, int mon, int year, int wday, int yday, int isdst)
3383 init_tm(&mytm); /* XXX workaround - see init_tm() above */
3386 mytm.tm_hour = hour;
3387 mytm.tm_mday = mday;
3389 mytm.tm_year = year;
3390 mytm.tm_wday = wday;
3391 mytm.tm_yday = yday;
3392 mytm.tm_isdst = isdst;
3394 /* use libc to get the values for tm_gmtoff and tm_zone [perl #18238] */
3395 #if defined(HAS_MKTIME) && (defined(HAS_TM_TM_GMTOFF) || defined(HAS_TM_TM_ZONE))
3400 #ifdef HAS_TM_TM_GMTOFF
3401 mytm.tm_gmtoff = mytm2.tm_gmtoff;
3403 #ifdef HAS_TM_TM_ZONE
3404 mytm.tm_zone = mytm2.tm_zone;
3409 New(0, buf, buflen, char);
3410 len = strftime(buf, buflen, fmt, &mytm);
3412 ** The following is needed to handle to the situation where
3413 ** tmpbuf overflows. Basically we want to allocate a buffer
3414 ** and try repeatedly. The reason why it is so complicated
3415 ** is that getting a return value of 0 from strftime can indicate
3416 ** one of the following:
3417 ** 1. buffer overflowed,
3418 ** 2. illegal conversion specifier, or
3419 ** 3. the format string specifies nothing to be returned(not
3420 ** an error). This could be because format is an empty string
3421 ** or it specifies %p that yields an empty string in some locale.
3422 ** If there is a better way to make it portable, go ahead by
3425 if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
3428 /* Possibly buf overflowed - try again with a bigger buf */
3429 int fmtlen = strlen(fmt);
3430 int bufsize = fmtlen + buflen;
3432 New(0, buf, bufsize, char);
3434 buflen = strftime(buf, bufsize, fmt, &mytm);
3435 if (buflen > 0 && buflen < bufsize)
3437 /* heuristic to prevent out-of-memory errors */
3438 if (bufsize > 100*fmtlen) {
3444 Renew(buf, bufsize, char);
3449 Perl_croak(aTHX_ "panic: no strftime");
3454 #define SV_CWD_RETURN_UNDEF \
3455 sv_setsv(sv, &PL_sv_undef); \
3458 #define SV_CWD_ISDOT(dp) \
3459 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
3460 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
3463 =head1 Miscellaneous Functions
3465 =for apidoc getcwd_sv
3467 Fill the sv with current working directory
3472 /* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
3473 * rewritten again by dougm, optimized for use with xs TARG, and to prefer
3474 * getcwd(3) if available
3475 * Comments from the orignal:
3476 * This is a faster version of getcwd. It's also more dangerous
3477 * because you might chdir out of a directory that you can't chdir
3481 Perl_getcwd_sv(pTHX_ register SV *sv)
3485 #ifndef INCOMPLETE_TAINTS
3491 char buf[MAXPATHLEN];
3493 /* Some getcwd()s automatically allocate a buffer of the given
3494 * size from the heap if they are given a NULL buffer pointer.
3495 * The problem is that this behaviour is not portable. */
3496 if (getcwd(buf, sizeof(buf) - 1)) {
3497 STRLEN len = strlen(buf);
3498 sv_setpvn(sv, buf, len);
3502 sv_setsv(sv, &PL_sv_undef);
3510 int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
3511 int namelen, pathlen=0;
3515 (void)SvUPGRADE(sv, SVt_PV);
3517 if (PerlLIO_lstat(".", &statbuf) < 0) {
3518 SV_CWD_RETURN_UNDEF;
3521 orig_cdev = statbuf.st_dev;
3522 orig_cino = statbuf.st_ino;
3530 if (PerlDir_chdir("..") < 0) {
3531 SV_CWD_RETURN_UNDEF;
3533 if (PerlLIO_stat(".", &statbuf) < 0) {
3534 SV_CWD_RETURN_UNDEF;
3537 cdev = statbuf.st_dev;
3538 cino = statbuf.st_ino;
3540 if (odev == cdev && oino == cino) {
3543 if (!(dir = PerlDir_open("."))) {
3544 SV_CWD_RETURN_UNDEF;
3547 while ((dp = PerlDir_read(dir)) != NULL) {
3549 namelen = dp->d_namlen;
3551 namelen = strlen(dp->d_name);
3554 if (SV_CWD_ISDOT(dp)) {
3558 if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
3559 SV_CWD_RETURN_UNDEF;
3562 tdev = statbuf.st_dev;
3563 tino = statbuf.st_ino;
3564 if (tino == oino && tdev == odev) {
3570 SV_CWD_RETURN_UNDEF;
3573 if (pathlen + namelen + 1 >= MAXPATHLEN) {
3574 SV_CWD_RETURN_UNDEF;
3577 SvGROW(sv, pathlen + namelen + 1);
3581 Move(SvPVX(sv), SvPVX(sv) + namelen + 1, pathlen, char);
3584 /* prepend current directory to the front */
3586 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
3587 pathlen += (namelen + 1);
3589 #ifdef VOID_CLOSEDIR
3592 if (PerlDir_close(dir) < 0) {
3593 SV_CWD_RETURN_UNDEF;
3599 SvCUR_set(sv, pathlen);
3603 if (PerlDir_chdir(SvPVX(sv)) < 0) {
3604 SV_CWD_RETURN_UNDEF;
3607 if (PerlLIO_stat(".", &statbuf) < 0) {
3608 SV_CWD_RETURN_UNDEF;
3611 cdev = statbuf.st_dev;
3612 cino = statbuf.st_ino;
3614 if (cdev != orig_cdev || cino != orig_cino) {
3615 Perl_croak(aTHX_ "Unstable directory path, "
3616 "current directory changed unexpectedly");
3628 =head1 SV Manipulation Functions
3630 =for apidoc scan_vstring
3632 Returns a pointer to the next character after the parsed
3633 vstring, as well as updating the passed in sv.
3635 Function must be called like
3638 s = scan_vstring(s,sv);
3640 The sv should already be large enough to store the vstring
3641 passed in, for performance reasons.
3647 Perl_scan_vstring(pTHX_ char *s, SV *sv)
3651 if (*pos == 'v') pos++; /* get past 'v' */
3652 while (isDIGIT(*pos) || *pos == '_')
3654 if (!isALPHA(*pos)) {
3656 U8 tmpbuf[UTF8_MAXLEN+1];
3659 if (*s == 'v') s++; /* get past 'v' */
3661 sv_setpvn(sv, "", 0);
3666 /* this is atoi() that tolerates underscores */
3669 while (--end >= s) {
3674 rev += (*end - '0') * mult;
3676 if (orev > rev && ckWARN_d(WARN_OVERFLOW))
3677 Perl_warner(aTHX_ packWARN(WARN_OVERFLOW),
3678 "Integer overflow in decimal number");
3682 if (rev > 0x7FFFFFFF)
3683 Perl_croak(aTHX "In EBCDIC the v-string components cannot exceed 2147483647");
3685 /* Append native character for the rev point */
3686 tmpend = uvchr_to_utf8(tmpbuf, rev);
3687 sv_catpvn(sv, (const char*)tmpbuf, tmpend - tmpbuf);
3688 if (!UNI_IS_INVARIANT(NATIVE_TO_UNI(rev)))
3690 if (*pos == '.' && isDIGIT(pos[1]))
3696 while (isDIGIT(*pos) || *pos == '_')
3700 sv_magic(sv,NULL,PERL_MAGIC_vstring,(const char*)start, pos-start);
3707 =for apidoc scan_version
3709 Returns a pointer to the next character after the parsed
3710 version string, as well as upgrading the passed in SV to
3713 Function must be called with an already existing SV like
3716 s = scan_version(s,sv);
3718 Performs some preprocessing to the string to ensure that
3719 it has the correct characteristics of a version. Flags the
3720 object if it contains an underscore (which denotes this
3727 Perl_scan_version(pTHX_ char *s, SV *rv)
3729 const char *start = s;
3733 SV* sv = newSVrv(rv, "version"); /* create an SV and upgrade the RV */
3734 (void)sv_upgrade(sv, SVt_PVAV); /* needs to be an AV type */
3736 /* pre-scan the imput string to check for decimals */
3737 while ( *pos == '.' || *pos == '_' || isDIGIT(*pos) )
3742 Perl_croak(aTHX_ "Invalid version format (underscores before decimal)");
3745 else if ( *pos == '_' )
3748 Perl_croak(aTHX_ "Invalid version format (multiple underscores)");
3755 if (*pos == 'v') pos++; /* get past 'v' */
3756 while (isDIGIT(*pos))
3758 if (!isALPHA(*pos)) {
3761 if (*s == 'v') s++; /* get past 'v' */
3766 /* this is atoi() that delimits on underscores */
3770 if ( s < pos && s > start && *(s-1) == '_' ) {
3771 mult *= -1; /* beta version */
3773 /* the following if() will only be true after the decimal
3774 * point of a version originally created with a bare
3775 * floating point number, i.e. not quoted in any way
3777 if ( s > start+1 && saw_period == 1 && !saw_under ) {
3781 rev += (*s - '0') * mult;
3783 if ( abs(orev) > abs(rev) )
3784 Perl_croak(aTHX_ "Integer overflow in version");
3789 while (--end >= s) {
3791 rev += (*end - '0') * mult;
3793 if ( abs(orev) > abs(rev) )
3794 Perl_croak(aTHX_ "Integer overflow in version");
3799 /* Append revision */
3800 av_push((AV *)sv, newSViv(rev));
3801 if ( (*pos == '.' || *pos == '_') && isDIGIT(pos[1]))
3803 else if ( isDIGIT(*pos) )
3809 while ( isDIGIT(*pos) ) {
3810 if ( !saw_under && saw_period == 1 && pos-s == 3 )
3820 =for apidoc new_version
3822 Returns a new version object based on the passed in SV:
3824 SV *sv = new_version(SV *ver);
3826 Does not alter the passed in ver SV. See "upg_version" if you
3827 want to upgrade the SV.
3833 Perl_new_version(pTHX_ SV *ver)
3837 if ( SvNOK(ver) ) /* may get too much accuracy */
3840 sprintf(tbuf,"%.9"NVgf, SvNVX(ver));
3841 version = savepv(tbuf);
3844 else if ( SvVOK(ver) ) { /* already a v-string */
3845 MAGIC* mg = mg_find(ver,PERL_MAGIC_vstring);
3846 version = savepvn( (const char*)mg->mg_ptr,mg->mg_len );
3849 else /* must be a string or something like a string */
3851 version = (char *)SvPV(ver,PL_na);
3853 version = scan_version(version,rv);
3858 =for apidoc upg_version
3860 In-place upgrade of the supplied SV to a version object.
3862 SV *sv = upg_version(SV *sv);
3864 Returns a pointer to the upgraded SV.
3870 Perl_upg_version(pTHX_ SV *ver)
3872 char *version = savepvn(SvPVX(ver),SvCUR(ver));
3874 if ( SvVOK(ver) ) { /* already a v-string */
3875 MAGIC* mg = mg_find(ver,PERL_MAGIC_vstring);
3876 version = savepvn( (const char*)mg->mg_ptr,mg->mg_len );
3879 version = scan_version(version,ver);
3887 Accepts a version object and returns the normalized floating
3888 point representation. Call like:
3892 NOTE: you can pass either the object directly or the SV
3893 contained within the RV.
3899 Perl_vnumify(pTHX_ SV *vs)
3902 SV *sv = NEWSV(92,0);
3905 len = av_len((AV *)vs);
3908 Perl_sv_catpv(aTHX_ sv,"0");
3911 digit = SvIVX(*av_fetch((AV *)vs, 0, 0));
3912 Perl_sv_setpvf(aTHX_ sv,"%d.",abs(digit));
3913 for ( i = 1 ; i <= len ; i++ )
3915 digit = SvIVX(*av_fetch((AV *)vs, i, 0));
3916 Perl_sv_catpvf(aTHX_ sv,"%03d",abs(digit));
3919 Perl_sv_catpv(aTHX_ sv,"000");
3920 sv_setnv(sv, SvNV(sv));
3925 =for apidoc vstringify
3927 Accepts a version object and returns the normalized string
3928 representation. Call like:
3930 sv = vstringify(rv);
3932 NOTE: you can pass either the object directly or the SV
3933 contained within the RV.
3939 Perl_vstringify(pTHX_ SV *vs)
3942 SV *sv = NEWSV(92,0);
3945 len = av_len((AV *)vs);
3948 Perl_sv_catpv(aTHX_ sv,"");
3951 digit = SvIVX(*av_fetch((AV *)vs, 0, 0));
3952 Perl_sv_setpvf(aTHX_ sv,"%"IVdf,(IV)digit);
3953 for ( i = 1 ; i <= len ; i++ )
3955 digit = SvIVX(*av_fetch((AV *)vs, i, 0));
3957 Perl_sv_catpvf(aTHX_ sv,"_%"IVdf,(IV)-digit);
3959 Perl_sv_catpvf(aTHX_ sv,".%"IVdf,(IV)digit);
3962 Perl_sv_catpv(aTHX_ sv,".0");
3969 Version object aware cmp. Both operands must already have been
3970 converted into version objects.
3976 Perl_vcmp(pTHX_ SV *lsv, SV *rsv)
3983 l = av_len((AV *)lsv);
3984 r = av_len((AV *)rsv);
3988 while ( i <= m && retval == 0 )
3990 I32 left = SvIV(*av_fetch((AV *)lsv,i,0));
3991 I32 right = SvIV(*av_fetch((AV *)rsv,i,0));
3992 bool lbeta = left < 0 ? 1 : 0;
3993 bool rbeta = right < 0 ? 1 : 0;
3996 if ( left < right || (left == right && lbeta && !rbeta) )
3998 if ( left > right || (left == right && rbeta && !lbeta) )
4003 if ( l != r && retval == 0 ) /* possible match except for trailing 0 */
4005 if ( !( l < r && r-l == 1 && SvIV(*av_fetch((AV *)rsv,r,0)) == 0 ) &&
4006 !( l-r == 1 && SvIV(*av_fetch((AV *)lsv,l,0)) == 0 ) )
4008 retval = l < r ? -1 : +1; /* not a match after all */
4014 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET) && defined(SOCK_DGRAM) && defined(HAS_SELECT)
4015 # define EMULATE_SOCKETPAIR_UDP
4018 #ifdef EMULATE_SOCKETPAIR_UDP
4020 S_socketpair_udp (int fd[2]) {
4022 /* Fake a datagram socketpair using UDP to localhost. */
4023 int sockets[2] = {-1, -1};
4024 struct sockaddr_in addresses[2];
4026 Sock_size_t size = sizeof(struct sockaddr_in);
4027 unsigned short port;
4030 memset(&addresses, 0, sizeof(addresses));
4033 sockets[i] = PerlSock_socket(AF_INET, SOCK_DGRAM, PF_INET);
4034 if (sockets[i] == -1)
4035 goto tidy_up_and_fail;
4037 addresses[i].sin_family = AF_INET;
4038 addresses[i].sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4039 addresses[i].sin_port = 0; /* kernel choses port. */
4040 if (PerlSock_bind(sockets[i], (struct sockaddr *) &addresses[i],
4041 sizeof(struct sockaddr_in)) == -1)
4042 goto tidy_up_and_fail;
4045 /* Now have 2 UDP sockets. Find out which port each is connected to, and
4046 for each connect the other socket to it. */
4049 if (PerlSock_getsockname(sockets[i], (struct sockaddr *) &addresses[i],
4051 goto tidy_up_and_fail;
4052 if (size != sizeof(struct sockaddr_in))
4053 goto abort_tidy_up_and_fail;
4054 /* !1 is 0, !0 is 1 */
4055 if (PerlSock_connect(sockets[!i], (struct sockaddr *) &addresses[i],
4056 sizeof(struct sockaddr_in)) == -1)
4057 goto tidy_up_and_fail;
4060 /* Now we have 2 sockets connected to each other. I don't trust some other
4061 process not to have already sent a packet to us (by random) so send
4062 a packet from each to the other. */
4065 /* I'm going to send my own port number. As a short.
4066 (Who knows if someone somewhere has sin_port as a bitfield and needs
4067 this routine. (I'm assuming crays have socketpair)) */
4068 port = addresses[i].sin_port;
4069 got = PerlLIO_write(sockets[i], &port, sizeof(port));
4070 if (got != sizeof(port)) {
4072 goto tidy_up_and_fail;
4073 goto abort_tidy_up_and_fail;
4077 /* Packets sent. I don't trust them to have arrived though.
4078 (As I understand it Solaris TCP stack is multithreaded. Non-blocking
4079 connect to localhost will use a second kernel thread. In 2.6 the
4080 first thread running the connect() returns before the second completes,
4081 so EINPROGRESS> In 2.7 the improved stack is faster and connect()
4082 returns 0. Poor programs have tripped up. One poor program's authors'
4083 had a 50-1 reverse stock split. Not sure how connected these were.)
4084 So I don't trust someone not to have an unpredictable UDP stack.
4088 struct timeval waitfor = {0, 100000}; /* You have 0.1 seconds */
4089 int max = sockets[1] > sockets[0] ? sockets[1] : sockets[0];
4093 FD_SET(sockets[0], &rset);
4094 FD_SET(sockets[1], &rset);
4096 got = PerlSock_select(max + 1, &rset, NULL, NULL, &waitfor);
4097 if (got != 2 || !FD_ISSET(sockets[0], &rset)
4098 || !FD_ISSET(sockets[1], &rset)) {
4099 /* I hope this is portable and appropriate. */
4101 goto tidy_up_and_fail;
4102 goto abort_tidy_up_and_fail;
4106 /* And the paranoia department even now doesn't trust it to have arrive
4107 (hence MSG_DONTWAIT). Or that what arrives was sent by us. */
4109 struct sockaddr_in readfrom;
4110 unsigned short buffer[2];
4115 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4116 sizeof(buffer), MSG_DONTWAIT,
4117 (struct sockaddr *) &readfrom, &size);
4119 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4121 (struct sockaddr *) &readfrom, &size);
4125 goto tidy_up_and_fail;
4126 if (got != sizeof(port)
4127 || size != sizeof(struct sockaddr_in)
4128 /* Check other socket sent us its port. */
4129 || buffer[0] != (unsigned short) addresses[!i].sin_port
4130 /* Check kernel says we got the datagram from that socket */
4131 || readfrom.sin_family != addresses[!i].sin_family
4132 || readfrom.sin_addr.s_addr != addresses[!i].sin_addr.s_addr
4133 || readfrom.sin_port != addresses[!i].sin_port)
4134 goto abort_tidy_up_and_fail;
4137 /* My caller (my_socketpair) has validated that this is non-NULL */
4140 /* I hereby declare this connection open. May God bless all who cross
4144 abort_tidy_up_and_fail:
4145 errno = ECONNABORTED;
4148 int save_errno = errno;
4149 if (sockets[0] != -1)
4150 PerlLIO_close(sockets[0]);
4151 if (sockets[1] != -1)
4152 PerlLIO_close(sockets[1]);
4157 #endif /* EMULATE_SOCKETPAIR_UDP */
4159 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET)
4161 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4162 /* Stevens says that family must be AF_LOCAL, protocol 0.
4163 I'm going to enforce that, then ignore it, and use TCP (or UDP). */
4168 struct sockaddr_in listen_addr;
4169 struct sockaddr_in connect_addr;
4174 || family != AF_UNIX
4177 errno = EAFNOSUPPORT;
4185 #ifdef EMULATE_SOCKETPAIR_UDP
4186 if (type == SOCK_DGRAM)
4187 return S_socketpair_udp(fd);
4190 listener = PerlSock_socket(AF_INET, type, 0);
4193 memset(&listen_addr, 0, sizeof(listen_addr));
4194 listen_addr.sin_family = AF_INET;
4195 listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4196 listen_addr.sin_port = 0; /* kernel choses port. */
4197 if (PerlSock_bind(listener, (struct sockaddr *) &listen_addr,
4198 sizeof(listen_addr)) == -1)
4199 goto tidy_up_and_fail;
4200 if (PerlSock_listen(listener, 1) == -1)
4201 goto tidy_up_and_fail;
4203 connector = PerlSock_socket(AF_INET, type, 0);
4204 if (connector == -1)
4205 goto tidy_up_and_fail;
4206 /* We want to find out the port number to connect to. */
4207 size = sizeof(connect_addr);
4208 if (PerlSock_getsockname(listener, (struct sockaddr *) &connect_addr,
4210 goto tidy_up_and_fail;
4211 if (size != sizeof(connect_addr))
4212 goto abort_tidy_up_and_fail;
4213 if (PerlSock_connect(connector, (struct sockaddr *) &connect_addr,
4214 sizeof(connect_addr)) == -1)
4215 goto tidy_up_and_fail;
4217 size = sizeof(listen_addr);
4218 acceptor = PerlSock_accept(listener, (struct sockaddr *) &listen_addr,
4221 goto tidy_up_and_fail;
4222 if (size != sizeof(listen_addr))
4223 goto abort_tidy_up_and_fail;
4224 PerlLIO_close(listener);
4225 /* Now check we are talking to ourself by matching port and host on the
4227 if (PerlSock_getsockname(connector, (struct sockaddr *) &connect_addr,
4229 goto tidy_up_and_fail;
4230 if (size != sizeof(connect_addr)
4231 || listen_addr.sin_family != connect_addr.sin_family
4232 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
4233 || listen_addr.sin_port != connect_addr.sin_port) {
4234 goto abort_tidy_up_and_fail;
4240 abort_tidy_up_and_fail:
4241 errno = ECONNABORTED; /* I hope this is portable and appropriate. */
4244 int save_errno = errno;
4246 PerlLIO_close(listener);
4247 if (connector != -1)
4248 PerlLIO_close(connector);
4250 PerlLIO_close(acceptor);
4256 /* In any case have a stub so that there's code corresponding
4257 * to the my_socketpair in global.sym. */
4259 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4260 #ifdef HAS_SOCKETPAIR
4261 return socketpair(family, type, protocol, fd);
4270 =for apidoc sv_nosharing
4272 Dummy routine which "shares" an SV when there is no sharing module present.
4273 Exists to avoid test for a NULL function pointer and because it could potentially warn under
4274 some level of strict-ness.
4280 Perl_sv_nosharing(pTHX_ SV *sv)
4285 =for apidoc sv_nolocking
4287 Dummy routine which "locks" an SV when there is no locking module present.
4288 Exists to avoid test for a NULL function pointer and because it could potentially warn under
4289 some level of strict-ness.
4295 Perl_sv_nolocking(pTHX_ SV *sv)
4301 =for apidoc sv_nounlocking
4303 Dummy routine which "unlocks" an SV when there is no locking module present.
4304 Exists to avoid test for a NULL function pointer and because it could potentially warn under
4305 some level of strict-ness.
4311 Perl_sv_nounlocking(pTHX_ SV *sv)