3 * Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999,
4 * 2000, 2001, 2002, 2003, 2004, 2005, 2006, 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.
64 /* Can't use PerlIO to write as it allocates memory */
65 PerlLIO_write(PerlIO_fileno(Perl_error_log),
66 PL_no_mem, strlen(PL_no_mem));
68 NORETURN_FUNCTION_END;
71 /* paranoid version of system's malloc() */
74 Perl_safesysmalloc(MEM_SIZE size)
80 PerlIO_printf(Perl_error_log,
81 "Allocation too large: %lx\n", size) FLUSH;
84 #endif /* HAS_64K_LIMIT */
85 #ifdef PERL_TRACK_MEMPOOL
90 Perl_croak_nocontext("panic: malloc");
92 ptr = (Malloc_t)PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
93 PERL_ALLOC_CHECK(ptr);
94 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) malloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
96 #ifdef PERL_TRACK_MEMPOOL
97 ((struct perl_memory_debug_header *)ptr)->interpreter = aTHX;
99 ((struct perl_memory_debug_header *)ptr)->size = size;
100 ((struct perl_memory_debug_header *)ptr)->in_use = PERL_POISON_INUSE;
102 ptr = (Malloc_t)((char*)ptr+sTHX);
109 return write_no_mem();
114 /* paranoid version of system's realloc() */
117 Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
121 #if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) && !defined(PERL_MICRO)
122 Malloc_t PerlMem_realloc();
123 #endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
127 PerlIO_printf(Perl_error_log,
128 "Reallocation too large: %lx\n", size) FLUSH;
131 #endif /* HAS_64K_LIMIT */
138 return safesysmalloc(size);
139 #ifdef PERL_TRACK_MEMPOOL
140 where = (Malloc_t)((char*)where-sTHX);
142 if (((struct perl_memory_debug_header *)where)->interpreter != aTHX) {
143 Perl_croak_nocontext("panic: realloc from wrong pool");
146 if (((struct perl_memory_debug_header *)where)->size > size) {
147 const MEM_SIZE freed_up =
148 ((struct perl_memory_debug_header *)where)->size - size;
149 char *start_of_freed = ((char *)where) + size;
150 Poison(start_of_freed, freed_up, char);
152 ((struct perl_memory_debug_header *)where)->size = size;
157 Perl_croak_nocontext("panic: realloc");
159 ptr = (Malloc_t)PerlMem_realloc(where,size);
160 PERL_ALLOC_CHECK(ptr);
162 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) rfree\n",PTR2UV(where),(long)PL_an++));
163 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) realloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
166 #ifdef PERL_TRACK_MEMPOOL
167 ptr = (Malloc_t)((char*)ptr+sTHX);
174 return write_no_mem();
179 /* safe version of system's free() */
182 Perl_safesysfree(Malloc_t where)
184 #if defined(PERL_IMPLICIT_SYS) || defined(PERL_TRACK_MEMPOOL)
189 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) free\n",PTR2UV(where),(long)PL_an++));
191 #ifdef PERL_TRACK_MEMPOOL
192 where = (Malloc_t)((char*)where-sTHX);
193 if (((struct perl_memory_debug_header *)where)->interpreter != aTHX) {
194 Perl_croak_nocontext("panic: free from wrong pool");
198 if (((struct perl_memory_debug_header *)where)->in_use
199 == PERL_POISON_FREE) {
200 Perl_croak_nocontext("panic: duplicate free");
202 if (((struct perl_memory_debug_header *)where)->in_use
203 != PERL_POISON_INUSE) {
204 Perl_croak_nocontext("panic: bad free ");
206 ((struct perl_memory_debug_header *)where)->in_use
209 Poison(where, ((struct perl_memory_debug_header *)where)->size, char);
216 /* safe version of system's calloc() */
219 Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
225 if (size * count > 0xffff) {
226 PerlIO_printf(Perl_error_log,
227 "Allocation too large: %lx\n", size * count) FLUSH;
230 #endif /* HAS_64K_LIMIT */
232 if ((long)size < 0 || (long)count < 0)
233 Perl_croak_nocontext("panic: calloc");
236 #ifdef PERL_TRACK_MEMPOOL
239 ptr = (Malloc_t)PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
240 PERL_ALLOC_CHECK(ptr);
241 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));
243 memset((void*)ptr, 0, size);
244 #ifdef PERL_TRACK_MEMPOOL
245 ((struct perl_memory_debug_header *)ptr)->interpreter = aTHX;
247 ((struct perl_memory_debug_header *)ptr)->size = size;
248 ((struct perl_memory_debug_header *)ptr)->in_use = PERL_POISON_INUSE;
250 ptr = (Malloc_t)((char*)ptr+sTHX);
256 return write_no_mem();
259 /* These must be defined when not using Perl's malloc for binary
264 Malloc_t Perl_malloc (MEM_SIZE nbytes)
267 return (Malloc_t)PerlMem_malloc(nbytes);
270 Malloc_t Perl_calloc (MEM_SIZE elements, MEM_SIZE size)
273 return (Malloc_t)PerlMem_calloc(elements, size);
276 Malloc_t Perl_realloc (Malloc_t where, MEM_SIZE nbytes)
279 return (Malloc_t)PerlMem_realloc(where, nbytes);
282 Free_t Perl_mfree (Malloc_t where)
290 /* copy a string up to some (non-backslashed) delimiter, if any */
293 Perl_delimcpy(pTHX_ register char *to, register const char *toend, register const char *from, register const char *fromend, register int delim, I32 *retlen)
296 for (tolen = 0; from < fromend; from++, tolen++) {
298 if (from[1] == delim)
307 else if (*from == delim)
318 /* return ptr to little string in big string, NULL if not found */
319 /* This routine was donated by Corey Satten. */
322 Perl_instr(pTHX_ register const char *big, register const char *little)
332 register const char *s, *x;
335 for (x=big,s=little; *s; /**/ ) {
346 return (char*)(big-1);
351 /* same as instr but allow embedded nulls */
354 Perl_ninstr(pTHX_ const char *big, const char *bigend, const char *little, const char *lend)
359 char first = *little++;
361 bigend -= lend - little;
363 while (big <= bigend) {
366 for (x=big,s=little; s < lend; x++,s++) {
370 return (char*)(big-1);
376 /* reverse of the above--find last substring */
379 Perl_rninstr(pTHX_ register const char *big, const char *bigend, const char *little, const char *lend)
381 register const char *bigbeg;
382 register const I32 first = *little;
383 register const char * const littleend = lend;
385 if (little >= littleend)
386 return (char*)bigend;
388 big = bigend - (littleend - little++);
389 while (big >= bigbeg) {
390 register const char *s, *x;
393 for (x=big+2,s=little; s < littleend; /**/ ) {
402 return (char*)(big+1);
407 #define FBM_TABLE_OFFSET 2 /* Number of bytes between EOS and table*/
409 /* As a space optimization, we do not compile tables for strings of length
410 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
411 special-cased in fbm_instr().
413 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
416 =head1 Miscellaneous Functions
418 =for apidoc fbm_compile
420 Analyses the string in order to make fast searches on it using fbm_instr()
421 -- the Boyer-Moore algorithm.
427 Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
430 register const U8 *s;
436 if (flags & FBMcf_TAIL) {
437 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL;
438 sv_catpvs(sv, "\n"); /* Taken into account in fbm_instr() */
439 if (mg && mg->mg_len >= 0)
442 s = (U8*)SvPV_force_mutable(sv, len);
443 SvUPGRADE(sv, SVt_PVBM);
444 if (len == 0) /* TAIL might be on a zero-length string. */
447 const unsigned char *sb;
448 const U8 mlen = (len>255) ? 255 : (U8)len;
451 Sv_Grow(sv, len + 256 + FBM_TABLE_OFFSET);
452 table = (unsigned char*)(SvPVX_mutable(sv) + len + FBM_TABLE_OFFSET);
453 s = table - 1 - FBM_TABLE_OFFSET; /* last char */
454 memset((void*)table, mlen, 256);
455 table[-1] = (U8)flags;
457 sb = s - mlen + 1; /* first char (maybe) */
459 if (table[*s] == mlen)
464 sv_magic(sv, NULL, PERL_MAGIC_bm, NULL, 0); /* deep magic */
467 s = (const unsigned char*)(SvPVX_const(sv)); /* deeper magic */
468 for (i = 0; i < len; i++) {
469 if (PL_freq[s[i]] < frequency) {
471 frequency = PL_freq[s[i]];
474 BmRARE(sv) = s[rarest];
475 BmPREVIOUS(sv) = (U16)rarest;
476 BmUSEFUL(sv) = 100; /* Initial value */
477 if (flags & FBMcf_TAIL)
479 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %d\n",
480 BmRARE(sv),BmPREVIOUS(sv)));
483 /* If SvTAIL(littlestr), it has a fake '\n' at end. */
484 /* If SvTAIL is actually due to \Z or \z, this gives false positives
488 =for apidoc fbm_instr
490 Returns the location of the SV in the string delimited by C<str> and
491 C<strend>. It returns C<NULL> if the string can't be found. The C<sv>
492 does not have to be fbm_compiled, but the search will not be as fast
499 Perl_fbm_instr(pTHX_ unsigned char *big, register unsigned char *bigend, SV *littlestr, U32 flags)
501 register unsigned char *s;
503 register const unsigned char *little
504 = (const unsigned char *)SvPV_const(littlestr,l);
505 register STRLEN littlelen = l;
506 register const I32 multiline = flags & FBMrf_MULTILINE;
508 if ((STRLEN)(bigend - big) < littlelen) {
509 if ( SvTAIL(littlestr)
510 && ((STRLEN)(bigend - big) == littlelen - 1)
512 || (*big == *little &&
513 memEQ((char *)big, (char *)little, littlelen - 1))))
518 if (littlelen <= 2) { /* Special-cased */
520 if (littlelen == 1) {
521 if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
522 /* Know that bigend != big. */
523 if (bigend[-1] == '\n')
524 return (char *)(bigend - 1);
525 return (char *) bigend;
533 if (SvTAIL(littlestr))
534 return (char *) bigend;
538 return (char*)big; /* Cannot be SvTAIL! */
541 if (SvTAIL(littlestr) && !multiline) {
542 if (bigend[-1] == '\n' && bigend[-2] == *little)
543 return (char*)bigend - 2;
544 if (bigend[-1] == *little)
545 return (char*)bigend - 1;
549 /* This should be better than FBM if c1 == c2, and almost
550 as good otherwise: maybe better since we do less indirection.
551 And we save a lot of memory by caching no table. */
552 const unsigned char c1 = little[0];
553 const unsigned char c2 = little[1];
558 while (s <= bigend) {
568 goto check_1char_anchor;
579 goto check_1char_anchor;
582 while (s <= bigend) {
587 goto check_1char_anchor;
596 check_1char_anchor: /* One char and anchor! */
597 if (SvTAIL(littlestr) && (*bigend == *little))
598 return (char *)bigend; /* bigend is already decremented. */
601 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
602 s = bigend - littlelen;
603 if (s >= big && bigend[-1] == '\n' && *s == *little
604 /* Automatically of length > 2 */
605 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
607 return (char*)s; /* how sweet it is */
610 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
612 return (char*)s + 1; /* how sweet it is */
616 if (SvTYPE(littlestr) != SVt_PVBM || !SvVALID(littlestr)) {
617 char * const b = ninstr((char*)big,(char*)bigend,
618 (char*)little, (char*)little + littlelen);
620 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
621 /* Chop \n from littlestr: */
622 s = bigend - littlelen + 1;
624 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
633 { /* Do actual FBM. */
634 register const unsigned char * const table = little + littlelen + FBM_TABLE_OFFSET;
635 register const unsigned char *oldlittle;
637 if (littlelen > (STRLEN)(bigend - big))
639 --littlelen; /* Last char found by table lookup */
642 little += littlelen; /* last char */
648 if ((tmp = table[*s])) {
649 if ((s += tmp) < bigend)
653 else { /* less expensive than calling strncmp() */
654 register unsigned char * const olds = s;
659 if (*--s == *--little)
661 s = olds + 1; /* here we pay the price for failure */
663 if (s < bigend) /* fake up continue to outer loop */
671 if ( s == bigend && (table[-1] & FBMcf_TAIL)
672 && memEQ((char *)(bigend - littlelen),
673 (char *)(oldlittle - littlelen), littlelen) )
674 return (char*)bigend - littlelen;
679 /* start_shift, end_shift are positive quantities which give offsets
680 of ends of some substring of bigstr.
681 If "last" we want the last occurrence.
682 old_posp is the way of communication between consequent calls if
683 the next call needs to find the .
684 The initial *old_posp should be -1.
686 Note that we take into account SvTAIL, so one can get extra
687 optimizations if _ALL flag is set.
690 /* If SvTAIL is actually due to \Z or \z, this gives false positives
691 if PL_multiline. In fact if !PL_multiline the authoritative answer
692 is not supported yet. */
695 Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
698 register const unsigned char *big;
700 register I32 previous;
702 register const unsigned char *little;
703 register I32 stop_pos;
704 register const unsigned char *littleend;
708 ? (pos = PL_screamfirst[BmRARE(littlestr)]) < 0
709 : (((pos = *old_posp), pos += PL_screamnext[pos]) == 0)) {
711 if ( BmRARE(littlestr) == '\n'
712 && BmPREVIOUS(littlestr) == SvCUR(littlestr) - 1) {
713 little = (const unsigned char *)(SvPVX_const(littlestr));
714 littleend = little + SvCUR(littlestr);
721 little = (const unsigned char *)(SvPVX_const(littlestr));
722 littleend = little + SvCUR(littlestr);
724 /* The value of pos we can start at: */
725 previous = BmPREVIOUS(littlestr);
726 big = (const unsigned char *)(SvPVX_const(bigstr));
727 /* The value of pos we can stop at: */
728 stop_pos = SvCUR(bigstr) - end_shift - (SvCUR(littlestr) - 1 - previous);
729 if (previous + start_shift > stop_pos) {
731 stop_pos does not include SvTAIL in the count, so this check is incorrect
732 (I think) - see [ID 20010618.006] and t/op/study.t. HVDS 2001/06/19
735 if (previous + start_shift == stop_pos + 1) /* A fake '\n'? */
740 while (pos < previous + start_shift) {
741 if (!(pos += PL_screamnext[pos]))
746 register const unsigned char *s, *x;
747 if (pos >= stop_pos) break;
748 if (big[pos] != first)
750 for (x=big+pos+1,s=little; s < littleend; /**/ ) {
756 if (s == littleend) {
758 if (!last) return (char *)(big+pos);
761 } while ( pos += PL_screamnext[pos] );
763 return (char *)(big+(*old_posp));
765 if (!SvTAIL(littlestr) || (end_shift > 0))
767 /* Ignore the trailing "\n". This code is not microoptimized */
768 big = (const unsigned char *)(SvPVX_const(bigstr) + SvCUR(bigstr));
769 stop_pos = littleend - little; /* Actual littlestr len */
774 && ((stop_pos == 1) ||
775 memEQ((char *)(big + 1), (char *)little, stop_pos - 1)))
781 Perl_ibcmp(pTHX_ const char *s1, const char *s2, register I32 len)
783 register const U8 *a = (const U8 *)s1;
784 register const U8 *b = (const U8 *)s2;
786 if (*a != *b && *a != PL_fold[*b])
794 Perl_ibcmp_locale(pTHX_ const char *s1, const char *s2, register I32 len)
797 register const U8 *a = (const U8 *)s1;
798 register const U8 *b = (const U8 *)s2;
800 if (*a != *b && *a != PL_fold_locale[*b])
807 /* copy a string to a safe spot */
810 =head1 Memory Management
814 Perl's version of C<strdup()>. Returns a pointer to a newly allocated
815 string which is a duplicate of C<pv>. The size of the string is
816 determined by C<strlen()>. The memory allocated for the new string can
817 be freed with the C<Safefree()> function.
823 Perl_savepv(pTHX_ const char *pv)
829 const STRLEN pvlen = strlen(pv)+1;
830 Newx(newaddr,pvlen,char);
831 return memcpy(newaddr,pv,pvlen);
836 /* same thing but with a known length */
841 Perl's version of what C<strndup()> would be if it existed. Returns a
842 pointer to a newly allocated string which is a duplicate of the first
843 C<len> bytes from C<pv>. The memory allocated for the new string can be
844 freed with the C<Safefree()> function.
850 Perl_savepvn(pTHX_ const char *pv, register I32 len)
852 register char *newaddr;
854 Newx(newaddr,len+1,char);
855 /* Give a meaning to NULL pointer mainly for the use in sv_magic() */
857 /* might not be null terminated */
859 return (char *) CopyD(pv,newaddr,len,char);
862 return (char *) ZeroD(newaddr,len+1,char);
867 =for apidoc savesharedpv
869 A version of C<savepv()> which allocates the duplicate string in memory
870 which is shared between threads.
875 Perl_savesharedpv(pTHX_ const char *pv)
877 register char *newaddr;
882 pvlen = strlen(pv)+1;
883 newaddr = (char*)PerlMemShared_malloc(pvlen);
885 return write_no_mem();
887 return memcpy(newaddr,pv,pvlen);
893 A version of C<savepv()>/C<savepvn()> which gets the string to duplicate from
894 the passed in SV using C<SvPV()>
900 Perl_savesvpv(pTHX_ SV *sv)
903 const char * const pv = SvPV_const(sv, len);
904 register char *newaddr;
907 Newx(newaddr,len,char);
908 return (char *) CopyD(pv,newaddr,len,char);
912 /* the SV for Perl_form() and mess() is not kept in an arena */
922 return sv_2mortal(newSVpvs(""));
927 /* Create as PVMG now, to avoid any upgrading later */
929 Newxz(any, 1, XPVMG);
930 SvFLAGS(sv) = SVt_PVMG;
931 SvANY(sv) = (void*)any;
933 SvREFCNT(sv) = 1 << 30; /* practically infinite */
938 #if defined(PERL_IMPLICIT_CONTEXT)
940 Perl_form_nocontext(const char* pat, ...)
946 retval = vform(pat, &args);
950 #endif /* PERL_IMPLICIT_CONTEXT */
953 =head1 Miscellaneous Functions
956 Takes a sprintf-style format pattern and conventional
957 (non-SV) arguments and returns the formatted string.
959 (char *) Perl_form(pTHX_ const char* pat, ...)
961 can be used any place a string (char *) is required:
963 char * s = Perl_form("%d.%d",major,minor);
965 Uses a single private buffer so if you want to format several strings you
966 must explicitly copy the earlier strings away (and free the copies when you
973 Perl_form(pTHX_ const char* pat, ...)
978 retval = vform(pat, &args);
984 Perl_vform(pTHX_ const char *pat, va_list *args)
986 SV * const sv = mess_alloc();
987 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
991 #if defined(PERL_IMPLICIT_CONTEXT)
993 Perl_mess_nocontext(const char *pat, ...)
999 retval = vmess(pat, &args);
1003 #endif /* PERL_IMPLICIT_CONTEXT */
1006 Perl_mess(pTHX_ const char *pat, ...)
1010 va_start(args, pat);
1011 retval = vmess(pat, &args);
1017 S_closest_cop(pTHX_ COP *cop, const OP *o)
1020 /* Look for PL_op starting from o. cop is the last COP we've seen. */
1022 if (!o || o == PL_op)
1025 if (o->op_flags & OPf_KIDS) {
1027 for (kid = cUNOPo->op_first; kid; kid = kid->op_sibling) {
1030 /* If the OP_NEXTSTATE has been optimised away we can still use it
1031 * the get the file and line number. */
1033 if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
1036 /* Keep searching, and return when we've found something. */
1038 new_cop = closest_cop(cop, kid);
1044 /* Nothing found. */
1050 Perl_vmess(pTHX_ const char *pat, va_list *args)
1053 SV * const sv = mess_alloc();
1054 static const char dgd[] = " during global destruction.\n";
1056 sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*));
1057 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1060 * Try and find the file and line for PL_op. This will usually be
1061 * PL_curcop, but it might be a cop that has been optimised away. We
1062 * can try to find such a cop by searching through the optree starting
1063 * from the sibling of PL_curcop.
1066 const COP *cop = closest_cop(PL_curcop, PL_curcop->op_sibling);
1067 if (!cop) cop = PL_curcop;
1070 Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
1071 OutCopFILE(cop), (IV)CopLINE(cop));
1072 if (GvIO(PL_last_in_gv) && IoLINES(GvIOp(PL_last_in_gv))) {
1073 const bool line_mode = (RsSIMPLE(PL_rs) &&
1074 SvCUR(PL_rs) == 1 && *SvPVX_const(PL_rs) == '\n');
1075 Perl_sv_catpvf(aTHX_ sv, ", <%s> %s %"IVdf,
1076 PL_last_in_gv == PL_argvgv ?
1077 "" : GvNAME(PL_last_in_gv),
1078 line_mode ? "line" : "chunk",
1079 (IV)IoLINES(GvIOp(PL_last_in_gv)));
1081 sv_catpv(sv, PL_dirty ? dgd : ".\n");
1087 Perl_write_to_stderr(pTHX_ const char* message, int msglen)
1093 if (PL_stderrgv && SvREFCNT(PL_stderrgv)
1094 && (io = GvIO(PL_stderrgv))
1095 && (mg = SvTIED_mg((SV*)io, PERL_MAGIC_tiedscalar)))
1102 SAVESPTR(PL_stderrgv);
1105 PUSHSTACKi(PERLSI_MAGIC);
1109 PUSHs(SvTIED_obj((SV*)io, mg));
1110 PUSHs(sv_2mortal(newSVpvn(message, msglen)));
1112 call_method("PRINT", G_SCALAR);
1120 /* SFIO can really mess with your errno */
1121 const int e = errno;
1123 PerlIO * const serr = Perl_error_log;
1125 PERL_WRITE_MSG_TO_CONSOLE(serr, message, msglen);
1126 (void)PerlIO_flush(serr);
1133 /* Common code used by vcroak, vdie, vwarn and vwarner */
1136 S_vdie_common(pTHX_ const char *message, STRLEN msglen, I32 utf8, bool warn)
1142 SV **const hook = warn ? &PL_warnhook : &PL_diehook;
1143 /* sv_2cv might call Perl_croak() or Perl_warner() */
1144 SV * const oldhook = *hook;
1151 cv = sv_2cv(oldhook, &stash, &gv, 0);
1153 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1163 if (warn || message) {
1164 msg = newSVpvn(message, msglen);
1165 SvFLAGS(msg) |= utf8;
1173 PUSHSTACKi(warn ? PERLSI_WARNHOOK : PERLSI_DIEHOOK);
1177 call_sv((SV*)cv, G_DISCARD);
1186 S_vdie_croak_common(pTHX_ const char* pat, va_list* args, STRLEN* msglen,
1190 const char *message;
1193 SV * const msv = vmess(pat, args);
1194 if (PL_errors && SvCUR(PL_errors)) {
1195 sv_catsv(PL_errors, msv);
1196 message = SvPV_const(PL_errors, *msglen);
1197 SvCUR_set(PL_errors, 0);
1200 message = SvPV_const(msv,*msglen);
1201 *utf8 = SvUTF8(msv);
1207 DEBUG_S(PerlIO_printf(Perl_debug_log,
1208 "%p: die/croak: message = %s\ndiehook = %p\n",
1209 thr, message, PL_diehook));
1211 S_vdie_common(aTHX_ message, *msglen, *utf8, FALSE);
1217 Perl_vdie(pTHX_ const char* pat, va_list *args)
1220 const char *message;
1221 const int was_in_eval = PL_in_eval;
1225 DEBUG_S(PerlIO_printf(Perl_debug_log,
1226 "%p: die: curstack = %p, mainstack = %p\n",
1227 thr, PL_curstack, PL_mainstack));
1229 message = vdie_croak_common(pat, args, &msglen, &utf8);
1231 PL_restartop = die_where(message, msglen);
1232 SvFLAGS(ERRSV) |= utf8;
1233 DEBUG_S(PerlIO_printf(Perl_debug_log,
1234 "%p: die: restartop = %p, was_in_eval = %d, top_env = %p\n",
1235 thr, PL_restartop, was_in_eval, PL_top_env));
1236 if ((!PL_restartop && was_in_eval) || PL_top_env->je_prev)
1238 return PL_restartop;
1241 #if defined(PERL_IMPLICIT_CONTEXT)
1243 Perl_die_nocontext(const char* pat, ...)
1248 va_start(args, pat);
1249 o = vdie(pat, &args);
1253 #endif /* PERL_IMPLICIT_CONTEXT */
1256 Perl_die(pTHX_ const char* pat, ...)
1260 va_start(args, pat);
1261 o = vdie(pat, &args);
1267 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1270 const char *message;
1274 message = S_vdie_croak_common(aTHX_ pat, args, &msglen, &utf8);
1277 PL_restartop = die_where(message, msglen);
1278 SvFLAGS(ERRSV) |= utf8;
1282 message = SvPVx_const(ERRSV, msglen);
1284 write_to_stderr(message, msglen);
1288 #if defined(PERL_IMPLICIT_CONTEXT)
1290 Perl_croak_nocontext(const char *pat, ...)
1294 va_start(args, pat);
1299 #endif /* PERL_IMPLICIT_CONTEXT */
1302 =head1 Warning and Dieing
1306 This is the XSUB-writer's interface to Perl's C<die> function.
1307 Normally call this function the same way you call the C C<printf>
1308 function. Calling C<croak> returns control directly to Perl,
1309 sidestepping the normal C order of execution. See C<warn>.
1311 If you want to throw an exception object, assign the object to
1312 C<$@> and then pass C<NULL> to croak():
1314 errsv = get_sv("@", TRUE);
1315 sv_setsv(errsv, exception_object);
1322 Perl_croak(pTHX_ const char *pat, ...)
1325 va_start(args, pat);
1332 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1336 SV * const msv = vmess(pat, args);
1337 const I32 utf8 = SvUTF8(msv);
1338 const char * const message = SvPV_const(msv, msglen);
1341 if (vdie_common(message, msglen, utf8, TRUE))
1345 write_to_stderr(message, msglen);
1348 #if defined(PERL_IMPLICIT_CONTEXT)
1350 Perl_warn_nocontext(const char *pat, ...)
1354 va_start(args, pat);
1358 #endif /* PERL_IMPLICIT_CONTEXT */
1363 This is the XSUB-writer's interface to Perl's C<warn> function. Call this
1364 function the same way you call the C C<printf> function. See C<croak>.
1370 Perl_warn(pTHX_ const char *pat, ...)
1373 va_start(args, pat);
1378 #if defined(PERL_IMPLICIT_CONTEXT)
1380 Perl_warner_nocontext(U32 err, const char *pat, ...)
1384 va_start(args, pat);
1385 vwarner(err, pat, &args);
1388 #endif /* PERL_IMPLICIT_CONTEXT */
1391 Perl_warner(pTHX_ U32 err, const char* pat,...)
1394 va_start(args, pat);
1395 vwarner(err, pat, &args);
1400 Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1404 SV * const msv = vmess(pat, args);
1406 const char * const message = SvPV_const(msv, msglen);
1407 const I32 utf8 = SvUTF8(msv);
1411 S_vdie_common(aTHX_ message, msglen, utf8, FALSE);
1414 PL_restartop = die_where(message, msglen);
1415 SvFLAGS(ERRSV) |= utf8;
1418 write_to_stderr(message, msglen);
1422 Perl_vwarn(aTHX_ pat, args);
1426 /* implements the ckWARN? macros */
1429 Perl_ckwarn(pTHX_ U32 w)
1435 && PL_curcop->cop_warnings != pWARN_NONE
1437 PL_curcop->cop_warnings == pWARN_ALL
1438 || isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w))
1439 || (unpackWARN2(w) &&
1440 isWARN_on(PL_curcop->cop_warnings, unpackWARN2(w)))
1441 || (unpackWARN3(w) &&
1442 isWARN_on(PL_curcop->cop_warnings, unpackWARN3(w)))
1443 || (unpackWARN4(w) &&
1444 isWARN_on(PL_curcop->cop_warnings, unpackWARN4(w)))
1449 isLEXWARN_off && PL_dowarn & G_WARN_ON
1454 /* implements the ckWARN?_d macro */
1457 Perl_ckwarn_d(pTHX_ U32 w)
1462 || PL_curcop->cop_warnings == pWARN_ALL
1464 PL_curcop->cop_warnings != pWARN_NONE
1466 isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w))
1467 || (unpackWARN2(w) &&
1468 isWARN_on(PL_curcop->cop_warnings, unpackWARN2(w)))
1469 || (unpackWARN3(w) &&
1470 isWARN_on(PL_curcop->cop_warnings, unpackWARN3(w)))
1471 || (unpackWARN4(w) &&
1472 isWARN_on(PL_curcop->cop_warnings, unpackWARN4(w)))
1480 /* since we've already done strlen() for both nam and val
1481 * we can use that info to make things faster than
1482 * sprintf(s, "%s=%s", nam, val)
1484 #define my_setenv_format(s, nam, nlen, val, vlen) \
1485 Copy(nam, s, nlen, char); \
1487 Copy(val, s+(nlen+1), vlen, char); \
1488 *(s+(nlen+1+vlen)) = '\0'
1490 #ifdef USE_ENVIRON_ARRAY
1491 /* VMS' my_setenv() is in vms.c */
1492 #if !defined(WIN32) && !defined(NETWARE)
1494 Perl_my_setenv(pTHX_ const char *nam, const char *val)
1498 /* only parent thread can modify process environment */
1499 if (PL_curinterp == aTHX)
1502 #ifndef PERL_USE_SAFE_PUTENV
1503 if (!PL_use_safe_putenv) {
1504 /* most putenv()s leak, so we manipulate environ directly */
1505 register I32 i=setenv_getix(nam); /* where does it go? */
1508 if (environ == PL_origenviron) { /* need we copy environment? */
1513 for (max = i; environ[max]; max++) ;
1514 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
1515 for (j=0; j<max; j++) { /* copy environment */
1516 const int len = strlen(environ[j]);
1517 tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
1518 Copy(environ[j], tmpenv[j], len+1, char);
1521 environ = tmpenv; /* tell exec where it is now */
1524 safesysfree(environ[i]);
1525 while (environ[i]) {
1526 environ[i] = environ[i+1];
1531 if (!environ[i]) { /* does not exist yet */
1532 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
1533 environ[i+1] = NULL; /* make sure it's null terminated */
1536 safesysfree(environ[i]);
1540 environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
1541 /* all that work just for this */
1542 my_setenv_format(environ[i], nam, nlen, val, vlen);
1545 # if defined(__CYGWIN__) || defined(EPOC) || defined(__SYMBIAN32__)
1546 # if defined(HAS_UNSETENV)
1548 (void)unsetenv(nam);
1550 (void)setenv(nam, val, 1);
1552 # else /* ! HAS_UNSETENV */
1553 (void)setenv(nam, val, 1);
1554 # endif /* HAS_UNSETENV */
1556 # if defined(HAS_UNSETENV)
1558 (void)unsetenv(nam);
1560 const int nlen = strlen(nam);
1561 const int vlen = strlen(val);
1562 char * const new_env =
1563 (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1564 my_setenv_format(new_env, nam, nlen, val, vlen);
1565 (void)putenv(new_env);
1567 # else /* ! HAS_UNSETENV */
1569 const int nlen = strlen(nam);
1575 new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1576 /* all that work just for this */
1577 my_setenv_format(new_env, nam, nlen, val, vlen);
1578 (void)putenv(new_env);
1579 # endif /* HAS_UNSETENV */
1580 # endif /* __CYGWIN__ */
1581 #ifndef PERL_USE_SAFE_PUTENV
1587 #else /* WIN32 || NETWARE */
1590 Perl_my_setenv(pTHX_ const char *nam, const char *val)
1593 register char *envstr;
1594 const int nlen = strlen(nam);
1601 Newx(envstr, nlen+vlen+2, char);
1602 my_setenv_format(envstr, nam, nlen, val, vlen);
1603 (void)PerlEnv_putenv(envstr);
1607 #endif /* WIN32 || NETWARE */
1611 Perl_setenv_getix(pTHX_ const char *nam)
1614 register const I32 len = strlen(nam);
1616 for (i = 0; environ[i]; i++) {
1619 strnicmp(environ[i],nam,len) == 0
1621 strnEQ(environ[i],nam,len)
1623 && environ[i][len] == '=')
1624 break; /* strnEQ must come first to avoid */
1625 } /* potential SEGV's */
1628 #endif /* !PERL_MICRO */
1630 #endif /* !VMS && !EPOC*/
1632 #ifdef UNLINK_ALL_VERSIONS
1634 Perl_unlnk(pTHX_ const char *f) /* unlink all versions of a file */
1638 for (i = 0; PerlLIO_unlink(f) >= 0; i++) ;
1643 /* this is a drop-in replacement for bcopy() */
1644 #if (!defined(HAS_MEMCPY) && !defined(HAS_BCOPY)) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY) && !defined(HAS_SAFE_BCOPY))
1646 Perl_my_bcopy(register const char *from,register char *to,register I32 len)
1648 char * const retval = to;
1650 if (from - to >= 0) {
1658 *(--to) = *(--from);
1664 /* this is a drop-in replacement for memset() */
1667 Perl_my_memset(register char *loc, register I32 ch, register I32 len)
1669 char * const retval = loc;
1677 /* this is a drop-in replacement for bzero() */
1678 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
1680 Perl_my_bzero(register char *loc, register I32 len)
1682 char * const retval = loc;
1690 /* this is a drop-in replacement for memcmp() */
1691 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
1693 Perl_my_memcmp(const char *s1, const char *s2, register I32 len)
1695 register const U8 *a = (const U8 *)s1;
1696 register const U8 *b = (const U8 *)s2;
1700 if ((tmp = *a++ - *b++))
1705 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
1709 #ifdef USE_CHAR_VSPRINTF
1714 vsprintf(char *dest, const char *pat, char *args)
1718 fakebuf._ptr = dest;
1719 fakebuf._cnt = 32767;
1723 fakebuf._flag = _IOWRT|_IOSTRG;
1724 _doprnt(pat, args, &fakebuf); /* what a kludge */
1725 (void)putc('\0', &fakebuf);
1726 #ifdef USE_CHAR_VSPRINTF
1729 return 0; /* perl doesn't use return value */
1733 #endif /* HAS_VPRINTF */
1736 #if BYTEORDER != 0x4321
1738 Perl_my_swap(pTHX_ short s)
1740 #if (BYTEORDER & 1) == 0
1743 result = ((s & 255) << 8) + ((s >> 8) & 255);
1751 Perl_my_htonl(pTHX_ long l)
1755 char c[sizeof(long)];
1758 #if BYTEORDER == 0x1234
1759 u.c[0] = (l >> 24) & 255;
1760 u.c[1] = (l >> 16) & 255;
1761 u.c[2] = (l >> 8) & 255;
1765 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1766 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
1771 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1772 u.c[o & 0xf] = (l >> s) & 255;
1780 Perl_my_ntohl(pTHX_ long l)
1784 char c[sizeof(long)];
1787 #if BYTEORDER == 0x1234
1788 u.c[0] = (l >> 24) & 255;
1789 u.c[1] = (l >> 16) & 255;
1790 u.c[2] = (l >> 8) & 255;
1794 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1795 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
1802 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1803 l |= (u.c[o & 0xf] & 255) << s;
1810 #endif /* BYTEORDER != 0x4321 */
1814 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
1815 * If these functions are defined,
1816 * the BYTEORDER is neither 0x1234 nor 0x4321.
1817 * However, this is not assumed.
1821 #define HTOLE(name,type) \
1823 name (register type n) \
1827 char c[sizeof(type)]; \
1830 register I32 s = 0; \
1831 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
1832 u.c[i] = (n >> s) & 0xFF; \
1837 #define LETOH(name,type) \
1839 name (register type n) \
1843 char c[sizeof(type)]; \
1846 register I32 s = 0; \
1849 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
1850 n |= ((type)(u.c[i] & 0xFF)) << s; \
1856 * Big-endian byte order functions.
1859 #define HTOBE(name,type) \
1861 name (register type n) \
1865 char c[sizeof(type)]; \
1868 register I32 s = 8*(sizeof(u.c)-1); \
1869 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
1870 u.c[i] = (n >> s) & 0xFF; \
1875 #define BETOH(name,type) \
1877 name (register type n) \
1881 char c[sizeof(type)]; \
1884 register I32 s = 8*(sizeof(u.c)-1); \
1887 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
1888 n |= ((type)(u.c[i] & 0xFF)) << s; \
1894 * If we just can't do it...
1897 #define NOT_AVAIL(name,type) \
1899 name (register type n) \
1901 Perl_croak_nocontext(#name "() not available"); \
1902 return n; /* not reached */ \
1906 #if defined(HAS_HTOVS) && !defined(htovs)
1909 #if defined(HAS_HTOVL) && !defined(htovl)
1912 #if defined(HAS_VTOHS) && !defined(vtohs)
1915 #if defined(HAS_VTOHL) && !defined(vtohl)
1919 #ifdef PERL_NEED_MY_HTOLE16
1921 HTOLE(Perl_my_htole16,U16)
1923 NOT_AVAIL(Perl_my_htole16,U16)
1926 #ifdef PERL_NEED_MY_LETOH16
1928 LETOH(Perl_my_letoh16,U16)
1930 NOT_AVAIL(Perl_my_letoh16,U16)
1933 #ifdef PERL_NEED_MY_HTOBE16
1935 HTOBE(Perl_my_htobe16,U16)
1937 NOT_AVAIL(Perl_my_htobe16,U16)
1940 #ifdef PERL_NEED_MY_BETOH16
1942 BETOH(Perl_my_betoh16,U16)
1944 NOT_AVAIL(Perl_my_betoh16,U16)
1948 #ifdef PERL_NEED_MY_HTOLE32
1950 HTOLE(Perl_my_htole32,U32)
1952 NOT_AVAIL(Perl_my_htole32,U32)
1955 #ifdef PERL_NEED_MY_LETOH32
1957 LETOH(Perl_my_letoh32,U32)
1959 NOT_AVAIL(Perl_my_letoh32,U32)
1962 #ifdef PERL_NEED_MY_HTOBE32
1964 HTOBE(Perl_my_htobe32,U32)
1966 NOT_AVAIL(Perl_my_htobe32,U32)
1969 #ifdef PERL_NEED_MY_BETOH32
1971 BETOH(Perl_my_betoh32,U32)
1973 NOT_AVAIL(Perl_my_betoh32,U32)
1977 #ifdef PERL_NEED_MY_HTOLE64
1979 HTOLE(Perl_my_htole64,U64)
1981 NOT_AVAIL(Perl_my_htole64,U64)
1984 #ifdef PERL_NEED_MY_LETOH64
1986 LETOH(Perl_my_letoh64,U64)
1988 NOT_AVAIL(Perl_my_letoh64,U64)
1991 #ifdef PERL_NEED_MY_HTOBE64
1993 HTOBE(Perl_my_htobe64,U64)
1995 NOT_AVAIL(Perl_my_htobe64,U64)
1998 #ifdef PERL_NEED_MY_BETOH64
2000 BETOH(Perl_my_betoh64,U64)
2002 NOT_AVAIL(Perl_my_betoh64,U64)
2006 #ifdef PERL_NEED_MY_HTOLES
2007 HTOLE(Perl_my_htoles,short)
2009 #ifdef PERL_NEED_MY_LETOHS
2010 LETOH(Perl_my_letohs,short)
2012 #ifdef PERL_NEED_MY_HTOBES
2013 HTOBE(Perl_my_htobes,short)
2015 #ifdef PERL_NEED_MY_BETOHS
2016 BETOH(Perl_my_betohs,short)
2019 #ifdef PERL_NEED_MY_HTOLEI
2020 HTOLE(Perl_my_htolei,int)
2022 #ifdef PERL_NEED_MY_LETOHI
2023 LETOH(Perl_my_letohi,int)
2025 #ifdef PERL_NEED_MY_HTOBEI
2026 HTOBE(Perl_my_htobei,int)
2028 #ifdef PERL_NEED_MY_BETOHI
2029 BETOH(Perl_my_betohi,int)
2032 #ifdef PERL_NEED_MY_HTOLEL
2033 HTOLE(Perl_my_htolel,long)
2035 #ifdef PERL_NEED_MY_LETOHL
2036 LETOH(Perl_my_letohl,long)
2038 #ifdef PERL_NEED_MY_HTOBEL
2039 HTOBE(Perl_my_htobel,long)
2041 #ifdef PERL_NEED_MY_BETOHL
2042 BETOH(Perl_my_betohl,long)
2046 Perl_my_swabn(void *ptr, int n)
2048 register char *s = (char *)ptr;
2049 register char *e = s + (n-1);
2052 for (n /= 2; n > 0; s++, e--, n--) {
2060 Perl_my_popen_list(pTHX_ char *mode, int n, SV **args)
2062 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(OS2) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL) && !defined(NETWARE)
2065 register I32 This, that;
2071 PERL_FLUSHALL_FOR_CHILD;
2072 This = (*mode == 'w');
2076 taint_proper("Insecure %s%s", "EXEC");
2078 if (PerlProc_pipe(p) < 0)
2080 /* Try for another pipe pair for error return */
2081 if (PerlProc_pipe(pp) >= 0)
2083 while ((pid = PerlProc_fork()) < 0) {
2084 if (errno != EAGAIN) {
2085 PerlLIO_close(p[This]);
2086 PerlLIO_close(p[that]);
2088 PerlLIO_close(pp[0]);
2089 PerlLIO_close(pp[1]);
2101 /* Close parent's end of error status pipe (if any) */
2103 PerlLIO_close(pp[0]);
2104 #if defined(HAS_FCNTL) && defined(F_SETFD)
2105 /* Close error pipe automatically if exec works */
2106 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2109 /* Now dup our end of _the_ pipe to right position */
2110 if (p[THIS] != (*mode == 'r')) {
2111 PerlLIO_dup2(p[THIS], *mode == 'r');
2112 PerlLIO_close(p[THIS]);
2113 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2114 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2117 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2118 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2119 /* No automatic close - do it by hand */
2126 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
2132 do_aexec5(NULL, args-1, args-1+n, pp[1], did_pipes);
2138 do_execfree(); /* free any memory malloced by child on fork */
2140 PerlLIO_close(pp[1]);
2141 /* Keep the lower of the two fd numbers */
2142 if (p[that] < p[This]) {
2143 PerlLIO_dup2(p[This], p[that]);
2144 PerlLIO_close(p[This]);
2148 PerlLIO_close(p[that]); /* close child's end of pipe */
2151 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2153 SvUPGRADE(sv,SVt_IV);
2155 PL_forkprocess = pid;
2156 /* If we managed to get status pipe check for exec fail */
2157 if (did_pipes && pid > 0) {
2161 while (n < sizeof(int)) {
2162 n1 = PerlLIO_read(pp[0],
2163 (void*)(((char*)&errkid)+n),
2169 PerlLIO_close(pp[0]);
2171 if (n) { /* Error */
2173 PerlLIO_close(p[This]);
2174 if (n != sizeof(int))
2175 Perl_croak(aTHX_ "panic: kid popen errno read");
2177 pid2 = wait4pid(pid, &status, 0);
2178 } while (pid2 == -1 && errno == EINTR);
2179 errno = errkid; /* Propagate errno from kid */
2184 PerlLIO_close(pp[0]);
2185 return PerlIO_fdopen(p[This], mode);
2187 Perl_croak(aTHX_ "List form of piped open not implemented");
2188 return (PerlIO *) NULL;
2192 /* VMS' my_popen() is in VMS.c, same with OS/2. */
2193 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
2195 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2199 register I32 This, that;
2202 const I32 doexec = !(*cmd == '-' && cmd[1] == '\0');
2206 PERL_FLUSHALL_FOR_CHILD;
2209 return my_syspopen(aTHX_ cmd,mode);
2212 This = (*mode == 'w');
2214 if (doexec && PL_tainting) {
2216 taint_proper("Insecure %s%s", "EXEC");
2218 if (PerlProc_pipe(p) < 0)
2220 if (doexec && PerlProc_pipe(pp) >= 0)
2222 while ((pid = PerlProc_fork()) < 0) {
2223 if (errno != EAGAIN) {
2224 PerlLIO_close(p[This]);
2225 PerlLIO_close(p[that]);
2227 PerlLIO_close(pp[0]);
2228 PerlLIO_close(pp[1]);
2231 Perl_croak(aTHX_ "Can't fork");
2244 PerlLIO_close(pp[0]);
2245 #if defined(HAS_FCNTL) && defined(F_SETFD)
2246 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2249 if (p[THIS] != (*mode == 'r')) {
2250 PerlLIO_dup2(p[THIS], *mode == 'r');
2251 PerlLIO_close(p[THIS]);
2252 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2253 PerlLIO_close(p[THAT]);
2256 PerlLIO_close(p[THAT]);
2259 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2266 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2271 /* may or may not use the shell */
2272 do_exec3(cmd, pp[1], did_pipes);
2275 #endif /* defined OS2 */
2276 if ((tmpgv = gv_fetchpvs("$", GV_ADD|GV_NOTQUAL, SVt_PV))) {
2277 SvREADONLY_off(GvSV(tmpgv));
2278 sv_setiv(GvSV(tmpgv), PerlProc_getpid());
2279 SvREADONLY_on(GvSV(tmpgv));
2281 #ifdef THREADS_HAVE_PIDS
2282 PL_ppid = (IV)getppid();
2285 #ifdef PERL_USES_PL_PIDSTATUS
2286 hv_clear(PL_pidstatus); /* we have no children */
2292 do_execfree(); /* free any memory malloced by child on vfork */
2294 PerlLIO_close(pp[1]);
2295 if (p[that] < p[This]) {
2296 PerlLIO_dup2(p[This], p[that]);
2297 PerlLIO_close(p[This]);
2301 PerlLIO_close(p[that]);
2304 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2306 SvUPGRADE(sv,SVt_IV);
2308 PL_forkprocess = pid;
2309 if (did_pipes && pid > 0) {
2313 while (n < sizeof(int)) {
2314 n1 = PerlLIO_read(pp[0],
2315 (void*)(((char*)&errkid)+n),
2321 PerlLIO_close(pp[0]);
2323 if (n) { /* Error */
2325 PerlLIO_close(p[This]);
2326 if (n != sizeof(int))
2327 Perl_croak(aTHX_ "panic: kid popen errno read");
2329 pid2 = wait4pid(pid, &status, 0);
2330 } while (pid2 == -1 && errno == EINTR);
2331 errno = errkid; /* Propagate errno from kid */
2336 PerlLIO_close(pp[0]);
2337 return PerlIO_fdopen(p[This], mode);
2340 #if defined(atarist) || defined(EPOC)
2343 Perl_my_popen(pTHX_ char *cmd, char *mode)
2345 PERL_FLUSHALL_FOR_CHILD;
2346 /* Call system's popen() to get a FILE *, then import it.
2347 used 0 for 2nd parameter to PerlIO_importFILE;
2350 return PerlIO_importFILE(popen(cmd, mode), 0);
2354 FILE *djgpp_popen();
2356 Perl_my_popen(pTHX_ char *cmd, char *mode)
2358 PERL_FLUSHALL_FOR_CHILD;
2359 /* Call system's popen() to get a FILE *, then import it.
2360 used 0 for 2nd parameter to PerlIO_importFILE;
2363 return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2368 #endif /* !DOSISH */
2370 /* this is called in parent before the fork() */
2372 Perl_atfork_lock(void)
2375 #if defined(USE_ITHREADS)
2376 /* locks must be held in locking order (if any) */
2378 MUTEX_LOCK(&PL_malloc_mutex);
2384 /* this is called in both parent and child after the fork() */
2386 Perl_atfork_unlock(void)
2389 #if defined(USE_ITHREADS)
2390 /* locks must be released in same order as in atfork_lock() */
2392 MUTEX_UNLOCK(&PL_malloc_mutex);
2401 #if defined(HAS_FORK)
2403 #if defined(USE_ITHREADS) && !defined(HAS_PTHREAD_ATFORK)
2408 /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2409 * handlers elsewhere in the code */
2414 /* this "canna happen" since nothing should be calling here if !HAS_FORK */
2415 Perl_croak_nocontext("fork() not available");
2417 #endif /* HAS_FORK */
2422 Perl_dump_fds(pTHX_ char *s)
2427 PerlIO_printf(Perl_debug_log,"%s", s);
2428 for (fd = 0; fd < 32; fd++) {
2429 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
2430 PerlIO_printf(Perl_debug_log," %d",fd);
2432 PerlIO_printf(Perl_debug_log,"\n");
2435 #endif /* DUMP_FDS */
2439 dup2(int oldfd, int newfd)
2441 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2444 PerlLIO_close(newfd);
2445 return fcntl(oldfd, F_DUPFD, newfd);
2447 #define DUP2_MAX_FDS 256
2448 int fdtmp[DUP2_MAX_FDS];
2454 PerlLIO_close(newfd);
2455 /* good enough for low fd's... */
2456 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2457 if (fdx >= DUP2_MAX_FDS) {
2465 PerlLIO_close(fdtmp[--fdx]);
2472 #ifdef HAS_SIGACTION
2474 #ifdef MACOS_TRADITIONAL
2475 /* We don't want restart behavior on MacOS */
2480 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2483 struct sigaction act, oact;
2486 /* only "parent" interpreter can diddle signals */
2487 if (PL_curinterp != aTHX)
2488 return (Sighandler_t) SIG_ERR;
2491 act.sa_handler = (void(*)(int))handler;
2492 sigemptyset(&act.sa_mask);
2495 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2496 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2498 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2499 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2500 act.sa_flags |= SA_NOCLDWAIT;
2502 if (sigaction(signo, &act, &oact) == -1)
2503 return (Sighandler_t) SIG_ERR;
2505 return (Sighandler_t) oact.sa_handler;
2509 Perl_rsignal_state(pTHX_ int signo)
2511 struct sigaction oact;
2513 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2514 return (Sighandler_t) SIG_ERR;
2516 return (Sighandler_t) oact.sa_handler;
2520 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2523 struct sigaction act;
2526 /* only "parent" interpreter can diddle signals */
2527 if (PL_curinterp != aTHX)
2531 act.sa_handler = (void(*)(int))handler;
2532 sigemptyset(&act.sa_mask);
2535 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2536 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2538 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2539 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2540 act.sa_flags |= SA_NOCLDWAIT;
2542 return sigaction(signo, &act, save);
2546 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2550 /* only "parent" interpreter can diddle signals */
2551 if (PL_curinterp != aTHX)
2555 return sigaction(signo, save, (struct sigaction *)NULL);
2558 #else /* !HAS_SIGACTION */
2561 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2563 #if defined(USE_ITHREADS) && !defined(WIN32)
2564 /* only "parent" interpreter can diddle signals */
2565 if (PL_curinterp != aTHX)
2566 return (Sighandler_t) SIG_ERR;
2569 return PerlProc_signal(signo, handler);
2580 Perl_rsignal_state(pTHX_ int signo)
2583 Sighandler_t oldsig;
2585 #if defined(USE_ITHREADS) && !defined(WIN32)
2586 /* only "parent" interpreter can diddle signals */
2587 if (PL_curinterp != aTHX)
2588 return (Sighandler_t) SIG_ERR;
2592 oldsig = PerlProc_signal(signo, sig_trap);
2593 PerlProc_signal(signo, oldsig);
2595 PerlProc_kill(PerlProc_getpid(), signo);
2600 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2602 #if defined(USE_ITHREADS) && !defined(WIN32)
2603 /* only "parent" interpreter can diddle signals */
2604 if (PL_curinterp != aTHX)
2607 *save = PerlProc_signal(signo, handler);
2608 return (*save == (Sighandler_t) SIG_ERR) ? -1 : 0;
2612 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2614 #if defined(USE_ITHREADS) && !defined(WIN32)
2615 /* only "parent" interpreter can diddle signals */
2616 if (PL_curinterp != aTHX)
2619 return (PerlProc_signal(signo, *save) == (Sighandler_t) SIG_ERR) ? -1 : 0;
2622 #endif /* !HAS_SIGACTION */
2623 #endif /* !PERL_MICRO */
2625 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
2626 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
2628 Perl_my_pclose(pTHX_ PerlIO *ptr)
2631 Sigsave_t hstat, istat, qstat;
2637 int saved_errno = 0;
2639 int saved_win32_errno;
2643 svp = av_fetch(PL_fdpid,PerlIO_fileno(ptr),TRUE);
2645 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
2647 *svp = &PL_sv_undef;
2649 if (pid == -1) { /* Opened by popen. */
2650 return my_syspclose(ptr);
2653 if ((close_failed = (PerlIO_close(ptr) == EOF))) {
2654 saved_errno = errno;
2656 saved_win32_errno = GetLastError();
2660 if(PerlProc_kill(pid, 0) < 0) { return(pid); } /* HOM 12/23/91 */
2663 rsignal_save(SIGHUP, (Sighandler_t) SIG_IGN, &hstat);
2664 rsignal_save(SIGINT, (Sighandler_t) SIG_IGN, &istat);
2665 rsignal_save(SIGQUIT, (Sighandler_t) SIG_IGN, &qstat);
2668 pid2 = wait4pid(pid, &status, 0);
2669 } while (pid2 == -1 && errno == EINTR);
2671 rsignal_restore(SIGHUP, &hstat);
2672 rsignal_restore(SIGINT, &istat);
2673 rsignal_restore(SIGQUIT, &qstat);
2676 SETERRNO(saved_errno, 0);
2679 return(pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status));
2681 #endif /* !DOSISH */
2683 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(MACOS_TRADITIONAL)
2685 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
2691 #ifdef PERL_USES_PL_PIDSTATUS
2694 /* The keys in PL_pidstatus are now the raw 4 (or 8) bytes of the
2695 pid, rather than a string form. */
2696 SV * const * const svp = hv_fetch(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),FALSE);
2697 if (svp && *svp != &PL_sv_undef) {
2698 *statusp = SvIVX(*svp);
2699 (void)hv_delete(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),
2707 hv_iterinit(PL_pidstatus);
2708 if ((entry = hv_iternext(PL_pidstatus))) {
2709 SV * const sv = hv_iterval(PL_pidstatus,entry);
2711 const char * const spid = hv_iterkey(entry,&len);
2713 assert (len == sizeof(Pid_t));
2714 memcpy((char *)&pid, spid, len);
2715 *statusp = SvIVX(sv);
2716 /* The hash iterator is currently on this entry, so simply
2717 calling hv_delete would trigger the lazy delete, which on
2718 aggregate does more work, beacuse next call to hv_iterinit()
2719 would spot the flag, and have to call the delete routine,
2720 while in the meantime any new entries can't re-use that
2722 hv_iterinit(PL_pidstatus);
2723 (void)hv_delete(PL_pidstatus,spid,len,G_DISCARD);
2730 # ifdef HAS_WAITPID_RUNTIME
2731 if (!HAS_WAITPID_RUNTIME)
2734 result = PerlProc_waitpid(pid,statusp,flags);
2737 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
2738 result = wait4((pid==-1)?0:pid,statusp,flags,Null(struct rusage *));
2741 #ifdef PERL_USES_PL_PIDSTATUS
2742 #if defined(HAS_WAITPID) && defined(HAS_WAITPID_RUNTIME)
2747 Perl_croak(aTHX_ "Can't do waitpid with flags");
2749 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
2750 pidgone(result,*statusp);
2756 #if defined(HAS_WAITPID) || defined(HAS_WAIT4)
2759 if (result < 0 && errno == EINTR) {
2764 #endif /* !DOSISH || OS2 || WIN32 || NETWARE */
2766 #ifdef PERL_USES_PL_PIDSTATUS
2768 Perl_pidgone(pTHX_ Pid_t pid, int status)
2772 sv = *hv_fetch(PL_pidstatus,(const char*)&pid,sizeof(Pid_t),TRUE);
2773 SvUPGRADE(sv,SVt_IV);
2774 SvIV_set(sv, status);
2779 #if defined(atarist) || defined(OS2) || defined(EPOC)
2782 int /* Cannot prototype with I32
2784 my_syspclose(PerlIO *ptr)
2787 Perl_my_pclose(pTHX_ PerlIO *ptr)
2790 /* Needs work for PerlIO ! */
2791 FILE * const f = PerlIO_findFILE(ptr);
2792 const I32 result = pclose(f);
2793 PerlIO_releaseFILE(ptr,f);
2801 Perl_my_pclose(pTHX_ PerlIO *ptr)
2803 /* Needs work for PerlIO ! */
2804 FILE * const f = PerlIO_findFILE(ptr);
2805 I32 result = djgpp_pclose(f);
2806 result = (result << 8) & 0xff00;
2807 PerlIO_releaseFILE(ptr,f);
2813 Perl_repeatcpy(pTHX_ register char *to, register const char *from, I32 len, register I32 count)
2816 register const char * const frombase = from;
2819 register const char c = *from;
2824 while (count-- > 0) {
2825 for (todo = len; todo > 0; todo--) {
2834 Perl_same_dirent(pTHX_ const char *a, const char *b)
2836 char *fa = strrchr(a,'/');
2837 char *fb = strrchr(b,'/');
2840 SV * const tmpsv = sv_newmortal();
2853 sv_setpvn(tmpsv, ".", 1);
2855 sv_setpvn(tmpsv, a, fa - a);
2856 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf1) < 0)
2859 sv_setpvn(tmpsv, ".", 1);
2861 sv_setpvn(tmpsv, b, fb - b);
2862 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf2) < 0)
2864 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
2865 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
2867 #endif /* !HAS_RENAME */
2870 Perl_find_script(pTHX_ const char *scriptname, bool dosearch,
2871 const char *const *const search_ext, I32 flags)
2874 const char *xfound = NULL;
2875 char *xfailed = NULL;
2876 char tmpbuf[MAXPATHLEN];
2880 #if defined(DOSISH) && !defined(OS2) && !defined(atarist)
2881 # define SEARCH_EXTS ".bat", ".cmd", NULL
2882 # define MAX_EXT_LEN 4
2885 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
2886 # define MAX_EXT_LEN 4
2889 # define SEARCH_EXTS ".pl", ".com", NULL
2890 # define MAX_EXT_LEN 4
2892 /* additional extensions to try in each dir if scriptname not found */
2894 static const char *const exts[] = { SEARCH_EXTS };
2895 const char *const *const ext = search_ext ? search_ext : exts;
2896 int extidx = 0, i = 0;
2897 const char *curext = NULL;
2899 PERL_UNUSED_ARG(search_ext);
2900 # define MAX_EXT_LEN 0
2904 * If dosearch is true and if scriptname does not contain path
2905 * delimiters, search the PATH for scriptname.
2907 * If SEARCH_EXTS is also defined, will look for each
2908 * scriptname{SEARCH_EXTS} whenever scriptname is not found
2909 * while searching the PATH.
2911 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
2912 * proceeds as follows:
2913 * If DOSISH or VMSISH:
2914 * + look for ./scriptname{,.foo,.bar}
2915 * + search the PATH for scriptname{,.foo,.bar}
2918 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
2919 * this will not look in '.' if it's not in the PATH)
2924 # ifdef ALWAYS_DEFTYPES
2925 len = strlen(scriptname);
2926 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
2927 int idx = 0, deftypes = 1;
2930 const int hasdir = !dosearch || (strpbrk(scriptname,":[</") != NULL);
2933 int idx = 0, deftypes = 1;
2936 const int hasdir = (strpbrk(scriptname,":[</") != NULL);
2938 /* The first time through, just add SEARCH_EXTS to whatever we
2939 * already have, so we can check for default file types. */
2941 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
2947 if ((strlen(tmpbuf) + strlen(scriptname)
2948 + MAX_EXT_LEN) >= sizeof tmpbuf)
2949 continue; /* don't search dir with too-long name */
2950 strcat(tmpbuf, scriptname);
2954 if (strEQ(scriptname, "-"))
2956 if (dosearch) { /* Look in '.' first. */
2957 const char *cur = scriptname;
2959 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
2961 if (strEQ(ext[i++],curext)) {
2962 extidx = -1; /* already has an ext */
2967 DEBUG_p(PerlIO_printf(Perl_debug_log,
2968 "Looking for %s\n",cur));
2969 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
2970 && !S_ISDIR(PL_statbuf.st_mode)) {
2978 if (cur == scriptname) {
2979 len = strlen(scriptname);
2980 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
2982 /* FIXME? Convert to memcpy */
2983 cur = strcpy(tmpbuf, scriptname);
2985 } while (extidx >= 0 && ext[extidx] /* try an extension? */
2986 && strcpy(tmpbuf+len, ext[extidx++]));
2991 #ifdef MACOS_TRADITIONAL
2992 if (dosearch && !strchr(scriptname, ':') &&
2993 (s = PerlEnv_getenv("Commands")))
2995 if (dosearch && !strchr(scriptname, '/')
2997 && !strchr(scriptname, '\\')
2999 && (s = PerlEnv_getenv("PATH")))
3004 PL_bufend = s + strlen(s);
3005 while (s < PL_bufend) {
3006 #ifdef MACOS_TRADITIONAL
3007 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
3011 #if defined(atarist) || defined(DOSISH)
3016 && *s != ';'; len++, s++) {
3017 if (len < sizeof tmpbuf)
3020 if (len < sizeof tmpbuf)
3022 #else /* ! (atarist || DOSISH) */
3023 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
3026 #endif /* ! (atarist || DOSISH) */
3027 #endif /* MACOS_TRADITIONAL */
3030 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
3031 continue; /* don't search dir with too-long name */
3032 #ifdef MACOS_TRADITIONAL
3033 if (len && tmpbuf[len - 1] != ':')
3034 tmpbuf[len++] = ':';
3037 # if defined(atarist) || defined(__MINT__) || defined(DOSISH)
3038 && tmpbuf[len - 1] != '/'
3039 && tmpbuf[len - 1] != '\\'
3042 tmpbuf[len++] = '/';
3043 if (len == 2 && tmpbuf[0] == '.')
3046 /* FIXME? Convert to memcpy by storing previous strlen(scriptname)
3048 (void)strcpy(tmpbuf + len, scriptname);
3052 len = strlen(tmpbuf);
3053 if (extidx > 0) /* reset after previous loop */
3057 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
3058 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
3059 if (S_ISDIR(PL_statbuf.st_mode)) {
3063 } while ( retval < 0 /* not there */
3064 && extidx>=0 && ext[extidx] /* try an extension? */
3065 && strcpy(tmpbuf+len, ext[extidx++])
3070 if (S_ISREG(PL_statbuf.st_mode)
3071 && cando(S_IRUSR,TRUE,&PL_statbuf)
3072 #if !defined(DOSISH) && !defined(MACOS_TRADITIONAL)
3073 && cando(S_IXUSR,TRUE,&PL_statbuf)
3077 xfound = tmpbuf; /* bingo! */
3081 xfailed = savepv(tmpbuf);
3084 if (!xfound && !seen_dot && !xfailed &&
3085 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
3086 || S_ISDIR(PL_statbuf.st_mode)))
3088 seen_dot = 1; /* Disable message. */
3090 if (flags & 1) { /* do or die? */
3091 Perl_croak(aTHX_ "Can't %s %s%s%s",
3092 (xfailed ? "execute" : "find"),
3093 (xfailed ? xfailed : scriptname),
3094 (xfailed ? "" : " on PATH"),
3095 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
3100 scriptname = xfound;
3102 return (scriptname ? savepv(scriptname) : NULL);
3105 #ifndef PERL_GET_CONTEXT_DEFINED
3108 Perl_get_context(void)
3111 #if defined(USE_ITHREADS)
3112 # ifdef OLD_PTHREADS_API
3114 if (pthread_getspecific(PL_thr_key, &t))
3115 Perl_croak_nocontext("panic: pthread_getspecific");
3118 # ifdef I_MACH_CTHREADS
3119 return (void*)cthread_data(cthread_self());
3121 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
3130 Perl_set_context(void *t)
3133 #if defined(USE_ITHREADS)
3134 # ifdef I_MACH_CTHREADS
3135 cthread_set_data(cthread_self(), t);
3137 if (pthread_setspecific(PL_thr_key, t))
3138 Perl_croak_nocontext("panic: pthread_setspecific");
3145 #endif /* !PERL_GET_CONTEXT_DEFINED */
3147 #if defined(PERL_GLOBAL_STRUCT) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
3156 Perl_get_op_names(pTHX)
3158 return (char **)PL_op_name;
3162 Perl_get_op_descs(pTHX)
3164 return (char **)PL_op_desc;
3168 Perl_get_no_modify(pTHX)
3170 return PL_no_modify;
3174 Perl_get_opargs(pTHX)
3176 return (U32 *)PL_opargs;
3180 Perl_get_ppaddr(pTHX)
3183 return (PPADDR_t*)PL_ppaddr;
3186 #ifndef HAS_GETENV_LEN
3188 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3190 char * const env_trans = PerlEnv_getenv(env_elem);
3192 *len = strlen(env_trans);
3199 Perl_get_vtbl(pTHX_ int vtbl_id)
3201 const MGVTBL* result;
3205 result = &PL_vtbl_sv;
3208 result = &PL_vtbl_env;
3210 case want_vtbl_envelem:
3211 result = &PL_vtbl_envelem;
3214 result = &PL_vtbl_sig;
3216 case want_vtbl_sigelem:
3217 result = &PL_vtbl_sigelem;
3219 case want_vtbl_pack:
3220 result = &PL_vtbl_pack;
3222 case want_vtbl_packelem:
3223 result = &PL_vtbl_packelem;
3225 case want_vtbl_dbline:
3226 result = &PL_vtbl_dbline;
3229 result = &PL_vtbl_isa;
3231 case want_vtbl_isaelem:
3232 result = &PL_vtbl_isaelem;
3234 case want_vtbl_arylen:
3235 result = &PL_vtbl_arylen;
3237 case want_vtbl_glob:
3238 result = &PL_vtbl_glob;
3240 case want_vtbl_mglob:
3241 result = &PL_vtbl_mglob;
3243 case want_vtbl_nkeys:
3244 result = &PL_vtbl_nkeys;
3246 case want_vtbl_taint:
3247 result = &PL_vtbl_taint;
3249 case want_vtbl_substr:
3250 result = &PL_vtbl_substr;
3253 result = &PL_vtbl_vec;
3256 result = &PL_vtbl_pos;
3259 result = &PL_vtbl_bm;
3262 result = &PL_vtbl_fm;
3264 case want_vtbl_uvar:
3265 result = &PL_vtbl_uvar;
3267 case want_vtbl_defelem:
3268 result = &PL_vtbl_defelem;
3270 case want_vtbl_regexp:
3271 result = &PL_vtbl_regexp;
3273 case want_vtbl_regdata:
3274 result = &PL_vtbl_regdata;
3276 case want_vtbl_regdatum:
3277 result = &PL_vtbl_regdatum;
3279 #ifdef USE_LOCALE_COLLATE
3280 case want_vtbl_collxfrm:
3281 result = &PL_vtbl_collxfrm;
3284 case want_vtbl_amagic:
3285 result = &PL_vtbl_amagic;
3287 case want_vtbl_amagicelem:
3288 result = &PL_vtbl_amagicelem;
3290 case want_vtbl_backref:
3291 result = &PL_vtbl_backref;
3293 case want_vtbl_utf8:
3294 result = &PL_vtbl_utf8;
3297 result = Null(MGVTBL*);
3300 return (MGVTBL*)result;
3304 Perl_my_fflush_all(pTHX)
3306 #if defined(USE_PERLIO) || defined(FFLUSH_NULL) || defined(USE_SFIO)
3307 return PerlIO_flush(NULL);
3309 # if defined(HAS__FWALK)
3310 extern int fflush(FILE *);
3311 /* undocumented, unprototyped, but very useful BSDism */
3312 extern void _fwalk(int (*)(FILE *));
3316 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3318 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3319 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3321 # if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3322 open_max = sysconf(_SC_OPEN_MAX);
3325 open_max = FOPEN_MAX;
3328 open_max = OPEN_MAX;
3339 for (i = 0; i < open_max; i++)
3340 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3341 STDIO_STREAM_ARRAY[i]._file < open_max &&
3342 STDIO_STREAM_ARRAY[i]._flag)
3343 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3347 SETERRNO(EBADF,RMS_IFI);
3354 Perl_report_evil_fh(pTHX_ const GV *gv, const IO *io, I32 op)
3356 const char * const func =
3357 op == OP_READLINE ? "readline" : /* "<HANDLE>" not nice */
3358 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
3360 const char * const pars = OP_IS_FILETEST(op) ? "" : "()";
3361 const char * const type = OP_IS_SOCKET(op)
3362 || (gv && io && IoTYPE(io) == IoTYPE_SOCKET)
3363 ? "socket" : "filehandle";
3364 const char * const name = gv && isGV(gv) ? GvENAME(gv) : NULL;
3366 if (op == OP_phoney_OUTPUT_ONLY || op == OP_phoney_INPUT_ONLY) {
3367 if (ckWARN(WARN_IO)) {
3368 const char * const direction = (op == OP_phoney_INPUT_ONLY) ? "in" : "out";
3370 Perl_warner(aTHX_ packWARN(WARN_IO),
3371 "Filehandle %s opened only for %sput",
3374 Perl_warner(aTHX_ packWARN(WARN_IO),
3375 "Filehandle opened only for %sput", direction);
3382 if (gv && io && IoTYPE(io) == IoTYPE_CLOSED) {
3384 warn_type = WARN_CLOSED;
3388 warn_type = WARN_UNOPENED;
3391 if (ckWARN(warn_type)) {
3392 if (name && *name) {
3393 Perl_warner(aTHX_ packWARN(warn_type),
3394 "%s%s on %s %s %s", func, pars, vile, type, name);
3395 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3397 aTHX_ packWARN(warn_type),
3398 "\t(Are you trying to call %s%s on dirhandle %s?)\n",
3403 Perl_warner(aTHX_ packWARN(warn_type),
3404 "%s%s on %s %s", func, pars, vile, type);
3405 if (gv && io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3407 aTHX_ packWARN(warn_type),
3408 "\t(Are you trying to call %s%s on dirhandle?)\n",
3417 /* in ASCII order, not that it matters */
3418 static const char controllablechars[] = "?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_";
3421 Perl_ebcdic_control(pTHX_ int ch)
3429 if ((ctlp = strchr(controllablechars, ch)) == 0) {
3430 Perl_die(aTHX_ "unrecognised control character '%c'\n", ch);
3433 if (ctlp == controllablechars)
3434 return('\177'); /* DEL */
3436 return((unsigned char)(ctlp - controllablechars - 1));
3437 } else { /* Want uncontrol */
3438 if (ch == '\177' || ch == -1)
3440 else if (ch == '\157')
3442 else if (ch == '\174')
3444 else if (ch == '^') /* '\137' in 1047, '\260' in 819 */
3446 else if (ch == '\155')
3448 else if (0 < ch && ch < (sizeof(controllablechars) - 1))
3449 return(controllablechars[ch+1]);
3451 Perl_die(aTHX_ "invalid control request: '\\%03o'\n", ch & 0xFF);
3456 /* To workaround core dumps from the uninitialised tm_zone we get the
3457 * system to give us a reasonable struct to copy. This fix means that
3458 * strftime uses the tm_zone and tm_gmtoff values returned by
3459 * localtime(time()). That should give the desired result most of the
3460 * time. But probably not always!
3462 * This does not address tzname aspects of NETaa14816.
3467 # ifndef STRUCT_TM_HASZONE
3468 # define STRUCT_TM_HASZONE
3472 #ifdef STRUCT_TM_HASZONE /* Backward compat */
3473 # ifndef HAS_TM_TM_ZONE
3474 # define HAS_TM_TM_ZONE
3479 Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
3481 #ifdef HAS_TM_TM_ZONE
3483 const struct tm* my_tm;
3485 my_tm = localtime(&now);
3487 Copy(my_tm, ptm, 1, struct tm);
3489 PERL_UNUSED_ARG(ptm);
3494 * mini_mktime - normalise struct tm values without the localtime()
3495 * semantics (and overhead) of mktime().
3498 Perl_mini_mktime(pTHX_ struct tm *ptm)
3502 int month, mday, year, jday;
3503 int odd_cent, odd_year;
3505 #define DAYS_PER_YEAR 365
3506 #define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
3507 #define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
3508 #define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
3509 #define SECS_PER_HOUR (60*60)
3510 #define SECS_PER_DAY (24*SECS_PER_HOUR)
3511 /* parentheses deliberately absent on these two, otherwise they don't work */
3512 #define MONTH_TO_DAYS 153/5
3513 #define DAYS_TO_MONTH 5/153
3514 /* offset to bias by March (month 4) 1st between month/mday & year finding */
3515 #define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
3516 /* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
3517 #define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
3520 * Year/day algorithm notes:
3522 * With a suitable offset for numeric value of the month, one can find
3523 * an offset into the year by considering months to have 30.6 (153/5) days,
3524 * using integer arithmetic (i.e., with truncation). To avoid too much
3525 * messing about with leap days, we consider January and February to be
3526 * the 13th and 14th month of the previous year. After that transformation,
3527 * we need the month index we use to be high by 1 from 'normal human' usage,
3528 * so the month index values we use run from 4 through 15.
3530 * Given that, and the rules for the Gregorian calendar (leap years are those
3531 * divisible by 4 unless also divisible by 100, when they must be divisible
3532 * by 400 instead), we can simply calculate the number of days since some
3533 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
3534 * the days we derive from our month index, and adding in the day of the
3535 * month. The value used here is not adjusted for the actual origin which
3536 * it normally would use (1 January A.D. 1), since we're not exposing it.
3537 * We're only building the value so we can turn around and get the
3538 * normalised values for the year, month, day-of-month, and day-of-year.
3540 * For going backward, we need to bias the value we're using so that we find
3541 * the right year value. (Basically, we don't want the contribution of
3542 * March 1st to the number to apply while deriving the year). Having done
3543 * that, we 'count up' the contribution to the year number by accounting for
3544 * full quadracenturies (400-year periods) with their extra leap days, plus
3545 * the contribution from full centuries (to avoid counting in the lost leap
3546 * days), plus the contribution from full quad-years (to count in the normal
3547 * leap days), plus the leftover contribution from any non-leap years.
3548 * At this point, if we were working with an actual leap day, we'll have 0
3549 * days left over. This is also true for March 1st, however. So, we have
3550 * to special-case that result, and (earlier) keep track of the 'odd'
3551 * century and year contributions. If we got 4 extra centuries in a qcent,
3552 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
3553 * Otherwise, we add back in the earlier bias we removed (the 123 from
3554 * figuring in March 1st), find the month index (integer division by 30.6),
3555 * and the remainder is the day-of-month. We then have to convert back to
3556 * 'real' months (including fixing January and February from being 14/15 in
3557 * the previous year to being in the proper year). After that, to get
3558 * tm_yday, we work with the normalised year and get a new yearday value for
3559 * January 1st, which we subtract from the yearday value we had earlier,
3560 * representing the date we've re-built. This is done from January 1
3561 * because tm_yday is 0-origin.
3563 * Since POSIX time routines are only guaranteed to work for times since the
3564 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
3565 * applies Gregorian calendar rules even to dates before the 16th century
3566 * doesn't bother me. Besides, you'd need cultural context for a given
3567 * date to know whether it was Julian or Gregorian calendar, and that's
3568 * outside the scope for this routine. Since we convert back based on the
3569 * same rules we used to build the yearday, you'll only get strange results
3570 * for input which needed normalising, or for the 'odd' century years which
3571 * were leap years in the Julian calander but not in the Gregorian one.
3572 * I can live with that.
3574 * This algorithm also fails to handle years before A.D. 1 gracefully, but
3575 * that's still outside the scope for POSIX time manipulation, so I don't
3579 year = 1900 + ptm->tm_year;
3580 month = ptm->tm_mon;
3581 mday = ptm->tm_mday;
3582 /* allow given yday with no month & mday to dominate the result */
3583 if (ptm->tm_yday >= 0 && mday <= 0 && month <= 0) {
3586 jday = 1 + ptm->tm_yday;
3595 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
3596 yearday += month*MONTH_TO_DAYS + mday + jday;
3598 * Note that we don't know when leap-seconds were or will be,
3599 * so we have to trust the user if we get something which looks
3600 * like a sensible leap-second. Wild values for seconds will
3601 * be rationalised, however.
3603 if ((unsigned) ptm->tm_sec <= 60) {
3610 secs += 60 * ptm->tm_min;
3611 secs += SECS_PER_HOUR * ptm->tm_hour;
3613 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
3614 /* got negative remainder, but need positive time */
3615 /* back off an extra day to compensate */
3616 yearday += (secs/SECS_PER_DAY)-1;
3617 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
3620 yearday += (secs/SECS_PER_DAY);
3621 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
3624 else if (secs >= SECS_PER_DAY) {
3625 yearday += (secs/SECS_PER_DAY);
3626 secs %= SECS_PER_DAY;
3628 ptm->tm_hour = secs/SECS_PER_HOUR;
3629 secs %= SECS_PER_HOUR;
3630 ptm->tm_min = secs/60;
3632 ptm->tm_sec += secs;
3633 /* done with time of day effects */
3635 * The algorithm for yearday has (so far) left it high by 428.
3636 * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
3637 * bias it by 123 while trying to figure out what year it
3638 * really represents. Even with this tweak, the reverse
3639 * translation fails for years before A.D. 0001.
3640 * It would still fail for Feb 29, but we catch that one below.
3642 jday = yearday; /* save for later fixup vis-a-vis Jan 1 */
3643 yearday -= YEAR_ADJUST;
3644 year = (yearday / DAYS_PER_QCENT) * 400;
3645 yearday %= DAYS_PER_QCENT;
3646 odd_cent = yearday / DAYS_PER_CENT;
3647 year += odd_cent * 100;
3648 yearday %= DAYS_PER_CENT;
3649 year += (yearday / DAYS_PER_QYEAR) * 4;
3650 yearday %= DAYS_PER_QYEAR;
3651 odd_year = yearday / DAYS_PER_YEAR;
3653 yearday %= DAYS_PER_YEAR;
3654 if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
3659 yearday += YEAR_ADJUST; /* recover March 1st crock */
3660 month = yearday*DAYS_TO_MONTH;
3661 yearday -= month*MONTH_TO_DAYS;
3662 /* recover other leap-year adjustment */
3671 ptm->tm_year = year - 1900;
3673 ptm->tm_mday = yearday;
3674 ptm->tm_mon = month;
3678 ptm->tm_mon = month - 1;
3680 /* re-build yearday based on Jan 1 to get tm_yday */
3682 yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
3683 yearday += 14*MONTH_TO_DAYS + 1;
3684 ptm->tm_yday = jday - yearday;
3685 /* fix tm_wday if not overridden by caller */
3686 if ((unsigned)ptm->tm_wday > 6)
3687 ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
3691 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)
3699 init_tm(&mytm); /* XXX workaround - see init_tm() above */
3702 mytm.tm_hour = hour;
3703 mytm.tm_mday = mday;
3705 mytm.tm_year = year;
3706 mytm.tm_wday = wday;
3707 mytm.tm_yday = yday;
3708 mytm.tm_isdst = isdst;
3710 /* use libc to get the values for tm_gmtoff and tm_zone [perl #18238] */
3711 #if defined(HAS_MKTIME) && (defined(HAS_TM_TM_GMTOFF) || defined(HAS_TM_TM_ZONE))
3716 #ifdef HAS_TM_TM_GMTOFF
3717 mytm.tm_gmtoff = mytm2.tm_gmtoff;
3719 #ifdef HAS_TM_TM_ZONE
3720 mytm.tm_zone = mytm2.tm_zone;
3725 Newx(buf, buflen, char);
3726 len = strftime(buf, buflen, fmt, &mytm);
3728 ** The following is needed to handle to the situation where
3729 ** tmpbuf overflows. Basically we want to allocate a buffer
3730 ** and try repeatedly. The reason why it is so complicated
3731 ** is that getting a return value of 0 from strftime can indicate
3732 ** one of the following:
3733 ** 1. buffer overflowed,
3734 ** 2. illegal conversion specifier, or
3735 ** 3. the format string specifies nothing to be returned(not
3736 ** an error). This could be because format is an empty string
3737 ** or it specifies %p that yields an empty string in some locale.
3738 ** If there is a better way to make it portable, go ahead by
3741 if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
3744 /* Possibly buf overflowed - try again with a bigger buf */
3745 const int fmtlen = strlen(fmt);
3746 const int bufsize = fmtlen + buflen;
3748 Newx(buf, bufsize, char);
3750 buflen = strftime(buf, bufsize, fmt, &mytm);
3751 if (buflen > 0 && buflen < bufsize)
3753 /* heuristic to prevent out-of-memory errors */
3754 if (bufsize > 100*fmtlen) {
3759 Renew(buf, bufsize*2, char);
3764 Perl_croak(aTHX_ "panic: no strftime");
3770 #define SV_CWD_RETURN_UNDEF \
3771 sv_setsv(sv, &PL_sv_undef); \
3774 #define SV_CWD_ISDOT(dp) \
3775 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
3776 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
3779 =head1 Miscellaneous Functions
3781 =for apidoc getcwd_sv
3783 Fill the sv with current working directory
3788 /* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
3789 * rewritten again by dougm, optimized for use with xs TARG, and to prefer
3790 * getcwd(3) if available
3791 * Comments from the orignal:
3792 * This is a faster version of getcwd. It's also more dangerous
3793 * because you might chdir out of a directory that you can't chdir
3797 Perl_getcwd_sv(pTHX_ register SV *sv)
3801 #ifndef INCOMPLETE_TAINTS
3807 char buf[MAXPATHLEN];
3809 /* Some getcwd()s automatically allocate a buffer of the given
3810 * size from the heap if they are given a NULL buffer pointer.
3811 * The problem is that this behaviour is not portable. */
3812 if (getcwd(buf, sizeof(buf) - 1)) {
3817 sv_setsv(sv, &PL_sv_undef);
3825 int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
3829 SvUPGRADE(sv, SVt_PV);
3831 if (PerlLIO_lstat(".", &statbuf) < 0) {
3832 SV_CWD_RETURN_UNDEF;
3835 orig_cdev = statbuf.st_dev;
3836 orig_cino = statbuf.st_ino;
3845 if (PerlDir_chdir("..") < 0) {
3846 SV_CWD_RETURN_UNDEF;
3848 if (PerlLIO_stat(".", &statbuf) < 0) {
3849 SV_CWD_RETURN_UNDEF;
3852 cdev = statbuf.st_dev;
3853 cino = statbuf.st_ino;
3855 if (odev == cdev && oino == cino) {
3858 if (!(dir = PerlDir_open("."))) {
3859 SV_CWD_RETURN_UNDEF;
3862 while ((dp = PerlDir_read(dir)) != NULL) {
3864 const int namelen = dp->d_namlen;
3866 const int namelen = strlen(dp->d_name);
3869 if (SV_CWD_ISDOT(dp)) {
3873 if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
3874 SV_CWD_RETURN_UNDEF;
3877 tdev = statbuf.st_dev;
3878 tino = statbuf.st_ino;
3879 if (tino == oino && tdev == odev) {
3885 SV_CWD_RETURN_UNDEF;
3888 if (pathlen + namelen + 1 >= MAXPATHLEN) {
3889 SV_CWD_RETURN_UNDEF;
3892 SvGROW(sv, pathlen + namelen + 1);
3896 Move(SvPVX_const(sv), SvPVX(sv) + namelen + 1, pathlen, char);
3899 /* prepend current directory to the front */
3901 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
3902 pathlen += (namelen + 1);
3904 #ifdef VOID_CLOSEDIR
3907 if (PerlDir_close(dir) < 0) {
3908 SV_CWD_RETURN_UNDEF;
3914 SvCUR_set(sv, pathlen);
3918 if (PerlDir_chdir(SvPVX_const(sv)) < 0) {
3919 SV_CWD_RETURN_UNDEF;
3922 if (PerlLIO_stat(".", &statbuf) < 0) {
3923 SV_CWD_RETURN_UNDEF;
3926 cdev = statbuf.st_dev;
3927 cino = statbuf.st_ino;
3929 if (cdev != orig_cdev || cino != orig_cino) {
3930 Perl_croak(aTHX_ "Unstable directory path, "
3931 "current directory changed unexpectedly");
3943 =for apidoc scan_version
3945 Returns a pointer to the next character after the parsed
3946 version string, as well as upgrading the passed in SV to
3949 Function must be called with an already existing SV like
3952 s = scan_version(s,SV *sv, bool qv);
3954 Performs some preprocessing to the string to ensure that
3955 it has the correct characteristics of a version. Flags the
3956 object if it contains an underscore (which denotes this
3957 is a alpha version). The boolean qv denotes that the version
3958 should be interpreted as if it had multiple decimals, even if
3965 Perl_scan_version(pTHX_ const char *s, SV *rv, bool qv)
3973 AV * const av = newAV();
3974 SV * const hv = newSVrv(rv, "version"); /* create an SV and upgrade the RV */
3975 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
3977 #ifndef NODEFAULT_SHAREKEYS
3978 HvSHAREKEYS_on(hv); /* key-sharing on by default */
3981 while (isSPACE(*s)) /* leading whitespace is OK */
3985 s++; /* get past 'v' */
3986 qv = 1; /* force quoted version processing */
3989 start = last = pos = s;
3991 /* pre-scan the input string to check for decimals/underbars */
3992 while ( *pos == '.' || *pos == '_' || isDIGIT(*pos) )
3997 Perl_croak(aTHX_ "Invalid version format (underscores before decimal)");
4001 else if ( *pos == '_' )
4004 Perl_croak(aTHX_ "Invalid version format (multiple underscores)");
4006 width = pos - last - 1; /* natural width of sub-version */
4011 if ( alpha && !saw_period )
4012 Perl_croak(aTHX_ "Invalid version format (alpha without decimal)");
4014 if ( saw_period > 1 )
4015 qv = 1; /* force quoted version processing */
4020 hv_store((HV *)hv, "qv", 2, newSViv(qv), 0);
4022 hv_store((HV *)hv, "alpha", 5, newSViv(alpha), 0);
4023 if ( !qv && width < 3 )
4024 hv_store((HV *)hv, "width", 5, newSViv(width), 0);
4026 while (isDIGIT(*pos))
4028 if (!isALPHA(*pos)) {
4034 /* this is atoi() that delimits on underscores */
4035 const char *end = pos;
4039 /* the following if() will only be true after the decimal
4040 * point of a version originally created with a bare
4041 * floating point number, i.e. not quoted in any way
4043 if ( !qv && s > start && saw_period == 1 ) {
4047 rev += (*s - '0') * mult;
4049 if ( PERL_ABS(orev) > PERL_ABS(rev) )
4050 Perl_croak(aTHX_ "Integer overflow in version");
4057 while (--end >= s) {
4059 rev += (*end - '0') * mult;
4061 if ( PERL_ABS(orev) > PERL_ABS(rev) )
4062 Perl_croak(aTHX_ "Integer overflow in version");
4067 /* Append revision */
4068 av_push(av, newSViv(rev));
4069 if ( *pos == '.' && isDIGIT(pos[1]) )
4071 else if ( *pos == '_' && isDIGIT(pos[1]) )
4073 else if ( isDIGIT(*pos) )
4080 while ( isDIGIT(*pos) )
4085 while ( ( isDIGIT(*pos) || *pos == '_' ) && digits < 3 ) {
4093 if ( qv ) { /* quoted versions always get at least three terms*/
4094 I32 len = av_len(av);
4095 /* This for loop appears to trigger a compiler bug on OS X, as it
4096 loops infinitely. Yes, len is negative. No, it makes no sense.
4097 Compiler in question is:
4098 gcc version 3.3 20030304 (Apple Computer, Inc. build 1640)
4099 for ( len = 2 - len; len > 0; len-- )
4100 av_push((AV *)sv, newSViv(0));
4104 av_push(av, newSViv(0));
4107 if ( av_len(av) == -1 ) /* oops, someone forgot to pass a value */
4108 av_push(av, newSViv(0));
4110 /* And finally, store the AV in the hash */
4111 hv_store((HV *)hv, "version", 7, newRV_noinc((SV *)av), 0);
4116 =for apidoc new_version
4118 Returns a new version object based on the passed in SV:
4120 SV *sv = new_version(SV *ver);
4122 Does not alter the passed in ver SV. See "upg_version" if you
4123 want to upgrade the SV.
4129 Perl_new_version(pTHX_ SV *ver)
4132 SV * const rv = newSV(0);
4133 if ( sv_derived_from(ver,"version") ) /* can just copy directly */
4136 AV * const av = newAV();
4138 /* This will get reblessed later if a derived class*/
4139 SV * const hv = newSVrv(rv, "version");
4140 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
4141 #ifndef NODEFAULT_SHAREKEYS
4142 HvSHAREKEYS_on(hv); /* key-sharing on by default */
4148 /* Begin copying all of the elements */
4149 if ( hv_exists((HV *)ver, "qv", 2) )
4150 hv_store((HV *)hv, "qv", 2, &PL_sv_yes, 0);
4152 if ( hv_exists((HV *)ver, "alpha", 5) )
4153 hv_store((HV *)hv, "alpha", 5, &PL_sv_yes, 0);
4155 if ( hv_exists((HV*)ver, "width", 5 ) )
4157 const I32 width = SvIV(*hv_fetchs((HV*)ver, "width", FALSE));
4158 hv_store((HV *)hv, "width", 5, newSViv(width), 0);
4161 sav = (AV *)SvRV(*hv_fetchs((HV*)ver, "version", FALSE));
4162 /* This will get reblessed later if a derived class*/
4163 for ( key = 0; key <= av_len(sav); key++ )
4165 const I32 rev = SvIV(*av_fetch(sav, key, FALSE));
4166 av_push(av, newSViv(rev));
4169 hv_store((HV *)hv, "version", 7, newRV_noinc((SV *)av), 0);
4174 const MAGIC* const mg = SvVOK(ver);
4175 if ( mg ) { /* already a v-string */
4176 const STRLEN len = mg->mg_len;
4177 char * const version = savepvn( (const char*)mg->mg_ptr, len);
4178 sv_setpvn(rv,version,len);
4183 sv_setsv(rv,ver); /* make a duplicate */
4188 return upg_version(rv);
4192 =for apidoc upg_version
4194 In-place upgrade of the supplied SV to a version object.
4196 SV *sv = upg_version(SV *sv);
4198 Returns a pointer to the upgraded SV.
4204 Perl_upg_version(pTHX_ SV *ver)
4206 const char *version, *s;
4212 if ( SvNOK(ver) ) /* may get too much accuracy */
4215 const STRLEN len = my_sprintf(tbuf,"%.9"NVgf, SvNVX(ver));
4216 version = savepvn(tbuf, len);
4219 else if ( (mg = SvVOK(ver)) ) { /* already a v-string */
4220 version = savepvn( (const char*)mg->mg_ptr,mg->mg_len );
4224 else /* must be a string or something like a string */
4226 version = savepv(SvPV_nolen(ver));
4228 s = scan_version(version, ver, qv);
4230 if(ckWARN(WARN_MISC))
4231 Perl_warner(aTHX_ packWARN(WARN_MISC),
4232 "Version string '%s' contains invalid data; "
4233 "ignoring: '%s'", version, s);
4241 Validates that the SV contains a valid version object.
4243 bool vverify(SV *vobj);
4245 Note that it only confirms the bare minimum structure (so as not to get
4246 confused by derived classes which may contain additional hash entries):
4250 =item * The SV contains a [reference to a] hash
4252 =item * The hash contains a "version" key
4254 =item * The "version" key has [a reference to] an AV as its value
4262 Perl_vverify(pTHX_ SV *vs)
4268 /* see if the appropriate elements exist */
4269 if ( SvTYPE(vs) == SVt_PVHV
4270 && hv_exists((HV*)vs, "version", 7)
4271 && (sv = SvRV(*hv_fetchs((HV*)vs, "version", FALSE)))
4272 && SvTYPE(sv) == SVt_PVAV )
4281 Accepts a version object and returns the normalized floating
4282 point representation. Call like:
4286 NOTE: you can pass either the object directly or the SV
4287 contained within the RV.
4293 Perl_vnumify(pTHX_ SV *vs)
4298 SV * const sv = newSV(0);
4304 Perl_croak(aTHX_ "Invalid version object");
4306 /* see if various flags exist */
4307 if ( hv_exists((HV*)vs, "alpha", 5 ) )
4309 if ( hv_exists((HV*)vs, "width", 5 ) )
4310 width = SvIV(*hv_fetchs((HV*)vs, "width", FALSE));
4315 /* attempt to retrieve the version array */
4316 if ( !(av = (AV *)SvRV(*hv_fetchs((HV*)vs, "version", FALSE)) ) ) {
4328 digit = SvIV(*av_fetch(av, 0, 0));
4329 Perl_sv_setpvf(aTHX_ sv, "%d.", (int)PERL_ABS(digit));
4330 for ( i = 1 ; i < len ; i++ )
4332 digit = SvIV(*av_fetch(av, i, 0));
4334 const int denom = (width == 2 ? 10 : 100);
4335 const div_t term = div((int)PERL_ABS(digit),denom);
4336 Perl_sv_catpvf(aTHX_ sv, "%0*d_%d", width, term.quot, term.rem);
4339 Perl_sv_catpvf(aTHX_ sv, "%0*d", width, (int)digit);
4345 digit = SvIV(*av_fetch(av, len, 0));
4346 if ( alpha && width == 3 ) /* alpha version */
4348 Perl_sv_catpvf(aTHX_ sv, "%0*d", width, (int)digit);
4352 sv_catpvs(sv, "000");
4360 Accepts a version object and returns the normalized string
4361 representation. Call like:
4365 NOTE: you can pass either the object directly or the SV
4366 contained within the RV.
4372 Perl_vnormal(pTHX_ SV *vs)
4376 SV * const sv = newSV(0);
4382 Perl_croak(aTHX_ "Invalid version object");
4384 if ( hv_exists((HV*)vs, "alpha", 5 ) )
4386 av = (AV *)SvRV(*hv_fetchs((HV*)vs, "version", FALSE));
4394 digit = SvIV(*av_fetch(av, 0, 0));
4395 Perl_sv_setpvf(aTHX_ sv, "v%"IVdf, (IV)digit);
4396 for ( i = 1 ; i < len ; i++ ) {
4397 digit = SvIV(*av_fetch(av, i, 0));
4398 Perl_sv_catpvf(aTHX_ sv, ".%"IVdf, (IV)digit);
4403 /* handle last digit specially */
4404 digit = SvIV(*av_fetch(av, len, 0));
4406 Perl_sv_catpvf(aTHX_ sv, "_%"IVdf, (IV)digit);
4408 Perl_sv_catpvf(aTHX_ sv, ".%"IVdf, (IV)digit);
4411 if ( len <= 2 ) { /* short version, must be at least three */
4412 for ( len = 2 - len; len != 0; len-- )
4419 =for apidoc vstringify
4421 In order to maintain maximum compatibility with earlier versions
4422 of Perl, this function will return either the floating point
4423 notation or the multiple dotted notation, depending on whether
4424 the original version contained 1 or more dots, respectively
4430 Perl_vstringify(pTHX_ SV *vs)
4436 Perl_croak(aTHX_ "Invalid version object");
4438 if ( hv_exists((HV *)vs, "qv", 2) )
4447 Version object aware cmp. Both operands must already have been
4448 converted into version objects.
4454 Perl_vcmp(pTHX_ SV *lhv, SV *rhv)
4457 bool lalpha = FALSE;
4458 bool ralpha = FALSE;
4467 if ( !vverify(lhv) )
4468 Perl_croak(aTHX_ "Invalid version object");
4470 if ( !vverify(rhv) )
4471 Perl_croak(aTHX_ "Invalid version object");
4473 /* get the left hand term */
4474 lav = (AV *)SvRV(*hv_fetchs((HV*)lhv, "version", FALSE));
4475 if ( hv_exists((HV*)lhv, "alpha", 5 ) )
4478 /* and the right hand term */
4479 rav = (AV *)SvRV(*hv_fetchs((HV*)rhv, "version", FALSE));
4480 if ( hv_exists((HV*)rhv, "alpha", 5 ) )
4488 while ( i <= m && retval == 0 )
4490 left = SvIV(*av_fetch(lav,i,0));
4491 right = SvIV(*av_fetch(rav,i,0));
4499 /* tiebreaker for alpha with identical terms */
4500 if ( retval == 0 && l == r && left == right && ( lalpha || ralpha ) )
4502 if ( lalpha && !ralpha )
4506 else if ( ralpha && !lalpha)
4512 if ( l != r && retval == 0 ) /* possible match except for trailing 0's */
4516 while ( i <= r && retval == 0 )
4518 if ( SvIV(*av_fetch(rav,i,0)) != 0 )
4519 retval = -1; /* not a match after all */
4525 while ( i <= l && retval == 0 )
4527 if ( SvIV(*av_fetch(lav,i,0)) != 0 )
4528 retval = +1; /* not a match after all */
4536 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET) && defined(SOCK_DGRAM) && defined(HAS_SELECT)
4537 # define EMULATE_SOCKETPAIR_UDP
4540 #ifdef EMULATE_SOCKETPAIR_UDP
4542 S_socketpair_udp (int fd[2]) {
4544 /* Fake a datagram socketpair using UDP to localhost. */
4545 int sockets[2] = {-1, -1};
4546 struct sockaddr_in addresses[2];
4548 Sock_size_t size = sizeof(struct sockaddr_in);
4549 unsigned short port;
4552 memset(&addresses, 0, sizeof(addresses));
4555 sockets[i] = PerlSock_socket(AF_INET, SOCK_DGRAM, PF_INET);
4556 if (sockets[i] == -1)
4557 goto tidy_up_and_fail;
4559 addresses[i].sin_family = AF_INET;
4560 addresses[i].sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4561 addresses[i].sin_port = 0; /* kernel choses port. */
4562 if (PerlSock_bind(sockets[i], (struct sockaddr *) &addresses[i],
4563 sizeof(struct sockaddr_in)) == -1)
4564 goto tidy_up_and_fail;
4567 /* Now have 2 UDP sockets. Find out which port each is connected to, and
4568 for each connect the other socket to it. */
4571 if (PerlSock_getsockname(sockets[i], (struct sockaddr *) &addresses[i],
4573 goto tidy_up_and_fail;
4574 if (size != sizeof(struct sockaddr_in))
4575 goto abort_tidy_up_and_fail;
4576 /* !1 is 0, !0 is 1 */
4577 if (PerlSock_connect(sockets[!i], (struct sockaddr *) &addresses[i],
4578 sizeof(struct sockaddr_in)) == -1)
4579 goto tidy_up_and_fail;
4582 /* Now we have 2 sockets connected to each other. I don't trust some other
4583 process not to have already sent a packet to us (by random) so send
4584 a packet from each to the other. */
4587 /* I'm going to send my own port number. As a short.
4588 (Who knows if someone somewhere has sin_port as a bitfield and needs
4589 this routine. (I'm assuming crays have socketpair)) */
4590 port = addresses[i].sin_port;
4591 got = PerlLIO_write(sockets[i], &port, sizeof(port));
4592 if (got != sizeof(port)) {
4594 goto tidy_up_and_fail;
4595 goto abort_tidy_up_and_fail;
4599 /* Packets sent. I don't trust them to have arrived though.
4600 (As I understand it Solaris TCP stack is multithreaded. Non-blocking
4601 connect to localhost will use a second kernel thread. In 2.6 the
4602 first thread running the connect() returns before the second completes,
4603 so EINPROGRESS> In 2.7 the improved stack is faster and connect()
4604 returns 0. Poor programs have tripped up. One poor program's authors'
4605 had a 50-1 reverse stock split. Not sure how connected these were.)
4606 So I don't trust someone not to have an unpredictable UDP stack.
4610 struct timeval waitfor = {0, 100000}; /* You have 0.1 seconds */
4611 int max = sockets[1] > sockets[0] ? sockets[1] : sockets[0];
4615 FD_SET((unsigned int)sockets[0], &rset);
4616 FD_SET((unsigned int)sockets[1], &rset);
4618 got = PerlSock_select(max + 1, &rset, NULL, NULL, &waitfor);
4619 if (got != 2 || !FD_ISSET(sockets[0], &rset)
4620 || !FD_ISSET(sockets[1], &rset)) {
4621 /* I hope this is portable and appropriate. */
4623 goto tidy_up_and_fail;
4624 goto abort_tidy_up_and_fail;
4628 /* And the paranoia department even now doesn't trust it to have arrive
4629 (hence MSG_DONTWAIT). Or that what arrives was sent by us. */
4631 struct sockaddr_in readfrom;
4632 unsigned short buffer[2];
4637 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4638 sizeof(buffer), MSG_DONTWAIT,
4639 (struct sockaddr *) &readfrom, &size);
4641 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4643 (struct sockaddr *) &readfrom, &size);
4647 goto tidy_up_and_fail;
4648 if (got != sizeof(port)
4649 || size != sizeof(struct sockaddr_in)
4650 /* Check other socket sent us its port. */
4651 || buffer[0] != (unsigned short) addresses[!i].sin_port
4652 /* Check kernel says we got the datagram from that socket */
4653 || readfrom.sin_family != addresses[!i].sin_family
4654 || readfrom.sin_addr.s_addr != addresses[!i].sin_addr.s_addr
4655 || readfrom.sin_port != addresses[!i].sin_port)
4656 goto abort_tidy_up_and_fail;
4659 /* My caller (my_socketpair) has validated that this is non-NULL */
4662 /* I hereby declare this connection open. May God bless all who cross
4666 abort_tidy_up_and_fail:
4667 errno = ECONNABORTED;
4670 const int save_errno = errno;
4671 if (sockets[0] != -1)
4672 PerlLIO_close(sockets[0]);
4673 if (sockets[1] != -1)
4674 PerlLIO_close(sockets[1]);
4679 #endif /* EMULATE_SOCKETPAIR_UDP */
4681 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET)
4683 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4684 /* Stevens says that family must be AF_LOCAL, protocol 0.
4685 I'm going to enforce that, then ignore it, and use TCP (or UDP). */
4690 struct sockaddr_in listen_addr;
4691 struct sockaddr_in connect_addr;
4696 || family != AF_UNIX
4699 errno = EAFNOSUPPORT;
4707 #ifdef EMULATE_SOCKETPAIR_UDP
4708 if (type == SOCK_DGRAM)
4709 return S_socketpair_udp(fd);
4712 listener = PerlSock_socket(AF_INET, type, 0);
4715 memset(&listen_addr, 0, sizeof(listen_addr));
4716 listen_addr.sin_family = AF_INET;
4717 listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4718 listen_addr.sin_port = 0; /* kernel choses port. */
4719 if (PerlSock_bind(listener, (struct sockaddr *) &listen_addr,
4720 sizeof(listen_addr)) == -1)
4721 goto tidy_up_and_fail;
4722 if (PerlSock_listen(listener, 1) == -1)
4723 goto tidy_up_and_fail;
4725 connector = PerlSock_socket(AF_INET, type, 0);
4726 if (connector == -1)
4727 goto tidy_up_and_fail;
4728 /* We want to find out the port number to connect to. */
4729 size = sizeof(connect_addr);
4730 if (PerlSock_getsockname(listener, (struct sockaddr *) &connect_addr,
4732 goto tidy_up_and_fail;
4733 if (size != sizeof(connect_addr))
4734 goto abort_tidy_up_and_fail;
4735 if (PerlSock_connect(connector, (struct sockaddr *) &connect_addr,
4736 sizeof(connect_addr)) == -1)
4737 goto tidy_up_and_fail;
4739 size = sizeof(listen_addr);
4740 acceptor = PerlSock_accept(listener, (struct sockaddr *) &listen_addr,
4743 goto tidy_up_and_fail;
4744 if (size != sizeof(listen_addr))
4745 goto abort_tidy_up_and_fail;
4746 PerlLIO_close(listener);
4747 /* Now check we are talking to ourself by matching port and host on the
4749 if (PerlSock_getsockname(connector, (struct sockaddr *) &connect_addr,
4751 goto tidy_up_and_fail;
4752 if (size != sizeof(connect_addr)
4753 || listen_addr.sin_family != connect_addr.sin_family
4754 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
4755 || listen_addr.sin_port != connect_addr.sin_port) {
4756 goto abort_tidy_up_and_fail;
4762 abort_tidy_up_and_fail:
4764 errno = ECONNABORTED; /* This would be the standard thing to do. */
4766 # ifdef ECONNREFUSED
4767 errno = ECONNREFUSED; /* E.g. Symbian does not have ECONNABORTED. */
4769 errno = ETIMEDOUT; /* Desperation time. */
4774 const int save_errno = errno;
4776 PerlLIO_close(listener);
4777 if (connector != -1)
4778 PerlLIO_close(connector);
4780 PerlLIO_close(acceptor);
4786 /* In any case have a stub so that there's code corresponding
4787 * to the my_socketpair in global.sym. */
4789 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4790 #ifdef HAS_SOCKETPAIR
4791 return socketpair(family, type, protocol, fd);
4800 =for apidoc sv_nosharing
4802 Dummy routine which "shares" an SV when there is no sharing module present.
4803 Or "locks" it. Or "unlocks" it. In other words, ignores its single SV argument.
4804 Exists to avoid test for a NULL function pointer and because it could
4805 potentially warn under some level of strict-ness.
4811 Perl_sv_nosharing(pTHX_ SV *sv)
4813 PERL_UNUSED_ARG(sv);
4817 Perl_parse_unicode_opts(pTHX_ const char **popt)
4819 const char *p = *popt;
4824 opt = (U32) atoi(p);
4825 while (isDIGIT(*p)) p++;
4826 if (*p && *p != '\n' && *p != '\r')
4827 Perl_croak(aTHX_ "Unknown Unicode option letter '%c'", *p);
4832 case PERL_UNICODE_STDIN:
4833 opt |= PERL_UNICODE_STDIN_FLAG; break;
4834 case PERL_UNICODE_STDOUT:
4835 opt |= PERL_UNICODE_STDOUT_FLAG; break;
4836 case PERL_UNICODE_STDERR:
4837 opt |= PERL_UNICODE_STDERR_FLAG; break;
4838 case PERL_UNICODE_STD:
4839 opt |= PERL_UNICODE_STD_FLAG; break;
4840 case PERL_UNICODE_IN:
4841 opt |= PERL_UNICODE_IN_FLAG; break;
4842 case PERL_UNICODE_OUT:
4843 opt |= PERL_UNICODE_OUT_FLAG; break;
4844 case PERL_UNICODE_INOUT:
4845 opt |= PERL_UNICODE_INOUT_FLAG; break;
4846 case PERL_UNICODE_LOCALE:
4847 opt |= PERL_UNICODE_LOCALE_FLAG; break;
4848 case PERL_UNICODE_ARGV:
4849 opt |= PERL_UNICODE_ARGV_FLAG; break;
4851 if (*p != '\n' && *p != '\r')
4853 "Unknown Unicode option letter '%c'", *p);
4859 opt = PERL_UNICODE_DEFAULT_FLAGS;
4861 if (opt & ~PERL_UNICODE_ALL_FLAGS)
4862 Perl_croak(aTHX_ "Unknown Unicode option value %"UVuf,
4863 (UV) (opt & ~PERL_UNICODE_ALL_FLAGS));
4875 * This is really just a quick hack which grabs various garbage
4876 * values. It really should be a real hash algorithm which
4877 * spreads the effect of every input bit onto every output bit,
4878 * if someone who knows about such things would bother to write it.
4879 * Might be a good idea to add that function to CORE as well.
4880 * No numbers below come from careful analysis or anything here,
4881 * except they are primes and SEED_C1 > 1E6 to get a full-width
4882 * value from (tv_sec * SEED_C1 + tv_usec). The multipliers should
4883 * probably be bigger too.
4886 # define SEED_C1 1000003
4887 #define SEED_C4 73819
4889 # define SEED_C1 25747
4890 #define SEED_C4 20639
4894 #define SEED_C5 26107
4896 #ifndef PERL_NO_DEV_RANDOM
4901 # include <starlet.h>
4902 /* when[] = (low 32 bits, high 32 bits) of time since epoch
4903 * in 100-ns units, typically incremented ever 10 ms. */
4904 unsigned int when[2];
4906 # ifdef HAS_GETTIMEOFDAY
4907 struct timeval when;
4913 /* This test is an escape hatch, this symbol isn't set by Configure. */
4914 #ifndef PERL_NO_DEV_RANDOM
4915 #ifndef PERL_RANDOM_DEVICE
4916 /* /dev/random isn't used by default because reads from it will block
4917 * if there isn't enough entropy available. You can compile with
4918 * PERL_RANDOM_DEVICE to it if you'd prefer Perl to block until there
4919 * is enough real entropy to fill the seed. */
4920 # define PERL_RANDOM_DEVICE "/dev/urandom"
4922 fd = PerlLIO_open(PERL_RANDOM_DEVICE, 0);
4924 if (PerlLIO_read(fd, (void*)&u, sizeof u) != sizeof u)
4933 _ckvmssts(sys$gettim(when));
4934 u = (U32)SEED_C1 * when[0] + (U32)SEED_C2 * when[1];
4936 # ifdef HAS_GETTIMEOFDAY
4937 PerlProc_gettimeofday(&when,NULL);
4938 u = (U32)SEED_C1 * when.tv_sec + (U32)SEED_C2 * when.tv_usec;
4941 u = (U32)SEED_C1 * when;
4944 u += SEED_C3 * (U32)PerlProc_getpid();
4945 u += SEED_C4 * (U32)PTR2UV(PL_stack_sp);
4946 #ifndef PLAN9 /* XXX Plan9 assembler chokes on this; fix needed */
4947 u += SEED_C5 * (U32)PTR2UV(&when);
4953 Perl_get_hash_seed(pTHX)
4956 const char *s = PerlEnv_getenv("PERL_HASH_SEED");
4960 while (isSPACE(*s)) s++;
4961 if (s && isDIGIT(*s))
4962 myseed = (UV)Atoul(s);
4964 #ifdef USE_HASH_SEED_EXPLICIT
4968 /* Compute a random seed */
4969 (void)seedDrand01((Rand_seed_t)seed());
4970 myseed = (UV)(Drand01() * (NV)UV_MAX);
4971 #if RANDBITS < (UVSIZE * 8)
4972 /* Since there are not enough randbits to to reach all
4973 * the bits of a UV, the low bits might need extra
4974 * help. Sum in another random number that will
4975 * fill in the low bits. */
4977 (UV)(Drand01() * (NV)((1 << ((UVSIZE * 8 - RANDBITS))) - 1));
4978 #endif /* RANDBITS < (UVSIZE * 8) */
4979 if (myseed == 0) { /* Superparanoia. */
4980 myseed = (UV)(Drand01() * (NV)UV_MAX); /* One more chance. */
4982 Perl_croak(aTHX_ "Your random numbers are not that random");
4985 PL_rehash_seed_set = TRUE;
4992 Perl_stashpv_hvname_match(pTHX_ const COP *c, const HV *hv)
4994 const char * const stashpv = CopSTASHPV(c);
4995 const char * const name = HvNAME_get(hv);
4997 if (stashpv == name)
4999 if (stashpv && name)
5000 if (strEQ(stashpv, name))
5007 #ifdef PERL_GLOBAL_STRUCT
5010 Perl_init_global_struct(pTHX)
5012 struct perl_vars *plvarsp = NULL;
5013 #ifdef PERL_GLOBAL_STRUCT
5014 # define PERL_GLOBAL_STRUCT_INIT
5015 # include "opcode.h" /* the ppaddr and check */
5016 const IV nppaddr = sizeof(Gppaddr)/sizeof(Perl_ppaddr_t);
5017 const IV ncheck = sizeof(Gcheck) /sizeof(Perl_check_t);
5018 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
5019 /* PerlMem_malloc() because can't use even safesysmalloc() this early. */
5020 plvarsp = (struct perl_vars*)PerlMem_malloc(sizeof(struct perl_vars));
5024 plvarsp = PL_VarsPtr;
5025 # endif /* PERL_GLOBAL_STRUCT_PRIVATE */
5031 # define PERLVAR(var,type) /**/
5032 # define PERLVARA(var,n,type) /**/
5033 # define PERLVARI(var,type,init) plvarsp->var = init;
5034 # define PERLVARIC(var,type,init) plvarsp->var = init;
5035 # define PERLVARISC(var,init) Copy(init, plvarsp->var, sizeof(init), char);