3 * Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999,
4 * 2000, 2001, 2002, 2003, 2004, 2005, by Larry Wall and others
6 * You may distribute under the terms of either the GNU General Public
7 * License or the Artistic License, as specified in the README file.
12 * "Very useful, no doubt, that was to Saruman; yet it seems that he was
13 * not content." --Gandalf
16 /* This file contains assorted utility routines.
17 * Which is a polite way of saying any stuff that people couldn't think of
18 * a better place for. Amongst other things, it includes the warning and
19 * dieing stuff, plus wrappers for malloc code.
23 #define PERL_IN_UTIL_C
29 # define SIG_ERR ((Sighandler_t) -1)
34 /* Missing protos on LynxOS */
39 # include <sys/wait.h>
44 # include <sys/select.h>
50 #if defined(HAS_FCNTL) && defined(F_SETFD) && !defined(FD_CLOEXEC)
51 # define FD_CLOEXEC 1 /* NeXT needs this */
54 /* NOTE: Do not call the next three routines directly. Use the macros
55 * in handy.h, so that we can easily redefine everything to do tracking of
56 * allocated hunks back to the original New to track down any memory leaks.
57 * XXX This advice seems to be widely ignored :-( --AD August 1996.
63 /* Can't use PerlIO to write as it allocates memory */
64 PerlLIO_write(PerlIO_fileno(Perl_error_log),
65 PL_no_mem, strlen(PL_no_mem));
67 NORETURN_FUNCTION_END;
70 /* paranoid version of system's malloc() */
73 Perl_safesysmalloc(MEM_SIZE size)
79 PerlIO_printf(Perl_error_log,
80 "Allocation too large: %lx\n", size) FLUSH;
83 #endif /* HAS_64K_LIMIT */
84 #ifdef PERL_TRACK_MEMPOOL
89 Perl_croak_nocontext("panic: malloc");
91 ptr = (Malloc_t)PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
92 PERL_ALLOC_CHECK(ptr);
93 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) malloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
95 #ifdef PERL_TRACK_MEMPOOL
97 ptr = (Malloc_t)((char*)ptr+sTHX);
104 return write_no_mem();
109 /* paranoid version of system's realloc() */
112 Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
116 #if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) && !defined(PERL_MICRO)
117 Malloc_t PerlMem_realloc();
118 #endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
122 PerlIO_printf(Perl_error_log,
123 "Reallocation too large: %lx\n", size) FLUSH;
126 #endif /* HAS_64K_LIMIT */
133 return safesysmalloc(size);
134 #ifdef PERL_TRACK_MEMPOOL
135 where = (Malloc_t)((char*)where-sTHX);
137 if (*(tTHX*)where != aTHX) {
138 /* int *nowhere = NULL; *nowhere = 0; */
139 Perl_croak_nocontext("panic: realloc from wrong pool");
144 Perl_croak_nocontext("panic: realloc");
146 ptr = (Malloc_t)PerlMem_realloc(where,size);
147 PERL_ALLOC_CHECK(ptr);
149 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) rfree\n",PTR2UV(where),(long)PL_an++));
150 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) realloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
153 #ifdef PERL_TRACK_MEMPOOL
154 ptr = (Malloc_t)((char*)ptr+sTHX);
161 return write_no_mem();
166 /* safe version of system's free() */
169 Perl_safesysfree(Malloc_t where)
172 #if defined(PERL_IMPLICIT_SYS) || defined(PERL_TRACK_MEMPOOL)
175 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) free\n",PTR2UV(where),(long)PL_an++));
177 #ifdef PERL_TRACK_MEMPOOL
178 where = (Malloc_t)((char*)where-sTHX);
179 if (*(tTHX*)where != aTHX) {
180 /* int *nowhere = NULL; *nowhere = 0; */
181 Perl_croak_nocontext("panic: free from wrong pool");
188 /* safe version of system's calloc() */
191 Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
197 if (size * count > 0xffff) {
198 PerlIO_printf(Perl_error_log,
199 "Allocation too large: %lx\n", size * count) FLUSH;
202 #endif /* HAS_64K_LIMIT */
204 if ((long)size < 0 || (long)count < 0)
205 Perl_croak_nocontext("panic: calloc");
208 #ifdef PERL_TRACK_MEMPOOL
211 ptr = (Malloc_t)PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
212 PERL_ALLOC_CHECK(ptr);
213 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));
215 memset((void*)ptr, 0, size);
216 #ifdef PERL_TRACK_MEMPOOL
218 ptr = (Malloc_t)((char*)ptr+sTHX);
224 return write_no_mem();
227 /* These must be defined when not using Perl's malloc for binary
232 Malloc_t Perl_malloc (MEM_SIZE nbytes)
235 return (Malloc_t)PerlMem_malloc(nbytes);
238 Malloc_t Perl_calloc (MEM_SIZE elements, MEM_SIZE size)
241 return (Malloc_t)PerlMem_calloc(elements, size);
244 Malloc_t Perl_realloc (Malloc_t where, MEM_SIZE nbytes)
247 return (Malloc_t)PerlMem_realloc(where, nbytes);
250 Free_t Perl_mfree (Malloc_t where)
258 /* copy a string up to some (non-backslashed) delimiter, if any */
261 Perl_delimcpy(pTHX_ register char *to, register const char *toend, register const char *from, register const char *fromend, register int delim, I32 *retlen)
264 for (tolen = 0; from < fromend; from++, tolen++) {
266 if (from[1] == delim)
275 else if (*from == delim)
286 /* return ptr to little string in big string, NULL if not found */
287 /* This routine was donated by Corey Satten. */
290 Perl_instr(pTHX_ register const char *big, register const char *little)
300 register const char *s, *x;
303 for (x=big,s=little; *s; /**/ ) {
312 return (char*)(big-1);
317 /* same as instr but allow embedded nulls */
320 Perl_ninstr(pTHX_ register const char *big, register const char *bigend, const char *little, const char *lend)
322 register const I32 first = *little;
323 register const char * const littleend = lend;
325 if (!first && little >= littleend)
327 if (bigend - big < littleend - little)
329 bigend -= littleend - little++;
330 while (big <= bigend) {
331 register const char *s, *x;
334 for (x=big,s=little; s < littleend; /**/ ) {
341 return (char*)(big-1);
346 /* reverse of the above--find last substring */
349 Perl_rninstr(pTHX_ register const char *big, const char *bigend, const char *little, const char *lend)
351 register const char *bigbeg;
352 register const I32 first = *little;
353 register const char * const littleend = lend;
355 if (!first && little >= littleend)
356 return (char*)bigend;
358 big = bigend - (littleend - little++);
359 while (big >= bigbeg) {
360 register const char *s, *x;
363 for (x=big+2,s=little; s < littleend; /**/ ) {
370 return (char*)(big+1);
375 #define FBM_TABLE_OFFSET 2 /* Number of bytes between EOS and table*/
377 /* As a space optimization, we do not compile tables for strings of length
378 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
379 special-cased in fbm_instr().
381 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
384 =head1 Miscellaneous Functions
386 =for apidoc fbm_compile
388 Analyses the string in order to make fast searches on it using fbm_instr()
389 -- the Boyer-Moore algorithm.
395 Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
397 register const U8 *s;
403 if (flags & FBMcf_TAIL) {
404 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL;
405 sv_catpvn(sv, "\n", 1); /* Taken into account in fbm_instr() */
406 if (mg && mg->mg_len >= 0)
409 s = (U8*)SvPV_force_mutable(sv, len);
410 SvUPGRADE(sv, SVt_PVBM);
411 if (len == 0) /* TAIL might be on a zero-length string. */
414 const unsigned char *sb;
415 const U8 mlen = (len>255) ? 255 : (U8)len;
418 Sv_Grow(sv, len + 256 + FBM_TABLE_OFFSET);
419 table = (unsigned char*)(SvPVX_mutable(sv) + len + FBM_TABLE_OFFSET);
420 s = table - 1 - FBM_TABLE_OFFSET; /* last char */
421 memset((void*)table, mlen, 256);
422 table[-1] = (U8)flags;
424 sb = s - mlen + 1; /* first char (maybe) */
426 if (table[*s] == mlen)
431 sv_magic(sv, Nullsv, PERL_MAGIC_bm, Nullch, 0); /* deep magic */
434 s = (const unsigned char*)(SvPVX_const(sv)); /* deeper magic */
435 for (i = 0; i < len; i++) {
436 if (PL_freq[s[i]] < frequency) {
438 frequency = PL_freq[s[i]];
441 BmRARE(sv) = s[rarest];
442 BmPREVIOUS(sv) = (U16)rarest;
443 BmUSEFUL(sv) = 100; /* Initial value */
444 if (flags & FBMcf_TAIL)
446 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %d\n",
447 BmRARE(sv),BmPREVIOUS(sv)));
450 /* If SvTAIL(littlestr), it has a fake '\n' at end. */
451 /* If SvTAIL is actually due to \Z or \z, this gives false positives
455 =for apidoc fbm_instr
457 Returns the location of the SV in the string delimited by C<str> and
458 C<strend>. It returns C<Nullch> if the string can't be found. The C<sv>
459 does not have to be fbm_compiled, but the search will not be as fast
466 Perl_fbm_instr(pTHX_ unsigned char *big, register unsigned char *bigend, SV *littlestr, U32 flags)
468 register unsigned char *s;
470 register const unsigned char *little
471 = (const unsigned char *)SvPV_const(littlestr,l);
472 register STRLEN littlelen = l;
473 register const I32 multiline = flags & FBMrf_MULTILINE;
475 if ((STRLEN)(bigend - big) < littlelen) {
476 if ( SvTAIL(littlestr)
477 && ((STRLEN)(bigend - big) == littlelen - 1)
479 || (*big == *little &&
480 memEQ((char *)big, (char *)little, littlelen - 1))))
485 if (littlelen <= 2) { /* Special-cased */
487 if (littlelen == 1) {
488 if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
489 /* Know that bigend != big. */
490 if (bigend[-1] == '\n')
491 return (char *)(bigend - 1);
492 return (char *) bigend;
500 if (SvTAIL(littlestr))
501 return (char *) bigend;
505 return (char*)big; /* Cannot be SvTAIL! */
508 if (SvTAIL(littlestr) && !multiline) {
509 if (bigend[-1] == '\n' && bigend[-2] == *little)
510 return (char*)bigend - 2;
511 if (bigend[-1] == *little)
512 return (char*)bigend - 1;
516 /* This should be better than FBM if c1 == c2, and almost
517 as good otherwise: maybe better since we do less indirection.
518 And we save a lot of memory by caching no table. */
519 const unsigned char c1 = little[0];
520 const unsigned char c2 = little[1];
525 while (s <= bigend) {
535 goto check_1char_anchor;
546 goto check_1char_anchor;
549 while (s <= bigend) {
554 goto check_1char_anchor;
563 check_1char_anchor: /* One char and anchor! */
564 if (SvTAIL(littlestr) && (*bigend == *little))
565 return (char *)bigend; /* bigend is already decremented. */
568 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
569 s = bigend - littlelen;
570 if (s >= big && bigend[-1] == '\n' && *s == *little
571 /* Automatically of length > 2 */
572 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
574 return (char*)s; /* how sweet it is */
577 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
579 return (char*)s + 1; /* how sweet it is */
583 if (SvTYPE(littlestr) != SVt_PVBM || !SvVALID(littlestr)) {
584 char * const b = ninstr((char*)big,(char*)bigend,
585 (char*)little, (char*)little + littlelen);
587 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
588 /* Chop \n from littlestr: */
589 s = bigend - littlelen + 1;
591 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
600 { /* Do actual FBM. */
601 register const unsigned char * const table = little + littlelen + FBM_TABLE_OFFSET;
602 register const unsigned char *oldlittle;
604 if (littlelen > (STRLEN)(bigend - big))
606 --littlelen; /* Last char found by table lookup */
609 little += littlelen; /* last char */
615 if ((tmp = table[*s])) {
616 if ((s += tmp) < bigend)
620 else { /* less expensive than calling strncmp() */
621 register unsigned char * const olds = s;
626 if (*--s == *--little)
628 s = olds + 1; /* here we pay the price for failure */
630 if (s < bigend) /* fake up continue to outer loop */
638 if ( s == bigend && (table[-1] & FBMcf_TAIL)
639 && memEQ((char *)(bigend - littlelen),
640 (char *)(oldlittle - littlelen), littlelen) )
641 return (char*)bigend - littlelen;
646 /* start_shift, end_shift are positive quantities which give offsets
647 of ends of some substring of bigstr.
648 If "last" we want the last occurrence.
649 old_posp is the way of communication between consequent calls if
650 the next call needs to find the .
651 The initial *old_posp should be -1.
653 Note that we take into account SvTAIL, so one can get extra
654 optimizations if _ALL flag is set.
657 /* If SvTAIL is actually due to \Z or \z, this gives false positives
658 if PL_multiline. In fact if !PL_multiline the authoritative answer
659 is not supported yet. */
662 Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
664 register const unsigned char *big;
666 register I32 previous;
668 register const unsigned char *little;
669 register I32 stop_pos;
670 register const unsigned char *littleend;
674 ? (pos = PL_screamfirst[BmRARE(littlestr)]) < 0
675 : (((pos = *old_posp), pos += PL_screamnext[pos]) == 0)) {
677 if ( BmRARE(littlestr) == '\n'
678 && BmPREVIOUS(littlestr) == SvCUR(littlestr) - 1) {
679 little = (const unsigned char *)(SvPVX_const(littlestr));
680 littleend = little + SvCUR(littlestr);
687 little = (const unsigned char *)(SvPVX_const(littlestr));
688 littleend = little + SvCUR(littlestr);
690 /* The value of pos we can start at: */
691 previous = BmPREVIOUS(littlestr);
692 big = (const unsigned char *)(SvPVX_const(bigstr));
693 /* The value of pos we can stop at: */
694 stop_pos = SvCUR(bigstr) - end_shift - (SvCUR(littlestr) - 1 - previous);
695 if (previous + start_shift > stop_pos) {
697 stop_pos does not include SvTAIL in the count, so this check is incorrect
698 (I think) - see [ID 20010618.006] and t/op/study.t. HVDS 2001/06/19
701 if (previous + start_shift == stop_pos + 1) /* A fake '\n'? */
706 while (pos < previous + start_shift) {
707 if (!(pos += PL_screamnext[pos]))
712 register const unsigned char *s, *x;
713 if (pos >= stop_pos) break;
714 if (big[pos] != first)
716 for (x=big+pos+1,s=little; s < littleend; /**/ ) {
722 if (s == littleend) {
724 if (!last) return (char *)(big+pos);
727 } while ( pos += PL_screamnext[pos] );
729 return (char *)(big+(*old_posp));
731 if (!SvTAIL(littlestr) || (end_shift > 0))
733 /* Ignore the trailing "\n". This code is not microoptimized */
734 big = (const unsigned char *)(SvPVX_const(bigstr) + SvCUR(bigstr));
735 stop_pos = littleend - little; /* Actual littlestr len */
740 && ((stop_pos == 1) ||
741 memEQ((char *)(big + 1), (char *)little, stop_pos - 1)))
747 Perl_ibcmp(pTHX_ const char *s1, const char *s2, register I32 len)
749 register const U8 *a = (const U8 *)s1;
750 register const U8 *b = (const U8 *)s2;
752 if (*a != *b && *a != PL_fold[*b])
760 Perl_ibcmp_locale(pTHX_ const char *s1, const char *s2, register I32 len)
763 register const U8 *a = (const U8 *)s1;
764 register const U8 *b = (const U8 *)s2;
766 if (*a != *b && *a != PL_fold_locale[*b])
773 /* copy a string to a safe spot */
776 =head1 Memory Management
780 Perl's version of C<strdup()>. Returns a pointer to a newly allocated
781 string which is a duplicate of C<pv>. The size of the string is
782 determined by C<strlen()>. The memory allocated for the new string can
783 be freed with the C<Safefree()> function.
789 Perl_savepv(pTHX_ const char *pv)
795 const STRLEN pvlen = strlen(pv)+1;
796 Newx(newaddr,pvlen,char);
797 return memcpy(newaddr,pv,pvlen);
802 /* same thing but with a known length */
807 Perl's version of what C<strndup()> would be if it existed. Returns a
808 pointer to a newly allocated string which is a duplicate of the first
809 C<len> bytes from C<pv>. The memory allocated for the new string can be
810 freed with the C<Safefree()> function.
816 Perl_savepvn(pTHX_ const char *pv, register I32 len)
818 register char *newaddr;
820 Newx(newaddr,len+1,char);
821 /* Give a meaning to NULL pointer mainly for the use in sv_magic() */
823 /* might not be null terminated */
825 return (char *) CopyD(pv,newaddr,len,char);
828 return (char *) ZeroD(newaddr,len+1,char);
833 =for apidoc savesharedpv
835 A version of C<savepv()> which allocates the duplicate string in memory
836 which is shared between threads.
841 Perl_savesharedpv(pTHX_ const char *pv)
843 register char *newaddr;
848 pvlen = strlen(pv)+1;
849 newaddr = (char*)PerlMemShared_malloc(pvlen);
851 return write_no_mem();
853 return memcpy(newaddr,pv,pvlen);
859 A version of C<savepv()>/C<savepvn()> which gets the string to duplicate from
860 the passed in SV using C<SvPV()>
866 Perl_savesvpv(pTHX_ SV *sv)
869 const char * const pv = SvPV_const(sv, len);
870 register char *newaddr;
873 Newx(newaddr,len,char);
874 return (char *) CopyD(pv,newaddr,len,char);
878 /* the SV for Perl_form() and mess() is not kept in an arena */
887 return sv_2mortal(newSVpvn("",0));
892 /* Create as PVMG now, to avoid any upgrading later */
894 Newxz(any, 1, XPVMG);
895 SvFLAGS(sv) = SVt_PVMG;
896 SvANY(sv) = (void*)any;
898 SvREFCNT(sv) = 1 << 30; /* practically infinite */
903 #if defined(PERL_IMPLICIT_CONTEXT)
905 Perl_form_nocontext(const char* pat, ...)
911 retval = vform(pat, &args);
915 #endif /* PERL_IMPLICIT_CONTEXT */
918 =head1 Miscellaneous Functions
921 Takes a sprintf-style format pattern and conventional
922 (non-SV) arguments and returns the formatted string.
924 (char *) Perl_form(pTHX_ const char* pat, ...)
926 can be used any place a string (char *) is required:
928 char * s = Perl_form("%d.%d",major,minor);
930 Uses a single private buffer so if you want to format several strings you
931 must explicitly copy the earlier strings away (and free the copies when you
938 Perl_form(pTHX_ const char* pat, ...)
943 retval = vform(pat, &args);
949 Perl_vform(pTHX_ const char *pat, va_list *args)
951 SV * const sv = mess_alloc();
952 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
956 #if defined(PERL_IMPLICIT_CONTEXT)
958 Perl_mess_nocontext(const char *pat, ...)
964 retval = vmess(pat, &args);
968 #endif /* PERL_IMPLICIT_CONTEXT */
971 Perl_mess(pTHX_ const char *pat, ...)
976 retval = vmess(pat, &args);
982 S_closest_cop(pTHX_ COP *cop, const OP *o)
984 /* Look for PL_op starting from o. cop is the last COP we've seen. */
986 if (!o || o == PL_op) return cop;
988 if (o->op_flags & OPf_KIDS) {
990 for (kid = cUNOPo->op_first; kid; kid = kid->op_sibling)
994 /* If the OP_NEXTSTATE has been optimised away we can still use it
995 * the get the file and line number. */
997 if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
1000 /* Keep searching, and return when we've found something. */
1002 new_cop = closest_cop(cop, kid);
1003 if (new_cop) return new_cop;
1007 /* Nothing found. */
1013 Perl_vmess(pTHX_ const char *pat, va_list *args)
1015 SV * const sv = mess_alloc();
1016 static const char dgd[] = " during global destruction.\n";
1018 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
1019 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1022 * Try and find the file and line for PL_op. This will usually be
1023 * PL_curcop, but it might be a cop that has been optimised away. We
1024 * can try to find such a cop by searching through the optree starting
1025 * from the sibling of PL_curcop.
1028 const COP *cop = closest_cop(PL_curcop, PL_curcop->op_sibling);
1029 if (!cop) cop = PL_curcop;
1032 Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
1033 OutCopFILE(cop), (IV)CopLINE(cop));
1034 if (GvIO(PL_last_in_gv) && IoLINES(GvIOp(PL_last_in_gv))) {
1035 const bool line_mode = (RsSIMPLE(PL_rs) &&
1036 SvCUR(PL_rs) == 1 && *SvPVX_const(PL_rs) == '\n');
1037 Perl_sv_catpvf(aTHX_ sv, ", <%s> %s %"IVdf,
1038 PL_last_in_gv == PL_argvgv ?
1039 "" : GvNAME(PL_last_in_gv),
1040 line_mode ? "line" : "chunk",
1041 (IV)IoLINES(GvIOp(PL_last_in_gv)));
1043 sv_catpv(sv, PL_dirty ? dgd : ".\n");
1049 Perl_write_to_stderr(pTHX_ const char* message, int msglen)
1055 if (PL_stderrgv && SvREFCNT(PL_stderrgv)
1056 && (io = GvIO(PL_stderrgv))
1057 && (mg = SvTIED_mg((SV*)io, PERL_MAGIC_tiedscalar)))
1064 SAVESPTR(PL_stderrgv);
1065 PL_stderrgv = Nullgv;
1067 PUSHSTACKi(PERLSI_MAGIC);
1071 PUSHs(SvTIED_obj((SV*)io, mg));
1072 PUSHs(sv_2mortal(newSVpvn(message, msglen)));
1074 call_method("PRINT", G_SCALAR);
1082 /* SFIO can really mess with your errno */
1083 const int e = errno;
1085 PerlIO * const serr = Perl_error_log;
1087 PERL_WRITE_MSG_TO_CONSOLE(serr, message, msglen);
1088 (void)PerlIO_flush(serr);
1095 /* Common code used by vcroak, vdie and vwarner */
1098 S_vdie_common(pTHX_ const char *message, STRLEN msglen, I32 utf8)
1103 /* sv_2cv might call Perl_croak() */
1104 SV * const olddiehook = PL_diehook;
1108 SAVESPTR(PL_diehook);
1109 PL_diehook = Nullsv;
1110 cv = sv_2cv(olddiehook, &stash, &gv, 0);
1112 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1119 msg = newSVpvn(message, msglen);
1120 SvFLAGS(msg) |= utf8;
1128 PUSHSTACKi(PERLSI_DIEHOOK);
1132 call_sv((SV*)cv, G_DISCARD);
1139 S_vdie_croak_common(pTHX_ const char* pat, va_list* args, STRLEN* msglen,
1143 const char *message;
1146 SV * const msv = vmess(pat, args);
1147 if (PL_errors && SvCUR(PL_errors)) {
1148 sv_catsv(PL_errors, msv);
1149 message = SvPV_const(PL_errors, *msglen);
1150 SvCUR_set(PL_errors, 0);
1153 message = SvPV_const(msv,*msglen);
1154 *utf8 = SvUTF8(msv);
1160 DEBUG_S(PerlIO_printf(Perl_debug_log,
1161 "%p: die/croak: message = %s\ndiehook = %p\n",
1162 thr, message, PL_diehook));
1164 S_vdie_common(aTHX_ message, *msglen, *utf8);
1170 Perl_vdie(pTHX_ const char* pat, va_list *args)
1172 const char *message;
1173 const int was_in_eval = PL_in_eval;
1177 DEBUG_S(PerlIO_printf(Perl_debug_log,
1178 "%p: die: curstack = %p, mainstack = %p\n",
1179 thr, PL_curstack, PL_mainstack));
1181 message = vdie_croak_common(pat, args, &msglen, &utf8);
1183 PL_restartop = die_where(message, msglen);
1184 SvFLAGS(ERRSV) |= utf8;
1185 DEBUG_S(PerlIO_printf(Perl_debug_log,
1186 "%p: die: restartop = %p, was_in_eval = %d, top_env = %p\n",
1187 thr, PL_restartop, was_in_eval, PL_top_env));
1188 if ((!PL_restartop && was_in_eval) || PL_top_env->je_prev)
1190 return PL_restartop;
1193 #if defined(PERL_IMPLICIT_CONTEXT)
1195 Perl_die_nocontext(const char* pat, ...)
1200 va_start(args, pat);
1201 o = vdie(pat, &args);
1205 #endif /* PERL_IMPLICIT_CONTEXT */
1208 Perl_die(pTHX_ const char* pat, ...)
1212 va_start(args, pat);
1213 o = vdie(pat, &args);
1219 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1221 const char *message;
1225 message = S_vdie_croak_common(aTHX_ pat, args, &msglen, &utf8);
1228 PL_restartop = die_where(message, msglen);
1229 SvFLAGS(ERRSV) |= utf8;
1233 message = SvPVx_const(ERRSV, msglen);
1235 write_to_stderr(message, msglen);
1239 #if defined(PERL_IMPLICIT_CONTEXT)
1241 Perl_croak_nocontext(const char *pat, ...)
1245 va_start(args, pat);
1250 #endif /* PERL_IMPLICIT_CONTEXT */
1253 =head1 Warning and Dieing
1257 This is the XSUB-writer's interface to Perl's C<die> function.
1258 Normally call this function the same way you call the C C<printf>
1259 function. Calling C<croak> returns control directly to Perl,
1260 sidestepping the normal C order of execution. See C<warn>.
1262 If you want to throw an exception object, assign the object to
1263 C<$@> and then pass C<Nullch> to croak():
1265 errsv = get_sv("@", TRUE);
1266 sv_setsv(errsv, exception_object);
1273 Perl_croak(pTHX_ const char *pat, ...)
1276 va_start(args, pat);
1283 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1287 SV * const msv = vmess(pat, args);
1288 const I32 utf8 = SvUTF8(msv);
1289 const char * const message = SvPV_const(msv, msglen);
1292 /* sv_2cv might call Perl_warn() */
1293 SV * const oldwarnhook = PL_warnhook;
1299 SAVESPTR(PL_warnhook);
1300 PL_warnhook = Nullsv;
1301 cv = sv_2cv(oldwarnhook, &stash, &gv, 0);
1303 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1308 SAVESPTR(PL_warnhook);
1309 PL_warnhook = Nullsv;
1311 msg = newSVpvn(message, msglen);
1312 SvFLAGS(msg) |= utf8;
1316 PUSHSTACKi(PERLSI_WARNHOOK);
1320 call_sv((SV*)cv, G_DISCARD);
1327 write_to_stderr(message, msglen);
1330 #if defined(PERL_IMPLICIT_CONTEXT)
1332 Perl_warn_nocontext(const char *pat, ...)
1336 va_start(args, pat);
1340 #endif /* PERL_IMPLICIT_CONTEXT */
1345 This is the XSUB-writer's interface to Perl's C<warn> function. Call this
1346 function the same way you call the C C<printf> function. See C<croak>.
1352 Perl_warn(pTHX_ const char *pat, ...)
1355 va_start(args, pat);
1360 #if defined(PERL_IMPLICIT_CONTEXT)
1362 Perl_warner_nocontext(U32 err, const char *pat, ...)
1366 va_start(args, pat);
1367 vwarner(err, pat, &args);
1370 #endif /* PERL_IMPLICIT_CONTEXT */
1373 Perl_warner(pTHX_ U32 err, const char* pat,...)
1376 va_start(args, pat);
1377 vwarner(err, pat, &args);
1382 Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1386 SV * const msv = vmess(pat, args);
1388 const char * const message = SvPV_const(msv, msglen);
1389 const I32 utf8 = SvUTF8(msv);
1393 S_vdie_common(aTHX_ message, msglen, utf8);
1396 PL_restartop = die_where(message, msglen);
1397 SvFLAGS(ERRSV) |= utf8;
1400 write_to_stderr(message, msglen);
1404 Perl_vwarn(aTHX_ pat, args);
1408 /* implements the ckWARN? macros */
1411 Perl_ckwarn(pTHX_ U32 w)
1416 && PL_curcop->cop_warnings != pWARN_NONE
1418 PL_curcop->cop_warnings == pWARN_ALL
1419 || isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w))
1420 || (unpackWARN2(w) &&
1421 isWARN_on(PL_curcop->cop_warnings, unpackWARN2(w)))
1422 || (unpackWARN3(w) &&
1423 isWARN_on(PL_curcop->cop_warnings, unpackWARN3(w)))
1424 || (unpackWARN4(w) &&
1425 isWARN_on(PL_curcop->cop_warnings, unpackWARN4(w)))
1430 isLEXWARN_off && PL_dowarn & G_WARN_ON
1435 /* implements the ckWARN?_d macro */
1438 Perl_ckwarn_d(pTHX_ U32 w)
1442 || PL_curcop->cop_warnings == pWARN_ALL
1444 PL_curcop->cop_warnings != pWARN_NONE
1446 isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w))
1447 || (unpackWARN2(w) &&
1448 isWARN_on(PL_curcop->cop_warnings, unpackWARN2(w)))
1449 || (unpackWARN3(w) &&
1450 isWARN_on(PL_curcop->cop_warnings, unpackWARN3(w)))
1451 || (unpackWARN4(w) &&
1452 isWARN_on(PL_curcop->cop_warnings, unpackWARN4(w)))
1460 /* since we've already done strlen() for both nam and val
1461 * we can use that info to make things faster than
1462 * sprintf(s, "%s=%s", nam, val)
1464 #define my_setenv_format(s, nam, nlen, val, vlen) \
1465 Copy(nam, s, nlen, char); \
1467 Copy(val, s+(nlen+1), vlen, char); \
1468 *(s+(nlen+1+vlen)) = '\0'
1470 #ifdef USE_ENVIRON_ARRAY
1471 /* VMS' my_setenv() is in vms.c */
1472 #if !defined(WIN32) && !defined(NETWARE)
1474 Perl_my_setenv(pTHX_ const char *nam, const char *val)
1478 /* only parent thread can modify process environment */
1479 if (PL_curinterp == aTHX)
1482 #ifndef PERL_USE_SAFE_PUTENV
1483 if (!PL_use_safe_putenv) {
1484 /* most putenv()s leak, so we manipulate environ directly */
1485 register I32 i=setenv_getix(nam); /* where does it go? */
1488 if (environ == PL_origenviron) { /* need we copy environment? */
1493 for (max = i; environ[max]; max++) ;
1494 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
1495 for (j=0; j<max; j++) { /* copy environment */
1496 const int len = strlen(environ[j]);
1497 tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
1498 Copy(environ[j], tmpenv[j], len+1, char);
1500 tmpenv[max] = Nullch;
1501 environ = tmpenv; /* tell exec where it is now */
1504 safesysfree(environ[i]);
1505 while (environ[i]) {
1506 environ[i] = environ[i+1];
1511 if (!environ[i]) { /* does not exist yet */
1512 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
1513 environ[i+1] = Nullch; /* make sure it's null terminated */
1516 safesysfree(environ[i]);
1520 environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
1521 /* all that work just for this */
1522 my_setenv_format(environ[i], nam, nlen, val, vlen);
1525 # if defined(__CYGWIN__) || defined(EPOC) || defined(__SYMBIAN32__)
1526 # if defined(HAS_UNSETENV)
1528 (void)unsetenv(nam);
1530 (void)setenv(nam, val, 1);
1532 # else /* ! HAS_UNSETENV */
1533 (void)setenv(nam, val, 1);
1534 # endif /* HAS_UNSETENV */
1536 # if defined(HAS_UNSETENV)
1538 (void)unsetenv(nam);
1540 const int nlen = strlen(nam);
1541 const int vlen = strlen(val);
1542 char * const new_env =
1543 (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1544 my_setenv_format(new_env, nam, nlen, val, vlen);
1545 (void)putenv(new_env);
1547 # else /* ! HAS_UNSETENV */
1549 const int nlen = strlen(nam);
1555 new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1556 /* all that work just for this */
1557 my_setenv_format(new_env, nam, nlen, val, vlen);
1558 (void)putenv(new_env);
1559 # endif /* HAS_UNSETENV */
1560 # endif /* __CYGWIN__ */
1561 #ifndef PERL_USE_SAFE_PUTENV
1567 #else /* WIN32 || NETWARE */
1570 Perl_my_setenv(pTHX_ const char *nam, const char *val)
1573 register char *envstr;
1574 const int nlen = strlen(nam);
1581 Newx(envstr, nlen+vlen+2, char);
1582 my_setenv_format(envstr, nam, nlen, val, vlen);
1583 (void)PerlEnv_putenv(envstr);
1587 #endif /* WIN32 || NETWARE */
1591 Perl_setenv_getix(pTHX_ const char *nam)
1594 register const I32 len = strlen(nam);
1596 for (i = 0; environ[i]; i++) {
1599 strnicmp(environ[i],nam,len) == 0
1601 strnEQ(environ[i],nam,len)
1603 && environ[i][len] == '=')
1604 break; /* strnEQ must come first to avoid */
1605 } /* potential SEGV's */
1608 #endif /* !PERL_MICRO */
1610 #endif /* !VMS && !EPOC*/
1612 #ifdef UNLINK_ALL_VERSIONS
1614 Perl_unlnk(pTHX_ const char *f) /* unlink all versions of a file */
1618 for (i = 0; PerlLIO_unlink(f) >= 0; i++) ;
1623 /* this is a drop-in replacement for bcopy() */
1624 #if (!defined(HAS_MEMCPY) && !defined(HAS_BCOPY)) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY) && !defined(HAS_SAFE_BCOPY))
1626 Perl_my_bcopy(register const char *from,register char *to,register I32 len)
1628 char * const retval = to;
1630 if (from - to >= 0) {
1638 *(--to) = *(--from);
1644 /* this is a drop-in replacement for memset() */
1647 Perl_my_memset(register char *loc, register I32 ch, register I32 len)
1649 char * const retval = loc;
1657 /* this is a drop-in replacement for bzero() */
1658 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
1660 Perl_my_bzero(register char *loc, register I32 len)
1662 char * const retval = loc;
1670 /* this is a drop-in replacement for memcmp() */
1671 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
1673 Perl_my_memcmp(const char *s1, const char *s2, register I32 len)
1675 register const U8 *a = (const U8 *)s1;
1676 register const U8 *b = (const U8 *)s2;
1680 if ((tmp = *a++ - *b++))
1685 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
1689 #ifdef USE_CHAR_VSPRINTF
1694 vsprintf(char *dest, const char *pat, char *args)
1698 fakebuf._ptr = dest;
1699 fakebuf._cnt = 32767;
1703 fakebuf._flag = _IOWRT|_IOSTRG;
1704 _doprnt(pat, args, &fakebuf); /* what a kludge */
1705 (void)putc('\0', &fakebuf);
1706 #ifdef USE_CHAR_VSPRINTF
1709 return 0; /* perl doesn't use return value */
1713 #endif /* HAS_VPRINTF */
1716 #if BYTEORDER != 0x4321
1718 Perl_my_swap(pTHX_ short s)
1720 #if (BYTEORDER & 1) == 0
1723 result = ((s & 255) << 8) + ((s >> 8) & 255);
1731 Perl_my_htonl(pTHX_ long l)
1735 char c[sizeof(long)];
1738 #if BYTEORDER == 0x1234
1739 u.c[0] = (l >> 24) & 255;
1740 u.c[1] = (l >> 16) & 255;
1741 u.c[2] = (l >> 8) & 255;
1745 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1746 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
1751 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1752 u.c[o & 0xf] = (l >> s) & 255;
1760 Perl_my_ntohl(pTHX_ long l)
1764 char c[sizeof(long)];
1767 #if BYTEORDER == 0x1234
1768 u.c[0] = (l >> 24) & 255;
1769 u.c[1] = (l >> 16) & 255;
1770 u.c[2] = (l >> 8) & 255;
1774 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1775 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
1782 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1783 l |= (u.c[o & 0xf] & 255) << s;
1790 #endif /* BYTEORDER != 0x4321 */
1794 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
1795 * If these functions are defined,
1796 * the BYTEORDER is neither 0x1234 nor 0x4321.
1797 * However, this is not assumed.
1801 #define HTOLE(name,type) \
1803 name (register type n) \
1807 char c[sizeof(type)]; \
1810 register I32 s = 0; \
1811 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
1812 u.c[i] = (n >> s) & 0xFF; \
1817 #define LETOH(name,type) \
1819 name (register type n) \
1823 char c[sizeof(type)]; \
1826 register I32 s = 0; \
1829 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
1830 n |= ((type)(u.c[i] & 0xFF)) << s; \
1836 * Big-endian byte order functions.
1839 #define HTOBE(name,type) \
1841 name (register type n) \
1845 char c[sizeof(type)]; \
1848 register I32 s = 8*(sizeof(u.c)-1); \
1849 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
1850 u.c[i] = (n >> s) & 0xFF; \
1855 #define BETOH(name,type) \
1857 name (register type n) \
1861 char c[sizeof(type)]; \
1864 register I32 s = 8*(sizeof(u.c)-1); \
1867 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
1868 n |= ((type)(u.c[i] & 0xFF)) << s; \
1874 * If we just can't do it...
1877 #define NOT_AVAIL(name,type) \
1879 name (register type n) \
1881 Perl_croak_nocontext(#name "() not available"); \
1882 return n; /* not reached */ \
1886 #if defined(HAS_HTOVS) && !defined(htovs)
1889 #if defined(HAS_HTOVL) && !defined(htovl)
1892 #if defined(HAS_VTOHS) && !defined(vtohs)
1895 #if defined(HAS_VTOHL) && !defined(vtohl)
1899 #ifdef PERL_NEED_MY_HTOLE16
1901 HTOLE(Perl_my_htole16,U16)
1903 NOT_AVAIL(Perl_my_htole16,U16)
1906 #ifdef PERL_NEED_MY_LETOH16
1908 LETOH(Perl_my_letoh16,U16)
1910 NOT_AVAIL(Perl_my_letoh16,U16)
1913 #ifdef PERL_NEED_MY_HTOBE16
1915 HTOBE(Perl_my_htobe16,U16)
1917 NOT_AVAIL(Perl_my_htobe16,U16)
1920 #ifdef PERL_NEED_MY_BETOH16
1922 BETOH(Perl_my_betoh16,U16)
1924 NOT_AVAIL(Perl_my_betoh16,U16)
1928 #ifdef PERL_NEED_MY_HTOLE32
1930 HTOLE(Perl_my_htole32,U32)
1932 NOT_AVAIL(Perl_my_htole32,U32)
1935 #ifdef PERL_NEED_MY_LETOH32
1937 LETOH(Perl_my_letoh32,U32)
1939 NOT_AVAIL(Perl_my_letoh32,U32)
1942 #ifdef PERL_NEED_MY_HTOBE32
1944 HTOBE(Perl_my_htobe32,U32)
1946 NOT_AVAIL(Perl_my_htobe32,U32)
1949 #ifdef PERL_NEED_MY_BETOH32
1951 BETOH(Perl_my_betoh32,U32)
1953 NOT_AVAIL(Perl_my_betoh32,U32)
1957 #ifdef PERL_NEED_MY_HTOLE64
1959 HTOLE(Perl_my_htole64,U64)
1961 NOT_AVAIL(Perl_my_htole64,U64)
1964 #ifdef PERL_NEED_MY_LETOH64
1966 LETOH(Perl_my_letoh64,U64)
1968 NOT_AVAIL(Perl_my_letoh64,U64)
1971 #ifdef PERL_NEED_MY_HTOBE64
1973 HTOBE(Perl_my_htobe64,U64)
1975 NOT_AVAIL(Perl_my_htobe64,U64)
1978 #ifdef PERL_NEED_MY_BETOH64
1980 BETOH(Perl_my_betoh64,U64)
1982 NOT_AVAIL(Perl_my_betoh64,U64)
1986 #ifdef PERL_NEED_MY_HTOLES
1987 HTOLE(Perl_my_htoles,short)
1989 #ifdef PERL_NEED_MY_LETOHS
1990 LETOH(Perl_my_letohs,short)
1992 #ifdef PERL_NEED_MY_HTOBES
1993 HTOBE(Perl_my_htobes,short)
1995 #ifdef PERL_NEED_MY_BETOHS
1996 BETOH(Perl_my_betohs,short)
1999 #ifdef PERL_NEED_MY_HTOLEI
2000 HTOLE(Perl_my_htolei,int)
2002 #ifdef PERL_NEED_MY_LETOHI
2003 LETOH(Perl_my_letohi,int)
2005 #ifdef PERL_NEED_MY_HTOBEI
2006 HTOBE(Perl_my_htobei,int)
2008 #ifdef PERL_NEED_MY_BETOHI
2009 BETOH(Perl_my_betohi,int)
2012 #ifdef PERL_NEED_MY_HTOLEL
2013 HTOLE(Perl_my_htolel,long)
2015 #ifdef PERL_NEED_MY_LETOHL
2016 LETOH(Perl_my_letohl,long)
2018 #ifdef PERL_NEED_MY_HTOBEL
2019 HTOBE(Perl_my_htobel,long)
2021 #ifdef PERL_NEED_MY_BETOHL
2022 BETOH(Perl_my_betohl,long)
2026 Perl_my_swabn(void *ptr, int n)
2028 register char *s = (char *)ptr;
2029 register char *e = s + (n-1);
2032 for (n /= 2; n > 0; s++, e--, n--) {
2040 Perl_my_popen_list(pTHX_ char *mode, int n, SV **args)
2042 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(OS2) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL) && !defined(NETWARE)
2044 register I32 This, that;
2050 PERL_FLUSHALL_FOR_CHILD;
2051 This = (*mode == 'w');
2055 taint_proper("Insecure %s%s", "EXEC");
2057 if (PerlProc_pipe(p) < 0)
2059 /* Try for another pipe pair for error return */
2060 if (PerlProc_pipe(pp) >= 0)
2062 while ((pid = PerlProc_fork()) < 0) {
2063 if (errno != EAGAIN) {
2064 PerlLIO_close(p[This]);
2065 PerlLIO_close(p[that]);
2067 PerlLIO_close(pp[0]);
2068 PerlLIO_close(pp[1]);
2080 /* Close parent's end of error status pipe (if any) */
2082 PerlLIO_close(pp[0]);
2083 #if defined(HAS_FCNTL) && defined(F_SETFD)
2084 /* Close error pipe automatically if exec works */
2085 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2088 /* Now dup our end of _the_ pipe to right position */
2089 if (p[THIS] != (*mode == 'r')) {
2090 PerlLIO_dup2(p[THIS], *mode == 'r');
2091 PerlLIO_close(p[THIS]);
2092 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2093 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2096 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2097 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2098 /* No automatic close - do it by hand */
2105 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
2111 do_aexec5(Nullsv, args-1, args-1+n, pp[1], did_pipes);
2117 do_execfree(); /* free any memory malloced by child on fork */
2119 PerlLIO_close(pp[1]);
2120 /* Keep the lower of the two fd numbers */
2121 if (p[that] < p[This]) {
2122 PerlLIO_dup2(p[This], p[that]);
2123 PerlLIO_close(p[This]);
2127 PerlLIO_close(p[that]); /* close child's end of pipe */
2130 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2132 SvUPGRADE(sv,SVt_IV);
2134 PL_forkprocess = pid;
2135 /* If we managed to get status pipe check for exec fail */
2136 if (did_pipes && pid > 0) {
2140 while (n < sizeof(int)) {
2141 n1 = PerlLIO_read(pp[0],
2142 (void*)(((char*)&errkid)+n),
2148 PerlLIO_close(pp[0]);
2150 if (n) { /* Error */
2152 PerlLIO_close(p[This]);
2153 if (n != sizeof(int))
2154 Perl_croak(aTHX_ "panic: kid popen errno read");
2156 pid2 = wait4pid(pid, &status, 0);
2157 } while (pid2 == -1 && errno == EINTR);
2158 errno = errkid; /* Propagate errno from kid */
2163 PerlLIO_close(pp[0]);
2164 return PerlIO_fdopen(p[This], mode);
2166 Perl_croak(aTHX_ "List form of piped open not implemented");
2167 return (PerlIO *) NULL;
2171 /* VMS' my_popen() is in VMS.c, same with OS/2. */
2172 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
2174 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2177 register I32 This, that;
2180 const I32 doexec = !(*cmd == '-' && cmd[1] == '\0');
2184 PERL_FLUSHALL_FOR_CHILD;
2187 return my_syspopen(aTHX_ cmd,mode);
2190 This = (*mode == 'w');
2192 if (doexec && PL_tainting) {
2194 taint_proper("Insecure %s%s", "EXEC");
2196 if (PerlProc_pipe(p) < 0)
2198 if (doexec && PerlProc_pipe(pp) >= 0)
2200 while ((pid = PerlProc_fork()) < 0) {
2201 if (errno != EAGAIN) {
2202 PerlLIO_close(p[This]);
2203 PerlLIO_close(p[that]);
2205 PerlLIO_close(pp[0]);
2206 PerlLIO_close(pp[1]);
2209 Perl_croak(aTHX_ "Can't fork");
2222 PerlLIO_close(pp[0]);
2223 #if defined(HAS_FCNTL) && defined(F_SETFD)
2224 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2227 if (p[THIS] != (*mode == 'r')) {
2228 PerlLIO_dup2(p[THIS], *mode == 'r');
2229 PerlLIO_close(p[THIS]);
2230 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2231 PerlLIO_close(p[THAT]);
2234 PerlLIO_close(p[THAT]);
2237 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2244 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2249 /* may or may not use the shell */
2250 do_exec3(cmd, pp[1], did_pipes);
2253 #endif /* defined OS2 */
2254 if ((tmpgv = gv_fetchpv("$",TRUE, SVt_PV))) {
2255 SvREADONLY_off(GvSV(tmpgv));
2256 sv_setiv(GvSV(tmpgv), PerlProc_getpid());
2257 SvREADONLY_on(GvSV(tmpgv));
2259 #ifdef THREADS_HAVE_PIDS
2260 PL_ppid = (IV)getppid();
2263 #ifdef PERL_USES_PL_PIDSTATUS
2264 hv_clear(PL_pidstatus); /* we have no children */
2270 do_execfree(); /* free any memory malloced by child on vfork */
2272 PerlLIO_close(pp[1]);
2273 if (p[that] < p[This]) {
2274 PerlLIO_dup2(p[This], p[that]);
2275 PerlLIO_close(p[This]);
2279 PerlLIO_close(p[that]);
2282 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2284 SvUPGRADE(sv,SVt_IV);
2286 PL_forkprocess = pid;
2287 if (did_pipes && pid > 0) {
2291 while (n < sizeof(int)) {
2292 n1 = PerlLIO_read(pp[0],
2293 (void*)(((char*)&errkid)+n),
2299 PerlLIO_close(pp[0]);
2301 if (n) { /* Error */
2303 PerlLIO_close(p[This]);
2304 if (n != sizeof(int))
2305 Perl_croak(aTHX_ "panic: kid popen errno read");
2307 pid2 = wait4pid(pid, &status, 0);
2308 } while (pid2 == -1 && errno == EINTR);
2309 errno = errkid; /* Propagate errno from kid */
2314 PerlLIO_close(pp[0]);
2315 return PerlIO_fdopen(p[This], mode);
2318 #if defined(atarist) || defined(EPOC)
2321 Perl_my_popen(pTHX_ char *cmd, char *mode)
2323 PERL_FLUSHALL_FOR_CHILD;
2324 /* Call system's popen() to get a FILE *, then import it.
2325 used 0 for 2nd parameter to PerlIO_importFILE;
2328 return PerlIO_importFILE(popen(cmd, mode), 0);
2332 FILE *djgpp_popen();
2334 Perl_my_popen(pTHX_ char *cmd, char *mode)
2336 PERL_FLUSHALL_FOR_CHILD;
2337 /* Call system's popen() to get a FILE *, then import it.
2338 used 0 for 2nd parameter to PerlIO_importFILE;
2341 return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2346 #endif /* !DOSISH */
2348 /* this is called in parent before the fork() */
2350 Perl_atfork_lock(void)
2353 #if defined(USE_ITHREADS)
2354 /* locks must be held in locking order (if any) */
2356 MUTEX_LOCK(&PL_malloc_mutex);
2362 /* this is called in both parent and child after the fork() */
2364 Perl_atfork_unlock(void)
2367 #if defined(USE_ITHREADS)
2368 /* locks must be released in same order as in atfork_lock() */
2370 MUTEX_UNLOCK(&PL_malloc_mutex);
2379 #if defined(HAS_FORK)
2381 #if defined(USE_ITHREADS) && !defined(HAS_PTHREAD_ATFORK)
2386 /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2387 * handlers elsewhere in the code */
2392 /* this "canna happen" since nothing should be calling here if !HAS_FORK */
2393 Perl_croak_nocontext("fork() not available");
2395 #endif /* HAS_FORK */
2400 Perl_dump_fds(pTHX_ char *s)
2405 PerlIO_printf(Perl_debug_log,"%s", s);
2406 for (fd = 0; fd < 32; fd++) {
2407 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
2408 PerlIO_printf(Perl_debug_log," %d",fd);
2410 PerlIO_printf(Perl_debug_log,"\n");
2413 #endif /* DUMP_FDS */
2417 dup2(int oldfd, int newfd)
2419 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2422 PerlLIO_close(newfd);
2423 return fcntl(oldfd, F_DUPFD, newfd);
2425 #define DUP2_MAX_FDS 256
2426 int fdtmp[DUP2_MAX_FDS];
2432 PerlLIO_close(newfd);
2433 /* good enough for low fd's... */
2434 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2435 if (fdx >= DUP2_MAX_FDS) {
2443 PerlLIO_close(fdtmp[--fdx]);
2450 #ifdef HAS_SIGACTION
2452 #ifdef MACOS_TRADITIONAL
2453 /* We don't want restart behavior on MacOS */
2458 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2461 struct sigaction act, oact;
2464 /* only "parent" interpreter can diddle signals */
2465 if (PL_curinterp != aTHX)
2466 return (Sighandler_t) SIG_ERR;
2469 act.sa_handler = (void(*)(int))handler;
2470 sigemptyset(&act.sa_mask);
2473 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2474 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2476 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2477 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2478 act.sa_flags |= SA_NOCLDWAIT;
2480 if (sigaction(signo, &act, &oact) == -1)
2481 return (Sighandler_t) SIG_ERR;
2483 return (Sighandler_t) oact.sa_handler;
2487 Perl_rsignal_state(pTHX_ int signo)
2489 struct sigaction oact;
2491 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2492 return (Sighandler_t) SIG_ERR;
2494 return (Sighandler_t) oact.sa_handler;
2498 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2501 struct sigaction act;
2504 /* only "parent" interpreter can diddle signals */
2505 if (PL_curinterp != aTHX)
2509 act.sa_handler = (void(*)(int))handler;
2510 sigemptyset(&act.sa_mask);
2513 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2514 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2516 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2517 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2518 act.sa_flags |= SA_NOCLDWAIT;
2520 return sigaction(signo, &act, save);
2524 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2528 /* only "parent" interpreter can diddle signals */
2529 if (PL_curinterp != aTHX)
2533 return sigaction(signo, save, (struct sigaction *)NULL);
2536 #else /* !HAS_SIGACTION */
2539 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2541 #if defined(USE_ITHREADS) && !defined(WIN32)
2542 /* only "parent" interpreter can diddle signals */
2543 if (PL_curinterp != aTHX)
2544 return (Sighandler_t) SIG_ERR;
2547 return PerlProc_signal(signo, handler);
2559 Perl_rsignal_state(pTHX_ int signo)
2562 Sighandler_t oldsig;
2564 #if defined(USE_ITHREADS) && !defined(WIN32)
2565 /* only "parent" interpreter can diddle signals */
2566 if (PL_curinterp != aTHX)
2567 return (Sighandler_t) SIG_ERR;
2571 oldsig = PerlProc_signal(signo, sig_trap);
2572 PerlProc_signal(signo, oldsig);
2574 PerlProc_kill(PerlProc_getpid(), signo);
2579 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2581 #if defined(USE_ITHREADS) && !defined(WIN32)
2582 /* only "parent" interpreter can diddle signals */
2583 if (PL_curinterp != aTHX)
2586 *save = PerlProc_signal(signo, handler);
2587 return (*save == (Sighandler_t) SIG_ERR) ? -1 : 0;
2591 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2593 #if defined(USE_ITHREADS) && !defined(WIN32)
2594 /* only "parent" interpreter can diddle signals */
2595 if (PL_curinterp != aTHX)
2598 return (PerlProc_signal(signo, *save) == (Sighandler_t) SIG_ERR) ? -1 : 0;
2601 #endif /* !HAS_SIGACTION */
2602 #endif /* !PERL_MICRO */
2604 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
2605 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
2607 Perl_my_pclose(pTHX_ PerlIO *ptr)
2609 Sigsave_t hstat, istat, qstat;
2615 int saved_errno = 0;
2617 int saved_win32_errno;
2621 svp = av_fetch(PL_fdpid,PerlIO_fileno(ptr),TRUE);
2623 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
2625 *svp = &PL_sv_undef;
2627 if (pid == -1) { /* Opened by popen. */
2628 return my_syspclose(ptr);
2631 if ((close_failed = (PerlIO_close(ptr) == EOF))) {
2632 saved_errno = errno;
2634 saved_win32_errno = GetLastError();
2638 if(PerlProc_kill(pid, 0) < 0) { return(pid); } /* HOM 12/23/91 */
2641 rsignal_save(SIGHUP, (Sighandler_t) SIG_IGN, &hstat);
2642 rsignal_save(SIGINT, (Sighandler_t) SIG_IGN, &istat);
2643 rsignal_save(SIGQUIT, (Sighandler_t) SIG_IGN, &qstat);
2646 pid2 = wait4pid(pid, &status, 0);
2647 } while (pid2 == -1 && errno == EINTR);
2649 rsignal_restore(SIGHUP, &hstat);
2650 rsignal_restore(SIGINT, &istat);
2651 rsignal_restore(SIGQUIT, &qstat);
2654 SETERRNO(saved_errno, 0);
2657 return(pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status));
2659 #endif /* !DOSISH */
2661 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(MACOS_TRADITIONAL)
2663 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
2668 #ifdef PERL_USES_PL_PIDSTATUS
2671 /* The keys in PL_pidstatus are now the raw 4 (or 8) bytes of the
2672 pid, rather than a string form. */
2673 SV * const * const svp = hv_fetch(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),FALSE);
2674 if (svp && *svp != &PL_sv_undef) {
2675 *statusp = SvIVX(*svp);
2676 (void)hv_delete(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),
2684 hv_iterinit(PL_pidstatus);
2685 if ((entry = hv_iternext(PL_pidstatus))) {
2686 SV * const sv = hv_iterval(PL_pidstatus,entry);
2688 const char * const spid = hv_iterkey(entry,&len);
2690 assert (len == sizeof(Pid_t));
2691 memcpy((char *)&pid, spid, len);
2692 *statusp = SvIVX(sv);
2693 /* The hash iterator is currently on this entry, so simply
2694 calling hv_delete would trigger the lazy delete, which on
2695 aggregate does more work, beacuse next call to hv_iterinit()
2696 would spot the flag, and have to call the delete routine,
2697 while in the meantime any new entries can't re-use that
2699 hv_iterinit(PL_pidstatus);
2700 (void)hv_delete(PL_pidstatus,spid,len,G_DISCARD);
2707 # ifdef HAS_WAITPID_RUNTIME
2708 if (!HAS_WAITPID_RUNTIME)
2711 result = PerlProc_waitpid(pid,statusp,flags);
2714 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
2715 result = wait4((pid==-1)?0:pid,statusp,flags,Null(struct rusage *));
2718 #ifdef PERL_USES_PL_PIDSTATUS
2719 #if defined(HAS_WAITPID) && defined(HAS_WAITPID_RUNTIME)
2724 Perl_croak(aTHX_ "Can't do waitpid with flags");
2726 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
2727 pidgone(result,*statusp);
2733 #if defined(HAS_WAITPID) || defined(HAS_WAIT4)
2736 if (result < 0 && errno == EINTR) {
2741 #endif /* !DOSISH || OS2 || WIN32 || NETWARE */
2743 #ifdef PERL_USES_PL_PIDSTATUS
2745 Perl_pidgone(pTHX_ Pid_t pid, int status)
2749 sv = *hv_fetch(PL_pidstatus,(const char*)&pid,sizeof(Pid_t),TRUE);
2750 SvUPGRADE(sv,SVt_IV);
2751 SvIV_set(sv, status);
2756 #if defined(atarist) || defined(OS2) || defined(EPOC)
2759 int /* Cannot prototype with I32
2761 my_syspclose(PerlIO *ptr)
2764 Perl_my_pclose(pTHX_ PerlIO *ptr)
2767 /* Needs work for PerlIO ! */
2768 FILE * const f = PerlIO_findFILE(ptr);
2769 const I32 result = pclose(f);
2770 PerlIO_releaseFILE(ptr,f);
2778 Perl_my_pclose(pTHX_ PerlIO *ptr)
2780 /* Needs work for PerlIO ! */
2781 FILE * const f = PerlIO_findFILE(ptr);
2782 I32 result = djgpp_pclose(f);
2783 result = (result << 8) & 0xff00;
2784 PerlIO_releaseFILE(ptr,f);
2790 Perl_repeatcpy(pTHX_ register char *to, register const char *from, I32 len, register I32 count)
2793 register const char * const frombase = from;
2796 register const char c = *from;
2801 while (count-- > 0) {
2802 for (todo = len; todo > 0; todo--) {
2811 Perl_same_dirent(pTHX_ const char *a, const char *b)
2813 char *fa = strrchr(a,'/');
2814 char *fb = strrchr(b,'/');
2817 SV * const tmpsv = sv_newmortal();
2830 sv_setpvn(tmpsv, ".", 1);
2832 sv_setpvn(tmpsv, a, fa - a);
2833 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf1) < 0)
2836 sv_setpvn(tmpsv, ".", 1);
2838 sv_setpvn(tmpsv, b, fb - b);
2839 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf2) < 0)
2841 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
2842 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
2844 #endif /* !HAS_RENAME */
2847 Perl_find_script(pTHX_ const char *scriptname, bool dosearch,
2848 const char *const *const search_ext, I32 flags)
2850 const char *xfound = Nullch;
2851 char *xfailed = Nullch;
2852 char tmpbuf[MAXPATHLEN];
2856 #if defined(DOSISH) && !defined(OS2) && !defined(atarist)
2857 # define SEARCH_EXTS ".bat", ".cmd", NULL
2858 # define MAX_EXT_LEN 4
2861 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
2862 # define MAX_EXT_LEN 4
2865 # define SEARCH_EXTS ".pl", ".com", NULL
2866 # define MAX_EXT_LEN 4
2868 /* additional extensions to try in each dir if scriptname not found */
2870 static const char *const exts[] = { SEARCH_EXTS };
2871 const char *const *const ext = search_ext ? search_ext : exts;
2872 int extidx = 0, i = 0;
2873 const char *curext = Nullch;
2875 PERL_UNUSED_ARG(search_ext);
2876 # define MAX_EXT_LEN 0
2880 * If dosearch is true and if scriptname does not contain path
2881 * delimiters, search the PATH for scriptname.
2883 * If SEARCH_EXTS is also defined, will look for each
2884 * scriptname{SEARCH_EXTS} whenever scriptname is not found
2885 * while searching the PATH.
2887 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
2888 * proceeds as follows:
2889 * If DOSISH or VMSISH:
2890 * + look for ./scriptname{,.foo,.bar}
2891 * + search the PATH for scriptname{,.foo,.bar}
2894 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
2895 * this will not look in '.' if it's not in the PATH)
2900 # ifdef ALWAYS_DEFTYPES
2901 len = strlen(scriptname);
2902 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
2903 int idx = 0, deftypes = 1;
2906 const int hasdir = !dosearch || (strpbrk(scriptname,":[</") != Nullch);
2909 int idx = 0, deftypes = 1;
2912 const int hasdir = (strpbrk(scriptname,":[</") != Nullch);
2914 /* The first time through, just add SEARCH_EXTS to whatever we
2915 * already have, so we can check for default file types. */
2917 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
2923 if ((strlen(tmpbuf) + strlen(scriptname)
2924 + MAX_EXT_LEN) >= sizeof tmpbuf)
2925 continue; /* don't search dir with too-long name */
2926 strcat(tmpbuf, scriptname);
2930 if (strEQ(scriptname, "-"))
2932 if (dosearch) { /* Look in '.' first. */
2933 const char *cur = scriptname;
2935 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
2937 if (strEQ(ext[i++],curext)) {
2938 extidx = -1; /* already has an ext */
2943 DEBUG_p(PerlIO_printf(Perl_debug_log,
2944 "Looking for %s\n",cur));
2945 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
2946 && !S_ISDIR(PL_statbuf.st_mode)) {
2954 if (cur == scriptname) {
2955 len = strlen(scriptname);
2956 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
2958 /* FIXME? Convert to memcpy */
2959 cur = strcpy(tmpbuf, scriptname);
2961 } while (extidx >= 0 && ext[extidx] /* try an extension? */
2962 && strcpy(tmpbuf+len, ext[extidx++]));
2967 #ifdef MACOS_TRADITIONAL
2968 if (dosearch && !strchr(scriptname, ':') &&
2969 (s = PerlEnv_getenv("Commands")))
2971 if (dosearch && !strchr(scriptname, '/')
2973 && !strchr(scriptname, '\\')
2975 && (s = PerlEnv_getenv("PATH")))
2980 PL_bufend = s + strlen(s);
2981 while (s < PL_bufend) {
2982 #ifdef MACOS_TRADITIONAL
2983 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
2987 #if defined(atarist) || defined(DOSISH)
2992 && *s != ';'; len++, s++) {
2993 if (len < sizeof tmpbuf)
2996 if (len < sizeof tmpbuf)
2998 #else /* ! (atarist || DOSISH) */
2999 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
3002 #endif /* ! (atarist || DOSISH) */
3003 #endif /* MACOS_TRADITIONAL */
3006 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
3007 continue; /* don't search dir with too-long name */
3008 #ifdef MACOS_TRADITIONAL
3009 if (len && tmpbuf[len - 1] != ':')
3010 tmpbuf[len++] = ':';
3013 # if defined(atarist) || defined(__MINT__) || defined(DOSISH)
3014 && tmpbuf[len - 1] != '/'
3015 && tmpbuf[len - 1] != '\\'
3018 tmpbuf[len++] = '/';
3019 if (len == 2 && tmpbuf[0] == '.')
3022 /* FIXME? Convert to memcpy by storing previous strlen(scriptname)
3024 (void)strcpy(tmpbuf + len, scriptname);
3028 len = strlen(tmpbuf);
3029 if (extidx > 0) /* reset after previous loop */
3033 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
3034 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
3035 if (S_ISDIR(PL_statbuf.st_mode)) {
3039 } while ( retval < 0 /* not there */
3040 && extidx>=0 && ext[extidx] /* try an extension? */
3041 && strcpy(tmpbuf+len, ext[extidx++])
3046 if (S_ISREG(PL_statbuf.st_mode)
3047 && cando(S_IRUSR,TRUE,&PL_statbuf)
3048 #if !defined(DOSISH) && !defined(MACOS_TRADITIONAL)
3049 && cando(S_IXUSR,TRUE,&PL_statbuf)
3053 xfound = tmpbuf; /* bingo! */
3057 xfailed = savepv(tmpbuf);
3060 if (!xfound && !seen_dot && !xfailed &&
3061 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
3062 || S_ISDIR(PL_statbuf.st_mode)))
3064 seen_dot = 1; /* Disable message. */
3066 if (flags & 1) { /* do or die? */
3067 Perl_croak(aTHX_ "Can't %s %s%s%s",
3068 (xfailed ? "execute" : "find"),
3069 (xfailed ? xfailed : scriptname),
3070 (xfailed ? "" : " on PATH"),
3071 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
3073 scriptname = Nullch;
3076 scriptname = xfound;
3078 return (scriptname ? savepv(scriptname) : Nullch);
3081 #ifndef PERL_GET_CONTEXT_DEFINED
3084 Perl_get_context(void)
3087 #if defined(USE_ITHREADS)
3088 # ifdef OLD_PTHREADS_API
3090 if (pthread_getspecific(PL_thr_key, &t))
3091 Perl_croak_nocontext("panic: pthread_getspecific");
3094 # ifdef I_MACH_CTHREADS
3095 return (void*)cthread_data(cthread_self());
3097 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
3106 Perl_set_context(void *t)
3109 #if defined(USE_ITHREADS)
3110 # ifdef I_MACH_CTHREADS
3111 cthread_set_data(cthread_self(), t);
3113 if (pthread_setspecific(PL_thr_key, t))
3114 Perl_croak_nocontext("panic: pthread_setspecific");
3121 #endif /* !PERL_GET_CONTEXT_DEFINED */
3123 #if defined(PERL_GLOBAL_STRUCT) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
3132 Perl_get_op_names(pTHX)
3134 return (char **)PL_op_name;
3138 Perl_get_op_descs(pTHX)
3140 return (char **)PL_op_desc;
3144 Perl_get_no_modify(pTHX)
3146 return PL_no_modify;
3150 Perl_get_opargs(pTHX)
3152 return (U32 *)PL_opargs;
3156 Perl_get_ppaddr(pTHX)
3159 return (PPADDR_t*)PL_ppaddr;
3162 #ifndef HAS_GETENV_LEN
3164 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3166 char * const env_trans = PerlEnv_getenv(env_elem);
3168 *len = strlen(env_trans);
3175 Perl_get_vtbl(pTHX_ int vtbl_id)
3177 const MGVTBL* result;
3181 result = &PL_vtbl_sv;
3184 result = &PL_vtbl_env;
3186 case want_vtbl_envelem:
3187 result = &PL_vtbl_envelem;
3190 result = &PL_vtbl_sig;
3192 case want_vtbl_sigelem:
3193 result = &PL_vtbl_sigelem;
3195 case want_vtbl_pack:
3196 result = &PL_vtbl_pack;
3198 case want_vtbl_packelem:
3199 result = &PL_vtbl_packelem;
3201 case want_vtbl_dbline:
3202 result = &PL_vtbl_dbline;
3205 result = &PL_vtbl_isa;
3207 case want_vtbl_isaelem:
3208 result = &PL_vtbl_isaelem;
3210 case want_vtbl_arylen:
3211 result = &PL_vtbl_arylen;
3213 case want_vtbl_glob:
3214 result = &PL_vtbl_glob;
3216 case want_vtbl_mglob:
3217 result = &PL_vtbl_mglob;
3219 case want_vtbl_nkeys:
3220 result = &PL_vtbl_nkeys;
3222 case want_vtbl_taint:
3223 result = &PL_vtbl_taint;
3225 case want_vtbl_substr:
3226 result = &PL_vtbl_substr;
3229 result = &PL_vtbl_vec;
3232 result = &PL_vtbl_pos;
3235 result = &PL_vtbl_bm;
3238 result = &PL_vtbl_fm;
3240 case want_vtbl_uvar:
3241 result = &PL_vtbl_uvar;
3243 case want_vtbl_defelem:
3244 result = &PL_vtbl_defelem;
3246 case want_vtbl_regexp:
3247 result = &PL_vtbl_regexp;
3249 case want_vtbl_regdata:
3250 result = &PL_vtbl_regdata;
3252 case want_vtbl_regdatum:
3253 result = &PL_vtbl_regdatum;
3255 #ifdef USE_LOCALE_COLLATE
3256 case want_vtbl_collxfrm:
3257 result = &PL_vtbl_collxfrm;
3260 case want_vtbl_amagic:
3261 result = &PL_vtbl_amagic;
3263 case want_vtbl_amagicelem:
3264 result = &PL_vtbl_amagicelem;
3266 case want_vtbl_backref:
3267 result = &PL_vtbl_backref;
3269 case want_vtbl_utf8:
3270 result = &PL_vtbl_utf8;
3273 result = Null(MGVTBL*);
3276 return (MGVTBL*)result;
3280 Perl_my_fflush_all(pTHX)
3282 #if defined(USE_PERLIO) || defined(FFLUSH_NULL) || defined(USE_SFIO)
3283 return PerlIO_flush(NULL);
3285 # if defined(HAS__FWALK)
3286 extern int fflush(FILE *);
3287 /* undocumented, unprototyped, but very useful BSDism */
3288 extern void _fwalk(int (*)(FILE *));
3292 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3294 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3295 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3297 # if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3298 open_max = sysconf(_SC_OPEN_MAX);
3301 open_max = FOPEN_MAX;
3304 open_max = OPEN_MAX;
3315 for (i = 0; i < open_max; i++)
3316 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3317 STDIO_STREAM_ARRAY[i]._file < open_max &&
3318 STDIO_STREAM_ARRAY[i]._flag)
3319 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3323 SETERRNO(EBADF,RMS_IFI);
3330 Perl_report_evil_fh(pTHX_ const GV *gv, const IO *io, I32 op)
3332 const char * const func =
3333 op == OP_READLINE ? "readline" : /* "<HANDLE>" not nice */
3334 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
3336 const char * const pars = OP_IS_FILETEST(op) ? "" : "()";
3337 const char * const type = OP_IS_SOCKET(op)
3338 || (gv && io && IoTYPE(io) == IoTYPE_SOCKET)
3339 ? "socket" : "filehandle";
3340 const char * const name = gv && isGV(gv) ? GvENAME(gv) : NULL;
3342 if (op == OP_phoney_OUTPUT_ONLY || op == OP_phoney_INPUT_ONLY) {
3343 if (ckWARN(WARN_IO)) {
3344 const char * const direction = (op == OP_phoney_INPUT_ONLY) ? "in" : "out";
3346 Perl_warner(aTHX_ packWARN(WARN_IO),
3347 "Filehandle %s opened only for %sput",
3350 Perl_warner(aTHX_ packWARN(WARN_IO),
3351 "Filehandle opened only for %sput", direction);
3358 if (gv && io && IoTYPE(io) == IoTYPE_CLOSED) {
3360 warn_type = WARN_CLOSED;
3364 warn_type = WARN_UNOPENED;
3367 if (ckWARN(warn_type)) {
3368 if (name && *name) {
3369 Perl_warner(aTHX_ packWARN(warn_type),
3370 "%s%s on %s %s %s", func, pars, vile, type, name);
3371 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3373 aTHX_ packWARN(warn_type),
3374 "\t(Are you trying to call %s%s on dirhandle %s?)\n",
3379 Perl_warner(aTHX_ packWARN(warn_type),
3380 "%s%s on %s %s", func, pars, vile, type);
3381 if (gv && io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3383 aTHX_ packWARN(warn_type),
3384 "\t(Are you trying to call %s%s on dirhandle?)\n",
3393 /* in ASCII order, not that it matters */
3394 static const char controllablechars[] = "?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_";
3397 Perl_ebcdic_control(pTHX_ int ch)
3405 if ((ctlp = strchr(controllablechars, ch)) == 0) {
3406 Perl_die(aTHX_ "unrecognised control character '%c'\n", ch);
3409 if (ctlp == controllablechars)
3410 return('\177'); /* DEL */
3412 return((unsigned char)(ctlp - controllablechars - 1));
3413 } else { /* Want uncontrol */
3414 if (ch == '\177' || ch == -1)
3416 else if (ch == '\157')
3418 else if (ch == '\174')
3420 else if (ch == '^') /* '\137' in 1047, '\260' in 819 */
3422 else if (ch == '\155')
3424 else if (0 < ch && ch < (sizeof(controllablechars) - 1))
3425 return(controllablechars[ch+1]);
3427 Perl_die(aTHX_ "invalid control request: '\\%03o'\n", ch & 0xFF);
3432 /* To workaround core dumps from the uninitialised tm_zone we get the
3433 * system to give us a reasonable struct to copy. This fix means that
3434 * strftime uses the tm_zone and tm_gmtoff values returned by
3435 * localtime(time()). That should give the desired result most of the
3436 * time. But probably not always!
3438 * This does not address tzname aspects of NETaa14816.
3443 # ifndef STRUCT_TM_HASZONE
3444 # define STRUCT_TM_HASZONE
3448 #ifdef STRUCT_TM_HASZONE /* Backward compat */
3449 # ifndef HAS_TM_TM_ZONE
3450 # define HAS_TM_TM_ZONE
3455 Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
3457 #ifdef HAS_TM_TM_ZONE
3459 const struct tm* my_tm;
3461 my_tm = localtime(&now);
3463 Copy(my_tm, ptm, 1, struct tm);
3465 PERL_UNUSED_ARG(ptm);
3470 * mini_mktime - normalise struct tm values without the localtime()
3471 * semantics (and overhead) of mktime().
3474 Perl_mini_mktime(pTHX_ struct tm *ptm)
3478 int month, mday, year, jday;
3479 int odd_cent, odd_year;
3481 #define DAYS_PER_YEAR 365
3482 #define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
3483 #define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
3484 #define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
3485 #define SECS_PER_HOUR (60*60)
3486 #define SECS_PER_DAY (24*SECS_PER_HOUR)
3487 /* parentheses deliberately absent on these two, otherwise they don't work */
3488 #define MONTH_TO_DAYS 153/5
3489 #define DAYS_TO_MONTH 5/153
3490 /* offset to bias by March (month 4) 1st between month/mday & year finding */
3491 #define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
3492 /* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
3493 #define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
3496 * Year/day algorithm notes:
3498 * With a suitable offset for numeric value of the month, one can find
3499 * an offset into the year by considering months to have 30.6 (153/5) days,
3500 * using integer arithmetic (i.e., with truncation). To avoid too much
3501 * messing about with leap days, we consider January and February to be
3502 * the 13th and 14th month of the previous year. After that transformation,
3503 * we need the month index we use to be high by 1 from 'normal human' usage,
3504 * so the month index values we use run from 4 through 15.
3506 * Given that, and the rules for the Gregorian calendar (leap years are those
3507 * divisible by 4 unless also divisible by 100, when they must be divisible
3508 * by 400 instead), we can simply calculate the number of days since some
3509 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
3510 * the days we derive from our month index, and adding in the day of the
3511 * month. The value used here is not adjusted for the actual origin which
3512 * it normally would use (1 January A.D. 1), since we're not exposing it.
3513 * We're only building the value so we can turn around and get the
3514 * normalised values for the year, month, day-of-month, and day-of-year.
3516 * For going backward, we need to bias the value we're using so that we find
3517 * the right year value. (Basically, we don't want the contribution of
3518 * March 1st to the number to apply while deriving the year). Having done
3519 * that, we 'count up' the contribution to the year number by accounting for
3520 * full quadracenturies (400-year periods) with their extra leap days, plus
3521 * the contribution from full centuries (to avoid counting in the lost leap
3522 * days), plus the contribution from full quad-years (to count in the normal
3523 * leap days), plus the leftover contribution from any non-leap years.
3524 * At this point, if we were working with an actual leap day, we'll have 0
3525 * days left over. This is also true for March 1st, however. So, we have
3526 * to special-case that result, and (earlier) keep track of the 'odd'
3527 * century and year contributions. If we got 4 extra centuries in a qcent,
3528 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
3529 * Otherwise, we add back in the earlier bias we removed (the 123 from
3530 * figuring in March 1st), find the month index (integer division by 30.6),
3531 * and the remainder is the day-of-month. We then have to convert back to
3532 * 'real' months (including fixing January and February from being 14/15 in
3533 * the previous year to being in the proper year). After that, to get
3534 * tm_yday, we work with the normalised year and get a new yearday value for
3535 * January 1st, which we subtract from the yearday value we had earlier,
3536 * representing the date we've re-built. This is done from January 1
3537 * because tm_yday is 0-origin.
3539 * Since POSIX time routines are only guaranteed to work for times since the
3540 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
3541 * applies Gregorian calendar rules even to dates before the 16th century
3542 * doesn't bother me. Besides, you'd need cultural context for a given
3543 * date to know whether it was Julian or Gregorian calendar, and that's
3544 * outside the scope for this routine. Since we convert back based on the
3545 * same rules we used to build the yearday, you'll only get strange results
3546 * for input which needed normalising, or for the 'odd' century years which
3547 * were leap years in the Julian calander but not in the Gregorian one.
3548 * I can live with that.
3550 * This algorithm also fails to handle years before A.D. 1 gracefully, but
3551 * that's still outside the scope for POSIX time manipulation, so I don't
3555 year = 1900 + ptm->tm_year;
3556 month = ptm->tm_mon;
3557 mday = ptm->tm_mday;
3558 /* allow given yday with no month & mday to dominate the result */
3559 if (ptm->tm_yday >= 0 && mday <= 0 && month <= 0) {
3562 jday = 1 + ptm->tm_yday;
3571 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
3572 yearday += month*MONTH_TO_DAYS + mday + jday;
3574 * Note that we don't know when leap-seconds were or will be,
3575 * so we have to trust the user if we get something which looks
3576 * like a sensible leap-second. Wild values for seconds will
3577 * be rationalised, however.
3579 if ((unsigned) ptm->tm_sec <= 60) {
3586 secs += 60 * ptm->tm_min;
3587 secs += SECS_PER_HOUR * ptm->tm_hour;
3589 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
3590 /* got negative remainder, but need positive time */
3591 /* back off an extra day to compensate */
3592 yearday += (secs/SECS_PER_DAY)-1;
3593 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
3596 yearday += (secs/SECS_PER_DAY);
3597 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
3600 else if (secs >= SECS_PER_DAY) {
3601 yearday += (secs/SECS_PER_DAY);
3602 secs %= SECS_PER_DAY;
3604 ptm->tm_hour = secs/SECS_PER_HOUR;
3605 secs %= SECS_PER_HOUR;
3606 ptm->tm_min = secs/60;
3608 ptm->tm_sec += secs;
3609 /* done with time of day effects */
3611 * The algorithm for yearday has (so far) left it high by 428.
3612 * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
3613 * bias it by 123 while trying to figure out what year it
3614 * really represents. Even with this tweak, the reverse
3615 * translation fails for years before A.D. 0001.
3616 * It would still fail for Feb 29, but we catch that one below.
3618 jday = yearday; /* save for later fixup vis-a-vis Jan 1 */
3619 yearday -= YEAR_ADJUST;
3620 year = (yearday / DAYS_PER_QCENT) * 400;
3621 yearday %= DAYS_PER_QCENT;
3622 odd_cent = yearday / DAYS_PER_CENT;
3623 year += odd_cent * 100;
3624 yearday %= DAYS_PER_CENT;
3625 year += (yearday / DAYS_PER_QYEAR) * 4;
3626 yearday %= DAYS_PER_QYEAR;
3627 odd_year = yearday / DAYS_PER_YEAR;
3629 yearday %= DAYS_PER_YEAR;
3630 if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
3635 yearday += YEAR_ADJUST; /* recover March 1st crock */
3636 month = yearday*DAYS_TO_MONTH;
3637 yearday -= month*MONTH_TO_DAYS;
3638 /* recover other leap-year adjustment */
3647 ptm->tm_year = year - 1900;
3649 ptm->tm_mday = yearday;
3650 ptm->tm_mon = month;
3654 ptm->tm_mon = month - 1;
3656 /* re-build yearday based on Jan 1 to get tm_yday */
3658 yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
3659 yearday += 14*MONTH_TO_DAYS + 1;
3660 ptm->tm_yday = jday - yearday;
3661 /* fix tm_wday if not overridden by caller */
3662 if ((unsigned)ptm->tm_wday > 6)
3663 ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
3667 Perl_my_strftime(pTHX_ const char *fmt, int sec, int min, int hour, int mday, int mon, int year, int wday, int yday, int isdst)
3675 init_tm(&mytm); /* XXX workaround - see init_tm() above */
3678 mytm.tm_hour = hour;
3679 mytm.tm_mday = mday;
3681 mytm.tm_year = year;
3682 mytm.tm_wday = wday;
3683 mytm.tm_yday = yday;
3684 mytm.tm_isdst = isdst;
3686 /* use libc to get the values for tm_gmtoff and tm_zone [perl #18238] */
3687 #if defined(HAS_MKTIME) && (defined(HAS_TM_TM_GMTOFF) || defined(HAS_TM_TM_ZONE))
3692 #ifdef HAS_TM_TM_GMTOFF
3693 mytm.tm_gmtoff = mytm2.tm_gmtoff;
3695 #ifdef HAS_TM_TM_ZONE
3696 mytm.tm_zone = mytm2.tm_zone;
3701 Newx(buf, buflen, char);
3702 len = strftime(buf, buflen, fmt, &mytm);
3704 ** The following is needed to handle to the situation where
3705 ** tmpbuf overflows. Basically we want to allocate a buffer
3706 ** and try repeatedly. The reason why it is so complicated
3707 ** is that getting a return value of 0 from strftime can indicate
3708 ** one of the following:
3709 ** 1. buffer overflowed,
3710 ** 2. illegal conversion specifier, or
3711 ** 3. the format string specifies nothing to be returned(not
3712 ** an error). This could be because format is an empty string
3713 ** or it specifies %p that yields an empty string in some locale.
3714 ** If there is a better way to make it portable, go ahead by
3717 if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
3720 /* Possibly buf overflowed - try again with a bigger buf */
3721 const int fmtlen = strlen(fmt);
3722 const int bufsize = fmtlen + buflen;
3724 Newx(buf, bufsize, char);
3726 buflen = strftime(buf, bufsize, fmt, &mytm);
3727 if (buflen > 0 && buflen < bufsize)
3729 /* heuristic to prevent out-of-memory errors */
3730 if (bufsize > 100*fmtlen) {
3735 Renew(buf, bufsize*2, char);
3740 Perl_croak(aTHX_ "panic: no strftime");
3746 #define SV_CWD_RETURN_UNDEF \
3747 sv_setsv(sv, &PL_sv_undef); \
3750 #define SV_CWD_ISDOT(dp) \
3751 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
3752 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
3755 =head1 Miscellaneous Functions
3757 =for apidoc getcwd_sv
3759 Fill the sv with current working directory
3764 /* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
3765 * rewritten again by dougm, optimized for use with xs TARG, and to prefer
3766 * getcwd(3) if available
3767 * Comments from the orignal:
3768 * This is a faster version of getcwd. It's also more dangerous
3769 * because you might chdir out of a directory that you can't chdir
3773 Perl_getcwd_sv(pTHX_ register SV *sv)
3777 #ifndef INCOMPLETE_TAINTS
3783 char buf[MAXPATHLEN];
3785 /* Some getcwd()s automatically allocate a buffer of the given
3786 * size from the heap if they are given a NULL buffer pointer.
3787 * The problem is that this behaviour is not portable. */
3788 if (getcwd(buf, sizeof(buf) - 1)) {
3793 sv_setsv(sv, &PL_sv_undef);
3801 int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
3805 SvUPGRADE(sv, SVt_PV);
3807 if (PerlLIO_lstat(".", &statbuf) < 0) {
3808 SV_CWD_RETURN_UNDEF;
3811 orig_cdev = statbuf.st_dev;
3812 orig_cino = statbuf.st_ino;
3821 if (PerlDir_chdir("..") < 0) {
3822 SV_CWD_RETURN_UNDEF;
3824 if (PerlLIO_stat(".", &statbuf) < 0) {
3825 SV_CWD_RETURN_UNDEF;
3828 cdev = statbuf.st_dev;
3829 cino = statbuf.st_ino;
3831 if (odev == cdev && oino == cino) {
3834 if (!(dir = PerlDir_open("."))) {
3835 SV_CWD_RETURN_UNDEF;
3838 while ((dp = PerlDir_read(dir)) != NULL) {
3840 const int namelen = dp->d_namlen;
3842 const int namelen = strlen(dp->d_name);
3845 if (SV_CWD_ISDOT(dp)) {
3849 if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
3850 SV_CWD_RETURN_UNDEF;
3853 tdev = statbuf.st_dev;
3854 tino = statbuf.st_ino;
3855 if (tino == oino && tdev == odev) {
3861 SV_CWD_RETURN_UNDEF;
3864 if (pathlen + namelen + 1 >= MAXPATHLEN) {
3865 SV_CWD_RETURN_UNDEF;
3868 SvGROW(sv, pathlen + namelen + 1);
3872 Move(SvPVX_const(sv), SvPVX(sv) + namelen + 1, pathlen, char);
3875 /* prepend current directory to the front */
3877 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
3878 pathlen += (namelen + 1);
3880 #ifdef VOID_CLOSEDIR
3883 if (PerlDir_close(dir) < 0) {
3884 SV_CWD_RETURN_UNDEF;
3890 SvCUR_set(sv, pathlen);
3894 if (PerlDir_chdir(SvPVX_const(sv)) < 0) {
3895 SV_CWD_RETURN_UNDEF;
3898 if (PerlLIO_stat(".", &statbuf) < 0) {
3899 SV_CWD_RETURN_UNDEF;
3902 cdev = statbuf.st_dev;
3903 cino = statbuf.st_ino;
3905 if (cdev != orig_cdev || cino != orig_cino) {
3906 Perl_croak(aTHX_ "Unstable directory path, "
3907 "current directory changed unexpectedly");
3919 =for apidoc scan_version
3921 Returns a pointer to the next character after the parsed
3922 version string, as well as upgrading the passed in SV to
3925 Function must be called with an already existing SV like
3928 s = scan_version(s,SV *sv, bool qv);
3930 Performs some preprocessing to the string to ensure that
3931 it has the correct characteristics of a version. Flags the
3932 object if it contains an underscore (which denotes this
3933 is a alpha version). The boolean qv denotes that the version
3934 should be interpreted as if it had multiple decimals, even if
3941 Perl_scan_version(pTHX_ const char *s, SV *rv, bool qv)
3949 AV * const av = newAV();
3950 SV * const hv = newSVrv(rv, "version"); /* create an SV and upgrade the RV */
3951 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
3953 #ifndef NODEFAULT_SHAREKEYS
3954 HvSHAREKEYS_on(hv); /* key-sharing on by default */
3957 while (isSPACE(*s)) /* leading whitespace is OK */
3961 s++; /* get past 'v' */
3962 qv = 1; /* force quoted version processing */
3965 start = last = pos = s;
3967 /* pre-scan the input string to check for decimals/underbars */
3968 while ( *pos == '.' || *pos == '_' || isDIGIT(*pos) )
3973 Perl_croak(aTHX_ "Invalid version format (underscores before decimal)");
3977 else if ( *pos == '_' )
3980 Perl_croak(aTHX_ "Invalid version format (multiple underscores)");
3982 width = pos - last - 1; /* natural width of sub-version */
3987 if ( saw_period > 1 )
3988 qv = 1; /* force quoted version processing */
3993 hv_store((HV *)hv, "qv", 2, newSViv(qv), 0);
3995 hv_store((HV *)hv, "alpha", 5, newSViv(alpha), 0);
3996 if ( !qv && width < 3 )
3997 hv_store((HV *)hv, "width", 5, newSViv(width), 0);
3999 while (isDIGIT(*pos))
4001 if (!isALPHA(*pos)) {
4007 /* this is atoi() that delimits on underscores */
4008 const char *end = pos;
4012 /* the following if() will only be true after the decimal
4013 * point of a version originally created with a bare
4014 * floating point number, i.e. not quoted in any way
4016 if ( !qv && s > start && saw_period == 1 ) {
4020 rev += (*s - '0') * mult;
4022 if ( PERL_ABS(orev) > PERL_ABS(rev) )
4023 Perl_croak(aTHX_ "Integer overflow in version");
4030 while (--end >= s) {
4032 rev += (*end - '0') * mult;
4034 if ( PERL_ABS(orev) > PERL_ABS(rev) )
4035 Perl_croak(aTHX_ "Integer overflow in version");
4040 /* Append revision */
4041 av_push(av, newSViv(rev));
4042 if ( *pos == '.' && isDIGIT(pos[1]) )
4044 else if ( *pos == '_' && isDIGIT(pos[1]) )
4046 else if ( isDIGIT(*pos) )
4053 while ( isDIGIT(*pos) )
4058 while ( ( isDIGIT(*pos) || *pos == '_' ) && digits < 3 ) {
4066 if ( qv ) { /* quoted versions always get at least three terms*/
4067 I32 len = av_len(av);
4068 /* This for loop appears to trigger a compiler bug on OS X, as it
4069 loops infinitely. Yes, len is negative. No, it makes no sense.
4070 Compiler in question is:
4071 gcc version 3.3 20030304 (Apple Computer, Inc. build 1640)
4072 for ( len = 2 - len; len > 0; len-- )
4073 av_push((AV *)sv, newSViv(0));
4077 av_push(av, newSViv(0));
4080 if ( av_len(av) == -1 ) /* oops, someone forgot to pass a value */
4081 av_push(av, newSViv(0));
4083 /* And finally, store the AV in the hash */
4084 hv_store((HV *)hv, "version", 7, newRV_noinc((SV *)av), 0);
4089 =for apidoc new_version
4091 Returns a new version object based on the passed in SV:
4093 SV *sv = new_version(SV *ver);
4095 Does not alter the passed in ver SV. See "upg_version" if you
4096 want to upgrade the SV.
4102 Perl_new_version(pTHX_ SV *ver)
4104 SV * const rv = newSV(0);
4105 if ( sv_derived_from(ver,"version") ) /* can just copy directly */
4108 AV * const av = newAV();
4110 /* This will get reblessed later if a derived class*/
4111 SV * const hv = newSVrv(rv, "version");
4112 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
4113 #ifndef NODEFAULT_SHAREKEYS
4114 HvSHAREKEYS_on(hv); /* key-sharing on by default */
4120 /* Begin copying all of the elements */
4121 if ( hv_exists((HV *)ver, "qv", 2) )
4122 hv_store((HV *)hv, "qv", 2, &PL_sv_yes, 0);
4124 if ( hv_exists((HV *)ver, "alpha", 5) )
4125 hv_store((HV *)hv, "alpha", 5, &PL_sv_yes, 0);
4127 if ( hv_exists((HV*)ver, "width", 5 ) )
4129 const I32 width = SvIV(*hv_fetch((HV*)ver, "width", 5, FALSE));
4130 hv_store((HV *)hv, "width", 5, newSViv(width), 0);
4133 sav = (AV *)SvRV(*hv_fetch((HV*)ver, "version", 7, FALSE));
4134 /* This will get reblessed later if a derived class*/
4135 for ( key = 0; key <= av_len(sav); key++ )
4137 const I32 rev = SvIV(*av_fetch(sav, key, FALSE));
4138 av_push(av, newSViv(rev));
4141 hv_store((HV *)hv, "version", 7, newRV_noinc((SV *)av), 0);
4145 if ( SvVOK(ver) ) { /* already a v-string */
4146 const MAGIC* const mg = mg_find(ver,PERL_MAGIC_vstring);
4147 const STRLEN len = mg->mg_len;
4148 char * const version = savepvn( (const char*)mg->mg_ptr, len);
4149 sv_setpvn(rv,version,len);
4154 sv_setsv(rv,ver); /* make a duplicate */
4163 =for apidoc upg_version
4165 In-place upgrade of the supplied SV to a version object.
4167 SV *sv = upg_version(SV *sv);
4169 Returns a pointer to the upgraded SV.
4175 Perl_upg_version(pTHX_ SV *ver)
4180 if ( SvNOK(ver) ) /* may get too much accuracy */
4183 const STRLEN len = my_sprintf(tbuf,"%.9"NVgf, SvNVX(ver));
4184 version = savepvn(tbuf, len);
4187 else if ( SvVOK(ver) ) { /* already a v-string */
4188 const MAGIC* const mg = mg_find(ver,PERL_MAGIC_vstring);
4189 version = savepvn( (const char*)mg->mg_ptr,mg->mg_len );
4193 else /* must be a string or something like a string */
4195 version = savepv(SvPV_nolen(ver));
4197 (void)scan_version(version, ver, qv);
4205 Validates that the SV contains a valid version object.
4207 bool vverify(SV *vobj);
4209 Note that it only confirms the bare minimum structure (so as not to get
4210 confused by derived classes which may contain additional hash entries):
4214 =item * The SV contains a [reference to a] hash
4216 =item * The hash contains a "version" key
4218 =item * The "version" key has [a reference to] an AV as its value
4226 Perl_vverify(pTHX_ SV *vs)
4232 /* see if the appropriate elements exist */
4233 if ( SvTYPE(vs) == SVt_PVHV
4234 && hv_exists((HV*)vs, "version", 7)
4235 && (sv = SvRV(*hv_fetch((HV*)vs, "version", 7, FALSE)))
4236 && SvTYPE(sv) == SVt_PVAV )
4245 Accepts a version object and returns the normalized floating
4246 point representation. Call like:
4250 NOTE: you can pass either the object directly or the SV
4251 contained within the RV.
4257 Perl_vnumify(pTHX_ SV *vs)
4262 SV * const sv = newSV(0);
4268 Perl_croak(aTHX_ "Invalid version object");
4270 /* see if various flags exist */
4271 if ( hv_exists((HV*)vs, "alpha", 5 ) )
4273 if ( hv_exists((HV*)vs, "width", 5 ) )
4274 width = SvIV(*hv_fetch((HV*)vs, "width", 5, FALSE));
4279 /* attempt to retrieve the version array */
4280 if ( !(av = (AV *)SvRV(*hv_fetch((HV*)vs, "version", 7, FALSE)) ) ) {
4281 sv_catpvn(sv,"0",1);
4288 sv_catpvn(sv,"0",1);
4292 digit = SvIV(*av_fetch(av, 0, 0));
4293 Perl_sv_setpvf(aTHX_ sv, "%d.", (int)PERL_ABS(digit));
4294 for ( i = 1 ; i < len ; i++ )
4296 digit = SvIV(*av_fetch(av, i, 0));
4298 const int denom = (width == 2 ? 10 : 100);
4299 const div_t term = div((int)PERL_ABS(digit),denom);
4300 Perl_sv_catpvf(aTHX_ sv, "%0*d_%d", width, term.quot, term.rem);
4303 Perl_sv_catpvf(aTHX_ sv, "%0*d", width, (int)digit);
4309 digit = SvIV(*av_fetch(av, len, 0));
4310 if ( alpha && width == 3 ) /* alpha version */
4311 sv_catpvn(sv,"_",1);
4312 Perl_sv_catpvf(aTHX_ sv, "%0*d", width, (int)digit);
4316 sv_catpvn(sv,"000",3);
4324 Accepts a version object and returns the normalized string
4325 representation. Call like:
4329 NOTE: you can pass either the object directly or the SV
4330 contained within the RV.
4336 Perl_vnormal(pTHX_ SV *vs)
4340 SV * const sv = newSV(0);
4346 Perl_croak(aTHX_ "Invalid version object");
4348 if ( hv_exists((HV*)vs, "alpha", 5 ) )
4350 av = (AV *)SvRV(*hv_fetch((HV*)vs, "version", 7, FALSE));
4358 digit = SvIV(*av_fetch(av, 0, 0));
4359 Perl_sv_setpvf(aTHX_ sv, "v%"IVdf, (IV)digit);
4360 for ( i = 1 ; i < len ; i++ ) {
4361 digit = SvIV(*av_fetch(av, i, 0));
4362 Perl_sv_catpvf(aTHX_ sv, ".%"IVdf, (IV)digit);
4367 /* handle last digit specially */
4368 digit = SvIV(*av_fetch(av, len, 0));
4370 Perl_sv_catpvf(aTHX_ sv, "_%"IVdf, (IV)digit);
4372 Perl_sv_catpvf(aTHX_ sv, ".%"IVdf, (IV)digit);
4375 if ( len <= 2 ) { /* short version, must be at least three */
4376 for ( len = 2 - len; len != 0; len-- )
4377 sv_catpvn(sv,".0",2);
4383 =for apidoc vstringify
4385 In order to maintain maximum compatibility with earlier versions
4386 of Perl, this function will return either the floating point
4387 notation or the multiple dotted notation, depending on whether
4388 the original version contained 1 or more dots, respectively
4394 Perl_vstringify(pTHX_ SV *vs)
4400 Perl_croak(aTHX_ "Invalid version object");
4402 if ( hv_exists((HV *)vs, "qv", 2) )
4411 Version object aware cmp. Both operands must already have been
4412 converted into version objects.
4418 Perl_vcmp(pTHX_ SV *lhv, SV *rhv)
4421 bool lalpha = FALSE;
4422 bool ralpha = FALSE;
4431 if ( !vverify(lhv) )
4432 Perl_croak(aTHX_ "Invalid version object");
4434 if ( !vverify(rhv) )
4435 Perl_croak(aTHX_ "Invalid version object");
4437 /* get the left hand term */
4438 lav = (AV *)SvRV(*hv_fetch((HV*)lhv, "version", 7, FALSE));
4439 if ( hv_exists((HV*)lhv, "alpha", 5 ) )
4442 /* and the right hand term */
4443 rav = (AV *)SvRV(*hv_fetch((HV*)rhv, "version", 7, FALSE));
4444 if ( hv_exists((HV*)rhv, "alpha", 5 ) )
4452 while ( i <= m && retval == 0 )
4454 left = SvIV(*av_fetch(lav,i,0));
4455 right = SvIV(*av_fetch(rav,i,0));
4463 /* tiebreaker for alpha with identical terms */
4464 if ( retval == 0 && l == r && left == right && ( lalpha || ralpha ) )
4466 if ( lalpha && !ralpha )
4470 else if ( ralpha && !lalpha)
4476 if ( l != r && retval == 0 ) /* possible match except for trailing 0's */
4480 while ( i <= r && retval == 0 )
4482 if ( SvIV(*av_fetch(rav,i,0)) != 0 )
4483 retval = -1; /* not a match after all */
4489 while ( i <= l && retval == 0 )
4491 if ( SvIV(*av_fetch(lav,i,0)) != 0 )
4492 retval = +1; /* not a match after all */
4500 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET) && defined(SOCK_DGRAM) && defined(HAS_SELECT)
4501 # define EMULATE_SOCKETPAIR_UDP
4504 #ifdef EMULATE_SOCKETPAIR_UDP
4506 S_socketpair_udp (int fd[2]) {
4508 /* Fake a datagram socketpair using UDP to localhost. */
4509 int sockets[2] = {-1, -1};
4510 struct sockaddr_in addresses[2];
4512 Sock_size_t size = sizeof(struct sockaddr_in);
4513 unsigned short port;
4516 memset(&addresses, 0, sizeof(addresses));
4519 sockets[i] = PerlSock_socket(AF_INET, SOCK_DGRAM, PF_INET);
4520 if (sockets[i] == -1)
4521 goto tidy_up_and_fail;
4523 addresses[i].sin_family = AF_INET;
4524 addresses[i].sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4525 addresses[i].sin_port = 0; /* kernel choses port. */
4526 if (PerlSock_bind(sockets[i], (struct sockaddr *) &addresses[i],
4527 sizeof(struct sockaddr_in)) == -1)
4528 goto tidy_up_and_fail;
4531 /* Now have 2 UDP sockets. Find out which port each is connected to, and
4532 for each connect the other socket to it. */
4535 if (PerlSock_getsockname(sockets[i], (struct sockaddr *) &addresses[i],
4537 goto tidy_up_and_fail;
4538 if (size != sizeof(struct sockaddr_in))
4539 goto abort_tidy_up_and_fail;
4540 /* !1 is 0, !0 is 1 */
4541 if (PerlSock_connect(sockets[!i], (struct sockaddr *) &addresses[i],
4542 sizeof(struct sockaddr_in)) == -1)
4543 goto tidy_up_and_fail;
4546 /* Now we have 2 sockets connected to each other. I don't trust some other
4547 process not to have already sent a packet to us (by random) so send
4548 a packet from each to the other. */
4551 /* I'm going to send my own port number. As a short.
4552 (Who knows if someone somewhere has sin_port as a bitfield and needs
4553 this routine. (I'm assuming crays have socketpair)) */
4554 port = addresses[i].sin_port;
4555 got = PerlLIO_write(sockets[i], &port, sizeof(port));
4556 if (got != sizeof(port)) {
4558 goto tidy_up_and_fail;
4559 goto abort_tidy_up_and_fail;
4563 /* Packets sent. I don't trust them to have arrived though.
4564 (As I understand it Solaris TCP stack is multithreaded. Non-blocking
4565 connect to localhost will use a second kernel thread. In 2.6 the
4566 first thread running the connect() returns before the second completes,
4567 so EINPROGRESS> In 2.7 the improved stack is faster and connect()
4568 returns 0. Poor programs have tripped up. One poor program's authors'
4569 had a 50-1 reverse stock split. Not sure how connected these were.)
4570 So I don't trust someone not to have an unpredictable UDP stack.
4574 struct timeval waitfor = {0, 100000}; /* You have 0.1 seconds */
4575 int max = sockets[1] > sockets[0] ? sockets[1] : sockets[0];
4579 FD_SET(sockets[0], &rset);
4580 FD_SET(sockets[1], &rset);
4582 got = PerlSock_select(max + 1, &rset, NULL, NULL, &waitfor);
4583 if (got != 2 || !FD_ISSET(sockets[0], &rset)
4584 || !FD_ISSET(sockets[1], &rset)) {
4585 /* I hope this is portable and appropriate. */
4587 goto tidy_up_and_fail;
4588 goto abort_tidy_up_and_fail;
4592 /* And the paranoia department even now doesn't trust it to have arrive
4593 (hence MSG_DONTWAIT). Or that what arrives was sent by us. */
4595 struct sockaddr_in readfrom;
4596 unsigned short buffer[2];
4601 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4602 sizeof(buffer), MSG_DONTWAIT,
4603 (struct sockaddr *) &readfrom, &size);
4605 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4607 (struct sockaddr *) &readfrom, &size);
4611 goto tidy_up_and_fail;
4612 if (got != sizeof(port)
4613 || size != sizeof(struct sockaddr_in)
4614 /* Check other socket sent us its port. */
4615 || buffer[0] != (unsigned short) addresses[!i].sin_port
4616 /* Check kernel says we got the datagram from that socket */
4617 || readfrom.sin_family != addresses[!i].sin_family
4618 || readfrom.sin_addr.s_addr != addresses[!i].sin_addr.s_addr
4619 || readfrom.sin_port != addresses[!i].sin_port)
4620 goto abort_tidy_up_and_fail;
4623 /* My caller (my_socketpair) has validated that this is non-NULL */
4626 /* I hereby declare this connection open. May God bless all who cross
4630 abort_tidy_up_and_fail:
4631 errno = ECONNABORTED;
4634 const int save_errno = errno;
4635 if (sockets[0] != -1)
4636 PerlLIO_close(sockets[0]);
4637 if (sockets[1] != -1)
4638 PerlLIO_close(sockets[1]);
4643 #endif /* EMULATE_SOCKETPAIR_UDP */
4645 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET)
4647 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4648 /* Stevens says that family must be AF_LOCAL, protocol 0.
4649 I'm going to enforce that, then ignore it, and use TCP (or UDP). */
4654 struct sockaddr_in listen_addr;
4655 struct sockaddr_in connect_addr;
4660 || family != AF_UNIX
4663 errno = EAFNOSUPPORT;
4671 #ifdef EMULATE_SOCKETPAIR_UDP
4672 if (type == SOCK_DGRAM)
4673 return S_socketpair_udp(fd);
4676 listener = PerlSock_socket(AF_INET, type, 0);
4679 memset(&listen_addr, 0, sizeof(listen_addr));
4680 listen_addr.sin_family = AF_INET;
4681 listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4682 listen_addr.sin_port = 0; /* kernel choses port. */
4683 if (PerlSock_bind(listener, (struct sockaddr *) &listen_addr,
4684 sizeof(listen_addr)) == -1)
4685 goto tidy_up_and_fail;
4686 if (PerlSock_listen(listener, 1) == -1)
4687 goto tidy_up_and_fail;
4689 connector = PerlSock_socket(AF_INET, type, 0);
4690 if (connector == -1)
4691 goto tidy_up_and_fail;
4692 /* We want to find out the port number to connect to. */
4693 size = sizeof(connect_addr);
4694 if (PerlSock_getsockname(listener, (struct sockaddr *) &connect_addr,
4696 goto tidy_up_and_fail;
4697 if (size != sizeof(connect_addr))
4698 goto abort_tidy_up_and_fail;
4699 if (PerlSock_connect(connector, (struct sockaddr *) &connect_addr,
4700 sizeof(connect_addr)) == -1)
4701 goto tidy_up_and_fail;
4703 size = sizeof(listen_addr);
4704 acceptor = PerlSock_accept(listener, (struct sockaddr *) &listen_addr,
4707 goto tidy_up_and_fail;
4708 if (size != sizeof(listen_addr))
4709 goto abort_tidy_up_and_fail;
4710 PerlLIO_close(listener);
4711 /* Now check we are talking to ourself by matching port and host on the
4713 if (PerlSock_getsockname(connector, (struct sockaddr *) &connect_addr,
4715 goto tidy_up_and_fail;
4716 if (size != sizeof(connect_addr)
4717 || listen_addr.sin_family != connect_addr.sin_family
4718 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
4719 || listen_addr.sin_port != connect_addr.sin_port) {
4720 goto abort_tidy_up_and_fail;
4726 abort_tidy_up_and_fail:
4728 errno = ECONNABORTED; /* This would be the standard thing to do. */
4730 # ifdef ECONNREFUSED
4731 errno = ECONNREFUSED; /* E.g. Symbian does not have ECONNABORTED. */
4733 errno = ETIMEDOUT; /* Desperation time. */
4738 const int save_errno = errno;
4740 PerlLIO_close(listener);
4741 if (connector != -1)
4742 PerlLIO_close(connector);
4744 PerlLIO_close(acceptor);
4750 /* In any case have a stub so that there's code corresponding
4751 * to the my_socketpair in global.sym. */
4753 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4754 #ifdef HAS_SOCKETPAIR
4755 return socketpair(family, type, protocol, fd);
4764 =for apidoc sv_nosharing
4766 Dummy routine which "shares" an SV when there is no sharing module present.
4767 Or "locks" it. Or "unlocks" it. In other words, ignores its single SV argument.
4768 Exists to avoid test for a NULL function pointer and because it could
4769 potentially warn under some level of strict-ness.
4775 Perl_sv_nosharing(pTHX_ SV *sv)
4777 PERL_UNUSED_ARG(sv);
4781 Perl_parse_unicode_opts(pTHX_ const char **popt)
4783 const char *p = *popt;
4788 opt = (U32) atoi(p);
4789 while (isDIGIT(*p)) p++;
4790 if (*p && *p != '\n' && *p != '\r')
4791 Perl_croak(aTHX_ "Unknown Unicode option letter '%c'", *p);
4796 case PERL_UNICODE_STDIN:
4797 opt |= PERL_UNICODE_STDIN_FLAG; break;
4798 case PERL_UNICODE_STDOUT:
4799 opt |= PERL_UNICODE_STDOUT_FLAG; break;
4800 case PERL_UNICODE_STDERR:
4801 opt |= PERL_UNICODE_STDERR_FLAG; break;
4802 case PERL_UNICODE_STD:
4803 opt |= PERL_UNICODE_STD_FLAG; break;
4804 case PERL_UNICODE_IN:
4805 opt |= PERL_UNICODE_IN_FLAG; break;
4806 case PERL_UNICODE_OUT:
4807 opt |= PERL_UNICODE_OUT_FLAG; break;
4808 case PERL_UNICODE_INOUT:
4809 opt |= PERL_UNICODE_INOUT_FLAG; break;
4810 case PERL_UNICODE_LOCALE:
4811 opt |= PERL_UNICODE_LOCALE_FLAG; break;
4812 case PERL_UNICODE_ARGV:
4813 opt |= PERL_UNICODE_ARGV_FLAG; break;
4815 if (*p != '\n' && *p != '\r')
4817 "Unknown Unicode option letter '%c'", *p);
4823 opt = PERL_UNICODE_DEFAULT_FLAGS;
4825 if (opt & ~PERL_UNICODE_ALL_FLAGS)
4826 Perl_croak(aTHX_ "Unknown Unicode option value %"UVuf,
4827 (UV) (opt & ~PERL_UNICODE_ALL_FLAGS));
4838 * This is really just a quick hack which grabs various garbage
4839 * values. It really should be a real hash algorithm which
4840 * spreads the effect of every input bit onto every output bit,
4841 * if someone who knows about such things would bother to write it.
4842 * Might be a good idea to add that function to CORE as well.
4843 * No numbers below come from careful analysis or anything here,
4844 * except they are primes and SEED_C1 > 1E6 to get a full-width
4845 * value from (tv_sec * SEED_C1 + tv_usec). The multipliers should
4846 * probably be bigger too.
4849 # define SEED_C1 1000003
4850 #define SEED_C4 73819
4852 # define SEED_C1 25747
4853 #define SEED_C4 20639
4857 #define SEED_C5 26107
4859 #ifndef PERL_NO_DEV_RANDOM
4864 # include <starlet.h>
4865 /* when[] = (low 32 bits, high 32 bits) of time since epoch
4866 * in 100-ns units, typically incremented ever 10 ms. */
4867 unsigned int when[2];
4869 # ifdef HAS_GETTIMEOFDAY
4870 struct timeval when;
4876 /* This test is an escape hatch, this symbol isn't set by Configure. */
4877 #ifndef PERL_NO_DEV_RANDOM
4878 #ifndef PERL_RANDOM_DEVICE
4879 /* /dev/random isn't used by default because reads from it will block
4880 * if there isn't enough entropy available. You can compile with
4881 * PERL_RANDOM_DEVICE to it if you'd prefer Perl to block until there
4882 * is enough real entropy to fill the seed. */
4883 # define PERL_RANDOM_DEVICE "/dev/urandom"
4885 fd = PerlLIO_open(PERL_RANDOM_DEVICE, 0);
4887 if (PerlLIO_read(fd, (void*)&u, sizeof u) != sizeof u)
4896 _ckvmssts(sys$gettim(when));
4897 u = (U32)SEED_C1 * when[0] + (U32)SEED_C2 * when[1];
4899 # ifdef HAS_GETTIMEOFDAY
4900 PerlProc_gettimeofday(&when,NULL);
4901 u = (U32)SEED_C1 * when.tv_sec + (U32)SEED_C2 * when.tv_usec;
4904 u = (U32)SEED_C1 * when;
4907 u += SEED_C3 * (U32)PerlProc_getpid();
4908 u += SEED_C4 * (U32)PTR2UV(PL_stack_sp);
4909 #ifndef PLAN9 /* XXX Plan9 assembler chokes on this; fix needed */
4910 u += SEED_C5 * (U32)PTR2UV(&when);
4916 Perl_get_hash_seed(pTHX)
4918 const char *s = PerlEnv_getenv("PERL_HASH_SEED");
4922 while (isSPACE(*s)) s++;
4923 if (s && isDIGIT(*s))
4924 myseed = (UV)Atoul(s);
4926 #ifdef USE_HASH_SEED_EXPLICIT
4930 /* Compute a random seed */
4931 (void)seedDrand01((Rand_seed_t)seed());
4932 myseed = (UV)(Drand01() * (NV)UV_MAX);
4933 #if RANDBITS < (UVSIZE * 8)
4934 /* Since there are not enough randbits to to reach all
4935 * the bits of a UV, the low bits might need extra
4936 * help. Sum in another random number that will
4937 * fill in the low bits. */
4939 (UV)(Drand01() * (NV)((1 << ((UVSIZE * 8 - RANDBITS))) - 1));
4940 #endif /* RANDBITS < (UVSIZE * 8) */
4941 if (myseed == 0) { /* Superparanoia. */
4942 myseed = (UV)(Drand01() * (NV)UV_MAX); /* One more chance. */
4944 Perl_croak(aTHX_ "Your random numbers are not that random");
4947 PL_rehash_seed_set = TRUE;
4954 Perl_stashpv_hvname_match(pTHX_ const COP *c, const HV *hv)
4956 const char * const stashpv = CopSTASHPV(c);
4957 const char * const name = HvNAME_get(hv);
4959 if (stashpv == name)
4961 if (stashpv && name)
4962 if (strEQ(stashpv, name))
4969 #ifdef PERL_GLOBAL_STRUCT
4972 Perl_init_global_struct(pTHX)
4974 struct perl_vars *plvarsp = NULL;
4975 #ifdef PERL_GLOBAL_STRUCT
4976 # define PERL_GLOBAL_STRUCT_INIT
4977 # include "opcode.h" /* the ppaddr and check */
4978 const IV nppaddr = sizeof(Gppaddr)/sizeof(Perl_ppaddr_t);
4979 const IV ncheck = sizeof(Gcheck) /sizeof(Perl_check_t);
4980 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
4981 /* PerlMem_malloc() because can't use even safesysmalloc() this early. */
4982 plvarsp = (struct perl_vars*)PerlMem_malloc(sizeof(struct perl_vars));
4986 plvarsp = PL_VarsPtr;
4987 # endif /* PERL_GLOBAL_STRUCT_PRIVATE */
4993 # define PERLVAR(var,type) /**/
4994 # define PERLVARA(var,n,type) /**/
4995 # define PERLVARI(var,type,init) plvarsp->var = init;
4996 # define PERLVARIC(var,type,init) plvarsp->var = init;
4997 # define PERLVARISC(var,init) Copy(init, plvarsp->var, sizeof(init), char);
4998 # include "perlvars.h"
5004 # ifdef PERL_GLOBAL_STRUCT
5005 plvarsp->Gppaddr = PerlMem_malloc(nppaddr * sizeof(Perl_ppaddr_t));
5006 if (!plvarsp->Gppaddr)
5008 plvarsp->Gcheck = PerlMem_malloc(ncheck * sizeof(Perl_check_t));
5009 if (!plvarsp->Gcheck)
5011 Copy(Gppaddr, plvarsp->Gppaddr, nppaddr, Perl_ppaddr_t);
5012 Copy(Gcheck, plvarsp->Gcheck, ncheck, Perl_check_t);
5014 # ifdef PERL_SET_VARS
5015 PERL_SET_VARS(plvarsp);
5017 # undef PERL_GLOBAL_STRUCT_INIT
5022 #endif /* PERL_GLOBAL_STRUCT */
5024 #ifdef PERL_GLOBAL_STRUCT
5027 Perl_free_global_struct(pTHX_ struct perl_vars *plvarsp)
5029 #ifdef PERL_GLOBAL_STRUCT
5030 # ifdef PERL_UNSET_VARS
5031 PERL_UNSET_VARS(plvarsp);
5033 free(plvarsp->Gppaddr);
5034 free(plvarsp->Gcheck);
5035 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
5041 #endif /* PERL_GLOBAL_STRUCT */
5045 #define PERL_MEM_LOG_SPRINTF_BUF_SIZE 128
5048 Perl_mem_log_alloc(const UV n, const UV typesize, const char *typename, Malloc_t newalloc, const char *filename, const int linenumber, const char *funcname)
5050 #ifdef PERL_MEM_LOG_STDERR
5051 /* We can't use PerlIO for obvious reasons. */
5052 char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
5053 const STRLEN len = my_sprintf(buf,
5054 "alloc: %s:%d:%s: %"IVdf" %"UVuf
5055 " %s = %"IVdf": %"UVxf"\n",
5056 filename, linenumber, funcname, n, typesize,
5057 typename, n * typesize, PTR2UV(newalloc));
5058 PerlLIO_write(2, buf, len);
5064 Perl_mem_log_realloc(const UV n, const UV typesize, const char *typename, Malloc_t oldalloc, Malloc_t newalloc, const char *filename, const int linenumber, const char *funcname)
5066 #ifdef PERL_MEM_LOG_STDERR
5067 /* We can't use PerlIO for obvious reasons. */
5068 char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
5069 const STRLEN len = my_sprintf(buf, "realloc: %s:%d:%s: %"IVdf" %"UVuf
5070 " %s = %"IVdf": %"UVxf" -> %"UVxf"\n",
5071 filename, linenumber, funcname, n, typesize,
5072 typename, n * typesize, PTR2UV(oldalloc),
5074 PerlLIO_write(2, buf, len);
5080 Perl_mem_log_free(Malloc_t oldalloc, const char *filename, const int linenumber, const char *funcname)
5082 #ifdef PERL_MEM_LOG_STDERR
5083 /* We can't use PerlIO for obvious reasons. */
5084 char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
5085 const STRLEN len = my_sprintf(buf, "free: %s:%d:%s: %"UVxf"\n",
5086 filename, linenumber, funcname,
5088 PerlLIO_write(2, buf, len);
5093 #endif /* PERL_MEM_LOG */
5096 =for apidoc my_sprintf
5098 The C library C<sprintf>, wrapped if necessary, to ensure that it will return
5099 the length of the string written to the buffer. Only rare pre-ANSI systems
5100 need the wrapper function - usually this is a direct call to C<sprintf>.
5104 #ifndef SPRINTF_RETURNS_STRLEN
5106 Perl_my_sprintf(char *buffer, const char* pat, ...)
5109 va_start(args, pat);
5110 vsprintf(buffer, pat, args);
5112 return strlen(buffer);
5117 Perl_my_clearenv(pTHX)
5120 #if ! defined(PERL_MICRO)
5121 # if defined(PERL_IMPLICIT_SYS) || defined(WIN32)
5123 # else /* ! (PERL_IMPLICIT_SYS || WIN32) */
5124 # if defined(USE_ENVIRON_ARRAY)
5125 # if defined(USE_ITHREADS)
5126 /* only the parent thread can clobber the process environment */
5127 if (PL_curinterp == aTHX)
5128 # endif /* USE_ITHREADS */
5130 # if ! defined(PERL_USE_SAFE_PUTENV)
5131 if ( !PL_use_safe_putenv) {
5133 if (environ == PL_origenviron)
5134 environ = (char**)safesysmalloc(sizeof(char*));
5136 for (i = 0; environ[i]; i++)
5137 (void)safesysfree(environ[i]);
5140 # else /* PERL_USE_SAFE_PUTENV */
5141 # if defined(HAS_CLEARENV)
5143 # elif defined(HAS_UNSETENV)
5144 int bsiz = 80; /* Most envvar names will be shorter than this. */
5145 char *buf = (char*)safesysmalloc(bsiz * sizeof(char));
5146 while (*environ != NULL) {
5147 char *e = strchr(*environ, '=');
5148 int l = e ? e - *environ : strlen(*environ);
5150 (void)safesysfree(buf);
5152 buf = (char*)safesysmalloc(bsiz * sizeof(char));
5154 strncpy(buf, *environ, l);
5156 (void)unsetenv(buf);
5158 (void)safesysfree(buf);
5159 # else /* ! HAS_CLEARENV && ! HAS_UNSETENV */
5160 /* Just null environ and accept the leakage. */
5162 # endif /* HAS_CLEARENV || HAS_UNSETENV */
5163 # endif /* ! PERL_USE_SAFE_PUTENV */
5165 # endif /* USE_ENVIRON_ARRAY */
5166 # endif /* PERL_IMPLICIT_SYS || WIN32 */
5167 #endif /* PERL_MICRO */
5172 * c-indentation-style: bsd
5174 * indent-tabs-mode: t
5177 * ex: set ts=8 sts=4 sw=4 noet: