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 #ifdef USE_5005THREADS
972 Perl_sv_catpvf(aTHX_ sv, " thread %ld", thr->tid);
974 sv_catpv(sv, PL_dirty ? dgd : ".\n");
980 Perl_vdie(pTHX_ const char* pat, va_list *args)
983 int was_in_eval = PL_in_eval;
990 DEBUG_S(PerlIO_printf(Perl_debug_log,
991 "%p: die: curstack = %p, mainstack = %p\n",
992 thr, PL_curstack, PL_mainstack));
995 msv = vmess(pat, args);
996 if (PL_errors && SvCUR(PL_errors)) {
997 sv_catsv(PL_errors, msv);
998 message = SvPV(PL_errors, msglen);
999 SvCUR_set(PL_errors, 0);
1002 message = SvPV(msv,msglen);
1009 DEBUG_S(PerlIO_printf(Perl_debug_log,
1010 "%p: die: message = %s\ndiehook = %p\n",
1011 thr, message, PL_diehook));
1013 /* sv_2cv might call Perl_croak() */
1014 SV *olddiehook = PL_diehook;
1016 SAVESPTR(PL_diehook);
1017 PL_diehook = Nullsv;
1018 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1020 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1027 msg = newSVpvn(message, msglen);
1035 PUSHSTACKi(PERLSI_DIEHOOK);
1039 call_sv((SV*)cv, G_DISCARD);
1045 PL_restartop = die_where(message, msglen);
1046 DEBUG_S(PerlIO_printf(Perl_debug_log,
1047 "%p: die: restartop = %p, was_in_eval = %d, top_env = %p\n",
1048 thr, PL_restartop, was_in_eval, PL_top_env));
1049 if ((!PL_restartop && was_in_eval) || PL_top_env->je_prev)
1051 return PL_restartop;
1054 #if defined(PERL_IMPLICIT_CONTEXT)
1056 Perl_die_nocontext(const char* pat, ...)
1061 va_start(args, pat);
1062 o = vdie(pat, &args);
1066 #endif /* PERL_IMPLICIT_CONTEXT */
1069 Perl_die(pTHX_ const char* pat, ...)
1073 va_start(args, pat);
1074 o = vdie(pat, &args);
1080 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1090 msv = vmess(pat, args);
1091 if (PL_errors && SvCUR(PL_errors)) {
1092 sv_catsv(PL_errors, msv);
1093 message = SvPV(PL_errors, msglen);
1094 SvCUR_set(PL_errors, 0);
1097 message = SvPV(msv,msglen);
1104 DEBUG_S(PerlIO_printf(Perl_debug_log, "croak: 0x%"UVxf" %s",
1105 PTR2UV(thr), message));
1108 /* sv_2cv might call Perl_croak() */
1109 SV *olddiehook = PL_diehook;
1111 SAVESPTR(PL_diehook);
1112 PL_diehook = Nullsv;
1113 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1115 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1122 msg = newSVpvn(message, msglen);
1130 PUSHSTACKi(PERLSI_DIEHOOK);
1134 call_sv((SV*)cv, G_DISCARD);
1140 PL_restartop = die_where(message, msglen);
1144 message = SvPVx(ERRSV, msglen);
1148 /* SFIO can really mess with your errno */
1151 PerlIO *serr = Perl_error_log;
1153 PERL_WRITE_MSG_TO_CONSOLE(serr, message, msglen);
1154 (void)PerlIO_flush(serr);
1162 #if defined(PERL_IMPLICIT_CONTEXT)
1164 Perl_croak_nocontext(const char *pat, ...)
1168 va_start(args, pat);
1173 #endif /* PERL_IMPLICIT_CONTEXT */
1176 =head1 Warning and Dieing
1180 This is the XSUB-writer's interface to Perl's C<die> function.
1181 Normally use this function the same way you use the C C<printf>
1182 function. See C<warn>.
1184 If you want to throw an exception object, assign the object to
1185 C<$@> and then pass C<Nullch> to croak():
1187 errsv = get_sv("@", TRUE);
1188 sv_setsv(errsv, exception_object);
1195 Perl_croak(pTHX_ const char *pat, ...)
1198 va_start(args, pat);
1205 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1216 msv = vmess(pat, args);
1217 message = SvPV(msv, msglen);
1220 /* sv_2cv might call Perl_warn() */
1221 SV *oldwarnhook = PL_warnhook;
1223 SAVESPTR(PL_warnhook);
1224 PL_warnhook = Nullsv;
1225 cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1227 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1233 msg = newSVpvn(message, msglen);
1237 PUSHSTACKi(PERLSI_WARNHOOK);
1241 call_sv((SV*)cv, G_DISCARD);
1248 /* if STDERR is tied, use it instead */
1249 if (PL_stderrgv && (io = GvIOp(PL_stderrgv))
1250 && (mg = SvTIED_mg((SV*)io, PERL_MAGIC_tiedscalar))) {
1253 XPUSHs(SvTIED_obj((SV*)io, mg));
1254 XPUSHs(sv_2mortal(newSVpvn(message, msglen)));
1256 call_method("PRINT", G_SCALAR);
1262 PerlIO *serr = Perl_error_log;
1264 PERL_WRITE_MSG_TO_CONSOLE(serr, message, msglen);
1265 (void)PerlIO_flush(serr);
1269 #if defined(PERL_IMPLICIT_CONTEXT)
1271 Perl_warn_nocontext(const char *pat, ...)
1275 va_start(args, pat);
1279 #endif /* PERL_IMPLICIT_CONTEXT */
1284 This is the XSUB-writer's interface to Perl's C<warn> function. Use this
1285 function the same way you use the C C<printf> function. See
1292 Perl_warn(pTHX_ const char *pat, ...)
1295 va_start(args, pat);
1300 #if defined(PERL_IMPLICIT_CONTEXT)
1302 Perl_warner_nocontext(U32 err, const char *pat, ...)
1306 va_start(args, pat);
1307 vwarner(err, pat, &args);
1310 #endif /* PERL_IMPLICIT_CONTEXT */
1313 Perl_warner(pTHX_ U32 err, const char* pat,...)
1316 va_start(args, pat);
1317 vwarner(err, pat, &args);
1322 Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1331 msv = vmess(pat, args);
1332 message = SvPV(msv, msglen);
1335 #ifdef USE_5005THREADS
1336 DEBUG_S(PerlIO_printf(Perl_debug_log, "croak: 0x%"UVxf" %s", PTR2UV(thr), message));
1337 #endif /* USE_5005THREADS */
1339 /* sv_2cv might call Perl_croak() */
1340 SV *olddiehook = PL_diehook;
1342 SAVESPTR(PL_diehook);
1343 PL_diehook = Nullsv;
1344 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1346 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1352 msg = newSVpvn(message, msglen);
1356 PUSHSTACKi(PERLSI_DIEHOOK);
1360 call_sv((SV*)cv, G_DISCARD);
1366 PL_restartop = die_where(message, msglen);
1370 PerlIO *serr = Perl_error_log;
1371 PERL_WRITE_MSG_TO_CONSOLE(serr, message, msglen);
1372 (void)PerlIO_flush(serr);
1378 /* sv_2cv might call Perl_warn() */
1379 SV *oldwarnhook = PL_warnhook;
1381 SAVESPTR(PL_warnhook);
1382 PL_warnhook = Nullsv;
1383 cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1385 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1391 msg = newSVpvn(message, msglen);
1395 PUSHSTACKi(PERLSI_WARNHOOK);
1399 call_sv((SV*)cv, G_DISCARD);
1406 PerlIO *serr = Perl_error_log;
1407 PERL_WRITE_MSG_TO_CONSOLE(serr, message, msglen);
1408 (void)PerlIO_flush(serr);
1413 /* since we've already done strlen() for both nam and val
1414 * we can use that info to make things faster than
1415 * sprintf(s, "%s=%s", nam, val)
1417 #define my_setenv_format(s, nam, nlen, val, vlen) \
1418 Copy(nam, s, nlen, char); \
1420 Copy(val, s+(nlen+1), vlen, char); \
1421 *(s+(nlen+1+vlen)) = '\0'
1423 #ifdef USE_ENVIRON_ARRAY
1424 /* VMS' my_setenv() is in vms.c */
1425 #if !defined(WIN32) && !defined(NETWARE)
1427 Perl_my_setenv(pTHX_ char *nam, char *val)
1430 /* only parent thread can modify process environment */
1431 if (PL_curinterp == aTHX)
1434 #ifndef PERL_USE_SAFE_PUTENV
1435 /* most putenv()s leak, so we manipulate environ directly */
1436 register I32 i=setenv_getix(nam); /* where does it go? */
1439 if (environ == PL_origenviron) { /* need we copy environment? */
1445 for (max = i; environ[max]; max++) ;
1446 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
1447 for (j=0; j<max; j++) { /* copy environment */
1448 int len = strlen(environ[j]);
1449 tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
1450 Copy(environ[j], tmpenv[j], len+1, char);
1452 tmpenv[max] = Nullch;
1453 environ = tmpenv; /* tell exec where it is now */
1456 safesysfree(environ[i]);
1457 while (environ[i]) {
1458 environ[i] = environ[i+1];
1463 if (!environ[i]) { /* does not exist yet */
1464 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
1465 environ[i+1] = Nullch; /* make sure it's null terminated */
1468 safesysfree(environ[i]);
1472 environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
1473 /* all that work just for this */
1474 my_setenv_format(environ[i], nam, nlen, val, vlen);
1476 #else /* PERL_USE_SAFE_PUTENV */
1477 # if defined(__CYGWIN__) || defined( EPOC)
1478 setenv(nam, val, 1);
1481 int nlen = strlen(nam), vlen;
1486 new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1487 /* all that work just for this */
1488 my_setenv_format(new_env, nam, nlen, val, vlen);
1489 (void)putenv(new_env);
1490 # endif /* __CYGWIN__ */
1491 #endif /* PERL_USE_SAFE_PUTENV */
1495 #else /* WIN32 || NETWARE */
1498 Perl_my_setenv(pTHX_ char *nam,char *val)
1500 register char *envstr;
1501 int nlen = strlen(nam), vlen;
1507 New(904, envstr, nlen+vlen+2, char);
1508 my_setenv_format(envstr, nam, nlen, val, vlen);
1509 (void)PerlEnv_putenv(envstr);
1513 #endif /* WIN32 || NETWARE */
1516 Perl_setenv_getix(pTHX_ char *nam)
1518 register I32 i, len = strlen(nam);
1520 for (i = 0; environ[i]; i++) {
1523 strnicmp(environ[i],nam,len) == 0
1525 strnEQ(environ[i],nam,len)
1527 && environ[i][len] == '=')
1528 break; /* strnEQ must come first to avoid */
1529 } /* potential SEGV's */
1533 #endif /* !VMS && !EPOC*/
1535 #ifdef UNLINK_ALL_VERSIONS
1537 Perl_unlnk(pTHX_ char *f) /* unlink all versions of a file */
1541 for (i = 0; PerlLIO_unlink(f) >= 0; i++) ;
1546 /* this is a drop-in replacement for bcopy() */
1547 #if (!defined(HAS_MEMCPY) && !defined(HAS_BCOPY)) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY) && !defined(HAS_SAFE_BCOPY))
1549 Perl_my_bcopy(register const char *from,register char *to,register I32 len)
1553 if (from - to >= 0) {
1561 *(--to) = *(--from);
1567 /* this is a drop-in replacement for memset() */
1570 Perl_my_memset(register char *loc, register I32 ch, register I32 len)
1580 /* this is a drop-in replacement for bzero() */
1581 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
1583 Perl_my_bzero(register char *loc, register I32 len)
1593 /* this is a drop-in replacement for memcmp() */
1594 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
1596 Perl_my_memcmp(const char *s1, const char *s2, register I32 len)
1598 register U8 *a = (U8 *)s1;
1599 register U8 *b = (U8 *)s2;
1603 if (tmp = *a++ - *b++)
1608 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
1612 #ifdef USE_CHAR_VSPRINTF
1617 vsprintf(char *dest, const char *pat, char *args)
1621 fakebuf._ptr = dest;
1622 fakebuf._cnt = 32767;
1626 fakebuf._flag = _IOWRT|_IOSTRG;
1627 _doprnt(pat, args, &fakebuf); /* what a kludge */
1628 (void)putc('\0', &fakebuf);
1629 #ifdef USE_CHAR_VSPRINTF
1632 return 0; /* perl doesn't use return value */
1636 #endif /* HAS_VPRINTF */
1639 #if BYTEORDER != 0x4321
1641 Perl_my_swap(pTHX_ short s)
1643 #if (BYTEORDER & 1) == 0
1646 result = ((s & 255) << 8) + ((s >> 8) & 255);
1654 Perl_my_htonl(pTHX_ long l)
1658 char c[sizeof(long)];
1661 #if BYTEORDER == 0x1234
1662 u.c[0] = (l >> 24) & 255;
1663 u.c[1] = (l >> 16) & 255;
1664 u.c[2] = (l >> 8) & 255;
1668 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1669 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
1674 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1675 u.c[o & 0xf] = (l >> s) & 255;
1683 Perl_my_ntohl(pTHX_ long l)
1687 char c[sizeof(long)];
1690 #if BYTEORDER == 0x1234
1691 u.c[0] = (l >> 24) & 255;
1692 u.c[1] = (l >> 16) & 255;
1693 u.c[2] = (l >> 8) & 255;
1697 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1698 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
1705 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1706 l |= (u.c[o & 0xf] & 255) << s;
1713 #endif /* BYTEORDER != 0x4321 */
1717 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
1718 * If these functions are defined,
1719 * the BYTEORDER is neither 0x1234 nor 0x4321.
1720 * However, this is not assumed.
1724 #define HTOV(name,type) \
1726 name (register type n) \
1730 char c[sizeof(type)]; \
1734 for (i = 0, s = 0; i < sizeof(u.c); i++, s += 8) { \
1735 u.c[i] = (n >> s) & 0xFF; \
1740 #define VTOH(name,type) \
1742 name (register type n) \
1746 char c[sizeof(type)]; \
1752 for (i = 0, s = 0; i < sizeof(u.c); i++, s += 8) { \
1753 n += (u.c[i] & 0xFF) << s; \
1758 #if defined(HAS_HTOVS) && !defined(htovs)
1761 #if defined(HAS_HTOVL) && !defined(htovl)
1764 #if defined(HAS_VTOHS) && !defined(vtohs)
1767 #if defined(HAS_VTOHL) && !defined(vtohl)
1772 Perl_my_popen_list(pTHX_ char *mode, int n, SV **args)
1774 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(OS2) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL) && !defined(NETWARE)
1776 register I32 This, that;
1782 PERL_FLUSHALL_FOR_CHILD;
1783 This = (*mode == 'w');
1787 taint_proper("Insecure %s%s", "EXEC");
1789 if (PerlProc_pipe(p) < 0)
1791 /* Try for another pipe pair for error return */
1792 if (PerlProc_pipe(pp) >= 0)
1794 while ((pid = PerlProc_fork()) < 0) {
1795 if (errno != EAGAIN) {
1796 PerlLIO_close(p[This]);
1797 PerlLIO_close(p[that]);
1799 PerlLIO_close(pp[0]);
1800 PerlLIO_close(pp[1]);
1812 /* Close parent's end of error status pipe (if any) */
1814 PerlLIO_close(pp[0]);
1815 #if defined(HAS_FCNTL) && defined(F_SETFD)
1816 /* Close error pipe automatically if exec works */
1817 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
1820 /* Now dup our end of _the_ pipe to right position */
1821 if (p[THIS] != (*mode == 'r')) {
1822 PerlLIO_dup2(p[THIS], *mode == 'r');
1823 PerlLIO_close(p[THIS]);
1824 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
1825 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
1828 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
1829 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
1830 /* No automatic close - do it by hand */
1837 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
1843 do_aexec5(Nullsv, args-1, args-1+n, pp[1], did_pipes);
1849 do_execfree(); /* free any memory malloced by child on fork */
1851 PerlLIO_close(pp[1]);
1852 /* Keep the lower of the two fd numbers */
1853 if (p[that] < p[This]) {
1854 PerlLIO_dup2(p[This], p[that]);
1855 PerlLIO_close(p[This]);
1859 PerlLIO_close(p[that]); /* close child's end of pipe */
1862 sv = *av_fetch(PL_fdpid,p[This],TRUE);
1864 (void)SvUPGRADE(sv,SVt_IV);
1866 PL_forkprocess = pid;
1867 /* If we managed to get status pipe check for exec fail */
1868 if (did_pipes && pid > 0) {
1872 while (n < sizeof(int)) {
1873 n1 = PerlLIO_read(pp[0],
1874 (void*)(((char*)&errkid)+n),
1880 PerlLIO_close(pp[0]);
1882 if (n) { /* Error */
1884 PerlLIO_close(p[This]);
1885 if (n != sizeof(int))
1886 Perl_croak(aTHX_ "panic: kid popen errno read");
1888 pid2 = wait4pid(pid, &status, 0);
1889 } while (pid2 == -1 && errno == EINTR);
1890 errno = errkid; /* Propagate errno from kid */
1895 PerlLIO_close(pp[0]);
1896 return PerlIO_fdopen(p[This], mode);
1898 Perl_croak(aTHX_ "List form of piped open not implemented");
1899 return (PerlIO *) NULL;
1903 /* VMS' my_popen() is in VMS.c, same with OS/2. */
1904 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
1906 Perl_my_popen(pTHX_ char *cmd, char *mode)
1909 register I32 This, that;
1912 I32 doexec = strNE(cmd,"-");
1916 PERL_FLUSHALL_FOR_CHILD;
1919 return my_syspopen(aTHX_ cmd,mode);
1922 This = (*mode == 'w');
1924 if (doexec && PL_tainting) {
1926 taint_proper("Insecure %s%s", "EXEC");
1928 if (PerlProc_pipe(p) < 0)
1930 if (doexec && PerlProc_pipe(pp) >= 0)
1932 while ((pid = PerlProc_fork()) < 0) {
1933 if (errno != EAGAIN) {
1934 PerlLIO_close(p[This]);
1935 PerlLIO_close(p[that]);
1937 PerlLIO_close(pp[0]);
1938 PerlLIO_close(pp[1]);
1941 Perl_croak(aTHX_ "Can't fork");
1954 PerlLIO_close(pp[0]);
1955 #if defined(HAS_FCNTL) && defined(F_SETFD)
1956 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
1959 if (p[THIS] != (*mode == 'r')) {
1960 PerlLIO_dup2(p[THIS], *mode == 'r');
1961 PerlLIO_close(p[THIS]);
1962 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
1963 PerlLIO_close(p[THAT]);
1966 PerlLIO_close(p[THAT]);
1969 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
1978 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
1983 /* may or may not use the shell */
1984 do_exec3(cmd, pp[1], did_pipes);
1987 #endif /* defined OS2 */
1989 if ((tmpgv = gv_fetchpv("$",TRUE, SVt_PV))) {
1990 SvREADONLY_off(GvSV(tmpgv));
1991 sv_setiv(GvSV(tmpgv), PerlProc_getpid());
1992 SvREADONLY_on(GvSV(tmpgv));
1994 #ifdef THREADS_HAVE_PIDS
1995 PL_ppid = (IV)getppid();
1998 hv_clear(PL_pidstatus); /* we have no children */
2003 do_execfree(); /* free any memory malloced by child on vfork */
2005 PerlLIO_close(pp[1]);
2006 if (p[that] < p[This]) {
2007 PerlLIO_dup2(p[This], p[that]);
2008 PerlLIO_close(p[This]);
2012 PerlLIO_close(p[that]);
2015 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2017 (void)SvUPGRADE(sv,SVt_IV);
2019 PL_forkprocess = pid;
2020 if (did_pipes && pid > 0) {
2024 while (n < sizeof(int)) {
2025 n1 = PerlLIO_read(pp[0],
2026 (void*)(((char*)&errkid)+n),
2032 PerlLIO_close(pp[0]);
2034 if (n) { /* Error */
2036 PerlLIO_close(p[This]);
2037 if (n != sizeof(int))
2038 Perl_croak(aTHX_ "panic: kid popen errno read");
2040 pid2 = wait4pid(pid, &status, 0);
2041 } while (pid2 == -1 && errno == EINTR);
2042 errno = errkid; /* Propagate errno from kid */
2047 PerlLIO_close(pp[0]);
2048 return PerlIO_fdopen(p[This], mode);
2051 #if defined(atarist) || defined(EPOC)
2054 Perl_my_popen(pTHX_ char *cmd, char *mode)
2056 PERL_FLUSHALL_FOR_CHILD;
2057 /* Call system's popen() to get a FILE *, then import it.
2058 used 0 for 2nd parameter to PerlIO_importFILE;
2061 return PerlIO_importFILE(popen(cmd, mode), 0);
2065 FILE *djgpp_popen();
2067 Perl_my_popen(pTHX_ char *cmd, char *mode)
2069 PERL_FLUSHALL_FOR_CHILD;
2070 /* Call system's popen() to get a FILE *, then import it.
2071 used 0 for 2nd parameter to PerlIO_importFILE;
2074 return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2079 #endif /* !DOSISH */
2081 /* this is called in parent before the fork() */
2083 Perl_atfork_lock(void)
2085 #if defined(USE_5005THREADS) || defined(USE_ITHREADS)
2086 /* locks must be held in locking order (if any) */
2088 MUTEX_LOCK(&PL_malloc_mutex);
2094 /* this is called in both parent and child after the fork() */
2096 Perl_atfork_unlock(void)
2098 #if defined(USE_5005THREADS) || defined(USE_ITHREADS)
2099 /* locks must be released in same order as in atfork_lock() */
2101 MUTEX_UNLOCK(&PL_malloc_mutex);
2110 #if defined(HAS_FORK)
2112 #if (defined(USE_5005THREADS) || defined(USE_ITHREADS)) && !defined(HAS_PTHREAD_ATFORK)
2117 /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2118 * handlers elsewhere in the code */
2123 /* this "canna happen" since nothing should be calling here if !HAS_FORK */
2124 Perl_croak_nocontext("fork() not available");
2126 #endif /* HAS_FORK */
2131 Perl_dump_fds(pTHX_ char *s)
2136 PerlIO_printf(Perl_debug_log,"%s", s);
2137 for (fd = 0; fd < 32; fd++) {
2138 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
2139 PerlIO_printf(Perl_debug_log," %d",fd);
2141 PerlIO_printf(Perl_debug_log,"\n");
2143 #endif /* DUMP_FDS */
2147 dup2(int oldfd, int newfd)
2149 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2152 PerlLIO_close(newfd);
2153 return fcntl(oldfd, F_DUPFD, newfd);
2155 #define DUP2_MAX_FDS 256
2156 int fdtmp[DUP2_MAX_FDS];
2162 PerlLIO_close(newfd);
2163 /* good enough for low fd's... */
2164 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2165 if (fdx >= DUP2_MAX_FDS) {
2173 PerlLIO_close(fdtmp[--fdx]);
2180 #ifdef HAS_SIGACTION
2183 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2185 struct sigaction act, oact;
2188 /* only "parent" interpreter can diddle signals */
2189 if (PL_curinterp != aTHX)
2193 act.sa_handler = handler;
2194 sigemptyset(&act.sa_mask);
2197 #if defined(PERL_OLD_SIGNALS)
2198 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2202 if (signo == SIGCHLD && handler == (Sighandler_t)SIG_IGN)
2203 act.sa_flags |= SA_NOCLDWAIT;
2205 if (sigaction(signo, &act, &oact) == -1)
2208 return oact.sa_handler;
2212 Perl_rsignal_state(pTHX_ int signo)
2214 struct sigaction oact;
2216 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2219 return oact.sa_handler;
2223 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2225 struct sigaction act;
2228 /* only "parent" interpreter can diddle signals */
2229 if (PL_curinterp != aTHX)
2233 act.sa_handler = handler;
2234 sigemptyset(&act.sa_mask);
2237 #if defined(PERL_OLD_SIGNALS)
2238 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2242 if (signo == SIGCHLD && handler == (Sighandler_t)SIG_IGN)
2243 act.sa_flags |= SA_NOCLDWAIT;
2245 return sigaction(signo, &act, save);
2249 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2252 /* only "parent" interpreter can diddle signals */
2253 if (PL_curinterp != aTHX)
2257 return sigaction(signo, save, (struct sigaction *)NULL);
2260 #else /* !HAS_SIGACTION */
2263 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2265 #if defined(USE_ITHREADS) && !defined(WIN32)
2266 /* only "parent" interpreter can diddle signals */
2267 if (PL_curinterp != aTHX)
2271 return PerlProc_signal(signo, handler);
2274 static int sig_trapped; /* XXX signals are process-wide anyway, so we
2275 ignore the implications of this for threading */
2285 Perl_rsignal_state(pTHX_ int signo)
2287 Sighandler_t oldsig;
2289 #if defined(USE_ITHREADS) && !defined(WIN32)
2290 /* only "parent" interpreter can diddle signals */
2291 if (PL_curinterp != aTHX)
2296 oldsig = PerlProc_signal(signo, sig_trap);
2297 PerlProc_signal(signo, oldsig);
2299 PerlProc_kill(PerlProc_getpid(), signo);
2304 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2306 #if defined(USE_ITHREADS) && !defined(WIN32)
2307 /* only "parent" interpreter can diddle signals */
2308 if (PL_curinterp != aTHX)
2311 *save = PerlProc_signal(signo, handler);
2312 return (*save == SIG_ERR) ? -1 : 0;
2316 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2318 #if defined(USE_ITHREADS) && !defined(WIN32)
2319 /* only "parent" interpreter can diddle signals */
2320 if (PL_curinterp != aTHX)
2323 return (PerlProc_signal(signo, *save) == SIG_ERR) ? -1 : 0;
2326 #endif /* !HAS_SIGACTION */
2327 #endif /* !PERL_MICRO */
2329 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
2330 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
2332 Perl_my_pclose(pTHX_ PerlIO *ptr)
2334 Sigsave_t hstat, istat, qstat;
2340 int saved_errno = 0;
2342 int saved_vaxc_errno;
2345 int saved_win32_errno;
2349 svp = av_fetch(PL_fdpid,PerlIO_fileno(ptr),TRUE);
2351 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
2353 *svp = &PL_sv_undef;
2355 if (pid == -1) { /* Opened by popen. */
2356 return my_syspclose(ptr);
2359 if ((close_failed = (PerlIO_close(ptr) == EOF))) {
2360 saved_errno = errno;
2362 saved_vaxc_errno = vaxc$errno;
2365 saved_win32_errno = GetLastError();
2369 if(PerlProc_kill(pid, 0) < 0) { return(pid); } /* HOM 12/23/91 */
2372 rsignal_save(SIGHUP, SIG_IGN, &hstat);
2373 rsignal_save(SIGINT, SIG_IGN, &istat);
2374 rsignal_save(SIGQUIT, SIG_IGN, &qstat);
2377 pid2 = wait4pid(pid, &status, 0);
2378 } while (pid2 == -1 && errno == EINTR);
2380 rsignal_restore(SIGHUP, &hstat);
2381 rsignal_restore(SIGINT, &istat);
2382 rsignal_restore(SIGQUIT, &qstat);
2385 SETERRNO(saved_errno, saved_vaxc_errno);
2388 return(pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status));
2390 #endif /* !DOSISH */
2392 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(MACOS_TRADITIONAL)
2394 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
2399 #if !defined(HAS_WAITPID) && !defined(HAS_WAIT4) || defined(HAS_WAITPID_RUNTIME)
2403 char spid[TYPE_CHARS(int)];
2406 sprintf(spid, "%"IVdf, (IV)pid);
2407 svp = hv_fetch(PL_pidstatus,spid,strlen(spid),FALSE);
2408 if (svp && *svp != &PL_sv_undef) {
2409 *statusp = SvIVX(*svp);
2410 (void)hv_delete(PL_pidstatus,spid,strlen(spid),G_DISCARD);
2417 hv_iterinit(PL_pidstatus);
2418 if ((entry = hv_iternext(PL_pidstatus))) {
2420 char spid[TYPE_CHARS(int)];
2422 pid = atoi(hv_iterkey(entry,(I32*)statusp));
2423 sv = hv_iterval(PL_pidstatus,entry);
2424 *statusp = SvIVX(sv);
2425 sprintf(spid, "%"IVdf, (IV)pid);
2426 (void)hv_delete(PL_pidstatus,spid,strlen(spid),G_DISCARD);
2433 # ifdef HAS_WAITPID_RUNTIME
2434 if (!HAS_WAITPID_RUNTIME)
2437 result = PerlProc_waitpid(pid,statusp,flags);
2440 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
2441 result = wait4((pid==-1)?0:pid,statusp,flags,Null(struct rusage *));
2444 #if !defined(HAS_WAITPID) && !defined(HAS_WAIT4) || defined(HAS_WAITPID_RUNTIME)
2448 Perl_croak(aTHX_ "Can't do waitpid with flags");
2450 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
2451 pidgone(result,*statusp);
2458 if (result < 0 && errno == EINTR) {
2463 #endif /* !DOSISH || OS2 || WIN32 || NETWARE */
2467 Perl_pidgone(pTHX_ Pid_t pid, int status)
2470 char spid[TYPE_CHARS(int)];
2472 sprintf(spid, "%"IVdf, (IV)pid);
2473 sv = *hv_fetch(PL_pidstatus,spid,strlen(spid),TRUE);
2474 (void)SvUPGRADE(sv,SVt_IV);
2479 #if defined(atarist) || defined(OS2) || defined(EPOC)
2482 int /* Cannot prototype with I32
2484 my_syspclose(PerlIO *ptr)
2487 Perl_my_pclose(pTHX_ PerlIO *ptr)
2490 /* Needs work for PerlIO ! */
2491 FILE *f = PerlIO_findFILE(ptr);
2492 I32 result = pclose(f);
2493 PerlIO_releaseFILE(ptr,f);
2501 Perl_my_pclose(pTHX_ PerlIO *ptr)
2503 /* Needs work for PerlIO ! */
2504 FILE *f = PerlIO_findFILE(ptr);
2505 I32 result = djgpp_pclose(f);
2506 result = (result << 8) & 0xff00;
2507 PerlIO_releaseFILE(ptr,f);
2513 Perl_repeatcpy(pTHX_ register char *to, register const char *from, I32 len, register I32 count)
2516 register const char *frombase = from;
2519 register const char c = *from;
2524 while (count-- > 0) {
2525 for (todo = len; todo > 0; todo--) {
2534 Perl_same_dirent(pTHX_ char *a, char *b)
2536 char *fa = strrchr(a,'/');
2537 char *fb = strrchr(b,'/');
2540 SV *tmpsv = sv_newmortal();
2553 sv_setpv(tmpsv, ".");
2555 sv_setpvn(tmpsv, a, fa - a);
2556 if (PerlLIO_stat(SvPVX(tmpsv), &tmpstatbuf1) < 0)
2559 sv_setpv(tmpsv, ".");
2561 sv_setpvn(tmpsv, b, fb - b);
2562 if (PerlLIO_stat(SvPVX(tmpsv), &tmpstatbuf2) < 0)
2564 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
2565 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
2567 #endif /* !HAS_RENAME */
2570 Perl_find_script(pTHX_ char *scriptname, bool dosearch, char **search_ext, I32 flags)
2572 char *xfound = Nullch;
2573 char *xfailed = Nullch;
2574 char tmpbuf[MAXPATHLEN];
2578 #if defined(DOSISH) && !defined(OS2) && !defined(atarist)
2579 # define SEARCH_EXTS ".bat", ".cmd", NULL
2580 # define MAX_EXT_LEN 4
2583 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
2584 # define MAX_EXT_LEN 4
2587 # define SEARCH_EXTS ".pl", ".com", NULL
2588 # define MAX_EXT_LEN 4
2590 /* additional extensions to try in each dir if scriptname not found */
2592 char *exts[] = { SEARCH_EXTS };
2593 char **ext = search_ext ? search_ext : exts;
2594 int extidx = 0, i = 0;
2595 char *curext = Nullch;
2597 # define MAX_EXT_LEN 0
2601 * If dosearch is true and if scriptname does not contain path
2602 * delimiters, search the PATH for scriptname.
2604 * If SEARCH_EXTS is also defined, will look for each
2605 * scriptname{SEARCH_EXTS} whenever scriptname is not found
2606 * while searching the PATH.
2608 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
2609 * proceeds as follows:
2610 * If DOSISH or VMSISH:
2611 * + look for ./scriptname{,.foo,.bar}
2612 * + search the PATH for scriptname{,.foo,.bar}
2615 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
2616 * this will not look in '.' if it's not in the PATH)
2621 # ifdef ALWAYS_DEFTYPES
2622 len = strlen(scriptname);
2623 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
2624 int hasdir, idx = 0, deftypes = 1;
2627 hasdir = !dosearch || (strpbrk(scriptname,":[</") != Nullch) ;
2630 int hasdir, idx = 0, deftypes = 1;
2633 hasdir = (strpbrk(scriptname,":[</") != Nullch) ;
2635 /* The first time through, just add SEARCH_EXTS to whatever we
2636 * already have, so we can check for default file types. */
2638 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
2644 if ((strlen(tmpbuf) + strlen(scriptname)
2645 + MAX_EXT_LEN) >= sizeof tmpbuf)
2646 continue; /* don't search dir with too-long name */
2647 strcat(tmpbuf, scriptname);
2651 if (strEQ(scriptname, "-"))
2653 if (dosearch) { /* Look in '.' first. */
2654 char *cur = scriptname;
2656 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
2658 if (strEQ(ext[i++],curext)) {
2659 extidx = -1; /* already has an ext */
2664 DEBUG_p(PerlIO_printf(Perl_debug_log,
2665 "Looking for %s\n",cur));
2666 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
2667 && !S_ISDIR(PL_statbuf.st_mode)) {
2675 if (cur == scriptname) {
2676 len = strlen(scriptname);
2677 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
2679 cur = strcpy(tmpbuf, scriptname);
2681 } while (extidx >= 0 && ext[extidx] /* try an extension? */
2682 && strcpy(tmpbuf+len, ext[extidx++]));
2687 #ifdef MACOS_TRADITIONAL
2688 if (dosearch && !strchr(scriptname, ':') &&
2689 (s = PerlEnv_getenv("Commands")))
2691 if (dosearch && !strchr(scriptname, '/')
2693 && !strchr(scriptname, '\\')
2695 && (s = PerlEnv_getenv("PATH")))
2700 PL_bufend = s + strlen(s);
2701 while (s < PL_bufend) {
2702 #ifdef MACOS_TRADITIONAL
2703 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
2707 #if defined(atarist) || defined(DOSISH)
2712 && *s != ';'; len++, s++) {
2713 if (len < sizeof tmpbuf)
2716 if (len < sizeof tmpbuf)
2718 #else /* ! (atarist || DOSISH) */
2719 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
2722 #endif /* ! (atarist || DOSISH) */
2723 #endif /* MACOS_TRADITIONAL */
2726 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
2727 continue; /* don't search dir with too-long name */
2728 #ifdef MACOS_TRADITIONAL
2729 if (len && tmpbuf[len - 1] != ':')
2730 tmpbuf[len++] = ':';
2733 #if defined(atarist) || defined(__MINT__) || defined(DOSISH)
2734 && tmpbuf[len - 1] != '/'
2735 && tmpbuf[len - 1] != '\\'
2738 tmpbuf[len++] = '/';
2739 if (len == 2 && tmpbuf[0] == '.')
2742 (void)strcpy(tmpbuf + len, scriptname);
2746 len = strlen(tmpbuf);
2747 if (extidx > 0) /* reset after previous loop */
2751 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
2752 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
2753 if (S_ISDIR(PL_statbuf.st_mode)) {
2757 } while ( retval < 0 /* not there */
2758 && extidx>=0 && ext[extidx] /* try an extension? */
2759 && strcpy(tmpbuf+len, ext[extidx++])
2764 if (S_ISREG(PL_statbuf.st_mode)
2765 && cando(S_IRUSR,TRUE,&PL_statbuf)
2766 #if !defined(DOSISH) && !defined(MACOS_TRADITIONAL)
2767 && cando(S_IXUSR,TRUE,&PL_statbuf)
2771 xfound = tmpbuf; /* bingo! */
2775 xfailed = savepv(tmpbuf);
2778 if (!xfound && !seen_dot && !xfailed &&
2779 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
2780 || S_ISDIR(PL_statbuf.st_mode)))
2782 seen_dot = 1; /* Disable message. */
2784 if (flags & 1) { /* do or die? */
2785 Perl_croak(aTHX_ "Can't %s %s%s%s",
2786 (xfailed ? "execute" : "find"),
2787 (xfailed ? xfailed : scriptname),
2788 (xfailed ? "" : " on PATH"),
2789 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
2791 scriptname = Nullch;
2795 scriptname = xfound;
2797 return (scriptname ? savepv(scriptname) : Nullch);
2800 #ifndef PERL_GET_CONTEXT_DEFINED
2803 Perl_get_context(void)
2805 #if defined(USE_5005THREADS) || defined(USE_ITHREADS)
2806 # ifdef OLD_PTHREADS_API
2808 if (pthread_getspecific(PL_thr_key, &t))
2809 Perl_croak_nocontext("panic: pthread_getspecific");
2812 # ifdef I_MACH_CTHREADS
2813 return (void*)cthread_data(cthread_self());
2815 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
2824 Perl_set_context(void *t)
2826 #if defined(USE_5005THREADS) || defined(USE_ITHREADS)
2827 # ifdef I_MACH_CTHREADS
2828 cthread_set_data(cthread_self(), t);
2830 if (pthread_setspecific(PL_thr_key, t))
2831 Perl_croak_nocontext("panic: pthread_setspecific");
2836 #endif /* !PERL_GET_CONTEXT_DEFINED */
2838 #ifdef USE_5005THREADS
2841 /* Very simplistic scheduler for now */
2845 thr = thr->i.next_run;
2849 Perl_cond_init(pTHX_ perl_cond *cp)
2855 Perl_cond_signal(pTHX_ perl_cond *cp)
2858 perl_cond cond = *cp;
2863 /* Insert t in the runnable queue just ahead of us */
2864 t->i.next_run = thr->i.next_run;
2865 thr->i.next_run->i.prev_run = t;
2866 t->i.prev_run = thr;
2867 thr->i.next_run = t;
2868 thr->i.wait_queue = 0;
2869 /* Remove from the wait queue */
2875 Perl_cond_broadcast(pTHX_ perl_cond *cp)
2878 perl_cond cond, cond_next;
2880 for (cond = *cp; cond; cond = cond_next) {
2882 /* Insert t in the runnable queue just ahead of us */
2883 t->i.next_run = thr->i.next_run;
2884 thr->i.next_run->i.prev_run = t;
2885 t->i.prev_run = thr;
2886 thr->i.next_run = t;
2887 thr->i.wait_queue = 0;
2888 /* Remove from the wait queue */
2889 cond_next = cond->next;
2896 Perl_cond_wait(pTHX_ perl_cond *cp)
2900 if (thr->i.next_run == thr)
2901 Perl_croak(aTHX_ "panic: perl_cond_wait called by last runnable thread");
2903 New(666, cond, 1, struct perl_wait_queue);
2907 thr->i.wait_queue = cond;
2908 /* Remove ourselves from runnable queue */
2909 thr->i.next_run->i.prev_run = thr->i.prev_run;
2910 thr->i.prev_run->i.next_run = thr->i.next_run;
2912 #endif /* FAKE_THREADS */
2915 Perl_condpair_magic(pTHX_ SV *sv)
2919 (void)SvUPGRADE(sv, SVt_PVMG);
2920 mg = mg_find(sv, PERL_MAGIC_mutex);
2924 New(53, cp, 1, condpair_t);
2925 MUTEX_INIT(&cp->mutex);
2926 COND_INIT(&cp->owner_cond);
2927 COND_INIT(&cp->cond);
2929 LOCK_CRED_MUTEX; /* XXX need separate mutex? */
2930 mg = mg_find(sv, PERL_MAGIC_mutex);
2932 /* someone else beat us to initialising it */
2933 UNLOCK_CRED_MUTEX; /* XXX need separate mutex? */
2934 MUTEX_DESTROY(&cp->mutex);
2935 COND_DESTROY(&cp->owner_cond);
2936 COND_DESTROY(&cp->cond);
2940 sv_magic(sv, Nullsv, PERL_MAGIC_mutex, 0, 0);
2942 mg->mg_ptr = (char *)cp;
2943 mg->mg_len = sizeof(cp);
2944 UNLOCK_CRED_MUTEX; /* XXX need separate mutex? */
2945 DEBUG_S(WITH_THR(PerlIO_printf(Perl_debug_log,
2946 "%p: condpair_magic %p\n", thr, sv)));
2953 Perl_sv_lock(pTHX_ SV *osv)
2963 mg = condpair_magic(sv);
2964 MUTEX_LOCK(MgMUTEXP(mg));
2965 if (MgOWNER(mg) == thr)
2966 MUTEX_UNLOCK(MgMUTEXP(mg));
2969 COND_WAIT(MgOWNERCONDP(mg), MgMUTEXP(mg));
2971 DEBUG_S(PerlIO_printf(Perl_debug_log,
2972 "0x%"UVxf": Perl_lock lock 0x%"UVxf"\n",
2973 PTR2UV(thr), PTR2UV(sv)));
2974 MUTEX_UNLOCK(MgMUTEXP(mg));
2975 SAVEDESTRUCTOR_X(Perl_unlock_condpair, sv);
2977 UNLOCK_SV_LOCK_MUTEX;
2982 * Make a new perl thread structure using t as a prototype. Some of the
2983 * fields for the new thread are copied from the prototype thread, t,
2984 * so t should not be running in perl at the time this function is
2985 * called. The use by ext/Thread/Thread.xs in core perl (where t is the
2986 * thread calling new_struct_thread) clearly satisfies this constraint.
2988 struct perl_thread *
2989 Perl_new_struct_thread(pTHX_ struct perl_thread *t)
2991 #if !defined(PERL_IMPLICIT_CONTEXT)
2992 struct perl_thread *thr;
2998 sv = newSVpvn("", 0);
2999 SvGROW(sv, sizeof(struct perl_thread) + 1);
3000 SvCUR_set(sv, sizeof(struct perl_thread));
3001 thr = (Thread) SvPVX(sv);
3003 Poison(thr, 1, struct perl_thread);
3010 Zero(&PL_hv_fetch_ent_mh, 1, HE);
3011 PL_efloatbuf = (char*)NULL;
3014 Zero(thr, 1, struct perl_thread);
3020 PL_curcop = &PL_compiling;
3021 thr->interp = t->interp;
3022 thr->cvcache = newHV();
3023 thr->threadsv = newAV();
3024 thr->specific = newAV();
3025 thr->errsv = newSVpvn("", 0);
3026 thr->flags = THRf_R_JOINABLE;
3028 MUTEX_INIT(&thr->mutex);
3032 PL_in_eval = EVAL_NULL; /* ~(EVAL_INEVAL|EVAL_WARNONLY|EVAL_KEEPERR|EVAL_INREQUIRE) */
3035 PL_statname = NEWSV(66,0);
3036 PL_errors = newSVpvn("", 0);
3038 PL_regcompp = MEMBER_TO_FPTR(Perl_pregcomp);
3039 PL_regexecp = MEMBER_TO_FPTR(Perl_regexec_flags);
3040 PL_regint_start = MEMBER_TO_FPTR(Perl_re_intuit_start);
3041 PL_regint_string = MEMBER_TO_FPTR(Perl_re_intuit_string);
3042 PL_regfree = MEMBER_TO_FPTR(Perl_pregfree);
3044 PL_reginterp_cnt = 0;
3045 PL_lastscream = Nullsv;
3048 PL_reg_start_tmp = 0;
3049 PL_reg_start_tmpl = 0;
3050 PL_reg_poscache = Nullch;
3052 PL_peepp = MEMBER_TO_FPTR(Perl_peep);
3054 /* parent thread's data needs to be locked while we make copy */
3055 MUTEX_LOCK(&t->mutex);
3057 #ifdef PERL_FLEXIBLE_EXCEPTIONS
3058 PL_protect = t->Tprotect;
3061 PL_curcop = t->Tcurcop; /* XXX As good a guess as any? */
3062 PL_defstash = t->Tdefstash; /* XXX maybe these should */
3063 PL_curstash = t->Tcurstash; /* always be set to main? */
3065 PL_tainted = t->Ttainted;
3066 PL_curpm = t->Tcurpm; /* XXX No PMOP ref count */
3067 PL_rs = newSVsv(t->Trs);
3068 PL_last_in_gv = Nullgv;
3069 PL_ofs_sv = t->Tofs_sv ? SvREFCNT_inc(PL_ofs_sv) : Nullsv;
3070 PL_defoutgv = (GV*)SvREFCNT_inc(t->Tdefoutgv);
3071 PL_chopset = t->Tchopset;
3072 PL_bodytarget = newSVsv(t->Tbodytarget);
3073 PL_toptarget = newSVsv(t->Ttoptarget);
3074 if (t->Tformtarget == t->Ttoptarget)
3075 PL_formtarget = PL_toptarget;
3077 PL_formtarget = PL_bodytarget;
3079 /* Initialise all per-thread SVs that the template thread used */
3080 svp = AvARRAY(t->threadsv);
3081 for (i = 0; i <= AvFILLp(t->threadsv); i++, svp++) {
3082 if (*svp && *svp != &PL_sv_undef) {
3083 SV *sv = newSVsv(*svp);
3084 av_store(thr->threadsv, i, sv);
3085 sv_magic(sv, 0, PERL_MAGIC_sv, &PL_threadsv_names[i], 1);
3086 DEBUG_S(PerlIO_printf(Perl_debug_log,
3087 "new_struct_thread: copied threadsv %"IVdf" %p->%p\n",
3091 thr->threadsvp = AvARRAY(thr->threadsv);
3093 MUTEX_LOCK(&PL_threads_mutex);
3095 thr->tid = ++PL_threadnum;
3096 thr->next = t->next;
3099 thr->next->prev = thr;
3100 MUTEX_UNLOCK(&PL_threads_mutex);
3102 /* done copying parent's state */
3103 MUTEX_UNLOCK(&t->mutex);
3105 #ifdef HAVE_THREAD_INTERN
3106 Perl_init_thread_intern(thr);
3107 #endif /* HAVE_THREAD_INTERN */
3110 #endif /* USE_5005THREADS */
3112 #ifdef PERL_GLOBAL_STRUCT
3121 Perl_get_op_names(pTHX)
3127 Perl_get_op_descs(pTHX)
3133 Perl_get_no_modify(pTHX)
3135 return (char*)PL_no_modify;
3139 Perl_get_opargs(pTHX)
3145 Perl_get_ppaddr(pTHX)
3147 return (PPADDR_t*)PL_ppaddr;
3150 #ifndef HAS_GETENV_LEN
3152 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3154 char *env_trans = PerlEnv_getenv(env_elem);
3156 *len = strlen(env_trans);
3163 Perl_get_vtbl(pTHX_ int vtbl_id)
3165 MGVTBL* result = Null(MGVTBL*);
3169 result = &PL_vtbl_sv;
3172 result = &PL_vtbl_env;
3174 case want_vtbl_envelem:
3175 result = &PL_vtbl_envelem;
3178 result = &PL_vtbl_sig;
3180 case want_vtbl_sigelem:
3181 result = &PL_vtbl_sigelem;
3183 case want_vtbl_pack:
3184 result = &PL_vtbl_pack;
3186 case want_vtbl_packelem:
3187 result = &PL_vtbl_packelem;
3189 case want_vtbl_dbline:
3190 result = &PL_vtbl_dbline;
3193 result = &PL_vtbl_isa;
3195 case want_vtbl_isaelem:
3196 result = &PL_vtbl_isaelem;
3198 case want_vtbl_arylen:
3199 result = &PL_vtbl_arylen;
3201 case want_vtbl_glob:
3202 result = &PL_vtbl_glob;
3204 case want_vtbl_mglob:
3205 result = &PL_vtbl_mglob;
3207 case want_vtbl_nkeys:
3208 result = &PL_vtbl_nkeys;
3210 case want_vtbl_taint:
3211 result = &PL_vtbl_taint;
3213 case want_vtbl_substr:
3214 result = &PL_vtbl_substr;
3217 result = &PL_vtbl_vec;
3220 result = &PL_vtbl_pos;
3223 result = &PL_vtbl_bm;
3226 result = &PL_vtbl_fm;
3228 case want_vtbl_uvar:
3229 result = &PL_vtbl_uvar;
3231 #ifdef USE_5005THREADS
3232 case want_vtbl_mutex:
3233 result = &PL_vtbl_mutex;
3236 case want_vtbl_defelem:
3237 result = &PL_vtbl_defelem;
3239 case want_vtbl_regexp:
3240 result = &PL_vtbl_regexp;
3242 case want_vtbl_regdata:
3243 result = &PL_vtbl_regdata;
3245 case want_vtbl_regdatum:
3246 result = &PL_vtbl_regdatum;
3248 #ifdef USE_LOCALE_COLLATE
3249 case want_vtbl_collxfrm:
3250 result = &PL_vtbl_collxfrm;
3253 case want_vtbl_amagic:
3254 result = &PL_vtbl_amagic;
3256 case want_vtbl_amagicelem:
3257 result = &PL_vtbl_amagicelem;
3259 case want_vtbl_backref:
3260 result = &PL_vtbl_backref;
3267 Perl_my_fflush_all(pTHX)
3269 #if defined(FFLUSH_NULL)
3270 return PerlIO_flush(NULL);
3272 # if defined(HAS__FWALK)
3273 extern int fflush(FILE *);
3274 /* undocumented, unprototyped, but very useful BSDism */
3275 extern void _fwalk(int (*)(FILE *));
3279 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3281 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3282 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3284 # if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3285 open_max = sysconf(_SC_OPEN_MAX);
3288 open_max = FOPEN_MAX;
3291 open_max = OPEN_MAX;
3302 for (i = 0; i < open_max; i++)
3303 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3304 STDIO_STREAM_ARRAY[i]._file < open_max &&
3305 STDIO_STREAM_ARRAY[i]._flag)
3306 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3310 SETERRNO(EBADF,RMS_IFI);
3317 Perl_report_evil_fh(pTHX_ GV *gv, IO *io, I32 op)
3320 op == OP_READLINE ? "readline" : /* "<HANDLE>" not nice */
3321 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
3323 char *pars = OP_IS_FILETEST(op) ? "" : "()";
3324 char *type = OP_IS_SOCKET(op)
3325 || (gv && io && IoTYPE(io) == IoTYPE_SOCKET)
3326 ? "socket" : "filehandle";
3329 if (gv && isGV(gv)) {
3333 if (op == OP_phoney_OUTPUT_ONLY || op == OP_phoney_INPUT_ONLY) {
3334 if (ckWARN(WARN_IO)) {
3335 const char *direction = (op == OP_phoney_INPUT_ONLY) ? "in" : "out";
3337 Perl_warner(aTHX_ packWARN(WARN_IO),
3338 "Filehandle %s opened only for %sput",
3341 Perl_warner(aTHX_ packWARN(WARN_IO),
3342 "Filehandle opened only for %sput", direction);
3349 if (gv && io && IoTYPE(io) == IoTYPE_CLOSED) {
3351 warn_type = WARN_CLOSED;
3355 warn_type = WARN_UNOPENED;
3358 if (ckWARN(warn_type)) {
3359 if (name && *name) {
3360 Perl_warner(aTHX_ packWARN(warn_type),
3361 "%s%s on %s %s %s", func, pars, vile, type, name);
3362 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3364 aTHX_ packWARN(warn_type),
3365 "\t(Are you trying to call %s%s on dirhandle %s?)\n",
3370 Perl_warner(aTHX_ packWARN(warn_type),
3371 "%s%s on %s %s", func, pars, vile, type);
3372 if (gv && io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3374 aTHX_ packWARN(warn_type),
3375 "\t(Are you trying to call %s%s on dirhandle?)\n",
3384 /* in ASCII order, not that it matters */
3385 static const char controllablechars[] = "?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_";
3388 Perl_ebcdic_control(pTHX_ int ch)
3396 if ((ctlp = strchr(controllablechars, ch)) == 0) {
3397 Perl_die(aTHX_ "unrecognised control character '%c'\n", ch);
3400 if (ctlp == controllablechars)
3401 return('\177'); /* DEL */
3403 return((unsigned char)(ctlp - controllablechars - 1));
3404 } else { /* Want uncontrol */
3405 if (ch == '\177' || ch == -1)
3407 else if (ch == '\157')
3409 else if (ch == '\174')
3411 else if (ch == '^') /* '\137' in 1047, '\260' in 819 */
3413 else if (ch == '\155')
3415 else if (0 < ch && ch < (sizeof(controllablechars) - 1))
3416 return(controllablechars[ch+1]);
3418 Perl_die(aTHX_ "invalid control request: '\\%03o'\n", ch & 0xFF);
3423 /* To workaround core dumps from the uninitialised tm_zone we get the
3424 * system to give us a reasonable struct to copy. This fix means that
3425 * strftime uses the tm_zone and tm_gmtoff values returned by
3426 * localtime(time()). That should give the desired result most of the
3427 * time. But probably not always!
3429 * This does not address tzname aspects of NETaa14816.
3434 # ifndef STRUCT_TM_HASZONE
3435 # define STRUCT_TM_HASZONE
3439 #ifdef STRUCT_TM_HASZONE /* Backward compat */
3440 # ifndef HAS_TM_TM_ZONE
3441 # define HAS_TM_TM_ZONE
3446 Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
3448 #ifdef HAS_TM_TM_ZONE
3451 Copy(localtime(&now), ptm, 1, struct tm);
3456 * mini_mktime - normalise struct tm values without the localtime()
3457 * semantics (and overhead) of mktime().
3460 Perl_mini_mktime(pTHX_ struct tm *ptm)
3464 int month, mday, year, jday;
3465 int odd_cent, odd_year;
3467 #define DAYS_PER_YEAR 365
3468 #define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
3469 #define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
3470 #define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
3471 #define SECS_PER_HOUR (60*60)
3472 #define SECS_PER_DAY (24*SECS_PER_HOUR)
3473 /* parentheses deliberately absent on these two, otherwise they don't work */
3474 #define MONTH_TO_DAYS 153/5
3475 #define DAYS_TO_MONTH 5/153
3476 /* offset to bias by March (month 4) 1st between month/mday & year finding */
3477 #define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
3478 /* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
3479 #define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
3482 * Year/day algorithm notes:
3484 * With a suitable offset for numeric value of the month, one can find
3485 * an offset into the year by considering months to have 30.6 (153/5) days,
3486 * using integer arithmetic (i.e., with truncation). To avoid too much
3487 * messing about with leap days, we consider January and February to be
3488 * the 13th and 14th month of the previous year. After that transformation,
3489 * we need the month index we use to be high by 1 from 'normal human' usage,
3490 * so the month index values we use run from 4 through 15.
3492 * Given that, and the rules for the Gregorian calendar (leap years are those
3493 * divisible by 4 unless also divisible by 100, when they must be divisible
3494 * by 400 instead), we can simply calculate the number of days since some
3495 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
3496 * the days we derive from our month index, and adding in the day of the
3497 * month. The value used here is not adjusted for the actual origin which
3498 * it normally would use (1 January A.D. 1), since we're not exposing it.
3499 * We're only building the value so we can turn around and get the
3500 * normalised values for the year, month, day-of-month, and day-of-year.
3502 * For going backward, we need to bias the value we're using so that we find
3503 * the right year value. (Basically, we don't want the contribution of
3504 * March 1st to the number to apply while deriving the year). Having done
3505 * that, we 'count up' the contribution to the year number by accounting for
3506 * full quadracenturies (400-year periods) with their extra leap days, plus
3507 * the contribution from full centuries (to avoid counting in the lost leap
3508 * days), plus the contribution from full quad-years (to count in the normal
3509 * leap days), plus the leftover contribution from any non-leap years.
3510 * At this point, if we were working with an actual leap day, we'll have 0
3511 * days left over. This is also true for March 1st, however. So, we have
3512 * to special-case that result, and (earlier) keep track of the 'odd'
3513 * century and year contributions. If we got 4 extra centuries in a qcent,
3514 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
3515 * Otherwise, we add back in the earlier bias we removed (the 123 from
3516 * figuring in March 1st), find the month index (integer division by 30.6),
3517 * and the remainder is the day-of-month. We then have to convert back to
3518 * 'real' months (including fixing January and February from being 14/15 in
3519 * the previous year to being in the proper year). After that, to get
3520 * tm_yday, we work with the normalised year and get a new yearday value for
3521 * January 1st, which we subtract from the yearday value we had earlier,
3522 * representing the date we've re-built. This is done from January 1
3523 * because tm_yday is 0-origin.
3525 * Since POSIX time routines are only guaranteed to work for times since the
3526 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
3527 * applies Gregorian calendar rules even to dates before the 16th century
3528 * doesn't bother me. Besides, you'd need cultural context for a given
3529 * date to know whether it was Julian or Gregorian calendar, and that's
3530 * outside the scope for this routine. Since we convert back based on the
3531 * same rules we used to build the yearday, you'll only get strange results
3532 * for input which needed normalising, or for the 'odd' century years which
3533 * were leap years in the Julian calander but not in the Gregorian one.
3534 * I can live with that.
3536 * This algorithm also fails to handle years before A.D. 1 gracefully, but
3537 * that's still outside the scope for POSIX time manipulation, so I don't
3541 year = 1900 + ptm->tm_year;
3542 month = ptm->tm_mon;
3543 mday = ptm->tm_mday;
3544 /* allow given yday with no month & mday to dominate the result */
3545 if (ptm->tm_yday >= 0 && mday <= 0 && month <= 0) {
3548 jday = 1 + ptm->tm_yday;
3557 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
3558 yearday += month*MONTH_TO_DAYS + mday + jday;
3560 * Note that we don't know when leap-seconds were or will be,
3561 * so we have to trust the user if we get something which looks
3562 * like a sensible leap-second. Wild values for seconds will
3563 * be rationalised, however.
3565 if ((unsigned) ptm->tm_sec <= 60) {
3572 secs += 60 * ptm->tm_min;
3573 secs += SECS_PER_HOUR * ptm->tm_hour;
3575 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
3576 /* got negative remainder, but need positive time */
3577 /* back off an extra day to compensate */
3578 yearday += (secs/SECS_PER_DAY)-1;
3579 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
3582 yearday += (secs/SECS_PER_DAY);
3583 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
3586 else if (secs >= SECS_PER_DAY) {
3587 yearday += (secs/SECS_PER_DAY);
3588 secs %= SECS_PER_DAY;
3590 ptm->tm_hour = secs/SECS_PER_HOUR;
3591 secs %= SECS_PER_HOUR;
3592 ptm->tm_min = secs/60;
3594 ptm->tm_sec += secs;
3595 /* done with time of day effects */
3597 * The algorithm for yearday has (so far) left it high by 428.
3598 * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
3599 * bias it by 123 while trying to figure out what year it
3600 * really represents. Even with this tweak, the reverse
3601 * translation fails for years before A.D. 0001.
3602 * It would still fail for Feb 29, but we catch that one below.
3604 jday = yearday; /* save for later fixup vis-a-vis Jan 1 */
3605 yearday -= YEAR_ADJUST;
3606 year = (yearday / DAYS_PER_QCENT) * 400;
3607 yearday %= DAYS_PER_QCENT;
3608 odd_cent = yearday / DAYS_PER_CENT;
3609 year += odd_cent * 100;
3610 yearday %= DAYS_PER_CENT;
3611 year += (yearday / DAYS_PER_QYEAR) * 4;
3612 yearday %= DAYS_PER_QYEAR;
3613 odd_year = yearday / DAYS_PER_YEAR;
3615 yearday %= DAYS_PER_YEAR;
3616 if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
3621 yearday += YEAR_ADJUST; /* recover March 1st crock */
3622 month = yearday*DAYS_TO_MONTH;
3623 yearday -= month*MONTH_TO_DAYS;
3624 /* recover other leap-year adjustment */
3633 ptm->tm_year = year - 1900;
3635 ptm->tm_mday = yearday;
3636 ptm->tm_mon = month;
3640 ptm->tm_mon = month - 1;
3642 /* re-build yearday based on Jan 1 to get tm_yday */
3644 yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
3645 yearday += 14*MONTH_TO_DAYS + 1;
3646 ptm->tm_yday = jday - yearday;
3647 /* fix tm_wday if not overridden by caller */
3648 if ((unsigned)ptm->tm_wday > 6)
3649 ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
3653 Perl_my_strftime(pTHX_ char *fmt, int sec, int min, int hour, int mday, int mon, int year, int wday, int yday, int isdst)
3661 init_tm(&mytm); /* XXX workaround - see init_tm() above */
3664 mytm.tm_hour = hour;
3665 mytm.tm_mday = mday;
3667 mytm.tm_year = year;
3668 mytm.tm_wday = wday;
3669 mytm.tm_yday = yday;
3670 mytm.tm_isdst = isdst;
3673 New(0, buf, buflen, char);
3674 len = strftime(buf, buflen, fmt, &mytm);
3676 ** The following is needed to handle to the situation where
3677 ** tmpbuf overflows. Basically we want to allocate a buffer
3678 ** and try repeatedly. The reason why it is so complicated
3679 ** is that getting a return value of 0 from strftime can indicate
3680 ** one of the following:
3681 ** 1. buffer overflowed,
3682 ** 2. illegal conversion specifier, or
3683 ** 3. the format string specifies nothing to be returned(not
3684 ** an error). This could be because format is an empty string
3685 ** or it specifies %p that yields an empty string in some locale.
3686 ** If there is a better way to make it portable, go ahead by
3689 if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
3692 /* Possibly buf overflowed - try again with a bigger buf */
3693 int fmtlen = strlen(fmt);
3694 int bufsize = fmtlen + buflen;
3696 New(0, buf, bufsize, char);
3698 buflen = strftime(buf, bufsize, fmt, &mytm);
3699 if (buflen > 0 && buflen < bufsize)
3701 /* heuristic to prevent out-of-memory errors */
3702 if (bufsize > 100*fmtlen) {
3708 Renew(buf, bufsize, char);
3713 Perl_croak(aTHX_ "panic: no strftime");
3718 #define SV_CWD_RETURN_UNDEF \
3719 sv_setsv(sv, &PL_sv_undef); \
3722 #define SV_CWD_ISDOT(dp) \
3723 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
3724 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
3727 =head1 Miscellaneous Functions
3729 =for apidoc getcwd_sv
3731 Fill the sv with current working directory
3736 /* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
3737 * rewritten again by dougm, optimized for use with xs TARG, and to prefer
3738 * getcwd(3) if available
3739 * Comments from the orignal:
3740 * This is a faster version of getcwd. It's also more dangerous
3741 * because you might chdir out of a directory that you can't chdir
3745 Perl_getcwd_sv(pTHX_ register SV *sv)
3749 #ifndef INCOMPLETE_TAINTS
3755 char buf[MAXPATHLEN];
3757 /* Some getcwd()s automatically allocate a buffer of the given
3758 * size from the heap if they are given a NULL buffer pointer.
3759 * The problem is that this behaviour is not portable. */
3760 if (getcwd(buf, sizeof(buf) - 1)) {
3761 STRLEN len = strlen(buf);
3762 sv_setpvn(sv, buf, len);
3766 sv_setsv(sv, &PL_sv_undef);
3774 int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
3775 int namelen, pathlen=0;
3779 (void)SvUPGRADE(sv, SVt_PV);
3781 if (PerlLIO_lstat(".", &statbuf) < 0) {
3782 SV_CWD_RETURN_UNDEF;
3785 orig_cdev = statbuf.st_dev;
3786 orig_cino = statbuf.st_ino;
3794 if (PerlDir_chdir("..") < 0) {
3795 SV_CWD_RETURN_UNDEF;
3797 if (PerlLIO_stat(".", &statbuf) < 0) {
3798 SV_CWD_RETURN_UNDEF;
3801 cdev = statbuf.st_dev;
3802 cino = statbuf.st_ino;
3804 if (odev == cdev && oino == cino) {
3807 if (!(dir = PerlDir_open("."))) {
3808 SV_CWD_RETURN_UNDEF;
3811 while ((dp = PerlDir_read(dir)) != NULL) {
3813 namelen = dp->d_namlen;
3815 namelen = strlen(dp->d_name);
3818 if (SV_CWD_ISDOT(dp)) {
3822 if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
3823 SV_CWD_RETURN_UNDEF;
3826 tdev = statbuf.st_dev;
3827 tino = statbuf.st_ino;
3828 if (tino == oino && tdev == odev) {
3834 SV_CWD_RETURN_UNDEF;
3837 if (pathlen + namelen + 1 >= MAXPATHLEN) {
3838 SV_CWD_RETURN_UNDEF;
3841 SvGROW(sv, pathlen + namelen + 1);
3845 Move(SvPVX(sv), SvPVX(sv) + namelen + 1, pathlen, char);
3848 /* prepend current directory to the front */
3850 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
3851 pathlen += (namelen + 1);
3853 #ifdef VOID_CLOSEDIR
3856 if (PerlDir_close(dir) < 0) {
3857 SV_CWD_RETURN_UNDEF;
3863 SvCUR_set(sv, pathlen);
3867 if (PerlDir_chdir(SvPVX(sv)) < 0) {
3868 SV_CWD_RETURN_UNDEF;
3871 if (PerlLIO_stat(".", &statbuf) < 0) {
3872 SV_CWD_RETURN_UNDEF;
3875 cdev = statbuf.st_dev;
3876 cino = statbuf.st_ino;
3878 if (cdev != orig_cdev || cino != orig_cino) {
3879 Perl_croak(aTHX_ "Unstable directory path, "
3880 "current directory changed unexpectedly");
3892 =head1 SV Manipulation Functions
3894 =for apidoc scan_vstring
3896 Returns a pointer to the next character after the parsed
3897 vstring, as well as updating the passed in sv.
3899 Function must be called like
3902 s = scan_vstring(s,sv);
3904 The sv should already be large enough to store the vstring
3905 passed in, for performance reasons.
3911 Perl_scan_vstring(pTHX_ char *s, SV *sv)
3915 if (*pos == 'v') pos++; /* get past 'v' */
3916 while (isDIGIT(*pos) || *pos == '_')
3918 if (!isALPHA(*pos)) {
3920 U8 tmpbuf[UTF8_MAXLEN+1];
3923 if (*s == 'v') s++; /* get past 'v' */
3925 sv_setpvn(sv, "", 0);
3930 /* this is atoi() that tolerates underscores */
3933 while (--end >= s) {
3938 rev += (*end - '0') * mult;
3940 if (orev > rev && ckWARN_d(WARN_OVERFLOW))
3941 Perl_warner(aTHX_ packWARN(WARN_OVERFLOW),
3942 "Integer overflow in decimal number");
3946 if (rev > 0x7FFFFFFF)
3947 Perl_croak(aTHX "In EBCDIC the v-string components cannot exceed 2147483647");
3949 /* Append native character for the rev point */
3950 tmpend = uvchr_to_utf8(tmpbuf, rev);
3951 sv_catpvn(sv, (const char*)tmpbuf, tmpend - tmpbuf);
3952 if (!UNI_IS_INVARIANT(NATIVE_TO_UNI(rev)))
3954 if (*pos == '.' && isDIGIT(pos[1]))
3960 while (isDIGIT(*pos) || *pos == '_')
3964 sv_magic(sv,NULL,PERL_MAGIC_vstring,(const char*)start, pos-start);
3971 =for apidoc scan_version
3973 Returns a pointer to the next character after the parsed
3974 version string, as well as upgrading the passed in SV to
3977 Function must be called with an already existing SV like
3980 s = scan_version(s,sv);
3982 Performs some preprocessing to the string to ensure that
3983 it has the correct characteristics of a version. Flags the
3984 object if it contains an underscore (which denotes this
3991 Perl_scan_version(pTHX_ char *s, SV *rv)
3996 SV* sv = newSVrv(rv, "version"); /* create an SV and upgrade the RV */
3997 (void)sv_upgrade(sv, SVt_PVAV); /* needs to be an AV type */
3999 /* pre-scan the imput string to check for decimals */
4000 while ( *pos == '.' || *pos == '_' || isDIGIT(*pos) )
4005 Perl_croak(aTHX_ "Invalid version format (underscores before decimal)");
4008 else if ( *pos == '_' )
4011 Perl_croak(aTHX_ "Invalid version format (multiple underscores)");
4018 if (*pos == 'v') pos++; /* get past 'v' */
4019 while (isDIGIT(*pos))
4021 if (!isALPHA(*pos)) {
4024 if (*s == 'v') s++; /* get past 'v' */
4029 /* this is atoi() that delimits on underscores */
4032 if ( s < pos && *(s-1) == '_' ) {
4033 if ( *s == '0' && *(s+1) != '0')
4034 mult = 10; /* perl-style */
4036 mult = -1; /* beta version */
4038 while (--end >= s) {
4042 rev += (*end - '0') * mult;
4044 if ( abs(orev) > abs(rev) )
4045 Perl_croak(aTHX_ "Integer overflow in version");
4049 /* Append revision */
4050 av_push((AV *)sv, newSViv(rev));
4051 if ( (*pos == '.' || *pos == '_') && isDIGIT(pos[1]))
4053 else if ( isDIGIT(*pos) )
4059 while ( isDIGIT(*pos) ) {
4060 if ( saw_period == 1 && pos-s == 3 )
4070 =for apidoc new_version
4072 Returns a new version object based on the passed in SV:
4074 SV *sv = new_version(SV *ver);
4076 Does not alter the passed in ver SV. See "upg_version" if you
4077 want to upgrade the SV.
4083 Perl_new_version(pTHX_ SV *ver)
4085 SV *rv = NEWSV(92,5);
4086 char *version = (char *)SvPV(ver,PL_na);
4089 if ( SvVOK(ver) ) { /* already a v-string */
4090 MAGIC* mg = mg_find(ver,PERL_MAGIC_vstring);
4091 version = savepvn( (const char*)mg->mg_ptr,mg->mg_len );
4094 version = scan_version(version,rv);
4099 =for apidoc upg_version
4101 In-place upgrade of the supplied SV to a version object.
4103 SV *sv = upg_version(SV *sv);
4105 Returns a pointer to the upgraded SV.
4111 Perl_upg_version(pTHX_ SV *ver)
4113 char *version = savepvn(SvPVX(ver),SvCUR(ver));
4115 if ( SvVOK(ver) ) { /* already a v-string */
4116 MAGIC* mg = mg_find(ver,PERL_MAGIC_vstring);
4117 version = savepvn( (const char*)mg->mg_ptr,mg->mg_len );
4120 version = scan_version(version,ver);
4128 Accepts a version object and returns the normalized floating
4129 point representation. Call like:
4133 NOTE: you can pass either the object directly or the SV
4134 contained within the RV.
4140 Perl_vnumify(pTHX_ SV *vs)
4143 SV *sv = NEWSV(92,0);
4146 len = av_len((AV *)vs);
4147 digit = SvIVX(*av_fetch((AV *)vs, 0, 0));
4148 Perl_sv_setpvf(aTHX_ sv,"%d.",abs(digit));
4149 for ( i = 1 ; i <= len ; i++ )
4151 digit = SvIVX(*av_fetch((AV *)vs, i, 0));
4152 Perl_sv_catpvf(aTHX_ sv,"%03d",abs(digit));
4155 Perl_sv_catpv(aTHX_ sv,"000");
4160 =for apidoc vstringify
4162 Accepts a version object and returns the normalized string
4163 representation. Call like:
4165 sv = vstringify(rv);
4167 NOTE: you can pass either the object directly or the SV
4168 contained within the RV.
4174 Perl_vstringify(pTHX_ SV *vs)
4177 SV *sv = NEWSV(92,0);
4180 len = av_len((AV *)vs);
4181 digit = SvIVX(*av_fetch((AV *)vs, 0, 0));
4182 Perl_sv_setpvf(aTHX_ sv,"%d",digit);
4183 for ( i = 1 ; i <= len ; i++ )
4185 digit = SvIVX(*av_fetch((AV *)vs, i, 0));
4187 Perl_sv_catpvf(aTHX_ sv,"_%d",-digit);
4189 Perl_sv_catpvf(aTHX_ sv,".%d",digit);
4192 Perl_sv_catpv(aTHX_ sv,".0");
4199 Version object aware cmp. Both operands must already have been
4200 converted into version objects.
4206 Perl_vcmp(pTHX_ SV *lsv, SV *rsv)
4213 l = av_len((AV *)lsv);
4214 r = av_len((AV *)rsv);
4218 while ( i <= m && retval == 0 )
4220 I32 left = SvIV(*av_fetch((AV *)lsv,i,0));
4221 I32 right = SvIV(*av_fetch((AV *)rsv,i,0));
4222 bool lbeta = left < 0 ? 1 : 0;
4223 bool rbeta = right < 0 ? 1 : 0;
4226 if ( left < right || (left == right && lbeta && !rbeta) )
4228 if ( left > right || (left == right && rbeta && !lbeta) )
4233 if ( l != r && retval == 0 )
4234 retval = l < r ? -1 : +1;
4238 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET) && defined(SOCK_DGRAM) && defined(HAS_SELECT)
4239 # define EMULATE_SOCKETPAIR_UDP
4242 #ifdef EMULATE_SOCKETPAIR_UDP
4244 S_socketpair_udp (int fd[2]) {
4246 /* Fake a datagram socketpair using UDP to localhost. */
4247 int sockets[2] = {-1, -1};
4248 struct sockaddr_in addresses[2];
4250 Sock_size_t size = sizeof(struct sockaddr_in);
4251 unsigned short port;
4254 memset(&addresses, 0, sizeof(addresses));
4257 sockets[i] = PerlSock_socket(AF_INET, SOCK_DGRAM, PF_INET);
4258 if (sockets[i] == -1)
4259 goto tidy_up_and_fail;
4261 addresses[i].sin_family = AF_INET;
4262 addresses[i].sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4263 addresses[i].sin_port = 0; /* kernel choses port. */
4264 if (PerlSock_bind(sockets[i], (struct sockaddr *) &addresses[i],
4265 sizeof(struct sockaddr_in)) == -1)
4266 goto tidy_up_and_fail;
4269 /* Now have 2 UDP sockets. Find out which port each is connected to, and
4270 for each connect the other socket to it. */
4273 if (PerlSock_getsockname(sockets[i], (struct sockaddr *) &addresses[i],
4275 goto tidy_up_and_fail;
4276 if (size != sizeof(struct sockaddr_in))
4277 goto abort_tidy_up_and_fail;
4278 /* !1 is 0, !0 is 1 */
4279 if (PerlSock_connect(sockets[!i], (struct sockaddr *) &addresses[i],
4280 sizeof(struct sockaddr_in)) == -1)
4281 goto tidy_up_and_fail;
4284 /* Now we have 2 sockets connected to each other. I don't trust some other
4285 process not to have already sent a packet to us (by random) so send
4286 a packet from each to the other. */
4289 /* I'm going to send my own port number. As a short.
4290 (Who knows if someone somewhere has sin_port as a bitfield and needs
4291 this routine. (I'm assuming crays have socketpair)) */
4292 port = addresses[i].sin_port;
4293 got = PerlLIO_write(sockets[i], &port, sizeof(port));
4294 if (got != sizeof(port)) {
4296 goto tidy_up_and_fail;
4297 goto abort_tidy_up_and_fail;
4301 /* Packets sent. I don't trust them to have arrived though.
4302 (As I understand it Solaris TCP stack is multithreaded. Non-blocking
4303 connect to localhost will use a second kernel thread. In 2.6 the
4304 first thread running the connect() returns before the second completes,
4305 so EINPROGRESS> In 2.7 the improved stack is faster and connect()
4306 returns 0. Poor programs have tripped up. One poor program's authors'
4307 had a 50-1 reverse stock split. Not sure how connected these were.)
4308 So I don't trust someone not to have an unpredictable UDP stack.
4312 struct timeval waitfor = {0, 100000}; /* You have 0.1 seconds */
4313 int max = sockets[1] > sockets[0] ? sockets[1] : sockets[0];
4317 FD_SET(sockets[0], &rset);
4318 FD_SET(sockets[1], &rset);
4320 got = PerlSock_select(max + 1, &rset, NULL, NULL, &waitfor);
4321 if (got != 2 || !FD_ISSET(sockets[0], &rset)
4322 || !FD_ISSET(sockets[1], &rset)) {
4323 /* I hope this is portable and appropriate. */
4325 goto tidy_up_and_fail;
4326 goto abort_tidy_up_and_fail;
4330 /* And the paranoia department even now doesn't trust it to have arrive
4331 (hence MSG_DONTWAIT). Or that what arrives was sent by us. */
4333 struct sockaddr_in readfrom;
4334 unsigned short buffer[2];
4339 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4340 sizeof(buffer), MSG_DONTWAIT,
4341 (struct sockaddr *) &readfrom, &size);
4343 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4345 (struct sockaddr *) &readfrom, &size);
4349 goto tidy_up_and_fail;
4350 if (got != sizeof(port)
4351 || size != sizeof(struct sockaddr_in)
4352 /* Check other socket sent us its port. */
4353 || buffer[0] != (unsigned short) addresses[!i].sin_port
4354 /* Check kernel says we got the datagram from that socket */
4355 || readfrom.sin_family != addresses[!i].sin_family
4356 || readfrom.sin_addr.s_addr != addresses[!i].sin_addr.s_addr
4357 || readfrom.sin_port != addresses[!i].sin_port)
4358 goto abort_tidy_up_and_fail;
4361 /* My caller (my_socketpair) has validated that this is non-NULL */
4364 /* I hereby declare this connection open. May God bless all who cross
4368 abort_tidy_up_and_fail:
4369 errno = ECONNABORTED;
4372 int save_errno = errno;
4373 if (sockets[0] != -1)
4374 PerlLIO_close(sockets[0]);
4375 if (sockets[1] != -1)
4376 PerlLIO_close(sockets[1]);
4381 #endif /* EMULATE_SOCKETPAIR_UDP */
4383 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET)
4385 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4386 /* Stevens says that family must be AF_LOCAL, protocol 0.
4387 I'm going to enforce that, then ignore it, and use TCP (or UDP). */
4392 struct sockaddr_in listen_addr;
4393 struct sockaddr_in connect_addr;
4398 || family != AF_UNIX
4401 errno = EAFNOSUPPORT;
4409 #ifdef EMULATE_SOCKETPAIR_UDP
4410 if (type == SOCK_DGRAM)
4411 return S_socketpair_udp(fd);
4414 listener = PerlSock_socket(AF_INET, type, 0);
4417 memset(&listen_addr, 0, sizeof(listen_addr));
4418 listen_addr.sin_family = AF_INET;
4419 listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4420 listen_addr.sin_port = 0; /* kernel choses port. */
4421 if (PerlSock_bind(listener, (struct sockaddr *) &listen_addr,
4422 sizeof(listen_addr)) == -1)
4423 goto tidy_up_and_fail;
4424 if (PerlSock_listen(listener, 1) == -1)
4425 goto tidy_up_and_fail;
4427 connector = PerlSock_socket(AF_INET, type, 0);
4428 if (connector == -1)
4429 goto tidy_up_and_fail;
4430 /* We want to find out the port number to connect to. */
4431 size = sizeof(connect_addr);
4432 if (PerlSock_getsockname(listener, (struct sockaddr *) &connect_addr,
4434 goto tidy_up_and_fail;
4435 if (size != sizeof(connect_addr))
4436 goto abort_tidy_up_and_fail;
4437 if (PerlSock_connect(connector, (struct sockaddr *) &connect_addr,
4438 sizeof(connect_addr)) == -1)
4439 goto tidy_up_and_fail;
4441 size = sizeof(listen_addr);
4442 acceptor = PerlSock_accept(listener, (struct sockaddr *) &listen_addr,
4445 goto tidy_up_and_fail;
4446 if (size != sizeof(listen_addr))
4447 goto abort_tidy_up_and_fail;
4448 PerlLIO_close(listener);
4449 /* Now check we are talking to ourself by matching port and host on the
4451 if (PerlSock_getsockname(connector, (struct sockaddr *) &connect_addr,
4453 goto tidy_up_and_fail;
4454 if (size != sizeof(connect_addr)
4455 || listen_addr.sin_family != connect_addr.sin_family
4456 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
4457 || listen_addr.sin_port != connect_addr.sin_port) {
4458 goto abort_tidy_up_and_fail;
4464 abort_tidy_up_and_fail:
4465 errno = ECONNABORTED; /* I hope this is portable and appropriate. */
4468 int save_errno = errno;
4470 PerlLIO_close(listener);
4471 if (connector != -1)
4472 PerlLIO_close(connector);
4474 PerlLIO_close(acceptor);
4480 /* In any case have a stub so that there's code corresponding
4481 * to the my_socketpair in global.sym. */
4483 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4484 #ifdef HAS_SOCKETPAIR
4485 return socketpair(family, type, protocol, fd);
4494 =for apidoc sv_nosharing
4496 Dummy routine which "shares" an SV when there is no sharing module present.
4497 Exists to avoid test for a NULL function pointer and because it could potentially warn under
4498 some level of strict-ness.
4504 Perl_sv_nosharing(pTHX_ SV *sv)
4509 =for apidoc sv_nolocking
4511 Dummy routine which "locks" an SV when there is no locking module present.
4512 Exists to avoid test for a NULL function pointer and because it could potentially warn under
4513 some level of strict-ness.
4519 Perl_sv_nolocking(pTHX_ SV *sv)
4525 =for apidoc sv_nounlocking
4527 Dummy routine which "unlocks" an SV when there is no locking module present.
4528 Exists to avoid test for a NULL function pointer and because it could potentially warn under
4529 some level of strict-ness.
4535 Perl_sv_nounlocking(pTHX_ SV *sv)