3 * Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999,
4 * 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 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 *const header
98 = (struct perl_memory_debug_header *)ptr;
102 PoisonNew(((char *)ptr), size, char);
105 #ifdef PERL_TRACK_MEMPOOL
106 header->interpreter = aTHX;
107 /* Link us into the list. */
108 header->prev = &PL_memory_debug_header;
109 header->next = PL_memory_debug_header.next;
110 PL_memory_debug_header.next = header;
111 header->next->prev = header;
115 ptr = (Malloc_t)((char*)ptr+sTHX);
122 return write_no_mem();
127 /* paranoid version of system's realloc() */
130 Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
134 #if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) && !defined(PERL_MICRO)
135 Malloc_t PerlMem_realloc();
136 #endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
140 PerlIO_printf(Perl_error_log,
141 "Reallocation too large: %lx\n", size) FLUSH;
144 #endif /* HAS_64K_LIMIT */
151 return safesysmalloc(size);
152 #ifdef PERL_TRACK_MEMPOOL
153 where = (Malloc_t)((char*)where-sTHX);
156 struct perl_memory_debug_header *const header
157 = (struct perl_memory_debug_header *)where;
159 if (header->interpreter != aTHX) {
160 Perl_croak_nocontext("panic: realloc from wrong pool");
162 assert(header->next->prev == header);
163 assert(header->prev->next == header);
165 if (header->size > size) {
166 const MEM_SIZE freed_up = header->size - size;
167 char *start_of_freed = ((char *)where) + size;
168 PoisonFree(start_of_freed, freed_up, char);
176 Perl_croak_nocontext("panic: realloc");
178 ptr = (Malloc_t)PerlMem_realloc(where,size);
179 PERL_ALLOC_CHECK(ptr);
181 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) rfree\n",PTR2UV(where),(long)PL_an++));
182 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) realloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
185 #ifdef PERL_TRACK_MEMPOOL
186 struct perl_memory_debug_header *const header
187 = (struct perl_memory_debug_header *)ptr;
190 if (header->size < size) {
191 const MEM_SIZE fresh = size - header->size;
192 char *start_of_fresh = ((char *)ptr) + size;
193 PoisonNew(start_of_fresh, fresh, char);
197 header->next->prev = header;
198 header->prev->next = header;
200 ptr = (Malloc_t)((char*)ptr+sTHX);
207 return write_no_mem();
212 /* safe version of system's free() */
215 Perl_safesysfree(Malloc_t where)
217 #if defined(PERL_IMPLICIT_SYS) || defined(PERL_TRACK_MEMPOOL)
222 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) free\n",PTR2UV(where),(long)PL_an++));
224 #ifdef PERL_TRACK_MEMPOOL
225 where = (Malloc_t)((char*)where-sTHX);
227 struct perl_memory_debug_header *const header
228 = (struct perl_memory_debug_header *)where;
230 if (header->interpreter != aTHX) {
231 Perl_croak_nocontext("panic: free from wrong pool");
234 Perl_croak_nocontext("panic: duplicate free");
236 if (!(header->next) || header->next->prev != header
237 || header->prev->next != header) {
238 Perl_croak_nocontext("panic: bad free");
240 /* Unlink us from the chain. */
241 header->next->prev = header->prev;
242 header->prev->next = header->next;
244 PoisonNew(where, header->size, char);
246 /* Trigger the duplicate free warning. */
254 /* safe version of system's calloc() */
257 Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
263 if (size * count > 0xffff) {
264 PerlIO_printf(Perl_error_log,
265 "Allocation too large: %lx\n", size * count) FLUSH;
268 #endif /* HAS_64K_LIMIT */
270 if ((long)size < 0 || (long)count < 0)
271 Perl_croak_nocontext("panic: calloc");
274 #ifdef PERL_TRACK_MEMPOOL
277 ptr = (Malloc_t)PerlMem_malloc(size?size:1); /* malloc(0) is NASTY on our system */
278 PERL_ALLOC_CHECK(ptr);
279 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));
281 memset((void*)ptr, 0, size);
282 #ifdef PERL_TRACK_MEMPOOL
284 struct perl_memory_debug_header *const header
285 = (struct perl_memory_debug_header *)ptr;
287 header->interpreter = aTHX;
288 /* Link us into the list. */
289 header->prev = &PL_memory_debug_header;
290 header->next = PL_memory_debug_header.next;
291 PL_memory_debug_header.next = header;
292 header->next->prev = header;
296 ptr = (Malloc_t)((char*)ptr+sTHX);
303 return write_no_mem();
306 /* These must be defined when not using Perl's malloc for binary
311 Malloc_t Perl_malloc (MEM_SIZE nbytes)
314 return (Malloc_t)PerlMem_malloc(nbytes);
317 Malloc_t Perl_calloc (MEM_SIZE elements, MEM_SIZE size)
320 return (Malloc_t)PerlMem_calloc(elements, size);
323 Malloc_t Perl_realloc (Malloc_t where, MEM_SIZE nbytes)
326 return (Malloc_t)PerlMem_realloc(where, nbytes);
329 Free_t Perl_mfree (Malloc_t where)
337 /* copy a string up to some (non-backslashed) delimiter, if any */
340 Perl_delimcpy(pTHX_ register char *to, register const char *toend, register const char *from, register const char *fromend, register int delim, I32 *retlen)
345 for (tolen = 0; from < fromend; from++, tolen++) {
347 if (from[1] != delim) {
354 else if (*from == delim)
365 /* return ptr to little string in big string, NULL if not found */
366 /* This routine was donated by Corey Satten. */
369 Perl_instr(pTHX_ register const char *big, register const char *little)
380 register const char *s, *x;
383 for (x=big,s=little; *s; /**/ ) {
394 return (char*)(big-1);
399 /* same as instr but allow embedded nulls */
402 Perl_ninstr(pTHX_ const char *big, const char *bigend, const char *little, const char *lend)
408 char first = *little++;
410 bigend -= lend - little;
412 while (big <= bigend) {
415 for (x=big,s=little; s < lend; x++,s++) {
419 return (char*)(big-1);
425 /* reverse of the above--find last substring */
428 Perl_rninstr(pTHX_ register const char *big, const char *bigend, const char *little, const char *lend)
430 register const char *bigbeg;
431 register const I32 first = *little;
432 register const char * const littleend = lend;
435 if (little >= littleend)
436 return (char*)bigend;
438 big = bigend - (littleend - little++);
439 while (big >= bigbeg) {
440 register const char *s, *x;
443 for (x=big+2,s=little; s < littleend; /**/ ) {
452 return (char*)(big+1);
457 /* As a space optimization, we do not compile tables for strings of length
458 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
459 special-cased in fbm_instr().
461 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
464 =head1 Miscellaneous Functions
466 =for apidoc fbm_compile
468 Analyses the string in order to make fast searches on it using fbm_instr()
469 -- the Boyer-Moore algorithm.
475 Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
478 register const U8 *s;
484 if (flags & FBMcf_TAIL) {
485 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL;
486 sv_catpvs(sv, "\n"); /* Taken into account in fbm_instr() */
487 if (mg && mg->mg_len >= 0)
490 s = (U8*)SvPV_force_mutable(sv, len);
491 if (len == 0) /* TAIL might be on a zero-length string. */
493 SvUPGRADE(sv, SVt_PVGV);
498 const unsigned char *sb;
499 const U8 mlen = (len>255) ? 255 : (U8)len;
502 Sv_Grow(sv, len + 256 + PERL_FBM_TABLE_OFFSET);
504 = (unsigned char*)(SvPVX_mutable(sv) + len + PERL_FBM_TABLE_OFFSET);
505 s = table - 1 - PERL_FBM_TABLE_OFFSET; /* last char */
506 memset((void*)table, mlen, 256);
508 sb = s - mlen + 1; /* first char (maybe) */
510 if (table[*s] == mlen)
515 Sv_Grow(sv, len + PERL_FBM_TABLE_OFFSET);
517 sv_magic(sv, NULL, PERL_MAGIC_bm, NULL, 0); /* deep magic */
519 s = (const unsigned char*)(SvPVX_const(sv)); /* deeper magic */
520 for (i = 0; i < len; i++) {
521 if (PL_freq[s[i]] < frequency) {
523 frequency = PL_freq[s[i]];
526 BmFLAGS(sv) = (U8)flags;
527 BmRARE(sv) = s[rarest];
528 BmPREVIOUS(sv) = rarest;
529 BmUSEFUL(sv) = 100; /* Initial value */
530 if (flags & FBMcf_TAIL)
532 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %lu\n",
533 BmRARE(sv),(unsigned long)BmPREVIOUS(sv)));
536 /* If SvTAIL(littlestr), it has a fake '\n' at end. */
537 /* If SvTAIL is actually due to \Z or \z, this gives false positives
541 =for apidoc fbm_instr
543 Returns the location of the SV in the string delimited by C<str> and
544 C<strend>. It returns C<NULL> if the string can't be found. The C<sv>
545 does not have to be fbm_compiled, but the search will not be as fast
552 Perl_fbm_instr(pTHX_ unsigned char *big, register unsigned char *bigend, SV *littlestr, U32 flags)
554 register unsigned char *s;
556 register const unsigned char *little
557 = (const unsigned char *)SvPV_const(littlestr,l);
558 register STRLEN littlelen = l;
559 register const I32 multiline = flags & FBMrf_MULTILINE;
561 if ((STRLEN)(bigend - big) < littlelen) {
562 if ( SvTAIL(littlestr)
563 && ((STRLEN)(bigend - big) == littlelen - 1)
565 || (*big == *little &&
566 memEQ((char *)big, (char *)little, littlelen - 1))))
571 if (littlelen <= 2) { /* Special-cased */
573 if (littlelen == 1) {
574 if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
575 /* Know that bigend != big. */
576 if (bigend[-1] == '\n')
577 return (char *)(bigend - 1);
578 return (char *) bigend;
586 if (SvTAIL(littlestr))
587 return (char *) bigend;
591 return (char*)big; /* Cannot be SvTAIL! */
594 if (SvTAIL(littlestr) && !multiline) {
595 if (bigend[-1] == '\n' && bigend[-2] == *little)
596 return (char*)bigend - 2;
597 if (bigend[-1] == *little)
598 return (char*)bigend - 1;
602 /* This should be better than FBM if c1 == c2, and almost
603 as good otherwise: maybe better since we do less indirection.
604 And we save a lot of memory by caching no table. */
605 const unsigned char c1 = little[0];
606 const unsigned char c2 = little[1];
611 while (s <= bigend) {
621 goto check_1char_anchor;
632 goto check_1char_anchor;
635 while (s <= bigend) {
640 goto check_1char_anchor;
649 check_1char_anchor: /* One char and anchor! */
650 if (SvTAIL(littlestr) && (*bigend == *little))
651 return (char *)bigend; /* bigend is already decremented. */
654 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
655 s = bigend - littlelen;
656 if (s >= big && bigend[-1] == '\n' && *s == *little
657 /* Automatically of length > 2 */
658 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
660 return (char*)s; /* how sweet it is */
663 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
665 return (char*)s + 1; /* how sweet it is */
669 if (!SvVALID(littlestr)) {
670 char * const b = ninstr((char*)big,(char*)bigend,
671 (char*)little, (char*)little + littlelen);
673 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
674 /* Chop \n from littlestr: */
675 s = bigend - littlelen + 1;
677 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
687 if (littlelen > (STRLEN)(bigend - big))
691 register const unsigned char * const table
692 = little + littlelen + PERL_FBM_TABLE_OFFSET;
693 register const unsigned char *oldlittle;
695 --littlelen; /* Last char found by table lookup */
698 little += littlelen; /* last char */
704 if ((tmp = table[*s])) {
705 if ((s += tmp) < bigend)
709 else { /* less expensive than calling strncmp() */
710 register unsigned char * const olds = s;
715 if (*--s == *--little)
717 s = olds + 1; /* here we pay the price for failure */
719 if (s < bigend) /* fake up continue to outer loop */
728 && (BmFLAGS(littlestr) & FBMcf_TAIL)
729 && memEQ((char *)(bigend - littlelen),
730 (char *)(oldlittle - littlelen), littlelen) )
731 return (char*)bigend - littlelen;
736 /* start_shift, end_shift are positive quantities which give offsets
737 of ends of some substring of bigstr.
738 If "last" we want the last occurrence.
739 old_posp is the way of communication between consequent calls if
740 the next call needs to find the .
741 The initial *old_posp should be -1.
743 Note that we take into account SvTAIL, so one can get extra
744 optimizations if _ALL flag is set.
747 /* If SvTAIL is actually due to \Z or \z, this gives false positives
748 if PL_multiline. In fact if !PL_multiline the authoritative answer
749 is not supported yet. */
752 Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
755 register const unsigned char *big;
757 register I32 previous;
759 register const unsigned char *little;
760 register I32 stop_pos;
761 register const unsigned char *littleend;
764 assert(SvTYPE(littlestr) == SVt_PVGV);
765 assert(SvVALID(littlestr));
768 ? (pos = PL_screamfirst[BmRARE(littlestr)]) < 0
769 : (((pos = *old_posp), pos += PL_screamnext[pos]) == 0)) {
771 if ( BmRARE(littlestr) == '\n'
772 && BmPREVIOUS(littlestr) == SvCUR(littlestr) - 1) {
773 little = (const unsigned char *)(SvPVX_const(littlestr));
774 littleend = little + SvCUR(littlestr);
781 little = (const unsigned char *)(SvPVX_const(littlestr));
782 littleend = little + SvCUR(littlestr);
784 /* The value of pos we can start at: */
785 previous = BmPREVIOUS(littlestr);
786 big = (const unsigned char *)(SvPVX_const(bigstr));
787 /* The value of pos we can stop at: */
788 stop_pos = SvCUR(bigstr) - end_shift - (SvCUR(littlestr) - 1 - previous);
789 if (previous + start_shift > stop_pos) {
791 stop_pos does not include SvTAIL in the count, so this check is incorrect
792 (I think) - see [ID 20010618.006] and t/op/study.t. HVDS 2001/06/19
795 if (previous + start_shift == stop_pos + 1) /* A fake '\n'? */
800 while (pos < previous + start_shift) {
801 if (!(pos += PL_screamnext[pos]))
806 register const unsigned char *s, *x;
807 if (pos >= stop_pos) break;
808 if (big[pos] != first)
810 for (x=big+pos+1,s=little; s < littleend; /**/ ) {
816 if (s == littleend) {
818 if (!last) return (char *)(big+pos);
821 } while ( pos += PL_screamnext[pos] );
823 return (char *)(big+(*old_posp));
825 if (!SvTAIL(littlestr) || (end_shift > 0))
827 /* Ignore the trailing "\n". This code is not microoptimized */
828 big = (const unsigned char *)(SvPVX_const(bigstr) + SvCUR(bigstr));
829 stop_pos = littleend - little; /* Actual littlestr len */
834 && ((stop_pos == 1) ||
835 memEQ((char *)(big + 1), (char *)little, stop_pos - 1)))
841 Perl_ibcmp(pTHX_ const char *s1, const char *s2, register I32 len)
843 register const U8 *a = (const U8 *)s1;
844 register const U8 *b = (const U8 *)s2;
848 if (*a != *b && *a != PL_fold[*b])
856 Perl_ibcmp_locale(pTHX_ const char *s1, const char *s2, register I32 len)
859 register const U8 *a = (const U8 *)s1;
860 register const U8 *b = (const U8 *)s2;
864 if (*a != *b && *a != PL_fold_locale[*b])
871 /* copy a string to a safe spot */
874 =head1 Memory Management
878 Perl's version of C<strdup()>. Returns a pointer to a newly allocated
879 string which is a duplicate of C<pv>. The size of the string is
880 determined by C<strlen()>. The memory allocated for the new string can
881 be freed with the C<Safefree()> function.
887 Perl_savepv(pTHX_ const char *pv)
894 const STRLEN pvlen = strlen(pv)+1;
895 Newx(newaddr, pvlen, char);
896 return (char*)memcpy(newaddr, pv, pvlen);
900 /* same thing but with a known length */
905 Perl's version of what C<strndup()> would be if it existed. Returns a
906 pointer to a newly allocated string which is a duplicate of the first
907 C<len> bytes from C<pv>, plus a trailing NUL byte. The memory allocated for
908 the new string can be freed with the C<Safefree()> function.
914 Perl_savepvn(pTHX_ const char *pv, register I32 len)
916 register char *newaddr;
919 Newx(newaddr,len+1,char);
920 /* Give a meaning to NULL pointer mainly for the use in sv_magic() */
922 /* might not be null terminated */
924 return (char *) CopyD(pv,newaddr,len,char);
927 return (char *) ZeroD(newaddr,len+1,char);
932 =for apidoc savesharedpv
934 A version of C<savepv()> which allocates the duplicate string in memory
935 which is shared between threads.
940 Perl_savesharedpv(pTHX_ const char *pv)
942 register char *newaddr;
947 pvlen = strlen(pv)+1;
948 newaddr = (char*)PerlMemShared_malloc(pvlen);
950 return write_no_mem();
952 return (char*)memcpy(newaddr, pv, pvlen);
956 =for apidoc savesharedpvn
958 A version of C<savepvn()> which allocates the duplicate string in memory
959 which is shared between threads. (With the specific difference that a NULL
960 pointer is not acceptable)
965 Perl_savesharedpvn(pTHX_ const char *const pv, const STRLEN len)
967 char *const newaddr = (char*)PerlMemShared_malloc(len + 1);
970 return write_no_mem();
973 return (char*)memcpy(newaddr, pv, len);
979 A version of C<savepv()>/C<savepvn()> which gets the string to duplicate from
980 the passed in SV using C<SvPV()>
986 Perl_savesvpv(pTHX_ SV *sv)
989 const char * const pv = SvPV_const(sv, len);
990 register char *newaddr;
993 Newx(newaddr,len,char);
994 return (char *) CopyD(pv,newaddr,len,char);
998 /* the SV for Perl_form() and mess() is not kept in an arena */
1008 return sv_2mortal(newSVpvs(""));
1013 /* Create as PVMG now, to avoid any upgrading later */
1015 Newxz(any, 1, XPVMG);
1016 SvFLAGS(sv) = SVt_PVMG;
1017 SvANY(sv) = (void*)any;
1019 SvREFCNT(sv) = 1 << 30; /* practically infinite */
1024 #if defined(PERL_IMPLICIT_CONTEXT)
1026 Perl_form_nocontext(const char* pat, ...)
1031 va_start(args, pat);
1032 retval = vform(pat, &args);
1036 #endif /* PERL_IMPLICIT_CONTEXT */
1039 =head1 Miscellaneous Functions
1042 Takes a sprintf-style format pattern and conventional
1043 (non-SV) arguments and returns the formatted string.
1045 (char *) Perl_form(pTHX_ const char* pat, ...)
1047 can be used any place a string (char *) is required:
1049 char * s = Perl_form("%d.%d",major,minor);
1051 Uses a single private buffer so if you want to format several strings you
1052 must explicitly copy the earlier strings away (and free the copies when you
1059 Perl_form(pTHX_ const char* pat, ...)
1063 va_start(args, pat);
1064 retval = vform(pat, &args);
1070 Perl_vform(pTHX_ const char *pat, va_list *args)
1072 SV * const sv = mess_alloc();
1073 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1077 #if defined(PERL_IMPLICIT_CONTEXT)
1079 Perl_mess_nocontext(const char *pat, ...)
1084 va_start(args, pat);
1085 retval = vmess(pat, &args);
1089 #endif /* PERL_IMPLICIT_CONTEXT */
1092 Perl_mess(pTHX_ const char *pat, ...)
1096 va_start(args, pat);
1097 retval = vmess(pat, &args);
1103 S_closest_cop(pTHX_ const COP *cop, const OP *o)
1106 /* Look for PL_op starting from o. cop is the last COP we've seen. */
1108 if (!o || o == PL_op)
1111 if (o->op_flags & OPf_KIDS) {
1113 for (kid = cUNOPo->op_first; kid; kid = kid->op_sibling) {
1116 /* If the OP_NEXTSTATE has been optimised away we can still use it
1117 * the get the file and line number. */
1119 if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
1120 cop = (const COP *)kid;
1122 /* Keep searching, and return when we've found something. */
1124 new_cop = closest_cop(cop, kid);
1130 /* Nothing found. */
1136 Perl_vmess(pTHX_ const char *pat, va_list *args)
1139 SV * const sv = mess_alloc();
1141 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1142 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1144 * Try and find the file and line for PL_op. This will usually be
1145 * PL_curcop, but it might be a cop that has been optimised away. We
1146 * can try to find such a cop by searching through the optree starting
1147 * from the sibling of PL_curcop.
1150 const COP *cop = closest_cop(PL_curcop, PL_curcop->op_sibling);
1155 Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
1156 OutCopFILE(cop), (IV)CopLINE(cop));
1157 /* Seems that GvIO() can be untrustworthy during global destruction. */
1158 if (GvIO(PL_last_in_gv) && (SvTYPE(GvIOp(PL_last_in_gv)) == SVt_PVIO)
1159 && IoLINES(GvIOp(PL_last_in_gv)))
1161 const bool line_mode = (RsSIMPLE(PL_rs) &&
1162 SvCUR(PL_rs) == 1 && *SvPVX_const(PL_rs) == '\n');
1163 Perl_sv_catpvf(aTHX_ sv, ", <%s> %s %"IVdf,
1164 PL_last_in_gv == PL_argvgv ? "" : GvNAME(PL_last_in_gv),
1165 line_mode ? "line" : "chunk",
1166 (IV)IoLINES(GvIOp(PL_last_in_gv)));
1169 sv_catpvs(sv, " during global destruction");
1170 sv_catpvs(sv, ".\n");
1176 Perl_write_to_stderr(pTHX_ const char* message, int msglen)
1182 if (PL_stderrgv && SvREFCNT(PL_stderrgv)
1183 && (io = GvIO(PL_stderrgv))
1184 && (mg = SvTIED_mg((SV*)io, PERL_MAGIC_tiedscalar)))
1191 SAVESPTR(PL_stderrgv);
1194 PUSHSTACKi(PERLSI_MAGIC);
1198 PUSHs(SvTIED_obj((SV*)io, mg));
1199 PUSHs(sv_2mortal(newSVpvn(message, msglen)));
1201 call_method("PRINT", G_SCALAR);
1209 /* SFIO can really mess with your errno */
1210 const int e = errno;
1212 PerlIO * const serr = Perl_error_log;
1214 PERL_WRITE_MSG_TO_CONSOLE(serr, message, msglen);
1215 (void)PerlIO_flush(serr);
1222 /* Common code used by vcroak, vdie, vwarn and vwarner */
1225 S_vdie_common(pTHX_ const char *message, STRLEN msglen, I32 utf8, bool warn)
1231 SV **const hook = warn ? &PL_warnhook : &PL_diehook;
1232 /* sv_2cv might call Perl_croak() or Perl_warner() */
1233 SV * const oldhook = *hook;
1240 cv = sv_2cv(oldhook, &stash, &gv, 0);
1242 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1252 if (warn || message) {
1253 msg = newSVpvn(message, msglen);
1254 SvFLAGS(msg) |= utf8;
1262 PUSHSTACKi(warn ? PERLSI_WARNHOOK : PERLSI_DIEHOOK);
1266 call_sv((SV*)cv, G_DISCARD);
1275 S_vdie_croak_common(pTHX_ const char* pat, va_list* args, STRLEN* msglen,
1279 const char *message;
1282 SV * const msv = vmess(pat, args);
1283 if (PL_errors && SvCUR(PL_errors)) {
1284 sv_catsv(PL_errors, msv);
1285 message = SvPV_const(PL_errors, *msglen);
1286 SvCUR_set(PL_errors, 0);
1289 message = SvPV_const(msv,*msglen);
1290 *utf8 = SvUTF8(msv);
1296 DEBUG_S(PerlIO_printf(Perl_debug_log,
1297 "%p: die/croak: message = %s\ndiehook = %p\n",
1298 (void*)thr, message, (void*)PL_diehook));
1300 S_vdie_common(aTHX_ message, *msglen, *utf8, FALSE);
1306 Perl_vdie(pTHX_ const char* pat, va_list *args)
1309 const char *message;
1310 const int was_in_eval = PL_in_eval;
1314 DEBUG_S(PerlIO_printf(Perl_debug_log,
1315 "%p: die: curstack = %p, mainstack = %p\n",
1316 (void*)thr, (void*)PL_curstack, (void*)PL_mainstack));
1318 message = vdie_croak_common(pat, args, &msglen, &utf8);
1320 PL_restartop = die_where(message, msglen);
1321 SvFLAGS(ERRSV) |= utf8;
1322 DEBUG_S(PerlIO_printf(Perl_debug_log,
1323 "%p: die: restartop = %p, was_in_eval = %d, top_env = %p\n",
1324 (void*)thr, (void*)PL_restartop, was_in_eval, (void*)PL_top_env));
1325 if ((!PL_restartop && was_in_eval) || PL_top_env->je_prev)
1327 return PL_restartop;
1330 #if defined(PERL_IMPLICIT_CONTEXT)
1332 Perl_die_nocontext(const char* pat, ...)
1337 va_start(args, pat);
1338 o = vdie(pat, &args);
1342 #endif /* PERL_IMPLICIT_CONTEXT */
1345 Perl_die(pTHX_ const char* pat, ...)
1349 va_start(args, pat);
1350 o = vdie(pat, &args);
1356 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1359 const char *message;
1363 message = S_vdie_croak_common(aTHX_ pat, args, &msglen, &utf8);
1366 PL_restartop = die_where(message, msglen);
1367 SvFLAGS(ERRSV) |= utf8;
1371 message = SvPVx_const(ERRSV, msglen);
1373 write_to_stderr(message, msglen);
1377 #if defined(PERL_IMPLICIT_CONTEXT)
1379 Perl_croak_nocontext(const char *pat, ...)
1383 va_start(args, pat);
1388 #endif /* PERL_IMPLICIT_CONTEXT */
1391 =head1 Warning and Dieing
1395 This is the XSUB-writer's interface to Perl's C<die> function.
1396 Normally call this function the same way you call the C C<printf>
1397 function. Calling C<croak> returns control directly to Perl,
1398 sidestepping the normal C order of execution. See C<warn>.
1400 If you want to throw an exception object, assign the object to
1401 C<$@> and then pass C<NULL> to croak():
1403 errsv = get_sv("@", TRUE);
1404 sv_setsv(errsv, exception_object);
1411 Perl_croak(pTHX_ const char *pat, ...)
1414 va_start(args, pat);
1421 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1425 SV * const msv = vmess(pat, args);
1426 const I32 utf8 = SvUTF8(msv);
1427 const char * const message = SvPV_const(msv, msglen);
1430 if (vdie_common(message, msglen, utf8, TRUE))
1434 write_to_stderr(message, msglen);
1437 #if defined(PERL_IMPLICIT_CONTEXT)
1439 Perl_warn_nocontext(const char *pat, ...)
1443 va_start(args, pat);
1447 #endif /* PERL_IMPLICIT_CONTEXT */
1452 This is the XSUB-writer's interface to Perl's C<warn> function. Call this
1453 function the same way you call the C C<printf> function. See C<croak>.
1459 Perl_warn(pTHX_ const char *pat, ...)
1462 va_start(args, pat);
1467 #if defined(PERL_IMPLICIT_CONTEXT)
1469 Perl_warner_nocontext(U32 err, const char *pat, ...)
1473 va_start(args, pat);
1474 vwarner(err, pat, &args);
1477 #endif /* PERL_IMPLICIT_CONTEXT */
1480 Perl_warner(pTHX_ U32 err, const char* pat,...)
1483 va_start(args, pat);
1484 vwarner(err, pat, &args);
1489 Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1492 if (PL_warnhook == PERL_WARNHOOK_FATAL || ckDEAD(err)) {
1493 SV * const msv = vmess(pat, args);
1495 const char * const message = SvPV_const(msv, msglen);
1496 const I32 utf8 = SvUTF8(msv);
1500 S_vdie_common(aTHX_ message, msglen, utf8, FALSE);
1503 PL_restartop = die_where(message, msglen);
1504 SvFLAGS(ERRSV) |= utf8;
1507 write_to_stderr(message, msglen);
1511 Perl_vwarn(aTHX_ pat, args);
1515 /* implements the ckWARN? macros */
1518 Perl_ckwarn(pTHX_ U32 w)
1524 && PL_curcop->cop_warnings != pWARN_NONE
1526 PL_curcop->cop_warnings == pWARN_ALL
1527 || isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w))
1528 || (unpackWARN2(w) &&
1529 isWARN_on(PL_curcop->cop_warnings, unpackWARN2(w)))
1530 || (unpackWARN3(w) &&
1531 isWARN_on(PL_curcop->cop_warnings, unpackWARN3(w)))
1532 || (unpackWARN4(w) &&
1533 isWARN_on(PL_curcop->cop_warnings, unpackWARN4(w)))
1538 isLEXWARN_off && PL_dowarn & G_WARN_ON
1543 /* implements the ckWARN?_d macro */
1546 Perl_ckwarn_d(pTHX_ U32 w)
1551 || PL_curcop->cop_warnings == pWARN_ALL
1553 PL_curcop->cop_warnings != pWARN_NONE
1555 isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w))
1556 || (unpackWARN2(w) &&
1557 isWARN_on(PL_curcop->cop_warnings, unpackWARN2(w)))
1558 || (unpackWARN3(w) &&
1559 isWARN_on(PL_curcop->cop_warnings, unpackWARN3(w)))
1560 || (unpackWARN4(w) &&
1561 isWARN_on(PL_curcop->cop_warnings, unpackWARN4(w)))
1567 /* Set buffer=NULL to get a new one. */
1569 Perl_new_warnings_bitfield(pTHX_ STRLEN *buffer, const char *const bits,
1571 const MEM_SIZE len_wanted = sizeof(STRLEN) + size;
1572 PERL_UNUSED_CONTEXT;
1575 (specialWARN(buffer) ?
1576 PerlMemShared_malloc(len_wanted) :
1577 PerlMemShared_realloc(buffer, len_wanted));
1579 Copy(bits, (buffer + 1), size, char);
1583 /* since we've already done strlen() for both nam and val
1584 * we can use that info to make things faster than
1585 * sprintf(s, "%s=%s", nam, val)
1587 #define my_setenv_format(s, nam, nlen, val, vlen) \
1588 Copy(nam, s, nlen, char); \
1590 Copy(val, s+(nlen+1), vlen, char); \
1591 *(s+(nlen+1+vlen)) = '\0'
1593 #ifdef USE_ENVIRON_ARRAY
1594 /* VMS' my_setenv() is in vms.c */
1595 #if !defined(WIN32) && !defined(NETWARE)
1597 Perl_my_setenv(pTHX_ const char *nam, const char *val)
1601 /* only parent thread can modify process environment */
1602 if (PL_curinterp == aTHX)
1605 #ifndef PERL_USE_SAFE_PUTENV
1606 if (!PL_use_safe_putenv) {
1607 /* most putenv()s leak, so we manipulate environ directly */
1608 register I32 i=setenv_getix(nam); /* where does it go? */
1611 if (environ == PL_origenviron) { /* need we copy environment? */
1617 while (environ[max])
1619 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
1620 for (j=0; j<max; j++) { /* copy environment */
1621 const int len = strlen(environ[j]);
1622 tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
1623 Copy(environ[j], tmpenv[j], len+1, char);
1626 environ = tmpenv; /* tell exec where it is now */
1629 safesysfree(environ[i]);
1630 while (environ[i]) {
1631 environ[i] = environ[i+1];
1636 if (!environ[i]) { /* does not exist yet */
1637 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
1638 environ[i+1] = NULL; /* make sure it's null terminated */
1641 safesysfree(environ[i]);
1645 environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
1646 /* all that work just for this */
1647 my_setenv_format(environ[i], nam, nlen, val, vlen);
1650 # if defined(__CYGWIN__) || defined(EPOC) || defined(__SYMBIAN32__) || defined(__riscos__)
1651 # if defined(HAS_UNSETENV)
1653 (void)unsetenv(nam);
1655 (void)setenv(nam, val, 1);
1657 # else /* ! HAS_UNSETENV */
1658 (void)setenv(nam, val, 1);
1659 # endif /* HAS_UNSETENV */
1661 # if defined(HAS_UNSETENV)
1663 (void)unsetenv(nam);
1665 const int nlen = strlen(nam);
1666 const int vlen = strlen(val);
1667 char * const new_env =
1668 (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1669 my_setenv_format(new_env, nam, nlen, val, vlen);
1670 (void)putenv(new_env);
1672 # else /* ! HAS_UNSETENV */
1674 const int nlen = strlen(nam);
1680 new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
1681 /* all that work just for this */
1682 my_setenv_format(new_env, nam, nlen, val, vlen);
1683 (void)putenv(new_env);
1684 # endif /* HAS_UNSETENV */
1685 # endif /* __CYGWIN__ */
1686 #ifndef PERL_USE_SAFE_PUTENV
1692 #else /* WIN32 || NETWARE */
1695 Perl_my_setenv(pTHX_ const char *nam, const char *val)
1698 register char *envstr;
1699 const int nlen = strlen(nam);
1706 Newx(envstr, nlen+vlen+2, char);
1707 my_setenv_format(envstr, nam, nlen, val, vlen);
1708 (void)PerlEnv_putenv(envstr);
1712 #endif /* WIN32 || NETWARE */
1716 Perl_setenv_getix(pTHX_ const char *nam)
1719 register const I32 len = strlen(nam);
1720 PERL_UNUSED_CONTEXT;
1722 for (i = 0; environ[i]; i++) {
1725 strnicmp(environ[i],nam,len) == 0
1727 strnEQ(environ[i],nam,len)
1729 && environ[i][len] == '=')
1730 break; /* strnEQ must come first to avoid */
1731 } /* potential SEGV's */
1734 #endif /* !PERL_MICRO */
1736 #endif /* !VMS && !EPOC*/
1738 #ifdef UNLINK_ALL_VERSIONS
1740 Perl_unlnk(pTHX_ const char *f) /* unlink all versions of a file */
1744 while (PerlLIO_unlink(f) >= 0)
1746 return retries ? 0 : -1;
1750 /* this is a drop-in replacement for bcopy() */
1751 #if (!defined(HAS_MEMCPY) && !defined(HAS_BCOPY)) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY) && !defined(HAS_SAFE_BCOPY))
1753 Perl_my_bcopy(register const char *from,register char *to,register I32 len)
1755 char * const retval = to;
1757 if (from - to >= 0) {
1765 *(--to) = *(--from);
1771 /* this is a drop-in replacement for memset() */
1774 Perl_my_memset(register char *loc, register I32 ch, register I32 len)
1776 char * const retval = loc;
1784 /* this is a drop-in replacement for bzero() */
1785 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
1787 Perl_my_bzero(register char *loc, register I32 len)
1789 char * const retval = loc;
1797 /* this is a drop-in replacement for memcmp() */
1798 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
1800 Perl_my_memcmp(const char *s1, const char *s2, register I32 len)
1802 register const U8 *a = (const U8 *)s1;
1803 register const U8 *b = (const U8 *)s2;
1807 if ((tmp = *a++ - *b++))
1812 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
1816 #ifdef USE_CHAR_VSPRINTF
1821 vsprintf(char *dest, const char *pat, char *args)
1825 fakebuf._ptr = dest;
1826 fakebuf._cnt = 32767;
1830 fakebuf._flag = _IOWRT|_IOSTRG;
1831 _doprnt(pat, args, &fakebuf); /* what a kludge */
1832 (void)putc('\0', &fakebuf);
1833 #ifdef USE_CHAR_VSPRINTF
1836 return 0; /* perl doesn't use return value */
1840 #endif /* HAS_VPRINTF */
1843 #if BYTEORDER != 0x4321
1845 Perl_my_swap(pTHX_ short s)
1847 #if (BYTEORDER & 1) == 0
1850 result = ((s & 255) << 8) + ((s >> 8) & 255);
1858 Perl_my_htonl(pTHX_ long l)
1862 char c[sizeof(long)];
1865 #if BYTEORDER == 0x1234
1866 u.c[0] = (l >> 24) & 255;
1867 u.c[1] = (l >> 16) & 255;
1868 u.c[2] = (l >> 8) & 255;
1872 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1873 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
1878 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1879 u.c[o & 0xf] = (l >> s) & 255;
1887 Perl_my_ntohl(pTHX_ long l)
1891 char c[sizeof(long)];
1894 #if BYTEORDER == 0x1234
1895 u.c[0] = (l >> 24) & 255;
1896 u.c[1] = (l >> 16) & 255;
1897 u.c[2] = (l >> 8) & 255;
1901 #if ((BYTEORDER - 0x1111) & 0x444) || !(BYTEORDER & 0xf)
1902 Perl_croak(aTHX_ "Unknown BYTEORDER\n");
1909 for (o = BYTEORDER - 0x1111, s = 0; s < (sizeof(long)*8); o >>= 4, s += 8) {
1910 l |= (u.c[o & 0xf] & 255) << s;
1917 #endif /* BYTEORDER != 0x4321 */
1921 * Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
1922 * If these functions are defined,
1923 * the BYTEORDER is neither 0x1234 nor 0x4321.
1924 * However, this is not assumed.
1928 #define HTOLE(name,type) \
1930 name (register type n) \
1934 char c[sizeof(type)]; \
1937 register U32 s = 0; \
1938 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
1939 u.c[i] = (n >> s) & 0xFF; \
1944 #define LETOH(name,type) \
1946 name (register type n) \
1950 char c[sizeof(type)]; \
1953 register U32 s = 0; \
1956 for (i = 0; i < sizeof(u.c); i++, s += 8) { \
1957 n |= ((type)(u.c[i] & 0xFF)) << s; \
1963 * Big-endian byte order functions.
1966 #define HTOBE(name,type) \
1968 name (register type n) \
1972 char c[sizeof(type)]; \
1975 register U32 s = 8*(sizeof(u.c)-1); \
1976 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
1977 u.c[i] = (n >> s) & 0xFF; \
1982 #define BETOH(name,type) \
1984 name (register type n) \
1988 char c[sizeof(type)]; \
1991 register U32 s = 8*(sizeof(u.c)-1); \
1994 for (i = 0; i < sizeof(u.c); i++, s -= 8) { \
1995 n |= ((type)(u.c[i] & 0xFF)) << s; \
2001 * If we just can't do it...
2004 #define NOT_AVAIL(name,type) \
2006 name (register type n) \
2008 Perl_croak_nocontext(#name "() not available"); \
2009 return n; /* not reached */ \
2013 #if defined(HAS_HTOVS) && !defined(htovs)
2016 #if defined(HAS_HTOVL) && !defined(htovl)
2019 #if defined(HAS_VTOHS) && !defined(vtohs)
2022 #if defined(HAS_VTOHL) && !defined(vtohl)
2026 #ifdef PERL_NEED_MY_HTOLE16
2028 HTOLE(Perl_my_htole16,U16)
2030 NOT_AVAIL(Perl_my_htole16,U16)
2033 #ifdef PERL_NEED_MY_LETOH16
2035 LETOH(Perl_my_letoh16,U16)
2037 NOT_AVAIL(Perl_my_letoh16,U16)
2040 #ifdef PERL_NEED_MY_HTOBE16
2042 HTOBE(Perl_my_htobe16,U16)
2044 NOT_AVAIL(Perl_my_htobe16,U16)
2047 #ifdef PERL_NEED_MY_BETOH16
2049 BETOH(Perl_my_betoh16,U16)
2051 NOT_AVAIL(Perl_my_betoh16,U16)
2055 #ifdef PERL_NEED_MY_HTOLE32
2057 HTOLE(Perl_my_htole32,U32)
2059 NOT_AVAIL(Perl_my_htole32,U32)
2062 #ifdef PERL_NEED_MY_LETOH32
2064 LETOH(Perl_my_letoh32,U32)
2066 NOT_AVAIL(Perl_my_letoh32,U32)
2069 #ifdef PERL_NEED_MY_HTOBE32
2071 HTOBE(Perl_my_htobe32,U32)
2073 NOT_AVAIL(Perl_my_htobe32,U32)
2076 #ifdef PERL_NEED_MY_BETOH32
2078 BETOH(Perl_my_betoh32,U32)
2080 NOT_AVAIL(Perl_my_betoh32,U32)
2084 #ifdef PERL_NEED_MY_HTOLE64
2086 HTOLE(Perl_my_htole64,U64)
2088 NOT_AVAIL(Perl_my_htole64,U64)
2091 #ifdef PERL_NEED_MY_LETOH64
2093 LETOH(Perl_my_letoh64,U64)
2095 NOT_AVAIL(Perl_my_letoh64,U64)
2098 #ifdef PERL_NEED_MY_HTOBE64
2100 HTOBE(Perl_my_htobe64,U64)
2102 NOT_AVAIL(Perl_my_htobe64,U64)
2105 #ifdef PERL_NEED_MY_BETOH64
2107 BETOH(Perl_my_betoh64,U64)
2109 NOT_AVAIL(Perl_my_betoh64,U64)
2113 #ifdef PERL_NEED_MY_HTOLES
2114 HTOLE(Perl_my_htoles,short)
2116 #ifdef PERL_NEED_MY_LETOHS
2117 LETOH(Perl_my_letohs,short)
2119 #ifdef PERL_NEED_MY_HTOBES
2120 HTOBE(Perl_my_htobes,short)
2122 #ifdef PERL_NEED_MY_BETOHS
2123 BETOH(Perl_my_betohs,short)
2126 #ifdef PERL_NEED_MY_HTOLEI
2127 HTOLE(Perl_my_htolei,int)
2129 #ifdef PERL_NEED_MY_LETOHI
2130 LETOH(Perl_my_letohi,int)
2132 #ifdef PERL_NEED_MY_HTOBEI
2133 HTOBE(Perl_my_htobei,int)
2135 #ifdef PERL_NEED_MY_BETOHI
2136 BETOH(Perl_my_betohi,int)
2139 #ifdef PERL_NEED_MY_HTOLEL
2140 HTOLE(Perl_my_htolel,long)
2142 #ifdef PERL_NEED_MY_LETOHL
2143 LETOH(Perl_my_letohl,long)
2145 #ifdef PERL_NEED_MY_HTOBEL
2146 HTOBE(Perl_my_htobel,long)
2148 #ifdef PERL_NEED_MY_BETOHL
2149 BETOH(Perl_my_betohl,long)
2153 Perl_my_swabn(void *ptr, int n)
2155 register char *s = (char *)ptr;
2156 register char *e = s + (n-1);
2159 for (n /= 2; n > 0; s++, e--, n--) {
2167 Perl_my_popen_list(pTHX_ char *mode, int n, SV **args)
2169 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(OS2) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL) && !defined(NETWARE)
2172 register I32 This, that;
2178 PERL_FLUSHALL_FOR_CHILD;
2179 This = (*mode == 'w');
2183 taint_proper("Insecure %s%s", "EXEC");
2185 if (PerlProc_pipe(p) < 0)
2187 /* Try for another pipe pair for error return */
2188 if (PerlProc_pipe(pp) >= 0)
2190 while ((pid = PerlProc_fork()) < 0) {
2191 if (errno != EAGAIN) {
2192 PerlLIO_close(p[This]);
2193 PerlLIO_close(p[that]);
2195 PerlLIO_close(pp[0]);
2196 PerlLIO_close(pp[1]);
2208 /* Close parent's end of error status pipe (if any) */
2210 PerlLIO_close(pp[0]);
2211 #if defined(HAS_FCNTL) && defined(F_SETFD)
2212 /* Close error pipe automatically if exec works */
2213 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2216 /* Now dup our end of _the_ pipe to right position */
2217 if (p[THIS] != (*mode == 'r')) {
2218 PerlLIO_dup2(p[THIS], *mode == 'r');
2219 PerlLIO_close(p[THIS]);
2220 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2221 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2224 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2225 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2226 /* No automatic close - do it by hand */
2233 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
2239 do_aexec5(NULL, args-1, args-1+n, pp[1], did_pipes);
2245 do_execfree(); /* free any memory malloced by child on fork */
2247 PerlLIO_close(pp[1]);
2248 /* Keep the lower of the two fd numbers */
2249 if (p[that] < p[This]) {
2250 PerlLIO_dup2(p[This], p[that]);
2251 PerlLIO_close(p[This]);
2255 PerlLIO_close(p[that]); /* close child's end of pipe */
2258 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2260 SvUPGRADE(sv,SVt_IV);
2262 PL_forkprocess = pid;
2263 /* If we managed to get status pipe check for exec fail */
2264 if (did_pipes && pid > 0) {
2269 while (n < sizeof(int)) {
2270 n1 = PerlLIO_read(pp[0],
2271 (void*)(((char*)&errkid)+n),
2277 PerlLIO_close(pp[0]);
2279 if (n) { /* Error */
2281 PerlLIO_close(p[This]);
2282 if (n != sizeof(int))
2283 Perl_croak(aTHX_ "panic: kid popen errno read");
2285 pid2 = wait4pid(pid, &status, 0);
2286 } while (pid2 == -1 && errno == EINTR);
2287 errno = errkid; /* Propagate errno from kid */
2292 PerlLIO_close(pp[0]);
2293 return PerlIO_fdopen(p[This], mode);
2295 # ifdef OS2 /* Same, without fork()ing and all extra overhead... */
2296 return my_syspopen4(aTHX_ Nullch, mode, n, args);
2298 Perl_croak(aTHX_ "List form of piped open not implemented");
2299 return (PerlIO *) NULL;
2304 /* VMS' my_popen() is in VMS.c, same with OS/2. */
2305 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
2307 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2311 register I32 This, that;
2314 const I32 doexec = !(*cmd == '-' && cmd[1] == '\0');
2318 PERL_FLUSHALL_FOR_CHILD;
2321 return my_syspopen(aTHX_ cmd,mode);
2324 This = (*mode == 'w');
2326 if (doexec && PL_tainting) {
2328 taint_proper("Insecure %s%s", "EXEC");
2330 if (PerlProc_pipe(p) < 0)
2332 if (doexec && PerlProc_pipe(pp) >= 0)
2334 while ((pid = PerlProc_fork()) < 0) {
2335 if (errno != EAGAIN) {
2336 PerlLIO_close(p[This]);
2337 PerlLIO_close(p[that]);
2339 PerlLIO_close(pp[0]);
2340 PerlLIO_close(pp[1]);
2343 Perl_croak(aTHX_ "Can't fork");
2356 PerlLIO_close(pp[0]);
2357 #if defined(HAS_FCNTL) && defined(F_SETFD)
2358 fcntl(pp[1], F_SETFD, FD_CLOEXEC);
2361 if (p[THIS] != (*mode == 'r')) {
2362 PerlLIO_dup2(p[THIS], *mode == 'r');
2363 PerlLIO_close(p[THIS]);
2364 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2365 PerlLIO_close(p[THAT]);
2368 PerlLIO_close(p[THAT]);
2371 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2378 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2383 /* may or may not use the shell */
2384 do_exec3(cmd, pp[1], did_pipes);
2387 #endif /* defined OS2 */
2389 #ifdef PERLIO_USING_CRLF
2390 /* Since we circumvent IO layers when we manipulate low-level
2391 filedescriptors directly, need to manually switch to the
2392 default, binary, low-level mode; see PerlIOBuf_open(). */
2393 PerlLIO_setmode((*mode == 'r'), O_BINARY);
2396 if ((tmpgv = gv_fetchpvs("$", GV_ADD|GV_NOTQUAL, SVt_PV))) {
2397 SvREADONLY_off(GvSV(tmpgv));
2398 sv_setiv(GvSV(tmpgv), PerlProc_getpid());
2399 SvREADONLY_on(GvSV(tmpgv));
2401 #ifdef THREADS_HAVE_PIDS
2402 PL_ppid = (IV)getppid();
2405 #ifdef PERL_USES_PL_PIDSTATUS
2406 hv_clear(PL_pidstatus); /* we have no children */
2412 do_execfree(); /* free any memory malloced by child on vfork */
2414 PerlLIO_close(pp[1]);
2415 if (p[that] < p[This]) {
2416 PerlLIO_dup2(p[This], p[that]);
2417 PerlLIO_close(p[This]);
2421 PerlLIO_close(p[that]);
2424 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2426 SvUPGRADE(sv,SVt_IV);
2428 PL_forkprocess = pid;
2429 if (did_pipes && pid > 0) {
2434 while (n < sizeof(int)) {
2435 n1 = PerlLIO_read(pp[0],
2436 (void*)(((char*)&errkid)+n),
2442 PerlLIO_close(pp[0]);
2444 if (n) { /* Error */
2446 PerlLIO_close(p[This]);
2447 if (n != sizeof(int))
2448 Perl_croak(aTHX_ "panic: kid popen errno read");
2450 pid2 = wait4pid(pid, &status, 0);
2451 } while (pid2 == -1 && errno == EINTR);
2452 errno = errkid; /* Propagate errno from kid */
2457 PerlLIO_close(pp[0]);
2458 return PerlIO_fdopen(p[This], mode);
2461 #if defined(atarist) || defined(EPOC)
2464 Perl_my_popen((pTHX_ const char *cmd, const char *mode)
2466 PERL_FLUSHALL_FOR_CHILD;
2467 /* Call system's popen() to get a FILE *, then import it.
2468 used 0 for 2nd parameter to PerlIO_importFILE;
2471 return PerlIO_importFILE(popen(cmd, mode), 0);
2475 FILE *djgpp_popen();
2477 Perl_my_popen((pTHX_ const char *cmd, const char *mode)
2479 PERL_FLUSHALL_FOR_CHILD;
2480 /* Call system's popen() to get a FILE *, then import it.
2481 used 0 for 2nd parameter to PerlIO_importFILE;
2484 return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2489 #endif /* !DOSISH */
2491 /* this is called in parent before the fork() */
2493 Perl_atfork_lock(void)
2496 #if defined(USE_ITHREADS)
2497 /* locks must be held in locking order (if any) */
2499 MUTEX_LOCK(&PL_malloc_mutex);
2505 /* this is called in both parent and child after the fork() */
2507 Perl_atfork_unlock(void)
2510 #if defined(USE_ITHREADS)
2511 /* locks must be released in same order as in atfork_lock() */
2513 MUTEX_UNLOCK(&PL_malloc_mutex);
2522 #if defined(HAS_FORK)
2524 #if defined(USE_ITHREADS) && !defined(HAS_PTHREAD_ATFORK)
2529 /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2530 * handlers elsewhere in the code */
2535 /* this "canna happen" since nothing should be calling here if !HAS_FORK */
2536 Perl_croak_nocontext("fork() not available");
2538 #endif /* HAS_FORK */
2543 Perl_dump_fds(pTHX_ char *s)
2548 PerlIO_printf(Perl_debug_log,"%s", s);
2549 for (fd = 0; fd < 32; fd++) {
2550 if (PerlLIO_fstat(fd,&tmpstatbuf) >= 0)
2551 PerlIO_printf(Perl_debug_log," %d",fd);
2553 PerlIO_printf(Perl_debug_log,"\n");
2556 #endif /* DUMP_FDS */
2560 dup2(int oldfd, int newfd)
2562 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2565 PerlLIO_close(newfd);
2566 return fcntl(oldfd, F_DUPFD, newfd);
2568 #define DUP2_MAX_FDS 256
2569 int fdtmp[DUP2_MAX_FDS];
2575 PerlLIO_close(newfd);
2576 /* good enough for low fd's... */
2577 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2578 if (fdx >= DUP2_MAX_FDS) {
2586 PerlLIO_close(fdtmp[--fdx]);
2593 #ifdef HAS_SIGACTION
2595 #ifdef MACOS_TRADITIONAL
2596 /* We don't want restart behavior on MacOS */
2601 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2604 struct sigaction act, oact;
2607 /* only "parent" interpreter can diddle signals */
2608 if (PL_curinterp != aTHX)
2609 return (Sighandler_t) SIG_ERR;
2612 act.sa_handler = (void(*)(int))handler;
2613 sigemptyset(&act.sa_mask);
2616 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2617 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2619 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2620 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2621 act.sa_flags |= SA_NOCLDWAIT;
2623 if (sigaction(signo, &act, &oact) == -1)
2624 return (Sighandler_t) SIG_ERR;
2626 return (Sighandler_t) oact.sa_handler;
2630 Perl_rsignal_state(pTHX_ int signo)
2632 struct sigaction oact;
2633 PERL_UNUSED_CONTEXT;
2635 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2636 return (Sighandler_t) SIG_ERR;
2638 return (Sighandler_t) oact.sa_handler;
2642 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2645 struct sigaction act;
2648 /* only "parent" interpreter can diddle signals */
2649 if (PL_curinterp != aTHX)
2653 act.sa_handler = (void(*)(int))handler;
2654 sigemptyset(&act.sa_mask);
2657 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2658 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2660 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2661 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2662 act.sa_flags |= SA_NOCLDWAIT;
2664 return sigaction(signo, &act, save);
2668 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2672 /* only "parent" interpreter can diddle signals */
2673 if (PL_curinterp != aTHX)
2677 return sigaction(signo, save, (struct sigaction *)NULL);
2680 #else /* !HAS_SIGACTION */
2683 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2685 #if defined(USE_ITHREADS) && !defined(WIN32)
2686 /* only "parent" interpreter can diddle signals */
2687 if (PL_curinterp != aTHX)
2688 return (Sighandler_t) SIG_ERR;
2691 return PerlProc_signal(signo, handler);
2702 Perl_rsignal_state(pTHX_ int signo)
2705 Sighandler_t oldsig;
2707 #if defined(USE_ITHREADS) && !defined(WIN32)
2708 /* only "parent" interpreter can diddle signals */
2709 if (PL_curinterp != aTHX)
2710 return (Sighandler_t) SIG_ERR;
2714 oldsig = PerlProc_signal(signo, sig_trap);
2715 PerlProc_signal(signo, oldsig);
2717 PerlProc_kill(PerlProc_getpid(), signo);
2722 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2724 #if defined(USE_ITHREADS) && !defined(WIN32)
2725 /* only "parent" interpreter can diddle signals */
2726 if (PL_curinterp != aTHX)
2729 *save = PerlProc_signal(signo, handler);
2730 return (*save == (Sighandler_t) SIG_ERR) ? -1 : 0;
2734 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2736 #if defined(USE_ITHREADS) && !defined(WIN32)
2737 /* only "parent" interpreter can diddle signals */
2738 if (PL_curinterp != aTHX)
2741 return (PerlProc_signal(signo, *save) == (Sighandler_t) SIG_ERR) ? -1 : 0;
2744 #endif /* !HAS_SIGACTION */
2745 #endif /* !PERL_MICRO */
2747 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
2748 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__OPEN_VM) && !defined(EPOC) && !defined(MACOS_TRADITIONAL)
2750 Perl_my_pclose(pTHX_ PerlIO *ptr)
2753 Sigsave_t hstat, istat, qstat;
2759 int saved_errno = 0;
2761 int saved_win32_errno;
2765 svp = av_fetch(PL_fdpid,PerlIO_fileno(ptr),TRUE);
2767 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
2769 *svp = &PL_sv_undef;
2771 if (pid == -1) { /* Opened by popen. */
2772 return my_syspclose(ptr);
2775 if ((close_failed = (PerlIO_close(ptr) == EOF))) {
2776 saved_errno = errno;
2778 saved_win32_errno = GetLastError();
2782 if(PerlProc_kill(pid, 0) < 0) { return(pid); } /* HOM 12/23/91 */
2785 rsignal_save(SIGHUP, (Sighandler_t) SIG_IGN, &hstat);
2786 rsignal_save(SIGINT, (Sighandler_t) SIG_IGN, &istat);
2787 rsignal_save(SIGQUIT, (Sighandler_t) SIG_IGN, &qstat);
2790 pid2 = wait4pid(pid, &status, 0);
2791 } while (pid2 == -1 && errno == EINTR);
2793 rsignal_restore(SIGHUP, &hstat);
2794 rsignal_restore(SIGINT, &istat);
2795 rsignal_restore(SIGQUIT, &qstat);
2798 SETERRNO(saved_errno, 0);
2801 return(pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status));
2803 #endif /* !DOSISH */
2805 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(MACOS_TRADITIONAL)
2807 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
2813 #ifdef PERL_USES_PL_PIDSTATUS
2816 /* The keys in PL_pidstatus are now the raw 4 (or 8) bytes of the
2817 pid, rather than a string form. */
2818 SV * const * const svp = hv_fetch(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),FALSE);
2819 if (svp && *svp != &PL_sv_undef) {
2820 *statusp = SvIVX(*svp);
2821 (void)hv_delete(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),
2829 hv_iterinit(PL_pidstatus);
2830 if ((entry = hv_iternext(PL_pidstatus))) {
2831 SV * const sv = hv_iterval(PL_pidstatus,entry);
2833 const char * const spid = hv_iterkey(entry,&len);
2835 assert (len == sizeof(Pid_t));
2836 memcpy((char *)&pid, spid, len);
2837 *statusp = SvIVX(sv);
2838 /* The hash iterator is currently on this entry, so simply
2839 calling hv_delete would trigger the lazy delete, which on
2840 aggregate does more work, beacuse next call to hv_iterinit()
2841 would spot the flag, and have to call the delete routine,
2842 while in the meantime any new entries can't re-use that
2844 hv_iterinit(PL_pidstatus);
2845 (void)hv_delete(PL_pidstatus,spid,len,G_DISCARD);
2852 # ifdef HAS_WAITPID_RUNTIME
2853 if (!HAS_WAITPID_RUNTIME)
2856 result = PerlProc_waitpid(pid,statusp,flags);
2859 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
2860 result = wait4((pid==-1)?0:pid,statusp,flags,NULL);
2863 #ifdef PERL_USES_PL_PIDSTATUS
2864 #if defined(HAS_WAITPID) && defined(HAS_WAITPID_RUNTIME)
2869 Perl_croak(aTHX_ "Can't do waitpid with flags");
2871 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
2872 pidgone(result,*statusp);
2878 #if defined(HAS_WAITPID) || defined(HAS_WAIT4)
2881 if (result < 0 && errno == EINTR) {
2886 #endif /* !DOSISH || OS2 || WIN32 || NETWARE */
2888 #ifdef PERL_USES_PL_PIDSTATUS
2890 Perl_pidgone(pTHX_ Pid_t pid, int status)
2894 sv = *hv_fetch(PL_pidstatus,(const char*)&pid,sizeof(Pid_t),TRUE);
2895 SvUPGRADE(sv,SVt_IV);
2896 SvIV_set(sv, status);
2901 #if defined(atarist) || defined(OS2) || defined(EPOC)
2904 int /* Cannot prototype with I32
2906 my_syspclose(PerlIO *ptr)
2909 Perl_my_pclose(pTHX_ PerlIO *ptr)
2912 /* Needs work for PerlIO ! */
2913 FILE * const f = PerlIO_findFILE(ptr);
2914 const I32 result = pclose(f);
2915 PerlIO_releaseFILE(ptr,f);
2923 Perl_my_pclose(pTHX_ PerlIO *ptr)
2925 /* Needs work for PerlIO ! */
2926 FILE * const f = PerlIO_findFILE(ptr);
2927 I32 result = djgpp_pclose(f);
2928 result = (result << 8) & 0xff00;
2929 PerlIO_releaseFILE(ptr,f);
2935 Perl_repeatcpy(pTHX_ register char *to, register const char *from, I32 len, register I32 count)
2938 register const char * const frombase = from;
2939 PERL_UNUSED_CONTEXT;
2942 register const char c = *from;
2947 while (count-- > 0) {
2948 for (todo = len; todo > 0; todo--) {
2957 Perl_same_dirent(pTHX_ const char *a, const char *b)
2959 char *fa = strrchr(a,'/');
2960 char *fb = strrchr(b,'/');
2963 SV * const tmpsv = sv_newmortal();
2976 sv_setpvn(tmpsv, ".", 1);
2978 sv_setpvn(tmpsv, a, fa - a);
2979 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf1) < 0)
2982 sv_setpvn(tmpsv, ".", 1);
2984 sv_setpvn(tmpsv, b, fb - b);
2985 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf2) < 0)
2987 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
2988 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
2990 #endif /* !HAS_RENAME */
2993 Perl_find_script(pTHX_ const char *scriptname, bool dosearch,
2994 const char *const *const search_ext, I32 flags)
2997 const char *xfound = NULL;
2998 char *xfailed = NULL;
2999 char tmpbuf[MAXPATHLEN];
3003 #if defined(DOSISH) && !defined(OS2) && !defined(atarist)
3004 # define SEARCH_EXTS ".bat", ".cmd", NULL
3005 # define MAX_EXT_LEN 4
3008 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
3009 # define MAX_EXT_LEN 4
3012 # define SEARCH_EXTS ".pl", ".com", NULL
3013 # define MAX_EXT_LEN 4
3015 /* additional extensions to try in each dir if scriptname not found */
3017 static const char *const exts[] = { SEARCH_EXTS };
3018 const char *const *const ext = search_ext ? search_ext : exts;
3019 int extidx = 0, i = 0;
3020 const char *curext = NULL;
3022 PERL_UNUSED_ARG(search_ext);
3023 # define MAX_EXT_LEN 0
3027 * If dosearch is true and if scriptname does not contain path
3028 * delimiters, search the PATH for scriptname.
3030 * If SEARCH_EXTS is also defined, will look for each
3031 * scriptname{SEARCH_EXTS} whenever scriptname is not found
3032 * while searching the PATH.
3034 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
3035 * proceeds as follows:
3036 * If DOSISH or VMSISH:
3037 * + look for ./scriptname{,.foo,.bar}
3038 * + search the PATH for scriptname{,.foo,.bar}
3041 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
3042 * this will not look in '.' if it's not in the PATH)
3047 # ifdef ALWAYS_DEFTYPES
3048 len = strlen(scriptname);
3049 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
3050 int idx = 0, deftypes = 1;
3053 const int hasdir = !dosearch || (strpbrk(scriptname,":[</") != NULL);
3056 int idx = 0, deftypes = 1;
3059 const int hasdir = (strpbrk(scriptname,":[</") != NULL);
3061 /* The first time through, just add SEARCH_EXTS to whatever we
3062 * already have, so we can check for default file types. */
3064 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
3070 if ((strlen(tmpbuf) + strlen(scriptname)
3071 + MAX_EXT_LEN) >= sizeof tmpbuf)
3072 continue; /* don't search dir with too-long name */
3073 my_strlcat(tmpbuf, scriptname, sizeof(tmpbuf));
3077 if (strEQ(scriptname, "-"))
3079 if (dosearch) { /* Look in '.' first. */
3080 const char *cur = scriptname;
3082 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
3084 if (strEQ(ext[i++],curext)) {
3085 extidx = -1; /* already has an ext */
3090 DEBUG_p(PerlIO_printf(Perl_debug_log,
3091 "Looking for %s\n",cur));
3092 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
3093 && !S_ISDIR(PL_statbuf.st_mode)) {
3101 if (cur == scriptname) {
3102 len = strlen(scriptname);
3103 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
3105 my_strlcpy(tmpbuf, scriptname, sizeof(tmpbuf));
3108 } while (extidx >= 0 && ext[extidx] /* try an extension? */
3109 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len));
3114 #ifdef MACOS_TRADITIONAL
3115 if (dosearch && !strchr(scriptname, ':') &&
3116 (s = PerlEnv_getenv("Commands")))
3118 if (dosearch && !strchr(scriptname, '/')
3120 && !strchr(scriptname, '\\')
3122 && (s = PerlEnv_getenv("PATH")))
3127 PL_bufend = s + strlen(s);
3128 while (s < PL_bufend) {
3129 #ifdef MACOS_TRADITIONAL
3130 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
3134 #if defined(atarist) || defined(DOSISH)
3139 && *s != ';'; len++, s++) {
3140 if (len < sizeof tmpbuf)
3143 if (len < sizeof tmpbuf)
3145 #else /* ! (atarist || DOSISH) */
3146 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, PL_bufend,
3149 #endif /* ! (atarist || DOSISH) */
3150 #endif /* MACOS_TRADITIONAL */
3153 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
3154 continue; /* don't search dir with too-long name */
3155 #ifdef MACOS_TRADITIONAL
3156 if (len && tmpbuf[len - 1] != ':')
3157 tmpbuf[len++] = ':';
3160 # if defined(atarist) || defined(__MINT__) || defined(DOSISH)
3161 && tmpbuf[len - 1] != '/'
3162 && tmpbuf[len - 1] != '\\'
3165 tmpbuf[len++] = '/';
3166 if (len == 2 && tmpbuf[0] == '.')
3169 (void)my_strlcpy(tmpbuf + len, scriptname, sizeof(tmpbuf) - len);
3173 len = strlen(tmpbuf);
3174 if (extidx > 0) /* reset after previous loop */
3178 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
3179 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
3180 if (S_ISDIR(PL_statbuf.st_mode)) {
3184 } while ( retval < 0 /* not there */
3185 && extidx>=0 && ext[extidx] /* try an extension? */
3186 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len)
3191 if (S_ISREG(PL_statbuf.st_mode)
3192 && cando(S_IRUSR,TRUE,&PL_statbuf)
3193 #if !defined(DOSISH) && !defined(MACOS_TRADITIONAL)
3194 && cando(S_IXUSR,TRUE,&PL_statbuf)
3198 xfound = tmpbuf; /* bingo! */
3202 xfailed = savepv(tmpbuf);
3205 if (!xfound && !seen_dot && !xfailed &&
3206 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
3207 || S_ISDIR(PL_statbuf.st_mode)))
3209 seen_dot = 1; /* Disable message. */
3211 if (flags & 1) { /* do or die? */
3212 Perl_croak(aTHX_ "Can't %s %s%s%s",
3213 (xfailed ? "execute" : "find"),
3214 (xfailed ? xfailed : scriptname),
3215 (xfailed ? "" : " on PATH"),
3216 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
3221 scriptname = xfound;
3223 return (scriptname ? savepv(scriptname) : NULL);
3226 #ifndef PERL_GET_CONTEXT_DEFINED
3229 Perl_get_context(void)
3232 #if defined(USE_ITHREADS)
3233 # ifdef OLD_PTHREADS_API
3235 if (pthread_getspecific(PL_thr_key, &t))
3236 Perl_croak_nocontext("panic: pthread_getspecific");
3239 # ifdef I_MACH_CTHREADS
3240 return (void*)cthread_data(cthread_self());
3242 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
3251 Perl_set_context(void *t)
3254 #if defined(USE_ITHREADS)
3255 # ifdef I_MACH_CTHREADS
3256 cthread_set_data(cthread_self(), t);
3258 if (pthread_setspecific(PL_thr_key, t))
3259 Perl_croak_nocontext("panic: pthread_setspecific");
3266 #endif /* !PERL_GET_CONTEXT_DEFINED */
3268 #if defined(PERL_GLOBAL_STRUCT) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
3277 Perl_get_op_names(pTHX)
3279 PERL_UNUSED_CONTEXT;
3280 return (char **)PL_op_name;
3284 Perl_get_op_descs(pTHX)
3286 PERL_UNUSED_CONTEXT;
3287 return (char **)PL_op_desc;
3291 Perl_get_no_modify(pTHX)
3293 PERL_UNUSED_CONTEXT;
3294 return PL_no_modify;
3298 Perl_get_opargs(pTHX)
3300 PERL_UNUSED_CONTEXT;
3301 return (U32 *)PL_opargs;
3305 Perl_get_ppaddr(pTHX)
3308 PERL_UNUSED_CONTEXT;
3309 return (PPADDR_t*)PL_ppaddr;
3312 #ifndef HAS_GETENV_LEN
3314 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3316 char * const env_trans = PerlEnv_getenv(env_elem);
3317 PERL_UNUSED_CONTEXT;
3319 *len = strlen(env_trans);
3326 Perl_get_vtbl(pTHX_ int vtbl_id)
3328 const MGVTBL* result;
3329 PERL_UNUSED_CONTEXT;
3333 result = &PL_vtbl_sv;
3336 result = &PL_vtbl_env;
3338 case want_vtbl_envelem:
3339 result = &PL_vtbl_envelem;
3342 result = &PL_vtbl_sig;
3344 case want_vtbl_sigelem:
3345 result = &PL_vtbl_sigelem;
3347 case want_vtbl_pack:
3348 result = &PL_vtbl_pack;
3350 case want_vtbl_packelem:
3351 result = &PL_vtbl_packelem;
3353 case want_vtbl_dbline:
3354 result = &PL_vtbl_dbline;
3357 result = &PL_vtbl_isa;
3359 case want_vtbl_isaelem:
3360 result = &PL_vtbl_isaelem;
3362 case want_vtbl_arylen:
3363 result = &PL_vtbl_arylen;
3365 case want_vtbl_mglob:
3366 result = &PL_vtbl_mglob;
3368 case want_vtbl_nkeys:
3369 result = &PL_vtbl_nkeys;
3371 case want_vtbl_taint:
3372 result = &PL_vtbl_taint;
3374 case want_vtbl_substr:
3375 result = &PL_vtbl_substr;
3378 result = &PL_vtbl_vec;
3381 result = &PL_vtbl_pos;
3384 result = &PL_vtbl_bm;
3387 result = &PL_vtbl_fm;
3389 case want_vtbl_uvar:
3390 result = &PL_vtbl_uvar;
3392 case want_vtbl_defelem:
3393 result = &PL_vtbl_defelem;
3395 case want_vtbl_regexp:
3396 result = &PL_vtbl_regexp;
3398 case want_vtbl_regdata:
3399 result = &PL_vtbl_regdata;
3401 case want_vtbl_regdatum:
3402 result = &PL_vtbl_regdatum;
3404 #ifdef USE_LOCALE_COLLATE
3405 case want_vtbl_collxfrm:
3406 result = &PL_vtbl_collxfrm;
3409 case want_vtbl_amagic:
3410 result = &PL_vtbl_amagic;
3412 case want_vtbl_amagicelem:
3413 result = &PL_vtbl_amagicelem;
3415 case want_vtbl_backref:
3416 result = &PL_vtbl_backref;
3418 case want_vtbl_utf8:
3419 result = &PL_vtbl_utf8;
3425 return (MGVTBL*)result;
3429 Perl_my_fflush_all(pTHX)
3431 #if defined(USE_PERLIO) || defined(FFLUSH_NULL) || defined(USE_SFIO)
3432 return PerlIO_flush(NULL);
3434 # if defined(HAS__FWALK)
3435 extern int fflush(FILE *);
3436 /* undocumented, unprototyped, but very useful BSDism */
3437 extern void _fwalk(int (*)(FILE *));
3441 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3443 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3444 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3446 # if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3447 open_max = sysconf(_SC_OPEN_MAX);
3450 open_max = FOPEN_MAX;
3453 open_max = OPEN_MAX;
3464 for (i = 0; i < open_max; i++)
3465 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3466 STDIO_STREAM_ARRAY[i]._file < open_max &&
3467 STDIO_STREAM_ARRAY[i]._flag)
3468 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3472 SETERRNO(EBADF,RMS_IFI);
3479 Perl_report_evil_fh(pTHX_ const GV *gv, const IO *io, I32 op)
3481 const char * const name = gv && isGV(gv) ? GvENAME(gv) : NULL;
3483 if (op == OP_phoney_OUTPUT_ONLY || op == OP_phoney_INPUT_ONLY) {
3484 if (ckWARN(WARN_IO)) {
3485 const char * const direction =
3486 (const char *)((op == OP_phoney_INPUT_ONLY) ? "in" : "out");
3488 Perl_warner(aTHX_ packWARN(WARN_IO),
3489 "Filehandle %s opened only for %sput",
3492 Perl_warner(aTHX_ packWARN(WARN_IO),
3493 "Filehandle opened only for %sput", direction);
3500 if (gv && io && IoTYPE(io) == IoTYPE_CLOSED) {
3502 warn_type = WARN_CLOSED;
3506 warn_type = WARN_UNOPENED;
3509 if (ckWARN(warn_type)) {
3510 const char * const pars =
3511 (const char *)(OP_IS_FILETEST(op) ? "" : "()");
3512 const char * const func =
3514 (op == OP_READLINE ? "readline" : /* "<HANDLE>" not nice */
3515 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
3516 op < 0 ? "" : /* handle phoney cases */
3518 const char * const type =
3520 (OP_IS_SOCKET(op) ||
3521 (gv && io && IoTYPE(io) == IoTYPE_SOCKET) ?
3522 "socket" : "filehandle");
3523 if (name && *name) {
3524 Perl_warner(aTHX_ packWARN(warn_type),
3525 "%s%s on %s %s %s", func, pars, vile, type, name);
3526 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3528 aTHX_ packWARN(warn_type),
3529 "\t(Are you trying to call %s%s on dirhandle %s?)\n",
3534 Perl_warner(aTHX_ packWARN(warn_type),
3535 "%s%s on %s %s", func, pars, vile, type);
3536 if (gv && io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3538 aTHX_ packWARN(warn_type),
3539 "\t(Are you trying to call %s%s on dirhandle?)\n",
3548 /* in ASCII order, not that it matters */
3549 static const char controllablechars[] = "?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_";
3552 Perl_ebcdic_control(pTHX_ int ch)
3560 if ((ctlp = strchr(controllablechars, ch)) == 0) {
3561 Perl_die(aTHX_ "unrecognised control character '%c'\n", ch);
3564 if (ctlp == controllablechars)
3565 return('\177'); /* DEL */
3567 return((unsigned char)(ctlp - controllablechars - 1));
3568 } else { /* Want uncontrol */
3569 if (ch == '\177' || ch == -1)
3571 else if (ch == '\157')
3573 else if (ch == '\174')
3575 else if (ch == '^') /* '\137' in 1047, '\260' in 819 */
3577 else if (ch == '\155')
3579 else if (0 < ch && ch < (sizeof(controllablechars) - 1))
3580 return(controllablechars[ch+1]);
3582 Perl_die(aTHX_ "invalid control request: '\\%03o'\n", ch & 0xFF);
3587 /* To workaround core dumps from the uninitialised tm_zone we get the
3588 * system to give us a reasonable struct to copy. This fix means that
3589 * strftime uses the tm_zone and tm_gmtoff values returned by
3590 * localtime(time()). That should give the desired result most of the
3591 * time. But probably not always!
3593 * This does not address tzname aspects of NETaa14816.
3598 # ifndef STRUCT_TM_HASZONE
3599 # define STRUCT_TM_HASZONE
3603 #ifdef STRUCT_TM_HASZONE /* Backward compat */
3604 # ifndef HAS_TM_TM_ZONE
3605 # define HAS_TM_TM_ZONE
3610 Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
3612 #ifdef HAS_TM_TM_ZONE
3614 const struct tm* my_tm;
3616 my_tm = localtime(&now);
3618 Copy(my_tm, ptm, 1, struct tm);
3620 PERL_UNUSED_ARG(ptm);
3625 * mini_mktime - normalise struct tm values without the localtime()
3626 * semantics (and overhead) of mktime().
3629 Perl_mini_mktime(pTHX_ struct tm *ptm)
3633 int month, mday, year, jday;
3634 int odd_cent, odd_year;
3635 PERL_UNUSED_CONTEXT;
3637 #define DAYS_PER_YEAR 365
3638 #define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
3639 #define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
3640 #define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
3641 #define SECS_PER_HOUR (60*60)
3642 #define SECS_PER_DAY (24*SECS_PER_HOUR)
3643 /* parentheses deliberately absent on these two, otherwise they don't work */
3644 #define MONTH_TO_DAYS 153/5
3645 #define DAYS_TO_MONTH 5/153
3646 /* offset to bias by March (month 4) 1st between month/mday & year finding */
3647 #define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
3648 /* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
3649 #define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
3652 * Year/day algorithm notes:
3654 * With a suitable offset for numeric value of the month, one can find
3655 * an offset into the year by considering months to have 30.6 (153/5) days,
3656 * using integer arithmetic (i.e., with truncation). To avoid too much
3657 * messing about with leap days, we consider January and February to be
3658 * the 13th and 14th month of the previous year. After that transformation,
3659 * we need the month index we use to be high by 1 from 'normal human' usage,
3660 * so the month index values we use run from 4 through 15.
3662 * Given that, and the rules for the Gregorian calendar (leap years are those
3663 * divisible by 4 unless also divisible by 100, when they must be divisible
3664 * by 400 instead), we can simply calculate the number of days since some
3665 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
3666 * the days we derive from our month index, and adding in the day of the
3667 * month. The value used here is not adjusted for the actual origin which
3668 * it normally would use (1 January A.D. 1), since we're not exposing it.
3669 * We're only building the value so we can turn around and get the
3670 * normalised values for the year, month, day-of-month, and day-of-year.
3672 * For going backward, we need to bias the value we're using so that we find
3673 * the right year value. (Basically, we don't want the contribution of
3674 * March 1st to the number to apply while deriving the year). Having done
3675 * that, we 'count up' the contribution to the year number by accounting for
3676 * full quadracenturies (400-year periods) with their extra leap days, plus
3677 * the contribution from full centuries (to avoid counting in the lost leap
3678 * days), plus the contribution from full quad-years (to count in the normal
3679 * leap days), plus the leftover contribution from any non-leap years.
3680 * At this point, if we were working with an actual leap day, we'll have 0
3681 * days left over. This is also true for March 1st, however. So, we have
3682 * to special-case that result, and (earlier) keep track of the 'odd'
3683 * century and year contributions. If we got 4 extra centuries in a qcent,
3684 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
3685 * Otherwise, we add back in the earlier bias we removed (the 123 from
3686 * figuring in March 1st), find the month index (integer division by 30.6),
3687 * and the remainder is the day-of-month. We then have to convert back to
3688 * 'real' months (including fixing January and February from being 14/15 in
3689 * the previous year to being in the proper year). After that, to get
3690 * tm_yday, we work with the normalised year and get a new yearday value for
3691 * January 1st, which we subtract from the yearday value we had earlier,
3692 * representing the date we've re-built. This is done from January 1
3693 * because tm_yday is 0-origin.
3695 * Since POSIX time routines are only guaranteed to work for times since the
3696 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
3697 * applies Gregorian calendar rules even to dates before the 16th century
3698 * doesn't bother me. Besides, you'd need cultural context for a given
3699 * date to know whether it was Julian or Gregorian calendar, and that's
3700 * outside the scope for this routine. Since we convert back based on the
3701 * same rules we used to build the yearday, you'll only get strange results
3702 * for input which needed normalising, or for the 'odd' century years which
3703 * were leap years in the Julian calander but not in the Gregorian one.
3704 * I can live with that.
3706 * This algorithm also fails to handle years before A.D. 1 gracefully, but
3707 * that's still outside the scope for POSIX time manipulation, so I don't
3711 year = 1900 + ptm->tm_year;
3712 month = ptm->tm_mon;
3713 mday = ptm->tm_mday;
3714 /* allow given yday with no month & mday to dominate the result */
3715 if (ptm->tm_yday >= 0 && mday <= 0 && month <= 0) {
3718 jday = 1 + ptm->tm_yday;
3727 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
3728 yearday += month*MONTH_TO_DAYS + mday + jday;
3730 * Note that we don't know when leap-seconds were or will be,
3731 * so we have to trust the user if we get something which looks
3732 * like a sensible leap-second. Wild values for seconds will
3733 * be rationalised, however.
3735 if ((unsigned) ptm->tm_sec <= 60) {
3742 secs += 60 * ptm->tm_min;
3743 secs += SECS_PER_HOUR * ptm->tm_hour;
3745 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
3746 /* got negative remainder, but need positive time */
3747 /* back off an extra day to compensate */
3748 yearday += (secs/SECS_PER_DAY)-1;
3749 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
3752 yearday += (secs/SECS_PER_DAY);
3753 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
3756 else if (secs >= SECS_PER_DAY) {
3757 yearday += (secs/SECS_PER_DAY);
3758 secs %= SECS_PER_DAY;
3760 ptm->tm_hour = secs/SECS_PER_HOUR;
3761 secs %= SECS_PER_HOUR;
3762 ptm->tm_min = secs/60;
3764 ptm->tm_sec += secs;
3765 /* done with time of day effects */
3767 * The algorithm for yearday has (so far) left it high by 428.
3768 * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
3769 * bias it by 123 while trying to figure out what year it
3770 * really represents. Even with this tweak, the reverse
3771 * translation fails for years before A.D. 0001.
3772 * It would still fail for Feb 29, but we catch that one below.
3774 jday = yearday; /* save for later fixup vis-a-vis Jan 1 */
3775 yearday -= YEAR_ADJUST;
3776 year = (yearday / DAYS_PER_QCENT) * 400;
3777 yearday %= DAYS_PER_QCENT;
3778 odd_cent = yearday / DAYS_PER_CENT;
3779 year += odd_cent * 100;
3780 yearday %= DAYS_PER_CENT;
3781 year += (yearday / DAYS_PER_QYEAR) * 4;
3782 yearday %= DAYS_PER_QYEAR;
3783 odd_year = yearday / DAYS_PER_YEAR;
3785 yearday %= DAYS_PER_YEAR;
3786 if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
3791 yearday += YEAR_ADJUST; /* recover March 1st crock */
3792 month = yearday*DAYS_TO_MONTH;
3793 yearday -= month*MONTH_TO_DAYS;
3794 /* recover other leap-year adjustment */
3803 ptm->tm_year = year - 1900;
3805 ptm->tm_mday = yearday;
3806 ptm->tm_mon = month;
3810 ptm->tm_mon = month - 1;
3812 /* re-build yearday based on Jan 1 to get tm_yday */
3814 yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
3815 yearday += 14*MONTH_TO_DAYS + 1;
3816 ptm->tm_yday = jday - yearday;
3817 /* fix tm_wday if not overridden by caller */
3818 if ((unsigned)ptm->tm_wday > 6)
3819 ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
3823 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)
3831 init_tm(&mytm); /* XXX workaround - see init_tm() above */
3834 mytm.tm_hour = hour;
3835 mytm.tm_mday = mday;
3837 mytm.tm_year = year;
3838 mytm.tm_wday = wday;
3839 mytm.tm_yday = yday;
3840 mytm.tm_isdst = isdst;
3842 /* use libc to get the values for tm_gmtoff and tm_zone [perl #18238] */
3843 #if defined(HAS_MKTIME) && (defined(HAS_TM_TM_GMTOFF) || defined(HAS_TM_TM_ZONE))
3848 #ifdef HAS_TM_TM_GMTOFF
3849 mytm.tm_gmtoff = mytm2.tm_gmtoff;
3851 #ifdef HAS_TM_TM_ZONE
3852 mytm.tm_zone = mytm2.tm_zone;
3857 Newx(buf, buflen, char);
3858 len = strftime(buf, buflen, fmt, &mytm);
3860 ** The following is needed to handle to the situation where
3861 ** tmpbuf overflows. Basically we want to allocate a buffer
3862 ** and try repeatedly. The reason why it is so complicated
3863 ** is that getting a return value of 0 from strftime can indicate
3864 ** one of the following:
3865 ** 1. buffer overflowed,
3866 ** 2. illegal conversion specifier, or
3867 ** 3. the format string specifies nothing to be returned(not
3868 ** an error). This could be because format is an empty string
3869 ** or it specifies %p that yields an empty string in some locale.
3870 ** If there is a better way to make it portable, go ahead by
3873 if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
3876 /* Possibly buf overflowed - try again with a bigger buf */
3877 const int fmtlen = strlen(fmt);
3878 int bufsize = fmtlen + buflen;
3880 Newx(buf, bufsize, char);
3882 buflen = strftime(buf, bufsize, fmt, &mytm);
3883 if (buflen > 0 && buflen < bufsize)
3885 /* heuristic to prevent out-of-memory errors */
3886 if (bufsize > 100*fmtlen) {
3892 Renew(buf, bufsize, char);
3897 Perl_croak(aTHX_ "panic: no strftime");
3903 #define SV_CWD_RETURN_UNDEF \
3904 sv_setsv(sv, &PL_sv_undef); \
3907 #define SV_CWD_ISDOT(dp) \
3908 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
3909 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
3912 =head1 Miscellaneous Functions
3914 =for apidoc getcwd_sv
3916 Fill the sv with current working directory
3921 /* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
3922 * rewritten again by dougm, optimized for use with xs TARG, and to prefer
3923 * getcwd(3) if available
3924 * Comments from the orignal:
3925 * This is a faster version of getcwd. It's also more dangerous
3926 * because you might chdir out of a directory that you can't chdir
3930 Perl_getcwd_sv(pTHX_ register SV *sv)
3934 #ifndef INCOMPLETE_TAINTS
3940 char buf[MAXPATHLEN];
3942 /* Some getcwd()s automatically allocate a buffer of the given
3943 * size from the heap if they are given a NULL buffer pointer.
3944 * The problem is that this behaviour is not portable. */
3945 if (getcwd(buf, sizeof(buf) - 1)) {
3950 sv_setsv(sv, &PL_sv_undef);
3958 int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
3962 SvUPGRADE(sv, SVt_PV);
3964 if (PerlLIO_lstat(".", &statbuf) < 0) {
3965 SV_CWD_RETURN_UNDEF;
3968 orig_cdev = statbuf.st_dev;
3969 orig_cino = statbuf.st_ino;
3978 if (PerlDir_chdir("..") < 0) {
3979 SV_CWD_RETURN_UNDEF;
3981 if (PerlLIO_stat(".", &statbuf) < 0) {
3982 SV_CWD_RETURN_UNDEF;
3985 cdev = statbuf.st_dev;
3986 cino = statbuf.st_ino;
3988 if (odev == cdev && oino == cino) {
3991 if (!(dir = PerlDir_open("."))) {
3992 SV_CWD_RETURN_UNDEF;
3995 while ((dp = PerlDir_read(dir)) != NULL) {
3997 const int namelen = dp->d_namlen;
3999 const int namelen = strlen(dp->d_name);
4002 if (SV_CWD_ISDOT(dp)) {
4006 if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
4007 SV_CWD_RETURN_UNDEF;
4010 tdev = statbuf.st_dev;
4011 tino = statbuf.st_ino;
4012 if (tino == oino && tdev == odev) {
4018 SV_CWD_RETURN_UNDEF;
4021 if (pathlen + namelen + 1 >= MAXPATHLEN) {
4022 SV_CWD_RETURN_UNDEF;
4025 SvGROW(sv, pathlen + namelen + 1);
4029 Move(SvPVX_const(sv), SvPVX(sv) + namelen + 1, pathlen, char);
4032 /* prepend current directory to the front */
4034 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
4035 pathlen += (namelen + 1);
4037 #ifdef VOID_CLOSEDIR
4040 if (PerlDir_close(dir) < 0) {
4041 SV_CWD_RETURN_UNDEF;
4047 SvCUR_set(sv, pathlen);
4051 if (PerlDir_chdir(SvPVX_const(sv)) < 0) {
4052 SV_CWD_RETURN_UNDEF;
4055 if (PerlLIO_stat(".", &statbuf) < 0) {
4056 SV_CWD_RETURN_UNDEF;
4059 cdev = statbuf.st_dev;
4060 cino = statbuf.st_ino;
4062 if (cdev != orig_cdev || cino != orig_cino) {
4063 Perl_croak(aTHX_ "Unstable directory path, "
4064 "current directory changed unexpectedly");
4076 =for apidoc scan_version
4078 Returns a pointer to the next character after the parsed
4079 version string, as well as upgrading the passed in SV to
4082 Function must be called with an already existing SV like
4085 s = scan_version(s, SV *sv, bool qv);
4087 Performs some preprocessing to the string to ensure that
4088 it has the correct characteristics of a version. Flags the
4089 object if it contains an underscore (which denotes this
4090 is an alpha version). The boolean qv denotes that the version
4091 should be interpreted as if it had multiple decimals, even if
4098 Perl_scan_version(pTHX_ const char *s, SV *rv, bool qv)
4106 AV * const av = newAV();
4107 SV * const hv = newSVrv(rv, "version"); /* create an SV and upgrade the RV */
4108 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
4110 #ifndef NODEFAULT_SHAREKEYS
4111 HvSHAREKEYS_on(hv); /* key-sharing on by default */
4114 while (isSPACE(*s)) /* leading whitespace is OK */
4118 s++; /* get past 'v' */
4119 qv = 1; /* force quoted version processing */
4122 start = last = pos = s;
4124 /* pre-scan the input string to check for decimals/underbars */
4125 while ( *pos == '.' || *pos == '_' || isDIGIT(*pos) )
4130 Perl_croak(aTHX_ "Invalid version format (underscores before decimal)");
4134 else if ( *pos == '_' )
4137 Perl_croak(aTHX_ "Invalid version format (multiple underscores)");
4139 width = pos - last - 1; /* natural width of sub-version */
4144 if ( alpha && !saw_period )
4145 Perl_croak(aTHX_ "Invalid version format (alpha without decimal)");
4147 if ( alpha && saw_period && width == 0 )
4148 Perl_croak(aTHX_ "Invalid version format (misplaced _ in number)");
4150 if ( saw_period > 1 )
4151 qv = 1; /* force quoted version processing */
4156 hv_store((HV *)hv, "qv", 2, newSViv(qv), 0);
4158 hv_store((HV *)hv, "alpha", 5, newSViv(alpha), 0);
4159 if ( !qv && width < 3 )
4160 hv_store((HV *)hv, "width", 5, newSViv(width), 0);
4162 while (isDIGIT(*pos))
4164 if (!isALPHA(*pos)) {
4170 /* this is atoi() that delimits on underscores */
4171 const char *end = pos;
4175 /* the following if() will only be true after the decimal
4176 * point of a version originally created with a bare
4177 * floating point number, i.e. not quoted in any way
4179 if ( !qv && s > start && saw_period == 1 ) {
4183 rev += (*s - '0') * mult;
4185 if ( PERL_ABS(orev) > PERL_ABS(rev) )
4186 Perl_croak(aTHX_ "Integer overflow in version");
4193 while (--end >= s) {
4195 rev += (*end - '0') * mult;
4197 if ( PERL_ABS(orev) > PERL_ABS(rev) )
4198 Perl_croak(aTHX_ "Integer overflow in version");
4203 /* Append revision */
4204 av_push(av, newSViv(rev));
4207 else if ( *pos == '_' && isDIGIT(pos[1]) )
4209 else if ( isDIGIT(*pos) )
4216 while ( isDIGIT(*pos) )
4221 while ( ( isDIGIT(*pos) || *pos == '_' ) && digits < 3 ) {
4229 if ( qv ) { /* quoted versions always get at least three terms*/
4230 I32 len = av_len(av);
4231 /* This for loop appears to trigger a compiler bug on OS X, as it
4232 loops infinitely. Yes, len is negative. No, it makes no sense.
4233 Compiler in question is:
4234 gcc version 3.3 20030304 (Apple Computer, Inc. build 1640)
4235 for ( len = 2 - len; len > 0; len-- )
4236 av_push((AV *)sv, newSViv(0));
4240 av_push(av, newSViv(0));
4243 if ( av_len(av) == -1 ) /* oops, someone forgot to pass a value */
4244 av_push(av, newSViv(0));
4246 /* fix RT#19517 - special case 'undef' as string */
4247 if ( *s == 'u' && strEQ(s,"undef") ) {
4251 /* And finally, store the AV in the hash */
4252 hv_store((HV *)hv, "version", 7, newRV_noinc((SV *)av), 0);
4257 =for apidoc new_version
4259 Returns a new version object based on the passed in SV:
4261 SV *sv = new_version(SV *ver);
4263 Does not alter the passed in ver SV. See "upg_version" if you
4264 want to upgrade the SV.
4270 Perl_new_version(pTHX_ SV *ver)
4273 SV * const rv = newSV(0);
4274 if ( sv_derived_from(ver,"version") ) /* can just copy directly */
4277 AV * const av = newAV();
4279 /* This will get reblessed later if a derived class*/
4280 SV * const hv = newSVrv(rv, "version");
4281 (void)sv_upgrade(hv, SVt_PVHV); /* needs to be an HV type */
4282 #ifndef NODEFAULT_SHAREKEYS
4283 HvSHAREKEYS_on(hv); /* key-sharing on by default */
4289 /* Begin copying all of the elements */
4290 if ( hv_exists((HV *)ver, "qv", 2) )
4291 hv_store((HV *)hv, "qv", 2, &PL_sv_yes, 0);
4293 if ( hv_exists((HV *)ver, "alpha", 5) )
4294 hv_store((HV *)hv, "alpha", 5, &PL_sv_yes, 0);
4296 if ( hv_exists((HV*)ver, "width", 5 ) )
4298 const I32 width = SvIV(*hv_fetchs((HV*)ver, "width", FALSE));
4299 hv_store((HV *)hv, "width", 5, newSViv(width), 0);
4302 sav = (AV *)SvRV(*hv_fetchs((HV*)ver, "version", FALSE));
4303 /* This will get reblessed later if a derived class*/
4304 for ( key = 0; key <= av_len(sav); key++ )
4306 const I32 rev = SvIV(*av_fetch(sav, key, FALSE));
4307 av_push(av, newSViv(rev));
4310 hv_store((HV *)hv, "version", 7, newRV_noinc((SV *)av), 0);
4315 const MAGIC* const mg = SvVSTRING_mg(ver);
4316 if ( mg ) { /* already a v-string */
4317 const STRLEN len = mg->mg_len;
4318 char * const version = savepvn( (const char*)mg->mg_ptr, len);
4319 sv_setpvn(rv,version,len);
4324 sv_setsv(rv,ver); /* make a duplicate */
4329 return upg_version(rv);
4333 =for apidoc upg_version
4335 In-place upgrade of the supplied SV to a version object.
4337 SV *sv = upg_version(SV *sv);
4339 Returns a pointer to the upgraded SV.
4345 Perl_upg_version(pTHX_ SV *ver)
4347 const char *version, *s;
4353 if ( SvNOK(ver) ) /* may get too much accuracy */
4356 #ifdef USE_LOCALE_NUMERIC
4357 char *loc = setlocale(LC_NUMERIC, "C");
4359 STRLEN len = my_snprintf(tbuf, sizeof(tbuf), "%.9"NVff, SvNVX(ver));
4360 #ifdef USE_LOCALE_NUMERIC
4361 setlocale(LC_NUMERIC, loc);
4363 while (tbuf[len-1] == '0' && len > 0) len--;
4364 version = savepvn(tbuf, len);
4367 else if ( (mg = SvVSTRING_mg(ver)) ) { /* already a v-string */
4368 version = savepvn( (const char*)mg->mg_ptr,mg->mg_len );
4372 else /* must be a string or something like a string */
4374 version = savepv(SvPV_nolen(ver));
4377 s = scan_version(version, ver, qv);
4379 if(ckWARN(WARN_MISC))
4380 Perl_warner(aTHX_ packWARN(WARN_MISC),
4381 "Version string '%s' contains invalid data; "
4382 "ignoring: '%s'", version, s);
4390 Validates that the SV contains a valid version object.
4392 bool vverify(SV *vobj);
4394 Note that it only confirms the bare minimum structure (so as not to get
4395 confused by derived classes which may contain additional hash entries):
4399 =item * The SV contains a [reference to a] hash
4401 =item * The hash contains a "version" key
4403 =item * The "version" key has [a reference to] an AV as its value
4411 Perl_vverify(pTHX_ SV *vs)
4417 /* see if the appropriate elements exist */
4418 if ( SvTYPE(vs) == SVt_PVHV
4419 && hv_exists((HV*)vs, "version", 7)
4420 && (sv = SvRV(*hv_fetchs((HV*)vs, "version", FALSE)))
4421 && SvTYPE(sv) == SVt_PVAV )
4430 Accepts a version object and returns the normalized floating
4431 point representation. Call like:
4435 NOTE: you can pass either the object directly or the SV
4436 contained within the RV.
4442 Perl_vnumify(pTHX_ SV *vs)
4447 SV * const sv = newSV(0);
4453 Perl_croak(aTHX_ "Invalid version object");
4455 /* see if various flags exist */
4456 if ( hv_exists((HV*)vs, "alpha", 5 ) )
4458 if ( hv_exists((HV*)vs, "width", 5 ) )
4459 width = SvIV(*hv_fetchs((HV*)vs, "width", FALSE));
4464 /* attempt to retrieve the version array */
4465 if ( !(av = (AV *)SvRV(*hv_fetchs((HV*)vs, "version", FALSE)) ) ) {
4477 digit = SvIV(*av_fetch(av, 0, 0));
4478 Perl_sv_setpvf(aTHX_ sv, "%d.", (int)PERL_ABS(digit));
4479 for ( i = 1 ; i < len ; i++ )
4481 digit = SvIV(*av_fetch(av, i, 0));
4483 const int denom = (width == 2 ? 10 : 100);
4484 const div_t term = div((int)PERL_ABS(digit),denom);
4485 Perl_sv_catpvf(aTHX_ sv, "%0*d_%d", width, term.quot, term.rem);
4488 Perl_sv_catpvf(aTHX_ sv, "%0*d", width, (int)digit);
4494 digit = SvIV(*av_fetch(av, len, 0));
4495 if ( alpha && width == 3 ) /* alpha version */
4497 Perl_sv_catpvf(aTHX_ sv, "%0*d", width, (int)digit);
4501 sv_catpvs(sv, "000");
4509 Accepts a version object and returns the normalized string
4510 representation. Call like:
4514 NOTE: you can pass either the object directly or the SV
4515 contained within the RV.
4521 Perl_vnormal(pTHX_ SV *vs)
4525 SV * const sv = newSV(0);
4531 Perl_croak(aTHX_ "Invalid version object");
4533 if ( hv_exists((HV*)vs, "alpha", 5 ) )
4535 av = (AV *)SvRV(*hv_fetchs((HV*)vs, "version", FALSE));
4543 digit = SvIV(*av_fetch(av, 0, 0));
4544 Perl_sv_setpvf(aTHX_ sv, "v%"IVdf, (IV)digit);
4545 for ( i = 1 ; i < len ; i++ ) {
4546 digit = SvIV(*av_fetch(av, i, 0));
4547 Perl_sv_catpvf(aTHX_ sv, ".%"IVdf, (IV)digit);
4552 /* handle last digit specially */
4553 digit = SvIV(*av_fetch(av, len, 0));
4555 Perl_sv_catpvf(aTHX_ sv, "_%"IVdf, (IV)digit);
4557 Perl_sv_catpvf(aTHX_ sv, ".%"IVdf, (IV)digit);
4560 if ( len <= 2 ) { /* short version, must be at least three */
4561 for ( len = 2 - len; len != 0; len-- )
4568 =for apidoc vstringify
4570 In order to maintain maximum compatibility with earlier versions
4571 of Perl, this function will return either the floating point
4572 notation or the multiple dotted notation, depending on whether
4573 the original version contained 1 or more dots, respectively
4579 Perl_vstringify(pTHX_ SV *vs)
4585 Perl_croak(aTHX_ "Invalid version object");
4587 if ( hv_exists((HV *)vs, "qv", 2) )
4596 Version object aware cmp. Both operands must already have been
4597 converted into version objects.
4603 Perl_vcmp(pTHX_ SV *lhv, SV *rhv)
4606 bool lalpha = FALSE;
4607 bool ralpha = FALSE;
4616 if ( !vverify(lhv) )
4617 Perl_croak(aTHX_ "Invalid version object");
4619 if ( !vverify(rhv) )
4620 Perl_croak(aTHX_ "Invalid version object");
4622 /* get the left hand term */
4623 lav = (AV *)SvRV(*hv_fetchs((HV*)lhv, "version", FALSE));
4624 if ( hv_exists((HV*)lhv, "alpha", 5 ) )
4627 /* and the right hand term */
4628 rav = (AV *)SvRV(*hv_fetchs((HV*)rhv, "version", FALSE));
4629 if ( hv_exists((HV*)rhv, "alpha", 5 ) )
4637 while ( i <= m && retval == 0 )
4639 left = SvIV(*av_fetch(lav,i,0));
4640 right = SvIV(*av_fetch(rav,i,0));
4648 /* tiebreaker for alpha with identical terms */
4649 if ( retval == 0 && l == r && left == right && ( lalpha || ralpha ) )
4651 if ( lalpha && !ralpha )
4655 else if ( ralpha && !lalpha)
4661 if ( l != r && retval == 0 ) /* possible match except for trailing 0's */
4665 while ( i <= r && retval == 0 )
4667 if ( SvIV(*av_fetch(rav,i,0)) != 0 )
4668 retval = -1; /* not a match after all */
4674 while ( i <= l && retval == 0 )
4676 if ( SvIV(*av_fetch(lav,i,0)) != 0 )
4677 retval = +1; /* not a match after all */
4685 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET) && defined(SOCK_DGRAM) && defined(HAS_SELECT)
4686 # define EMULATE_SOCKETPAIR_UDP
4689 #ifdef EMULATE_SOCKETPAIR_UDP
4691 S_socketpair_udp (int fd[2]) {
4693 /* Fake a datagram socketpair using UDP to localhost. */
4694 int sockets[2] = {-1, -1};
4695 struct sockaddr_in addresses[2];
4697 Sock_size_t size = sizeof(struct sockaddr_in);
4698 unsigned short port;
4701 memset(&addresses, 0, sizeof(addresses));
4704 sockets[i] = PerlSock_socket(AF_INET, SOCK_DGRAM, PF_INET);
4705 if (sockets[i] == -1)
4706 goto tidy_up_and_fail;
4708 addresses[i].sin_family = AF_INET;
4709 addresses[i].sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4710 addresses[i].sin_port = 0; /* kernel choses port. */
4711 if (PerlSock_bind(sockets[i], (struct sockaddr *) &addresses[i],
4712 sizeof(struct sockaddr_in)) == -1)
4713 goto tidy_up_and_fail;
4716 /* Now have 2 UDP sockets. Find out which port each is connected to, and
4717 for each connect the other socket to it. */
4720 if (PerlSock_getsockname(sockets[i], (struct sockaddr *) &addresses[i],
4722 goto tidy_up_and_fail;
4723 if (size != sizeof(struct sockaddr_in))
4724 goto abort_tidy_up_and_fail;
4725 /* !1 is 0, !0 is 1 */
4726 if (PerlSock_connect(sockets[!i], (struct sockaddr *) &addresses[i],
4727 sizeof(struct sockaddr_in)) == -1)
4728 goto tidy_up_and_fail;
4731 /* Now we have 2 sockets connected to each other. I don't trust some other
4732 process not to have already sent a packet to us (by random) so send
4733 a packet from each to the other. */
4736 /* I'm going to send my own port number. As a short.
4737 (Who knows if someone somewhere has sin_port as a bitfield and needs
4738 this routine. (I'm assuming crays have socketpair)) */
4739 port = addresses[i].sin_port;
4740 got = PerlLIO_write(sockets[i], &port, sizeof(port));
4741 if (got != sizeof(port)) {
4743 goto tidy_up_and_fail;
4744 goto abort_tidy_up_and_fail;
4748 /* Packets sent. I don't trust them to have arrived though.
4749 (As I understand it Solaris TCP stack is multithreaded. Non-blocking
4750 connect to localhost will use a second kernel thread. In 2.6 the
4751 first thread running the connect() returns before the second completes,
4752 so EINPROGRESS> In 2.7 the improved stack is faster and connect()
4753 returns 0. Poor programs have tripped up. One poor program's authors'
4754 had a 50-1 reverse stock split. Not sure how connected these were.)
4755 So I don't trust someone not to have an unpredictable UDP stack.
4759 struct timeval waitfor = {0, 100000}; /* You have 0.1 seconds */
4760 int max = sockets[1] > sockets[0] ? sockets[1] : sockets[0];
4764 FD_SET((unsigned int)sockets[0], &rset);
4765 FD_SET((unsigned int)sockets[1], &rset);
4767 got = PerlSock_select(max + 1, &rset, NULL, NULL, &waitfor);
4768 if (got != 2 || !FD_ISSET(sockets[0], &rset)
4769 || !FD_ISSET(sockets[1], &rset)) {
4770 /* I hope this is portable and appropriate. */
4772 goto tidy_up_and_fail;
4773 goto abort_tidy_up_and_fail;
4777 /* And the paranoia department even now doesn't trust it to have arrive
4778 (hence MSG_DONTWAIT). Or that what arrives was sent by us. */
4780 struct sockaddr_in readfrom;
4781 unsigned short buffer[2];
4786 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4787 sizeof(buffer), MSG_DONTWAIT,
4788 (struct sockaddr *) &readfrom, &size);
4790 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4792 (struct sockaddr *) &readfrom, &size);
4796 goto tidy_up_and_fail;
4797 if (got != sizeof(port)
4798 || size != sizeof(struct sockaddr_in)
4799 /* Check other socket sent us its port. */
4800 || buffer[0] != (unsigned short) addresses[!i].sin_port
4801 /* Check kernel says we got the datagram from that socket */
4802 || readfrom.sin_family != addresses[!i].sin_family
4803 || readfrom.sin_addr.s_addr != addresses[!i].sin_addr.s_addr
4804 || readfrom.sin_port != addresses[!i].sin_port)
4805 goto abort_tidy_up_and_fail;
4808 /* My caller (my_socketpair) has validated that this is non-NULL */
4811 /* I hereby declare this connection open. May God bless all who cross
4815 abort_tidy_up_and_fail:
4816 errno = ECONNABORTED;
4819 const int save_errno = errno;
4820 if (sockets[0] != -1)
4821 PerlLIO_close(sockets[0]);
4822 if (sockets[1] != -1)
4823 PerlLIO_close(sockets[1]);
4828 #endif /* EMULATE_SOCKETPAIR_UDP */
4830 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET)
4832 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4833 /* Stevens says that family must be AF_LOCAL, protocol 0.
4834 I'm going to enforce that, then ignore it, and use TCP (or UDP). */
4839 struct sockaddr_in listen_addr;
4840 struct sockaddr_in connect_addr;
4845 || family != AF_UNIX
4848 errno = EAFNOSUPPORT;
4856 #ifdef EMULATE_SOCKETPAIR_UDP
4857 if (type == SOCK_DGRAM)
4858 return S_socketpair_udp(fd);
4861 listener = PerlSock_socket(AF_INET, type, 0);
4864 memset(&listen_addr, 0, sizeof(listen_addr));
4865 listen_addr.sin_family = AF_INET;
4866 listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4867 listen_addr.sin_port = 0; /* kernel choses port. */
4868 if (PerlSock_bind(listener, (struct sockaddr *) &listen_addr,
4869 sizeof(listen_addr)) == -1)
4870 goto tidy_up_and_fail;
4871 if (PerlSock_listen(listener, 1) == -1)
4872 goto tidy_up_and_fail;
4874 connector = PerlSock_socket(AF_INET, type, 0);
4875 if (connector == -1)
4876 goto tidy_up_and_fail;
4877 /* We want to find out the port number to connect to. */
4878 size = sizeof(connect_addr);
4879 if (PerlSock_getsockname(listener, (struct sockaddr *) &connect_addr,
4881 goto tidy_up_and_fail;
4882 if (size != sizeof(connect_addr))
4883 goto abort_tidy_up_and_fail;
4884 if (PerlSock_connect(connector, (struct sockaddr *) &connect_addr,
4885 sizeof(connect_addr)) == -1)
4886 goto tidy_up_and_fail;
4888 size = sizeof(listen_addr);
4889 acceptor = PerlSock_accept(listener, (struct sockaddr *) &listen_addr,
4892 goto tidy_up_and_fail;
4893 if (size != sizeof(listen_addr))
4894 goto abort_tidy_up_and_fail;
4895 PerlLIO_close(listener);
4896 /* Now check we are talking to ourself by matching port and host on the
4898 if (PerlSock_getsockname(connector, (struct sockaddr *) &connect_addr,
4900 goto tidy_up_and_fail;
4901 if (size != sizeof(connect_addr)
4902 || listen_addr.sin_family != connect_addr.sin_family
4903 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
4904 || listen_addr.sin_port != connect_addr.sin_port) {
4905 goto abort_tidy_up_and_fail;
4911 abort_tidy_up_and_fail:
4913 errno = ECONNABORTED; /* This would be the standard thing to do. */
4915 # ifdef ECONNREFUSED
4916 errno = ECONNREFUSED; /* E.g. Symbian does not have ECONNABORTED. */
4918 errno = ETIMEDOUT; /* Desperation time. */
4923 const int save_errno = errno;
4925 PerlLIO_close(listener);
4926 if (connector != -1)
4927 PerlLIO_close(connector);
4929 PerlLIO_close(acceptor);
4935 /* In any case have a stub so that there's code corresponding
4936 * to the my_socketpair in global.sym. */
4938 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4939 #ifdef HAS_SOCKETPAIR
4940 return socketpair(family, type, protocol, fd);
4949 =for apidoc sv_nosharing
4951 Dummy routine which "shares" an SV when there is no sharing module present.
4952 Or "locks" it. Or "unlocks" it. In other words, ignores its single SV argument.
4953 Exists to avoid test for a NULL function pointer and because it could
4954 potentially warn under some level of strict-ness.
4960 Perl_sv_nosharing(pTHX_ SV *sv)
4962 PERL_UNUSED_CONTEXT;
4963 PERL_UNUSED_ARG(sv);
4967 Perl_parse_unicode_opts(pTHX_ const char **popt)
4969 const char *p = *popt;
4974 opt = (U32) atoi(p);
4977 if (*p && *p != '\n' && *p != '\r')
4978 Perl_croak(aTHX_ "Unknown Unicode option letter '%c'", *p);
4983 case PERL_UNICODE_STDIN:
4984 opt |= PERL_UNICODE_STDIN_FLAG; break;
4985 case PERL_UNICODE_STDOUT:
4986 opt |= PERL_UNICODE_STDOUT_FLAG; break;
4987 case PERL_UNICODE_STDERR:
4988 opt |= PERL_UNICODE_STDERR_FLAG; break;
4989 case PERL_UNICODE_STD:
4990 opt |= PERL_UNICODE_STD_FLAG; break;
4991 case PERL_UNICODE_IN:
4992 opt |= PERL_UNICODE_IN_FLAG; break;
4993 case PERL_UNICODE_OUT:
4994 opt |= PERL_UNICODE_OUT_FLAG; break;
4995 case PERL_UNICODE_INOUT:
4996 opt |= PERL_UNICODE_INOUT_FLAG; break;
4997 case PERL_UNICODE_LOCALE:
4998 opt |= PERL_UNICODE_LOCALE_FLAG; break;
4999 case PERL_UNICODE_ARGV:
5000 opt |= PERL_UNICODE_ARGV_FLAG; break;
5001 case PERL_UNICODE_UTF8CACHEASSERT:
5002 opt |= PERL_UNICODE_UTF8CACHEASSERT_FLAG; break;
5004 if (*p != '\n' && *p != '\r')
5006 "Unknown Unicode option letter '%c'", *p);
5012 opt = PERL_UNICODE_DEFAULT_FLAGS;
5014 if (opt & ~PERL_UNICODE_ALL_FLAGS)
5015 Perl_croak(aTHX_ "Unknown Unicode option value %"UVuf,
5016 (UV) (opt & ~PERL_UNICODE_ALL_FLAGS));
5028 * This is really just a quick hack which grabs various garbage
5029 * values. It really should be a real hash algorithm which
5030 * spreads the effect of every input bit onto every output bit,
5031 * if someone who knows about such things would bother to write it.
5032 * Might be a good idea to add that function to CORE as well.
5033 * No numbers below come from careful analysis or anything here,
5034 * except they are primes and SEED_C1 > 1E6 to get a full-width
5035 * value from (tv_sec * SEED_C1 + tv_usec). The multipliers should
5036 * probably be bigger too.
5039 # define SEED_C1 1000003
5040 #define SEED_C4 73819
5042 # define SEED_C1 25747
5043 #define SEED_C4 20639
5047 #define SEED_C5 26107
5049 #ifndef PERL_NO_DEV_RANDOM
5054 # include <starlet.h>
5055 /* when[] = (low 32 bits, high 32 bits) of time since epoch
5056 * in 100-ns units, typically incremented ever 10 ms. */
5057 unsigned int when[2];
5059 # ifdef HAS_GETTIMEOFDAY
5060 struct timeval when;
5066 /* This test is an escape hatch, this symbol isn't set by Configure. */
5067 #ifndef PERL_NO_DEV_RANDOM
5068 #ifndef PERL_RANDOM_DEVICE
5069 /* /dev/random isn't used by default because reads from it will block
5070 * if there isn't enough entropy available. You can compile with
5071 * PERL_RANDOM_DEVICE to it if you'd prefer Perl to block until there
5072 * is enough real entropy to fill the seed. */
5073 # define PERL_RANDOM_DEVICE "/dev/urandom"
5075 fd = PerlLIO_open(PERL_RANDOM_DEVICE, 0);
5077 if (PerlLIO_read(fd, (void*)&u, sizeof u) != sizeof u)
5086 _ckvmssts(sys$gettim(when));
5087 u = (U32)SEED_C1 * when[0] + (U32)SEED_C2 * when[1];
5089 # ifdef HAS_GETTIMEOFDAY
5090 PerlProc_gettimeofday(&when,NULL);
5091 u = (U32)SEED_C1 * when.tv_sec + (U32)SEED_C2 * when.tv_usec;
5094 u = (U32)SEED_C1 * when;
5097 u += SEED_C3 * (U32)PerlProc_getpid();
5098 u += SEED_C4 * (U32)PTR2UV(PL_stack_sp);
5099 #ifndef PLAN9 /* XXX Plan9 assembler chokes on this; fix needed */
5100 u += SEED_C5 * (U32)PTR2UV(&when);
5106 Perl_get_hash_seed(pTHX)
5109 const char *s = PerlEnv_getenv("PERL_HASH_SEED");
5115 if (s && isDIGIT(*s))
5116 myseed = (UV)Atoul(s);
5118 #ifdef USE_HASH_SEED_EXPLICIT
5122 /* Compute a random seed */
5123 (void)seedDrand01((Rand_seed_t)seed());
5124 myseed = (UV)(Drand01() * (NV)UV_MAX);
5125 #if RANDBITS < (UVSIZE * 8)
5126 /* Since there are not enough randbits to to reach all
5127 * the bits of a UV, the low bits might need extra
5128 * help. Sum in another random number that will
5129 * fill in the low bits. */
5131 (UV)(Drand01() * (NV)((1 << ((UVSIZE * 8 - RANDBITS))) - 1));
5132 #endif /* RANDBITS < (UVSIZE * 8) */
5133 if (myseed == 0) { /* Superparanoia. */
5134 myseed = (UV)(Drand01() * (NV)UV_MAX); /* One more chance. */
5136 Perl_croak(aTHX_ "Your random numbers are not that random");
5139 PL_rehash_seed_set = TRUE;
5146 Perl_stashpv_hvname_match(pTHX_ const COP *c, const HV *hv)
5148 const char * const stashpv = CopSTASHPV(c);
5149 const char * const name = HvNAME_get(hv);
5150 PERL_UNUSED_CONTEXT;
5152 if (stashpv == name)
5154 if (stashpv && name)
5155 if (strEQ(stashpv, name))
5162 #ifdef PERL_GLOBAL_STRUCT
5164 #define PERL_GLOBAL_STRUCT_INIT
5165 #include "opcode.h" /* the ppaddr and check */
5168 Perl_init_global_struct(pTHX)
5170 struct perl_vars *plvarsp = NULL;
5171 # ifdef PERL_GLOBAL_STRUCT
5172 const IV nppaddr = sizeof(Gppaddr)/sizeof(Perl_ppaddr_t);
5173 const IV ncheck = sizeof(Gcheck) /sizeof(Perl_check_t);
5174 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
5175 /* PerlMem_malloc() because can't use even safesysmalloc() this early. */
5176 plvarsp = (struct perl_vars*)PerlMem_malloc(sizeof(struct perl_vars));
5180 plvarsp = PL_VarsPtr;
5181 # endif /* PERL_GLOBAL_STRUCT_PRIVATE */
5187 # define PERLVAR(var,type) /**/
5188 # define PERLVARA(var,n,type) /**/
5189 # define PERLVARI(var,type,init) plvarsp->var = init;
5190 # define PERLVARIC(var,type,init) plvarsp->var = init;
5191 # define PERLVARISC(var,init) Copy(init, plvarsp->var, sizeof(init), char);
5192 # include "perlvars.h"
5198 # ifdef PERL_GLOBAL_STRUCT
5201 PerlMem_malloc(nppaddr * sizeof(Perl_ppaddr_t));
5202 if (!plvarsp->Gppaddr)
5206 PerlMem_malloc(ncheck * sizeof(Perl_check_t));
5207 if (!plvarsp->Gcheck)
5209 Copy(Gppaddr, plvarsp->Gppaddr, nppaddr, Perl_ppaddr_t);
5210 Copy(Gcheck, plvarsp->Gcheck, ncheck, Perl_check_t);
5212 # ifdef PERL_SET_VARS
5213 PERL_SET_VARS(plvarsp);
5215 # undef PERL_GLOBAL_STRUCT_INIT
5220 #endif /* PERL_GLOBAL_STRUCT */
5222 #ifdef PERL_GLOBAL_STRUCT
5225 Perl_free_global_struct(pTHX_ struct perl_vars *plvarsp)
5227 # ifdef PERL_GLOBAL_STRUCT
5228 # ifdef PERL_UNSET_VARS
5229 PERL_UNSET_VARS(plvarsp);
5231 free(plvarsp->Gppaddr);
5232 free(plvarsp->Gcheck);
5233 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
5239 #endif /* PERL_GLOBAL_STRUCT */
5244 * PERL_MEM_LOG: the Perl_mem_log_..() will be compiled.
5246 * PERL_MEM_LOG_ENV: if defined, during run time the environment
5247 * variable PERL_MEM_LOG will be consulted, and if the integer value
5248 * of that is true, the logging will happen. (The default is to
5249 * always log if the PERL_MEM_LOG define was in effect.)
5253 * PERL_MEM_LOG_SPRINTF_BUF_SIZE: size of a (stack-allocated) buffer
5254 * the Perl_mem_log_...() will use (either via sprintf or snprintf).
5256 #define PERL_MEM_LOG_SPRINTF_BUF_SIZE 128
5259 * PERL_MEM_LOG_FD: the file descriptor the Perl_mem_log_...() will
5260 * log to. You can also define in compile time PERL_MEM_LOG_ENV_FD,
5261 * in which case the environment variable PERL_MEM_LOG_FD will be
5262 * consulted for the file descriptor number to use.
5264 #ifndef PERL_MEM_LOG_FD
5265 # define PERL_MEM_LOG_FD 2 /* If STDERR is too boring for you. */
5269 Perl_mem_log_alloc(const UV n, const UV typesize, const char *typename, Malloc_t newalloc, const char *filename, const int linenumber, const char *funcname)
5271 #ifdef PERL_MEM_LOG_STDERR
5272 # if defined(PERL_MEM_LOG_ENV) || defined(PERL_MEM_LOG_ENV_FD)
5275 # ifdef PERL_MEM_LOG_ENV
5276 s = getenv("PERL_MEM_LOG");
5277 if (s ? atoi(s) : 0)
5280 /* We can't use SVs or PerlIO for obvious reasons,
5281 * so we'll use stdio and low-level IO instead. */
5282 char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
5283 # ifdef PERL_MEM_LOG_TIMESTAMP
5285 # ifdef HAS_GETTIMEOFDAY
5286 gettimeofday(&tv, 0);
5288 /* If there are other OS specific ways of hires time than
5289 * gettimeofday() (see ext/Time/HiRes), the easiest way is
5290 * probably that they would be used to fill in the struct
5297 # ifdef PERL_MEM_LOG_TIMESTAMP
5300 "alloc: %s:%d:%s: %"IVdf" %"UVuf
5301 " %s = %"IVdf": %"UVxf"\n",
5302 # ifdef PERL_MEM_LOG_TIMESTAMP
5303 (int)tv.tv_sec, (int)tv.tv_usec,
5305 filename, linenumber, funcname, n, typesize,
5306 typename, n * typesize, PTR2UV(newalloc));
5307 # ifdef PERL_MEM_LOG_ENV_FD
5308 s = PerlEnv_getenv("PERL_MEM_LOG_FD");
5309 PerlLIO_write(s ? atoi(s) : PERL_MEM_LOG_FD, buf, len);
5311 PerlLIO_write(PERL_MEM_LOG_FD, buf, len);
5320 Perl_mem_log_realloc(const UV n, const UV typesize, const char *typename, Malloc_t oldalloc, Malloc_t newalloc, const char *filename, const int linenumber, const char *funcname)
5322 #ifdef PERL_MEM_LOG_STDERR
5323 # if defined(PERL_MEM_LOG_ENV) || defined(PERL_MEM_LOG_ENV_FD)
5326 # ifdef PERL_MEM_LOG_ENV
5327 s = PerlEnv_getenv("PERL_MEM_LOG");
5328 if (s ? atoi(s) : 0)
5331 /* We can't use SVs or PerlIO for obvious reasons,
5332 * so we'll use stdio and low-level IO instead. */
5333 char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
5334 # ifdef PERL_MEM_LOG_TIMESTAMP
5336 gettimeofday(&tv, 0);
5342 # ifdef PERL_MEM_LOG_TIMESTAMP
5345 "realloc: %s:%d:%s: %"IVdf" %"UVuf
5346 " %s = %"IVdf": %"UVxf" -> %"UVxf"\n",
5347 # ifdef PERL_MEM_LOG_TIMESTAMP
5348 (int)tv.tv_sec, (int)tv.tv_usec,
5350 filename, linenumber, funcname, n, typesize,
5351 typename, n * typesize, PTR2UV(oldalloc),
5353 # ifdef PERL_MEM_LOG_ENV_FD
5354 s = PerlEnv_getenv("PERL_MEM_LOG_FD");
5355 PerlLIO_write(s ? atoi(s) : PERL_MEM_LOG_FD, buf, len);
5357 PerlLIO_write(PERL_MEM_LOG_FD, buf, len);
5366 Perl_mem_log_free(Malloc_t oldalloc, const char *filename, const int linenumber, const char *funcname)
5368 #ifdef PERL_MEM_LOG_STDERR
5369 # if defined(PERL_MEM_LOG_ENV) || defined(PERL_MEM_LOG_ENV_FD)
5372 # ifdef PERL_MEM_LOG_ENV
5373 s = PerlEnv_getenv("PERL_MEM_LOG");
5374 if (s ? atoi(s) : 0)
5377 /* We can't use SVs or PerlIO for obvious reasons,
5378 * so we'll use stdio and low-level IO instead. */
5379 char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
5380 # ifdef PERL_MEM_LOG_TIMESTAMP
5382 gettimeofday(&tv, 0);
5388 # ifdef PERL_MEM_LOG_TIMESTAMP
5391 "free: %s:%d:%s: %"UVxf"\n",
5392 # ifdef PERL_MEM_LOG_TIMESTAMP
5393 (int)tv.tv_sec, (int)tv.tv_usec,
5395 filename, linenumber, funcname,
5397 # ifdef PERL_MEM_LOG_ENV_FD
5398 s = PerlEnv_getenv("PERL_MEM_LOG_FD");
5399 PerlLIO_write(s ? atoi(s) : PERL_MEM_LOG_FD, buf, len);
5401 PerlLIO_write(PERL_MEM_LOG_FD, buf, len);
5409 #endif /* PERL_MEM_LOG */
5412 =for apidoc my_sprintf
5414 The C library C<sprintf>, wrapped if necessary, to ensure that it will return
5415 the length of the string written to the buffer. Only rare pre-ANSI systems
5416 need the wrapper function - usually this is a direct call to C<sprintf>.
5420 #ifndef SPRINTF_RETURNS_STRLEN
5422 Perl_my_sprintf(char *buffer, const char* pat, ...)
5425 va_start(args, pat);
5426 vsprintf(buffer, pat, args);
5428 return strlen(buffer);
5433 =for apidoc my_snprintf
5435 The C library C<snprintf> functionality, if available and
5436 standards-compliant (uses C<vsnprintf>, actually). However, if the
5437 C<vsnprintf> is not available, will unfortunately use the unsafe
5438 C<vsprintf> which can overrun the buffer (there is an overrun check,
5439 but that may be too late). Consider using C<sv_vcatpvf> instead, or
5440 getting C<vsnprintf>.
5445 Perl_my_snprintf(char *buffer, const Size_t len, const char *format, ...)
5450 va_start(ap, format);
5451 #ifdef HAS_VSNPRINTF
5452 retval = vsnprintf(buffer, len, format, ap);
5454 retval = vsprintf(buffer, format, ap);
5457 /* vsnprintf() shows failure with >= len, vsprintf() with < 0 */
5458 if (retval < 0 || (len > 0 && (Size_t)retval >= len))
5459 Perl_croak(aTHX_ "panic: my_snprintf buffer overflow");
5464 =for apidoc my_vsnprintf
5466 The C library C<vsnprintf> if available and standards-compliant.
5467 However, if if the C<vsnprintf> is not available, will unfortunately
5468 use the unsafe C<vsprintf> which can overrun the buffer (there is an
5469 overrun check, but that may be too late). Consider using
5470 C<sv_vcatpvf> instead, or getting C<vsnprintf>.
5475 Perl_my_vsnprintf(char *buffer, const Size_t len, const char *format, va_list ap)
5481 Perl_va_copy(ap, apc);
5482 # ifdef HAS_VSNPRINTF
5483 retval = vsnprintf(buffer, len, format, apc);
5485 retval = vsprintf(buffer, format, apc);
5488 # ifdef HAS_VSNPRINTF
5489 retval = vsnprintf(buffer, len, format, ap);
5491 retval = vsprintf(buffer, format, ap);
5493 #endif /* #ifdef NEED_VA_COPY */
5494 /* vsnprintf() shows failure with >= len, vsprintf() with < 0 */
5495 if (retval < 0 || (len > 0 && (Size_t)retval >= len))
5496 Perl_croak(aTHX_ "panic: my_vsnprintf buffer overflow");
5501 Perl_my_clearenv(pTHX)
5504 #if ! defined(PERL_MICRO)
5505 # if defined(PERL_IMPLICIT_SYS) || defined(WIN32)
5507 # else /* ! (PERL_IMPLICIT_SYS || WIN32) */
5508 # if defined(USE_ENVIRON_ARRAY)
5509 # if defined(USE_ITHREADS)
5510 /* only the parent thread can clobber the process environment */
5511 if (PL_curinterp == aTHX)
5512 # endif /* USE_ITHREADS */
5514 # if ! defined(PERL_USE_SAFE_PUTENV)
5515 if ( !PL_use_safe_putenv) {
5517 if (environ == PL_origenviron)
5518 environ = (char**)safesysmalloc(sizeof(char*));
5520 for (i = 0; environ[i]; i++)
5521 (void)safesysfree(environ[i]);
5524 # else /* PERL_USE_SAFE_PUTENV */
5525 # if defined(HAS_CLEARENV)
5527 # elif defined(HAS_UNSETENV)
5528 int bsiz = 80; /* Most envvar names will be shorter than this. */
5529 int bufsiz = bsiz * sizeof(char); /* sizeof(char) paranoid? */
5530 char *buf = (char*)safesysmalloc(bufsiz);
5531 while (*environ != NULL) {
5532 char *e = strchr(*environ, '=');
5533 int l = e ? e - *environ : (int)strlen(*environ);
5535 (void)safesysfree(buf);
5536 bsiz = l + 1; /* + 1 for the \0. */
5537 buf = (char*)safesysmalloc(bufsiz);
5539 my_strlcpy(buf, *environ, l + 1);
5540 (void)unsetenv(buf);
5542 (void)safesysfree(buf);
5543 # else /* ! HAS_CLEARENV && ! HAS_UNSETENV */
5544 /* Just null environ and accept the leakage. */
5546 # endif /* HAS_CLEARENV || HAS_UNSETENV */
5547 # endif /* ! PERL_USE_SAFE_PUTENV */
5549 # endif /* USE_ENVIRON_ARRAY */
5550 # endif /* PERL_IMPLICIT_SYS || WIN32 */
5551 #endif /* PERL_MICRO */
5554 #ifdef PERL_IMPLICIT_CONTEXT
5556 /* Implements the MY_CXT_INIT macro. The first time a module is loaded,
5557 the global PL_my_cxt_index is incremented, and that value is assigned to
5558 that module's static my_cxt_index (who's address is passed as an arg).
5559 Then, for each interpreter this function is called for, it makes sure a
5560 void* slot is available to hang the static data off, by allocating or
5561 extending the interpreter's PL_my_cxt_list array */
5563 #ifndef PERL_GLOBAL_STRUCT_PRIVATE
5565 Perl_my_cxt_init(pTHX_ int *index, size_t size)
5570 /* this module hasn't been allocated an index yet */
5571 MUTEX_LOCK(&PL_my_ctx_mutex);
5572 *index = PL_my_cxt_index++;
5573 MUTEX_UNLOCK(&PL_my_ctx_mutex);
5576 /* make sure the array is big enough */
5577 if (PL_my_cxt_size <= *index) {
5578 if (PL_my_cxt_size) {
5579 while (PL_my_cxt_size <= *index)
5580 PL_my_cxt_size *= 2;
5581 Renew(PL_my_cxt_list, PL_my_cxt_size, void *);
5584 PL_my_cxt_size = 16;
5585 Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
5588 /* newSV() allocates one more than needed */
5589 p = (void*)SvPVX(newSV(size-1));
5590 PL_my_cxt_list[*index] = p;
5591 Zero(p, size, char);
5595 #else /* #ifndef PERL_GLOBAL_STRUCT_PRIVATE */
5598 Perl_my_cxt_index(pTHX_ const char *my_cxt_key)
5603 for (index = 0; index < PL_my_cxt_index; index++) {
5604 const char *key = PL_my_cxt_keys[index];
5605 /* try direct pointer compare first - there are chances to success,
5606 * and it's much faster.
5608 if ((key == my_cxt_key) || strEQ(key, my_cxt_key))
5615 Perl_my_cxt_init(pTHX_ const char *my_cxt_key, size_t size)
5621 index = Perl_my_cxt_index(aTHX_ my_cxt_key);
5623 /* this module hasn't been allocated an index yet */
5624 MUTEX_LOCK(&PL_my_ctx_mutex);
5625 index = PL_my_cxt_index++;
5626 MUTEX_UNLOCK(&PL_my_ctx_mutex);
5629 /* make sure the array is big enough */
5630 if (PL_my_cxt_size <= index) {
5631 int old_size = PL_my_cxt_size;
5633 if (PL_my_cxt_size) {
5634 while (PL_my_cxt_size <= index)
5635 PL_my_cxt_size *= 2;
5636 Renew(PL_my_cxt_list, PL_my_cxt_size, void *);
5637 Renew(PL_my_cxt_keys, PL_my_cxt_size, const char *);
5640 PL_my_cxt_size = 16;
5641 Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
5642 Newx(PL_my_cxt_keys, PL_my_cxt_size, const char *);
5644 for (i = old_size; i < PL_my_cxt_size; i++) {
5645 PL_my_cxt_keys[i] = 0;
5646 PL_my_cxt_list[i] = 0;
5649 PL_my_cxt_keys[index] = my_cxt_key;
5650 /* newSV() allocates one more than needed */
5651 p = (void*)SvPVX(newSV(size-1));
5652 PL_my_cxt_list[index] = p;
5653 Zero(p, size, char);
5656 #endif /* #ifndef PERL_GLOBAL_STRUCT_PRIVATE */
5657 #endif /* PERL_IMPLICIT_CONTEXT */
5661 Perl_my_strlcat(char *dst, const char *src, Size_t size)
5663 Size_t used, length, copy;
5666 length = strlen(src);
5667 if (size > 0 && used < size - 1) {
5668 copy = (length >= size - used) ? size - used - 1 : length;
5669 memcpy(dst + used, src, copy);
5670 dst[used + copy] = '\0';
5672 return used + length;
5678 Perl_my_strlcpy(char *dst, const char *src, Size_t size)
5680 Size_t length, copy;
5682 length = strlen(src);
5684 copy = (length >= size) ? size - 1 : length;
5685 memcpy(dst, src, copy);
5692 #if defined(_MSC_VER) && (_MSC_VER >= 1300) && (_MSC_VER < 1400) && (WINVER < 0x0500)
5693 /* VC7 or 7.1, building with pre-VC7 runtime libraries. */
5694 long _ftol( double ); /* Defined by VC6 C libs. */
5695 long _ftol2( double dblSource ) { return _ftol( dblSource ); }
5699 Perl_get_db_sub(pTHX_ SV **svp, CV *cv)
5702 SV * const dbsv = GvSVn(PL_DBsub);
5703 /* We do not care about using sv to call CV;
5704 * it's for informational purposes only.
5708 if (!PERLDB_SUB_NN) {
5709 GV * const gv = CvGV(cv);
5711 if ( svp && ((CvFLAGS(cv) & (CVf_ANON | CVf_CLONED))
5712 || strEQ(GvNAME(gv), "END")
5713 || ((GvCV(gv) != cv) && /* Could be imported, and old sub redefined. */
5714 !( (SvTYPE(*svp) == SVt_PVGV) && (GvCV((GV*)*svp) == cv) )))) {
5715 /* Use GV from the stack as a fallback. */
5716 /* GV is potentially non-unique, or contain different CV. */
5717 SV * const tmp = newRV((SV*)cv);
5718 sv_setsv(dbsv, tmp);
5722 gv_efullname3(dbsv, gv, NULL);
5726 const int type = SvTYPE(dbsv);
5727 if (type < SVt_PVIV && type != SVt_IV)
5728 sv_upgrade(dbsv, SVt_PVIV);
5729 (void)SvIOK_on(dbsv);
5730 SvIV_set(dbsv, PTR2IV(cv)); /* Do it the quickest way */
5736 * c-indentation-style: bsd
5738 * indent-tabs-mode: t
5741 * ex: set ts=8 sts=4 sw=4 noet: