3 * Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
4 * 2002, 2003, 2004, 2005, 2006, 2007, 2008 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 to Pippin
15 * [p.598 of _The Lord of the Rings_, III/xi: "The PalantÃr"]
18 /* This file contains assorted utility routines.
19 * Which is a polite way of saying any stuff that people couldn't think of
20 * a better place for. Amongst other things, it includes the warning and
21 * dieing stuff, plus wrappers for malloc code.
25 #define PERL_IN_UTIL_C
29 #if defined(USE_PERLIO)
30 #include "perliol.h" /* For PerlIOUnix_refcnt */
36 # define SIG_ERR ((Sighandler_t) -1)
44 /* Missing protos on LynxOS */
50 # include <sys/select.h>
54 #ifdef USE_C_BACKTRACE
58 # undef USE_BFD /* BFD is useless in OS X. */
68 # include <execinfo.h>
72 #ifdef PERL_DEBUG_READONLY_COW
73 # include <sys/mman.h>
78 /* NOTE: Do not call the next three routines directly. Use the macros
79 * in handy.h, so that we can easily redefine everything to do tracking of
80 * allocated hunks back to the original New to track down any memory leaks.
81 * XXX This advice seems to be widely ignored :-( --AD August 1996.
84 #if defined (DEBUGGING) || defined(PERL_IMPLICIT_SYS) || defined (PERL_TRACK_MEMPOOL)
85 # define ALWAYS_NEED_THX
88 #if defined(PERL_TRACK_MEMPOOL) && defined(PERL_DEBUG_READONLY_COW)
90 S_maybe_protect_rw(pTHX_ struct perl_memory_debug_header *header)
93 && mprotect(header, header->size, PROT_READ|PROT_WRITE))
94 Perl_warn(aTHX_ "mprotect for COW string %p %lu failed with %d",
95 header, header->size, errno);
99 S_maybe_protect_ro(pTHX_ struct perl_memory_debug_header *header)
102 && mprotect(header, header->size, PROT_READ))
103 Perl_warn(aTHX_ "mprotect RW for COW string %p %lu failed with %d",
104 header, header->size, errno);
106 # define maybe_protect_rw(foo) S_maybe_protect_rw(aTHX_ foo)
107 # define maybe_protect_ro(foo) S_maybe_protect_ro(aTHX_ foo)
109 # define maybe_protect_rw(foo) NOOP
110 # define maybe_protect_ro(foo) NOOP
113 #if defined(PERL_TRACK_MEMPOOL) || defined(PERL_DEBUG_READONLY_COW)
114 /* Use memory_debug_header */
116 # if (defined(PERL_POISON) && defined(PERL_TRACK_MEMPOOL)) \
117 || defined(PERL_DEBUG_READONLY_COW)
118 # define MDH_HAS_SIZE
122 /* paranoid version of system's malloc() */
125 Perl_safesysmalloc(MEM_SIZE size)
127 #ifdef ALWAYS_NEED_THX
131 size += PERL_MEMORY_DEBUG_HEADER_SIZE;
133 if ((SSize_t)size < 0)
134 Perl_croak_nocontext("panic: malloc, size=%"UVuf, (UV) size);
136 if (!size) size = 1; /* malloc(0) is NASTY on our system */
137 #ifdef PERL_DEBUG_READONLY_COW
138 if ((ptr = mmap(0, size, PROT_READ|PROT_WRITE,
139 MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED) {
140 perror("mmap failed");
144 ptr = (Malloc_t)PerlMem_malloc(size?size:1);
146 PERL_ALLOC_CHECK(ptr);
149 struct perl_memory_debug_header *const header
150 = (struct perl_memory_debug_header *)ptr;
154 PoisonNew(((char *)ptr), size, char);
157 #ifdef PERL_TRACK_MEMPOOL
158 header->interpreter = aTHX;
159 /* Link us into the list. */
160 header->prev = &PL_memory_debug_header;
161 header->next = PL_memory_debug_header.next;
162 PL_memory_debug_header.next = header;
163 maybe_protect_rw(header->next);
164 header->next->prev = header;
165 maybe_protect_ro(header->next);
166 # ifdef PERL_DEBUG_READONLY_COW
167 header->readonly = 0;
173 ptr = (Malloc_t)((char*)ptr+PERL_MEMORY_DEBUG_HEADER_SIZE);
174 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) malloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
178 #ifndef ALWAYS_NEED_THX
190 /* paranoid version of system's realloc() */
193 Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
195 #ifdef ALWAYS_NEED_THX
199 #ifdef PERL_DEBUG_READONLY_COW
200 const MEM_SIZE oldsize = where
201 ? ((struct perl_memory_debug_header *)((char *)where - PERL_MEMORY_DEBUG_HEADER_SIZE))->size
204 #if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) && !defined(PERL_MICRO)
205 Malloc_t PerlMem_realloc();
206 #endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
214 return safesysmalloc(size);
216 where = (Malloc_t)((char*)where-PERL_MEMORY_DEBUG_HEADER_SIZE);
217 size += PERL_MEMORY_DEBUG_HEADER_SIZE;
219 struct perl_memory_debug_header *const header
220 = (struct perl_memory_debug_header *)where;
222 # ifdef PERL_TRACK_MEMPOOL
223 if (header->interpreter != aTHX) {
224 Perl_croak_nocontext("panic: realloc from wrong pool, %p!=%p",
225 header->interpreter, aTHX);
227 assert(header->next->prev == header);
228 assert(header->prev->next == header);
230 if (header->size > size) {
231 const MEM_SIZE freed_up = header->size - size;
232 char *start_of_freed = ((char *)where) + size;
233 PoisonFree(start_of_freed, freed_up, char);
243 if ((SSize_t)size < 0)
244 Perl_croak_nocontext("panic: realloc, size=%"UVuf, (UV)size);
246 #ifdef PERL_DEBUG_READONLY_COW
247 if ((ptr = mmap(0, size, PROT_READ|PROT_WRITE,
248 MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED) {
249 perror("mmap failed");
252 Copy(where,ptr,oldsize < size ? oldsize : size,char);
253 if (munmap(where, oldsize)) {
254 perror("munmap failed");
258 ptr = (Malloc_t)PerlMem_realloc(where,size);
260 PERL_ALLOC_CHECK(ptr);
262 /* MUST do this fixup first, before doing ANYTHING else, as anything else
263 might allocate memory/free/move memory, and until we do the fixup, it
264 may well be chasing (and writing to) free memory. */
266 #ifdef PERL_TRACK_MEMPOOL
267 struct perl_memory_debug_header *const header
268 = (struct perl_memory_debug_header *)ptr;
271 if (header->size < size) {
272 const MEM_SIZE fresh = size - header->size;
273 char *start_of_fresh = ((char *)ptr) + size;
274 PoisonNew(start_of_fresh, fresh, char);
278 maybe_protect_rw(header->next);
279 header->next->prev = header;
280 maybe_protect_ro(header->next);
281 maybe_protect_rw(header->prev);
282 header->prev->next = header;
283 maybe_protect_ro(header->prev);
285 ptr = (Malloc_t)((char*)ptr+PERL_MEMORY_DEBUG_HEADER_SIZE);
288 /* In particular, must do that fixup above before logging anything via
289 *printf(), as it can reallocate memory, which can cause SEGVs. */
291 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) rfree\n",PTR2UV(where),(long)PL_an++));
292 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) realloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
299 #ifndef ALWAYS_NEED_THX
311 /* safe version of system's free() */
314 Perl_safesysfree(Malloc_t where)
316 #ifdef ALWAYS_NEED_THX
319 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) free\n",PTR2UV(where),(long)PL_an++));
322 where = (Malloc_t)((char*)where-PERL_MEMORY_DEBUG_HEADER_SIZE);
324 struct perl_memory_debug_header *const header
325 = (struct perl_memory_debug_header *)where;
328 const MEM_SIZE size = header->size;
330 # ifdef PERL_TRACK_MEMPOOL
331 if (header->interpreter != aTHX) {
332 Perl_croak_nocontext("panic: free from wrong pool, %p!=%p",
333 header->interpreter, aTHX);
336 Perl_croak_nocontext("panic: duplicate free");
339 Perl_croak_nocontext("panic: bad free, header->next==NULL");
340 if (header->next->prev != header || header->prev->next != header) {
341 Perl_croak_nocontext("panic: bad free, ->next->prev=%p, "
342 "header=%p, ->prev->next=%p",
343 header->next->prev, header,
346 /* Unlink us from the chain. */
347 maybe_protect_rw(header->next);
348 header->next->prev = header->prev;
349 maybe_protect_ro(header->next);
350 maybe_protect_rw(header->prev);
351 header->prev->next = header->next;
352 maybe_protect_ro(header->prev);
353 maybe_protect_rw(header);
355 PoisonNew(where, size, char);
357 /* Trigger the duplicate free warning. */
360 # ifdef PERL_DEBUG_READONLY_COW
361 if (munmap(where, size)) {
362 perror("munmap failed");
368 #ifndef PERL_DEBUG_READONLY_COW
374 /* safe version of system's calloc() */
377 Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
379 #ifdef ALWAYS_NEED_THX
383 #if defined(USE_MDH) || defined(DEBUGGING)
384 MEM_SIZE total_size = 0;
387 /* Even though calloc() for zero bytes is strange, be robust. */
388 if (size && (count <= MEM_SIZE_MAX / size)) {
389 #if defined(USE_MDH) || defined(DEBUGGING)
390 total_size = size * count;
396 if (PERL_MEMORY_DEBUG_HEADER_SIZE <= MEM_SIZE_MAX - (MEM_SIZE)total_size)
397 total_size += PERL_MEMORY_DEBUG_HEADER_SIZE;
402 if ((SSize_t)size < 0 || (SSize_t)count < 0)
403 Perl_croak_nocontext("panic: calloc, size=%"UVuf", count=%"UVuf,
404 (UV)size, (UV)count);
406 #ifdef PERL_DEBUG_READONLY_COW
407 if ((ptr = mmap(0, total_size ? total_size : 1, PROT_READ|PROT_WRITE,
408 MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED) {
409 perror("mmap failed");
412 #elif defined(PERL_TRACK_MEMPOOL)
413 /* Have to use malloc() because we've added some space for our tracking
415 /* malloc(0) is non-portable. */
416 ptr = (Malloc_t)PerlMem_malloc(total_size ? total_size : 1);
418 /* Use calloc() because it might save a memset() if the memory is fresh
419 and clean from the OS. */
421 ptr = (Malloc_t)PerlMem_calloc(count, size);
422 else /* calloc(0) is non-portable. */
423 ptr = (Malloc_t)PerlMem_calloc(count ? count : 1, size ? size : 1);
425 PERL_ALLOC_CHECK(ptr);
426 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) calloc %ld x %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)count,(long)total_size));
430 struct perl_memory_debug_header *const header
431 = (struct perl_memory_debug_header *)ptr;
433 # ifndef PERL_DEBUG_READONLY_COW
434 memset((void*)ptr, 0, total_size);
436 # ifdef PERL_TRACK_MEMPOOL
437 header->interpreter = aTHX;
438 /* Link us into the list. */
439 header->prev = &PL_memory_debug_header;
440 header->next = PL_memory_debug_header.next;
441 PL_memory_debug_header.next = header;
442 maybe_protect_rw(header->next);
443 header->next->prev = header;
444 maybe_protect_ro(header->next);
445 # ifdef PERL_DEBUG_READONLY_COW
446 header->readonly = 0;
450 header->size = total_size;
452 ptr = (Malloc_t)((char*)ptr+PERL_MEMORY_DEBUG_HEADER_SIZE);
458 #ifndef ALWAYS_NEED_THX
467 /* These must be defined when not using Perl's malloc for binary
472 Malloc_t Perl_malloc (MEM_SIZE nbytes)
474 #ifdef PERL_IMPLICIT_SYS
477 return (Malloc_t)PerlMem_malloc(nbytes);
480 Malloc_t Perl_calloc (MEM_SIZE elements, MEM_SIZE size)
482 #ifdef PERL_IMPLICIT_SYS
485 return (Malloc_t)PerlMem_calloc(elements, size);
488 Malloc_t Perl_realloc (Malloc_t where, MEM_SIZE nbytes)
490 #ifdef PERL_IMPLICIT_SYS
493 return (Malloc_t)PerlMem_realloc(where, nbytes);
496 Free_t Perl_mfree (Malloc_t where)
498 #ifdef PERL_IMPLICIT_SYS
506 /* copy a string up to some (non-backslashed) delimiter, if any */
509 Perl_delimcpy(char *to, const char *toend, const char *from, const char *fromend, int delim, I32 *retlen)
513 PERL_ARGS_ASSERT_DELIMCPY;
515 for (tolen = 0; from < fromend; from++, tolen++) {
517 if (from[1] != delim) {
524 else if (*from == delim)
535 /* return ptr to little string in big string, NULL if not found */
536 /* This routine was donated by Corey Satten. */
539 Perl_instr(const char *big, const char *little)
542 PERL_ARGS_ASSERT_INSTR;
544 /* libc prior to 4.6.27 (late 1994) did not work properly on a NULL
548 return strstr((char*)big, (char*)little);
551 /* same as instr but allow embedded nulls. The end pointers point to 1 beyond
552 * the final character desired to be checked */
555 Perl_ninstr(const char *big, const char *bigend, const char *little, const char *lend)
557 PERL_ARGS_ASSERT_NINSTR;
561 const char first = *little;
563 bigend -= lend - little++;
565 while (big <= bigend) {
566 if (*big++ == first) {
567 for (x=big,s=little; s < lend; x++,s++) {
571 return (char*)(big-1);
578 /* reverse of the above--find last substring */
581 Perl_rninstr(const char *big, const char *bigend, const char *little, const char *lend)
584 const I32 first = *little;
585 const char * const littleend = lend;
587 PERL_ARGS_ASSERT_RNINSTR;
589 if (little >= littleend)
590 return (char*)bigend;
592 big = bigend - (littleend - little++);
593 while (big >= bigbeg) {
597 for (x=big+2,s=little; s < littleend; /**/ ) {
606 return (char*)(big+1);
611 /* As a space optimization, we do not compile tables for strings of length
612 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
613 special-cased in fbm_instr().
615 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
618 =head1 Miscellaneous Functions
620 =for apidoc fbm_compile
622 Analyses the string in order to make fast searches on it using fbm_instr()
623 -- the Boyer-Moore algorithm.
629 Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
636 PERL_DEB( STRLEN rarest = 0 );
638 PERL_ARGS_ASSERT_FBM_COMPILE;
640 if (isGV_with_GP(sv) || SvROK(sv))
646 if (flags & FBMcf_TAIL) {
647 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL;
648 sv_catpvs(sv, "\n"); /* Taken into account in fbm_instr() */
649 if (mg && mg->mg_len >= 0)
652 if (!SvPOK(sv) || SvNIOKp(sv))
653 s = (U8*)SvPV_force_mutable(sv, len);
654 else s = (U8 *)SvPV_mutable(sv, len);
655 if (len == 0) /* TAIL might be on a zero-length string. */
657 SvUPGRADE(sv, SVt_PVMG);
662 /* "deep magic", the comment used to add. The use of MAGIC itself isn't
663 really. MAGIC was originally added in 79072805bf63abe5 (perl 5.0 alpha 2)
664 to call SvVALID_off() if the scalar was assigned to.
666 The comment itself (and "deeper magic" below) date back to
667 378cc40b38293ffc (perl 2.0). "deep magic" was an annotation on
669 where the magic (presumably) was that the scalar had a BM table hidden
672 As MAGIC is always present on BMs [in Perl 5 :-)], we can use it to store
673 the table instead of the previous (somewhat hacky) approach of co-opting
674 the string buffer and storing it after the string. */
676 assert(!mg_find(sv, PERL_MAGIC_bm));
677 mg = sv_magicext(sv, NULL, PERL_MAGIC_bm, &PL_vtbl_bm, NULL, 0);
681 /* Shorter strings are special-cased in Perl_fbm_instr(), and don't use
683 const U8 mlen = (len>255) ? 255 : (U8)len;
684 const unsigned char *const sb = s + len - mlen; /* first char (maybe) */
687 Newx(table, 256, U8);
688 memset((void*)table, mlen, 256);
689 mg->mg_ptr = (char *)table;
692 s += len - 1; /* last char */
695 if (table[*s] == mlen)
701 s = (const unsigned char*)(SvPVX_const(sv)); /* deeper magic */
702 for (i = 0; i < len; i++) {
703 if (PL_freq[s[i]] < frequency) {
704 PERL_DEB( rarest = i );
705 frequency = PL_freq[s[i]];
708 BmUSEFUL(sv) = 100; /* Initial value */
709 if (flags & FBMcf_TAIL)
711 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %"UVuf"\n",
712 s[rarest], (UV)rarest));
715 /* If SvTAIL(littlestr), it has a fake '\n' at end. */
716 /* If SvTAIL is actually due to \Z or \z, this gives false positives
720 =for apidoc fbm_instr
722 Returns the location of the SV in the string delimited by C<big> and
723 C<bigend>. It returns C<NULL> if the string can't be found. The C<sv>
724 does not have to be fbm_compiled, but the search will not be as fast
731 Perl_fbm_instr(pTHX_ unsigned char *big, unsigned char *bigend, SV *littlestr, U32 flags)
735 const unsigned char *little = (const unsigned char *)SvPV_const(littlestr,l);
736 STRLEN littlelen = l;
737 const I32 multiline = flags & FBMrf_MULTILINE;
739 PERL_ARGS_ASSERT_FBM_INSTR;
741 if ((STRLEN)(bigend - big) < littlelen) {
742 if ( SvTAIL(littlestr)
743 && ((STRLEN)(bigend - big) == littlelen - 1)
745 || (*big == *little &&
746 memEQ((char *)big, (char *)little, littlelen - 1))))
751 switch (littlelen) { /* Special cases for 0, 1 and 2 */
753 return (char*)big; /* Cannot be SvTAIL! */
755 if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
756 /* Know that bigend != big. */
757 if (bigend[-1] == '\n')
758 return (char *)(bigend - 1);
759 return (char *) bigend;
767 if (SvTAIL(littlestr))
768 return (char *) bigend;
771 if (SvTAIL(littlestr) && !multiline) {
772 if (bigend[-1] == '\n' && bigend[-2] == *little)
773 return (char*)bigend - 2;
774 if (bigend[-1] == *little)
775 return (char*)bigend - 1;
779 /* This should be better than FBM if c1 == c2, and almost
780 as good otherwise: maybe better since we do less indirection.
781 And we save a lot of memory by caching no table. */
782 const unsigned char c1 = little[0];
783 const unsigned char c2 = little[1];
788 while (s <= bigend) {
798 goto check_1char_anchor;
809 goto check_1char_anchor;
812 while (s <= bigend) {
817 goto check_1char_anchor;
826 check_1char_anchor: /* One char and anchor! */
827 if (SvTAIL(littlestr) && (*bigend == *little))
828 return (char *)bigend; /* bigend is already decremented. */
831 break; /* Only lengths 0 1 and 2 have special-case code. */
834 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
835 s = bigend - littlelen;
836 if (s >= big && bigend[-1] == '\n' && *s == *little
837 /* Automatically of length > 2 */
838 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
840 return (char*)s; /* how sweet it is */
843 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
845 return (char*)s + 1; /* how sweet it is */
849 if (!SvVALID(littlestr)) {
850 char * const b = ninstr((char*)big,(char*)bigend,
851 (char*)little, (char*)little + littlelen);
853 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
854 /* Chop \n from littlestr: */
855 s = bigend - littlelen + 1;
857 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
867 if (littlelen > (STRLEN)(bigend - big))
871 const MAGIC *const mg = mg_find(littlestr, PERL_MAGIC_bm);
872 const unsigned char *oldlittle;
876 --littlelen; /* Last char found by table lookup */
879 little += littlelen; /* last char */
882 const unsigned char * const table = (const unsigned char *) mg->mg_ptr;
886 if ((tmp = table[*s])) {
887 if ((s += tmp) < bigend)
891 else { /* less expensive than calling strncmp() */
892 unsigned char * const olds = s;
897 if (*--s == *--little)
899 s = olds + 1; /* here we pay the price for failure */
901 if (s < bigend) /* fake up continue to outer loop */
911 && memEQ((char *)(bigend - littlelen),
912 (char *)(oldlittle - littlelen), littlelen) )
913 return (char*)bigend - littlelen;
919 Perl_screaminstr(pTHX_ SV *bigstr, SV *littlestr, I32 start_shift, I32 end_shift, I32 *old_posp, I32 last)
921 PERL_ARGS_ASSERT_SCREAMINSTR;
922 PERL_UNUSED_ARG(bigstr);
923 PERL_UNUSED_ARG(littlestr);
924 PERL_UNUSED_ARG(start_shift);
925 PERL_UNUSED_ARG(end_shift);
926 PERL_UNUSED_ARG(old_posp);
927 PERL_UNUSED_ARG(last);
929 /* This function must only ever be called on a scalar with study magic,
930 but those do not happen any more. */
931 Perl_croak(aTHX_ "panic: screaminstr");
932 NORETURN_FUNCTION_END;
938 Returns true if the leading len bytes of the strings s1 and s2 are the same
939 case-insensitively; false otherwise. Uppercase and lowercase ASCII range bytes
940 match themselves and their opposite case counterparts. Non-cased and non-ASCII
941 range bytes match only themselves.
948 Perl_foldEQ(const char *s1, const char *s2, I32 len)
950 const U8 *a = (const U8 *)s1;
951 const U8 *b = (const U8 *)s2;
953 PERL_ARGS_ASSERT_FOLDEQ;
958 if (*a != *b && *a != PL_fold[*b])
965 Perl_foldEQ_latin1(const char *s1, const char *s2, I32 len)
967 /* Compare non-utf8 using Unicode (Latin1) semantics. Does not work on
968 * MICRO_SIGN, LATIN_SMALL_LETTER_SHARP_S, nor
969 * LATIN_SMALL_LETTER_Y_WITH_DIAERESIS, and does not check for these. Nor
970 * does it check that the strings each have at least 'len' characters */
972 const U8 *a = (const U8 *)s1;
973 const U8 *b = (const U8 *)s2;
975 PERL_ARGS_ASSERT_FOLDEQ_LATIN1;
980 if (*a != *b && *a != PL_fold_latin1[*b]) {
989 =for apidoc foldEQ_locale
991 Returns true if the leading len bytes of the strings s1 and s2 are the same
992 case-insensitively in the current locale; false otherwise.
998 Perl_foldEQ_locale(const char *s1, const char *s2, I32 len)
1001 const U8 *a = (const U8 *)s1;
1002 const U8 *b = (const U8 *)s2;
1004 PERL_ARGS_ASSERT_FOLDEQ_LOCALE;
1009 if (*a != *b && *a != PL_fold_locale[*b])
1016 /* copy a string to a safe spot */
1019 =head1 Memory Management
1023 Perl's version of C<strdup()>. Returns a pointer to a newly allocated
1024 string which is a duplicate of C<pv>. The size of the string is
1025 determined by C<strlen()>, which means it may not contain embedded C<NUL>
1026 characters and must have a trailing C<NUL>. The memory allocated for the new
1027 string can be freed with the C<Safefree()> function.
1029 On some platforms, Windows for example, all allocated memory owned by a thread
1030 is deallocated when that thread ends. So if you need that not to happen, you
1031 need to use the shared memory functions, such as C<L</savesharedpv>>.
1037 Perl_savepv(pTHX_ const char *pv)
1039 PERL_UNUSED_CONTEXT;
1044 const STRLEN pvlen = strlen(pv)+1;
1045 Newx(newaddr, pvlen, char);
1046 return (char*)memcpy(newaddr, pv, pvlen);
1050 /* same thing but with a known length */
1055 Perl's version of what C<strndup()> would be if it existed. Returns a
1056 pointer to a newly allocated string which is a duplicate of the first
1057 C<len> bytes from C<pv>, plus a trailing
1058 C<NUL> byte. The memory allocated for
1059 the new string can be freed with the C<Safefree()> function.
1061 On some platforms, Windows for example, all allocated memory owned by a thread
1062 is deallocated when that thread ends. So if you need that not to happen, you
1063 need to use the shared memory functions, such as C<L</savesharedpvn>>.
1069 Perl_savepvn(pTHX_ const char *pv, I32 len)
1072 PERL_UNUSED_CONTEXT;
1076 Newx(newaddr,len+1,char);
1077 /* Give a meaning to NULL pointer mainly for the use in sv_magic() */
1079 /* might not be null terminated */
1080 newaddr[len] = '\0';
1081 return (char *) CopyD(pv,newaddr,len,char);
1084 return (char *) ZeroD(newaddr,len+1,char);
1089 =for apidoc savesharedpv
1091 A version of C<savepv()> which allocates the duplicate string in memory
1092 which is shared between threads.
1097 Perl_savesharedpv(pTHX_ const char *pv)
1102 PERL_UNUSED_CONTEXT;
1107 pvlen = strlen(pv)+1;
1108 newaddr = (char*)PerlMemShared_malloc(pvlen);
1112 return (char*)memcpy(newaddr, pv, pvlen);
1116 =for apidoc savesharedpvn
1118 A version of C<savepvn()> which allocates the duplicate string in memory
1119 which is shared between threads. (With the specific difference that a NULL
1120 pointer is not acceptable)
1125 Perl_savesharedpvn(pTHX_ const char *const pv, const STRLEN len)
1127 char *const newaddr = (char*)PerlMemShared_malloc(len + 1);
1129 PERL_UNUSED_CONTEXT;
1130 /* PERL_ARGS_ASSERT_SAVESHAREDPVN; */
1135 newaddr[len] = '\0';
1136 return (char*)memcpy(newaddr, pv, len);
1140 =for apidoc savesvpv
1142 A version of C<savepv()>/C<savepvn()> which gets the string to duplicate from
1143 the passed in SV using C<SvPV()>
1145 On some platforms, Windows for example, all allocated memory owned by a thread
1146 is deallocated when that thread ends. So if you need that not to happen, you
1147 need to use the shared memory functions, such as C<L</savesharedsvpv>>.
1153 Perl_savesvpv(pTHX_ SV *sv)
1156 const char * const pv = SvPV_const(sv, len);
1159 PERL_ARGS_ASSERT_SAVESVPV;
1162 Newx(newaddr,len,char);
1163 return (char *) CopyD(pv,newaddr,len,char);
1167 =for apidoc savesharedsvpv
1169 A version of C<savesharedpv()> which allocates the duplicate string in
1170 memory which is shared between threads.
1176 Perl_savesharedsvpv(pTHX_ SV *sv)
1179 const char * const pv = SvPV_const(sv, len);
1181 PERL_ARGS_ASSERT_SAVESHAREDSVPV;
1183 return savesharedpvn(pv, len);
1186 /* the SV for Perl_form() and mess() is not kept in an arena */
1194 if (PL_phase != PERL_PHASE_DESTRUCT)
1195 return newSVpvs_flags("", SVs_TEMP);
1200 /* Create as PVMG now, to avoid any upgrading later */
1202 Newxz(any, 1, XPVMG);
1203 SvFLAGS(sv) = SVt_PVMG;
1204 SvANY(sv) = (void*)any;
1206 SvREFCNT(sv) = 1 << 30; /* practically infinite */
1211 #if defined(PERL_IMPLICIT_CONTEXT)
1213 Perl_form_nocontext(const char* pat, ...)
1218 PERL_ARGS_ASSERT_FORM_NOCONTEXT;
1219 va_start(args, pat);
1220 retval = vform(pat, &args);
1224 #endif /* PERL_IMPLICIT_CONTEXT */
1227 =head1 Miscellaneous Functions
1230 Takes a sprintf-style format pattern and conventional
1231 (non-SV) arguments and returns the formatted string.
1233 (char *) Perl_form(pTHX_ const char* pat, ...)
1235 can be used any place a string (char *) is required:
1237 char * s = Perl_form("%d.%d",major,minor);
1239 Uses a single private buffer so if you want to format several strings you
1240 must explicitly copy the earlier strings away (and free the copies when you
1247 Perl_form(pTHX_ const char* pat, ...)
1251 PERL_ARGS_ASSERT_FORM;
1252 va_start(args, pat);
1253 retval = vform(pat, &args);
1259 Perl_vform(pTHX_ const char *pat, va_list *args)
1261 SV * const sv = mess_alloc();
1262 PERL_ARGS_ASSERT_VFORM;
1263 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1268 =for apidoc Am|SV *|mess|const char *pat|...
1270 Take a sprintf-style format pattern and argument list. These are used to
1271 generate a string message. If the message does not end with a newline,
1272 then it will be extended with some indication of the current location
1273 in the code, as described for L</mess_sv>.
1275 Normally, the resulting message is returned in a new mortal SV.
1276 During global destruction a single SV may be shared between uses of
1282 #if defined(PERL_IMPLICIT_CONTEXT)
1284 Perl_mess_nocontext(const char *pat, ...)
1289 PERL_ARGS_ASSERT_MESS_NOCONTEXT;
1290 va_start(args, pat);
1291 retval = vmess(pat, &args);
1295 #endif /* PERL_IMPLICIT_CONTEXT */
1298 Perl_mess(pTHX_ const char *pat, ...)
1302 PERL_ARGS_ASSERT_MESS;
1303 va_start(args, pat);
1304 retval = vmess(pat, &args);
1310 Perl_closest_cop(pTHX_ const COP *cop, const OP *o, const OP *curop,
1313 /* Look for curop starting from o. cop is the last COP we've seen. */
1314 /* opnext means that curop is actually the ->op_next of the op we are
1317 PERL_ARGS_ASSERT_CLOSEST_COP;
1319 if (!o || !curop || (
1320 opnext ? o->op_next == curop && o->op_type != OP_SCOPE : o == curop
1324 if (o->op_flags & OPf_KIDS) {
1326 for (kid = cUNOPo->op_first; kid; kid = OP_SIBLING(kid)) {
1329 /* If the OP_NEXTSTATE has been optimised away we can still use it
1330 * the get the file and line number. */
1332 if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
1333 cop = (const COP *)kid;
1335 /* Keep searching, and return when we've found something. */
1337 new_cop = closest_cop(cop, kid, curop, opnext);
1343 /* Nothing found. */
1349 =for apidoc Am|SV *|mess_sv|SV *basemsg|bool consume
1351 Expands a message, intended for the user, to include an indication of
1352 the current location in the code, if the message does not already appear
1355 C<basemsg> is the initial message or object. If it is a reference, it
1356 will be used as-is and will be the result of this function. Otherwise it
1357 is used as a string, and if it already ends with a newline, it is taken
1358 to be complete, and the result of this function will be the same string.
1359 If the message does not end with a newline, then a segment such as C<at
1360 foo.pl line 37> will be appended, and possibly other clauses indicating
1361 the current state of execution. The resulting message will end with a
1364 Normally, the resulting message is returned in a new mortal SV.
1365 During global destruction a single SV may be shared between uses of this
1366 function. If C<consume> is true, then the function is permitted (but not
1367 required) to modify and return C<basemsg> instead of allocating a new SV.
1373 Perl_mess_sv(pTHX_ SV *basemsg, bool consume)
1377 #if defined(USE_C_BACKTRACE) && defined(USE_C_BACKTRACE_ON_ERROR)
1381 /* The PERL_C_BACKTRACE_ON_WARN must be an integer of one or more. */
1382 if ((ws = PerlEnv_getenv("PERL_C_BACKTRACE_ON_ERROR")) &&
1383 (wi = grok_atou(ws, NULL)) > 0) {
1384 Perl_dump_c_backtrace(aTHX_ Perl_debug_log, wi, 1);
1389 PERL_ARGS_ASSERT_MESS_SV;
1391 if (SvROK(basemsg)) {
1397 sv_setsv(sv, basemsg);
1402 if (SvPOK(basemsg) && consume) {
1407 sv_copypv(sv, basemsg);
1410 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1412 * Try and find the file and line for PL_op. This will usually be
1413 * PL_curcop, but it might be a cop that has been optimised away. We
1414 * can try to find such a cop by searching through the optree starting
1415 * from the sibling of PL_curcop.
1419 closest_cop(PL_curcop, OP_SIBLING(PL_curcop), PL_op, FALSE);
1424 Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
1425 OutCopFILE(cop), (IV)CopLINE(cop));
1426 /* Seems that GvIO() can be untrustworthy during global destruction. */
1427 if (GvIO(PL_last_in_gv) && (SvTYPE(GvIOp(PL_last_in_gv)) == SVt_PVIO)
1428 && IoLINES(GvIOp(PL_last_in_gv)))
1431 const bool line_mode = (RsSIMPLE(PL_rs) &&
1432 *SvPV_const(PL_rs,l) == '\n' && l == 1);
1433 Perl_sv_catpvf(aTHX_ sv, ", <%"SVf"> %s %"IVdf,
1434 SVfARG(PL_last_in_gv == PL_argvgv
1436 : sv_2mortal(newSVhek(GvNAME_HEK(PL_last_in_gv)))),
1437 line_mode ? "line" : "chunk",
1438 (IV)IoLINES(GvIOp(PL_last_in_gv)));
1440 if (PL_phase == PERL_PHASE_DESTRUCT)
1441 sv_catpvs(sv, " during global destruction");
1442 sv_catpvs(sv, ".\n");
1448 =for apidoc Am|SV *|vmess|const char *pat|va_list *args
1450 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1451 argument list. These are used to generate a string message. If the
1452 message does not end with a newline, then it will be extended with
1453 some indication of the current location in the code, as described for
1456 Normally, the resulting message is returned in a new mortal SV.
1457 During global destruction a single SV may be shared between uses of
1464 Perl_vmess(pTHX_ const char *pat, va_list *args)
1466 SV * const sv = mess_alloc();
1468 PERL_ARGS_ASSERT_VMESS;
1470 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1471 return mess_sv(sv, 1);
1475 Perl_write_to_stderr(pTHX_ SV* msv)
1480 PERL_ARGS_ASSERT_WRITE_TO_STDERR;
1482 if (PL_stderrgv && SvREFCNT(PL_stderrgv)
1483 && (io = GvIO(PL_stderrgv))
1484 && (mg = SvTIED_mg((const SV *)io, PERL_MAGIC_tiedscalar)))
1485 Perl_magic_methcall(aTHX_ MUTABLE_SV(io), mg, SV_CONST(PRINT),
1486 G_SCALAR | G_DISCARD | G_WRITING_TO_STDERR, 1, msv);
1488 PerlIO * const serr = Perl_error_log;
1490 do_print(msv, serr);
1491 (void)PerlIO_flush(serr);
1496 =head1 Warning and Dieing
1499 /* Common code used in dieing and warning */
1502 S_with_queued_errors(pTHX_ SV *ex)
1504 PERL_ARGS_ASSERT_WITH_QUEUED_ERRORS;
1505 if (PL_errors && SvCUR(PL_errors) && !SvROK(ex)) {
1506 sv_catsv(PL_errors, ex);
1507 ex = sv_mortalcopy(PL_errors);
1508 SvCUR_set(PL_errors, 0);
1514 S_invoke_exception_hook(pTHX_ SV *ex, bool warn)
1519 SV **const hook = warn ? &PL_warnhook : &PL_diehook;
1520 /* sv_2cv might call Perl_croak() or Perl_warner() */
1521 SV * const oldhook = *hook;
1529 cv = sv_2cv(oldhook, &stash, &gv, 0);
1531 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1540 exarg = newSVsv(ex);
1541 SvREADONLY_on(exarg);
1544 PUSHSTACKi(warn ? PERLSI_WARNHOOK : PERLSI_DIEHOOK);
1548 call_sv(MUTABLE_SV(cv), G_DISCARD);
1557 =for apidoc Am|OP *|die_sv|SV *baseex
1559 Behaves the same as L</croak_sv>, except for the return type.
1560 It should be used only where the C<OP *> return type is required.
1561 The function never actually returns.
1567 Perl_die_sv(pTHX_ SV *baseex)
1569 PERL_ARGS_ASSERT_DIE_SV;
1571 assert(0); /* NOTREACHED */
1572 NORETURN_FUNCTION_END;
1576 =for apidoc Am|OP *|die|const char *pat|...
1578 Behaves the same as L</croak>, except for the return type.
1579 It should be used only where the C<OP *> return type is required.
1580 The function never actually returns.
1585 #if defined(PERL_IMPLICIT_CONTEXT)
1587 Perl_die_nocontext(const char* pat, ...)
1591 va_start(args, pat);
1593 assert(0); /* NOTREACHED */
1595 NORETURN_FUNCTION_END;
1597 #endif /* PERL_IMPLICIT_CONTEXT */
1600 Perl_die(pTHX_ const char* pat, ...)
1603 va_start(args, pat);
1605 assert(0); /* NOTREACHED */
1607 NORETURN_FUNCTION_END;
1611 =for apidoc Am|void|croak_sv|SV *baseex
1613 This is an XS interface to Perl's C<die> function.
1615 C<baseex> is the error message or object. If it is a reference, it
1616 will be used as-is. Otherwise it is used as a string, and if it does
1617 not end with a newline then it will be extended with some indication of
1618 the current location in the code, as described for L</mess_sv>.
1620 The error message or object will be used as an exception, by default
1621 returning control to the nearest enclosing C<eval>, but subject to
1622 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak_sv>
1623 function never returns normally.
1625 To die with a simple string message, the L</croak> function may be
1632 Perl_croak_sv(pTHX_ SV *baseex)
1634 SV *ex = with_queued_errors(mess_sv(baseex, 0));
1635 PERL_ARGS_ASSERT_CROAK_SV;
1636 invoke_exception_hook(ex, FALSE);
1641 =for apidoc Am|void|vcroak|const char *pat|va_list *args
1643 This is an XS interface to Perl's C<die> function.
1645 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1646 argument list. These are used to generate a string message. If the
1647 message does not end with a newline, then it will be extended with
1648 some indication of the current location in the code, as described for
1651 The error message will be used as an exception, by default
1652 returning control to the nearest enclosing C<eval>, but subject to
1653 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1654 function never returns normally.
1656 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1657 (C<$@>) will be used as an error message or object instead of building an
1658 error message from arguments. If you want to throw a non-string object,
1659 or build an error message in an SV yourself, it is preferable to use
1660 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1666 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1668 SV *ex = with_queued_errors(pat ? vmess(pat, args) : mess_sv(ERRSV, 0));
1669 invoke_exception_hook(ex, FALSE);
1674 =for apidoc Am|void|croak|const char *pat|...
1676 This is an XS interface to Perl's C<die> function.
1678 Take a sprintf-style format pattern and argument list. These are used to
1679 generate a string message. If the message does not end with a newline,
1680 then it will be extended with some indication of the current location
1681 in the code, as described for L</mess_sv>.
1683 The error message will be used as an exception, by default
1684 returning control to the nearest enclosing C<eval>, but subject to
1685 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1686 function never returns normally.
1688 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1689 (C<$@>) will be used as an error message or object instead of building an
1690 error message from arguments. If you want to throw a non-string object,
1691 or build an error message in an SV yourself, it is preferable to use
1692 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1697 #if defined(PERL_IMPLICIT_CONTEXT)
1699 Perl_croak_nocontext(const char *pat, ...)
1703 va_start(args, pat);
1705 assert(0); /* NOTREACHED */
1708 #endif /* PERL_IMPLICIT_CONTEXT */
1711 Perl_croak(pTHX_ const char *pat, ...)
1714 va_start(args, pat);
1716 assert(0); /* NOTREACHED */
1721 =for apidoc Am|void|croak_no_modify
1723 Exactly equivalent to C<Perl_croak(aTHX_ "%s", PL_no_modify)>, but generates
1724 terser object code than using C<Perl_croak>. Less code used on exception code
1725 paths reduces CPU cache pressure.
1731 Perl_croak_no_modify(void)
1733 Perl_croak_nocontext( "%s", PL_no_modify);
1736 /* does not return, used in util.c perlio.c and win32.c
1737 This is typically called when malloc returns NULL.
1740 Perl_croak_no_mem(void)
1744 int fd = PerlIO_fileno(Perl_error_log);
1746 SETERRNO(EBADF,RMS_IFI);
1748 /* Can't use PerlIO to write as it allocates memory */
1749 PERL_UNUSED_RESULT(PerlLIO_write(fd, PL_no_mem, sizeof(PL_no_mem)-1));
1754 /* does not return, used only in POPSTACK */
1756 Perl_croak_popstack(void)
1759 PerlIO_printf(Perl_error_log, "panic: POPSTACK\n");
1764 =for apidoc Am|void|warn_sv|SV *baseex
1766 This is an XS interface to Perl's C<warn> function.
1768 C<baseex> is the error message or object. If it is a reference, it
1769 will be used as-is. Otherwise it is used as a string, and if it does
1770 not end with a newline then it will be extended with some indication of
1771 the current location in the code, as described for L</mess_sv>.
1773 The error message or object will by default be written to standard error,
1774 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1776 To warn with a simple string message, the L</warn> function may be
1783 Perl_warn_sv(pTHX_ SV *baseex)
1785 SV *ex = mess_sv(baseex, 0);
1786 PERL_ARGS_ASSERT_WARN_SV;
1787 if (!invoke_exception_hook(ex, TRUE))
1788 write_to_stderr(ex);
1792 =for apidoc Am|void|vwarn|const char *pat|va_list *args
1794 This is an XS interface to Perl's C<warn> function.
1796 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1797 argument list. These are used to generate a string message. If the
1798 message does not end with a newline, then it will be extended with
1799 some indication of the current location in the code, as described for
1802 The error message or object will by default be written to standard error,
1803 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1805 Unlike with L</vcroak>, C<pat> is not permitted to be null.
1811 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1813 SV *ex = vmess(pat, args);
1814 PERL_ARGS_ASSERT_VWARN;
1815 if (!invoke_exception_hook(ex, TRUE))
1816 write_to_stderr(ex);
1820 =for apidoc Am|void|warn|const char *pat|...
1822 This is an XS interface to Perl's C<warn> function.
1824 Take a sprintf-style format pattern and argument list. These are used to
1825 generate a string message. If the message does not end with a newline,
1826 then it will be extended with some indication of the current location
1827 in the code, as described for L</mess_sv>.
1829 The error message or object will by default be written to standard error,
1830 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1832 Unlike with L</croak>, C<pat> is not permitted to be null.
1837 #if defined(PERL_IMPLICIT_CONTEXT)
1839 Perl_warn_nocontext(const char *pat, ...)
1843 PERL_ARGS_ASSERT_WARN_NOCONTEXT;
1844 va_start(args, pat);
1848 #endif /* PERL_IMPLICIT_CONTEXT */
1851 Perl_warn(pTHX_ const char *pat, ...)
1854 PERL_ARGS_ASSERT_WARN;
1855 va_start(args, pat);
1860 #if defined(PERL_IMPLICIT_CONTEXT)
1862 Perl_warner_nocontext(U32 err, const char *pat, ...)
1866 PERL_ARGS_ASSERT_WARNER_NOCONTEXT;
1867 va_start(args, pat);
1868 vwarner(err, pat, &args);
1871 #endif /* PERL_IMPLICIT_CONTEXT */
1874 Perl_ck_warner_d(pTHX_ U32 err, const char* pat, ...)
1876 PERL_ARGS_ASSERT_CK_WARNER_D;
1878 if (Perl_ckwarn_d(aTHX_ err)) {
1880 va_start(args, pat);
1881 vwarner(err, pat, &args);
1887 Perl_ck_warner(pTHX_ U32 err, const char* pat, ...)
1889 PERL_ARGS_ASSERT_CK_WARNER;
1891 if (Perl_ckwarn(aTHX_ err)) {
1893 va_start(args, pat);
1894 vwarner(err, pat, &args);
1900 Perl_warner(pTHX_ U32 err, const char* pat,...)
1903 PERL_ARGS_ASSERT_WARNER;
1904 va_start(args, pat);
1905 vwarner(err, pat, &args);
1910 Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1913 PERL_ARGS_ASSERT_VWARNER;
1914 if (PL_warnhook == PERL_WARNHOOK_FATAL || ckDEAD(err)) {
1915 SV * const msv = vmess(pat, args);
1917 invoke_exception_hook(msv, FALSE);
1921 Perl_vwarn(aTHX_ pat, args);
1925 /* implements the ckWARN? macros */
1928 Perl_ckwarn(pTHX_ U32 w)
1930 /* If lexical warnings have not been set, use $^W. */
1932 return PL_dowarn & G_WARN_ON;
1934 return ckwarn_common(w);
1937 /* implements the ckWARN?_d macro */
1940 Perl_ckwarn_d(pTHX_ U32 w)
1942 /* If lexical warnings have not been set then default classes warn. */
1946 return ckwarn_common(w);
1950 S_ckwarn_common(pTHX_ U32 w)
1952 if (PL_curcop->cop_warnings == pWARN_ALL)
1955 if (PL_curcop->cop_warnings == pWARN_NONE)
1958 /* Check the assumption that at least the first slot is non-zero. */
1959 assert(unpackWARN1(w));
1961 /* Check the assumption that it is valid to stop as soon as a zero slot is
1963 if (!unpackWARN2(w)) {
1964 assert(!unpackWARN3(w));
1965 assert(!unpackWARN4(w));
1966 } else if (!unpackWARN3(w)) {
1967 assert(!unpackWARN4(w));
1970 /* Right, dealt with all the special cases, which are implemented as non-
1971 pointers, so there is a pointer to a real warnings mask. */
1973 if (isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w)))
1975 } while (w >>= WARNshift);
1980 /* Set buffer=NULL to get a new one. */
1982 Perl_new_warnings_bitfield(pTHX_ STRLEN *buffer, const char *const bits,
1984 const MEM_SIZE len_wanted =
1985 sizeof(STRLEN) + (size > WARNsize ? size : WARNsize);
1986 PERL_UNUSED_CONTEXT;
1987 PERL_ARGS_ASSERT_NEW_WARNINGS_BITFIELD;
1990 (specialWARN(buffer) ?
1991 PerlMemShared_malloc(len_wanted) :
1992 PerlMemShared_realloc(buffer, len_wanted));
1994 Copy(bits, (buffer + 1), size, char);
1995 if (size < WARNsize)
1996 Zero((char *)(buffer + 1) + size, WARNsize - size, char);
2000 /* since we've already done strlen() for both nam and val
2001 * we can use that info to make things faster than
2002 * sprintf(s, "%s=%s", nam, val)
2004 #define my_setenv_format(s, nam, nlen, val, vlen) \
2005 Copy(nam, s, nlen, char); \
2007 Copy(val, s+(nlen+1), vlen, char); \
2008 *(s+(nlen+1+vlen)) = '\0'
2010 #ifdef USE_ENVIRON_ARRAY
2011 /* VMS' my_setenv() is in vms.c */
2012 #if !defined(WIN32) && !defined(NETWARE)
2014 Perl_my_setenv(pTHX_ const char *nam, const char *val)
2018 /* only parent thread can modify process environment */
2019 if (PL_curinterp == aTHX)
2022 #ifndef PERL_USE_SAFE_PUTENV
2023 if (!PL_use_safe_putenv) {
2024 /* most putenv()s leak, so we manipulate environ directly */
2026 const I32 len = strlen(nam);
2029 /* where does it go? */
2030 for (i = 0; environ[i]; i++) {
2031 if (strnEQ(environ[i],nam,len) && environ[i][len] == '=')
2035 if (environ == PL_origenviron) { /* need we copy environment? */
2041 while (environ[max])
2043 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
2044 for (j=0; j<max; j++) { /* copy environment */
2045 const int len = strlen(environ[j]);
2046 tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
2047 Copy(environ[j], tmpenv[j], len+1, char);
2050 environ = tmpenv; /* tell exec where it is now */
2053 safesysfree(environ[i]);
2054 while (environ[i]) {
2055 environ[i] = environ[i+1];
2060 if (!environ[i]) { /* does not exist yet */
2061 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
2062 environ[i+1] = NULL; /* make sure it's null terminated */
2065 safesysfree(environ[i]);
2069 environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
2070 /* all that work just for this */
2071 my_setenv_format(environ[i], nam, nlen, val, vlen);
2074 /* This next branch should only be called #if defined(HAS_SETENV), but
2075 Configure doesn't test for that yet. For Solaris, setenv() and unsetenv()
2076 were introduced in Solaris 9, so testing for HAS UNSETENV is sufficient.
2078 # if defined(__CYGWIN__)|| defined(__SYMBIAN32__) || defined(__riscos__) || (defined(__sun) && defined(HAS_UNSETENV))
2079 # if defined(HAS_UNSETENV)
2081 (void)unsetenv(nam);
2083 (void)setenv(nam, val, 1);
2085 # else /* ! HAS_UNSETENV */
2086 (void)setenv(nam, val, 1);
2087 # endif /* HAS_UNSETENV */
2089 # if defined(HAS_UNSETENV)
2091 if (environ) /* old glibc can crash with null environ */
2092 (void)unsetenv(nam);
2094 const int nlen = strlen(nam);
2095 const int vlen = strlen(val);
2096 char * const new_env =
2097 (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
2098 my_setenv_format(new_env, nam, nlen, val, vlen);
2099 (void)putenv(new_env);
2101 # else /* ! HAS_UNSETENV */
2103 const int nlen = strlen(nam);
2109 new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
2110 /* all that work just for this */
2111 my_setenv_format(new_env, nam, nlen, val, vlen);
2112 (void)putenv(new_env);
2113 # endif /* HAS_UNSETENV */
2114 # endif /* __CYGWIN__ */
2115 #ifndef PERL_USE_SAFE_PUTENV
2121 #else /* WIN32 || NETWARE */
2124 Perl_my_setenv(pTHX_ const char *nam, const char *val)
2128 const int nlen = strlen(nam);
2135 Newx(envstr, nlen+vlen+2, char);
2136 my_setenv_format(envstr, nam, nlen, val, vlen);
2137 (void)PerlEnv_putenv(envstr);
2141 #endif /* WIN32 || NETWARE */
2145 #ifdef UNLINK_ALL_VERSIONS
2147 Perl_unlnk(pTHX_ const char *f) /* unlink all versions of a file */
2151 PERL_ARGS_ASSERT_UNLNK;
2153 while (PerlLIO_unlink(f) >= 0)
2155 return retries ? 0 : -1;
2159 /* this is a drop-in replacement for bcopy() */
2160 #if (!defined(HAS_MEMCPY) && !defined(HAS_BCOPY)) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY) && !defined(HAS_SAFE_BCOPY))
2162 Perl_my_bcopy(const char *from, char *to, I32 len)
2164 char * const retval = to;
2166 PERL_ARGS_ASSERT_MY_BCOPY;
2170 if (from - to >= 0) {
2178 *(--to) = *(--from);
2184 /* this is a drop-in replacement for memset() */
2187 Perl_my_memset(char *loc, I32 ch, I32 len)
2189 char * const retval = loc;
2191 PERL_ARGS_ASSERT_MY_MEMSET;
2201 /* this is a drop-in replacement for bzero() */
2202 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
2204 Perl_my_bzero(char *loc, I32 len)
2206 char * const retval = loc;
2208 PERL_ARGS_ASSERT_MY_BZERO;
2218 /* this is a drop-in replacement for memcmp() */
2219 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
2221 Perl_my_memcmp(const char *s1, const char *s2, I32 len)
2223 const U8 *a = (const U8 *)s1;
2224 const U8 *b = (const U8 *)s2;
2227 PERL_ARGS_ASSERT_MY_MEMCMP;
2232 if ((tmp = *a++ - *b++))
2237 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
2240 /* This vsprintf replacement should generally never get used, since
2241 vsprintf was available in both System V and BSD 2.11. (There may
2242 be some cross-compilation or embedded set-ups where it is needed,
2245 If you encounter a problem in this function, it's probably a symptom
2246 that Configure failed to detect your system's vprintf() function.
2247 See the section on "item vsprintf" in the INSTALL file.
2249 This version may compile on systems with BSD-ish <stdio.h>,
2250 but probably won't on others.
2253 #ifdef USE_CHAR_VSPRINTF
2258 vsprintf(char *dest, const char *pat, void *args)
2262 #if defined(STDIO_PTR_LVALUE) && defined(STDIO_CNT_LVALUE)
2263 FILE_ptr(&fakebuf) = (STDCHAR *) dest;
2264 FILE_cnt(&fakebuf) = 32767;
2266 /* These probably won't compile -- If you really need
2267 this, you'll have to figure out some other method. */
2268 fakebuf._ptr = dest;
2269 fakebuf._cnt = 32767;
2274 fakebuf._flag = _IOWRT|_IOSTRG;
2275 _doprnt(pat, args, &fakebuf); /* what a kludge */
2276 #if defined(STDIO_PTR_LVALUE)
2277 *(FILE_ptr(&fakebuf)++) = '\0';
2279 /* PerlIO has probably #defined away fputc, but we want it here. */
2281 # undef fputc /* XXX Should really restore it later */
2283 (void)fputc('\0', &fakebuf);
2285 #ifdef USE_CHAR_VSPRINTF
2288 return 0; /* perl doesn't use return value */
2292 #endif /* HAS_VPRINTF */
2295 Perl_my_popen_list(pTHX_ const char *mode, int n, SV **args)
2297 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(OS2) && !defined(VMS) && !defined(NETWARE) && !defined(__LIBCATAMOUNT__)
2305 PERL_ARGS_ASSERT_MY_POPEN_LIST;
2307 PERL_FLUSHALL_FOR_CHILD;
2308 This = (*mode == 'w');
2312 taint_proper("Insecure %s%s", "EXEC");
2314 if (PerlProc_pipe(p) < 0)
2316 /* Try for another pipe pair for error return */
2317 if (PerlProc_pipe(pp) >= 0)
2319 while ((pid = PerlProc_fork()) < 0) {
2320 if (errno != EAGAIN) {
2321 PerlLIO_close(p[This]);
2322 PerlLIO_close(p[that]);
2324 PerlLIO_close(pp[0]);
2325 PerlLIO_close(pp[1]);
2329 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2338 /* Close parent's end of error status pipe (if any) */
2340 PerlLIO_close(pp[0]);
2341 #if defined(HAS_FCNTL) && defined(F_SETFD)
2342 /* Close error pipe automatically if exec works */
2343 if (fcntl(pp[1], F_SETFD, FD_CLOEXEC) < 0)
2347 /* Now dup our end of _the_ pipe to right position */
2348 if (p[THIS] != (*mode == 'r')) {
2349 PerlLIO_dup2(p[THIS], *mode == 'r');
2350 PerlLIO_close(p[THIS]);
2351 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2352 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2355 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2356 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2357 /* No automatic close - do it by hand */
2364 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
2370 do_aexec5(NULL, args-1, args-1+n, pp[1], did_pipes);
2376 do_execfree(); /* free any memory malloced by child on fork */
2378 PerlLIO_close(pp[1]);
2379 /* Keep the lower of the two fd numbers */
2380 if (p[that] < p[This]) {
2381 PerlLIO_dup2(p[This], p[that]);
2382 PerlLIO_close(p[This]);
2386 PerlLIO_close(p[that]); /* close child's end of pipe */
2388 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2389 SvUPGRADE(sv,SVt_IV);
2391 PL_forkprocess = pid;
2392 /* If we managed to get status pipe check for exec fail */
2393 if (did_pipes && pid > 0) {
2398 while (n < sizeof(int)) {
2399 n1 = PerlLIO_read(pp[0],
2400 (void*)(((char*)&errkid)+n),
2406 PerlLIO_close(pp[0]);
2408 if (n) { /* Error */
2410 PerlLIO_close(p[This]);
2411 if (n != sizeof(int))
2412 Perl_croak(aTHX_ "panic: kid popen errno read, n=%u", n);
2414 pid2 = wait4pid(pid, &status, 0);
2415 } while (pid2 == -1 && errno == EINTR);
2416 errno = errkid; /* Propagate errno from kid */
2421 PerlLIO_close(pp[0]);
2422 return PerlIO_fdopen(p[This], mode);
2424 # ifdef OS2 /* Same, without fork()ing and all extra overhead... */
2425 return my_syspopen4(aTHX_ NULL, mode, n, args);
2427 Perl_croak(aTHX_ "List form of piped open not implemented");
2428 return (PerlIO *) NULL;
2433 /* VMS' my_popen() is in VMS.c, same with OS/2. */
2434 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__LIBCATAMOUNT__)
2436 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2442 const I32 doexec = !(*cmd == '-' && cmd[1] == '\0');
2446 PERL_ARGS_ASSERT_MY_POPEN;
2448 PERL_FLUSHALL_FOR_CHILD;
2451 return my_syspopen(aTHX_ cmd,mode);
2454 This = (*mode == 'w');
2456 if (doexec && TAINTING_get) {
2458 taint_proper("Insecure %s%s", "EXEC");
2460 if (PerlProc_pipe(p) < 0)
2462 if (doexec && PerlProc_pipe(pp) >= 0)
2464 while ((pid = PerlProc_fork()) < 0) {
2465 if (errno != EAGAIN) {
2466 PerlLIO_close(p[This]);
2467 PerlLIO_close(p[that]);
2469 PerlLIO_close(pp[0]);
2470 PerlLIO_close(pp[1]);
2473 Perl_croak(aTHX_ "Can't fork: %s", Strerror(errno));
2476 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2486 PerlLIO_close(pp[0]);
2487 #if defined(HAS_FCNTL) && defined(F_SETFD)
2488 if (fcntl(pp[1], F_SETFD, FD_CLOEXEC) < 0)
2492 if (p[THIS] != (*mode == 'r')) {
2493 PerlLIO_dup2(p[THIS], *mode == 'r');
2494 PerlLIO_close(p[THIS]);
2495 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2496 PerlLIO_close(p[THAT]);
2499 PerlLIO_close(p[THAT]);
2502 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2509 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2514 /* may or may not use the shell */
2515 do_exec3(cmd, pp[1], did_pipes);
2518 #endif /* defined OS2 */
2520 #ifdef PERLIO_USING_CRLF
2521 /* Since we circumvent IO layers when we manipulate low-level
2522 filedescriptors directly, need to manually switch to the
2523 default, binary, low-level mode; see PerlIOBuf_open(). */
2524 PerlLIO_setmode((*mode == 'r'), O_BINARY);
2527 #ifdef PERL_USES_PL_PIDSTATUS
2528 hv_clear(PL_pidstatus); /* we have no children */
2534 do_execfree(); /* free any memory malloced by child on vfork */
2536 PerlLIO_close(pp[1]);
2537 if (p[that] < p[This]) {
2538 PerlLIO_dup2(p[This], p[that]);
2539 PerlLIO_close(p[This]);
2543 PerlLIO_close(p[that]);
2545 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2546 SvUPGRADE(sv,SVt_IV);
2548 PL_forkprocess = pid;
2549 if (did_pipes && pid > 0) {
2554 while (n < sizeof(int)) {
2555 n1 = PerlLIO_read(pp[0],
2556 (void*)(((char*)&errkid)+n),
2562 PerlLIO_close(pp[0]);
2564 if (n) { /* Error */
2566 PerlLIO_close(p[This]);
2567 if (n != sizeof(int))
2568 Perl_croak(aTHX_ "panic: kid popen errno read, n=%u", n);
2570 pid2 = wait4pid(pid, &status, 0);
2571 } while (pid2 == -1 && errno == EINTR);
2572 errno = errkid; /* Propagate errno from kid */
2577 PerlLIO_close(pp[0]);
2578 return PerlIO_fdopen(p[This], mode);
2582 FILE *djgpp_popen();
2584 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2586 PERL_FLUSHALL_FOR_CHILD;
2587 /* Call system's popen() to get a FILE *, then import it.
2588 used 0 for 2nd parameter to PerlIO_importFILE;
2591 return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2594 #if defined(__LIBCATAMOUNT__)
2596 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2603 #endif /* !DOSISH */
2605 /* this is called in parent before the fork() */
2607 Perl_atfork_lock(void)
2609 #if defined(USE_ITHREADS)
2611 /* locks must be held in locking order (if any) */
2613 MUTEX_LOCK(&PL_perlio_mutex);
2616 MUTEX_LOCK(&PL_malloc_mutex);
2622 /* this is called in both parent and child after the fork() */
2624 Perl_atfork_unlock(void)
2626 #if defined(USE_ITHREADS)
2628 /* locks must be released in same order as in atfork_lock() */
2630 MUTEX_UNLOCK(&PL_perlio_mutex);
2633 MUTEX_UNLOCK(&PL_malloc_mutex);
2642 #if defined(HAS_FORK)
2644 #if defined(USE_ITHREADS) && !defined(HAS_PTHREAD_ATFORK)
2649 /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2650 * handlers elsewhere in the code */
2655 /* this "canna happen" since nothing should be calling here if !HAS_FORK */
2656 Perl_croak_nocontext("fork() not available");
2658 #endif /* HAS_FORK */
2663 dup2(int oldfd, int newfd)
2665 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2668 PerlLIO_close(newfd);
2669 return fcntl(oldfd, F_DUPFD, newfd);
2671 #define DUP2_MAX_FDS 256
2672 int fdtmp[DUP2_MAX_FDS];
2678 PerlLIO_close(newfd);
2679 /* good enough for low fd's... */
2680 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2681 if (fdx >= DUP2_MAX_FDS) {
2689 PerlLIO_close(fdtmp[--fdx]);
2696 #ifdef HAS_SIGACTION
2699 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2701 struct sigaction act, oact;
2705 /* only "parent" interpreter can diddle signals */
2706 if (PL_curinterp != aTHX)
2707 return (Sighandler_t) SIG_ERR;
2710 act.sa_handler = (void(*)(int))handler;
2711 sigemptyset(&act.sa_mask);
2714 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2715 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2717 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2718 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2719 act.sa_flags |= SA_NOCLDWAIT;
2721 if (sigaction(signo, &act, &oact) == -1)
2722 return (Sighandler_t) SIG_ERR;
2724 return (Sighandler_t) oact.sa_handler;
2728 Perl_rsignal_state(pTHX_ int signo)
2730 struct sigaction oact;
2731 PERL_UNUSED_CONTEXT;
2733 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2734 return (Sighandler_t) SIG_ERR;
2736 return (Sighandler_t) oact.sa_handler;
2740 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2745 struct sigaction act;
2747 PERL_ARGS_ASSERT_RSIGNAL_SAVE;
2750 /* only "parent" interpreter can diddle signals */
2751 if (PL_curinterp != aTHX)
2755 act.sa_handler = (void(*)(int))handler;
2756 sigemptyset(&act.sa_mask);
2759 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2760 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2762 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2763 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2764 act.sa_flags |= SA_NOCLDWAIT;
2766 return sigaction(signo, &act, save);
2770 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2775 PERL_UNUSED_CONTEXT;
2777 /* only "parent" interpreter can diddle signals */
2778 if (PL_curinterp != aTHX)
2782 return sigaction(signo, save, (struct sigaction *)NULL);
2785 #else /* !HAS_SIGACTION */
2788 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2790 #if defined(USE_ITHREADS) && !defined(WIN32)
2791 /* only "parent" interpreter can diddle signals */
2792 if (PL_curinterp != aTHX)
2793 return (Sighandler_t) SIG_ERR;
2796 return PerlProc_signal(signo, handler);
2807 Perl_rsignal_state(pTHX_ int signo)
2810 Sighandler_t oldsig;
2812 #if defined(USE_ITHREADS) && !defined(WIN32)
2813 /* only "parent" interpreter can diddle signals */
2814 if (PL_curinterp != aTHX)
2815 return (Sighandler_t) SIG_ERR;
2819 oldsig = PerlProc_signal(signo, sig_trap);
2820 PerlProc_signal(signo, oldsig);
2822 PerlProc_kill(PerlProc_getpid(), signo);
2827 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2829 #if defined(USE_ITHREADS) && !defined(WIN32)
2830 /* only "parent" interpreter can diddle signals */
2831 if (PL_curinterp != aTHX)
2834 *save = PerlProc_signal(signo, handler);
2835 return (*save == (Sighandler_t) SIG_ERR) ? -1 : 0;
2839 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2841 #if defined(USE_ITHREADS) && !defined(WIN32)
2842 /* only "parent" interpreter can diddle signals */
2843 if (PL_curinterp != aTHX)
2846 return (PerlProc_signal(signo, *save) == (Sighandler_t) SIG_ERR) ? -1 : 0;
2849 #endif /* !HAS_SIGACTION */
2850 #endif /* !PERL_MICRO */
2852 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
2853 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__LIBCATAMOUNT__)
2855 Perl_my_pclose(pTHX_ PerlIO *ptr)
2863 const int fd = PerlIO_fileno(ptr);
2866 svp = av_fetch(PL_fdpid,fd,TRUE);
2867 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
2871 #if defined(USE_PERLIO)
2872 /* Find out whether the refcount is low enough for us to wait for the
2873 child proc without blocking. */
2874 should_wait = PerlIOUnix_refcnt(fd) == 1 && pid > 0;
2876 should_wait = pid > 0;
2880 if (pid == -1) { /* Opened by popen. */
2881 return my_syspclose(ptr);
2884 close_failed = (PerlIO_close(ptr) == EOF);
2886 if (should_wait) do {
2887 pid2 = wait4pid(pid, &status, 0);
2888 } while (pid2 == -1 && errno == EINTR);
2895 ? pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status)
2900 #if defined(__LIBCATAMOUNT__)
2902 Perl_my_pclose(pTHX_ PerlIO *ptr)
2907 #endif /* !DOSISH */
2909 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(__LIBCATAMOUNT__)
2911 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
2914 PERL_ARGS_ASSERT_WAIT4PID;
2915 #ifdef PERL_USES_PL_PIDSTATUS
2917 /* PERL_USES_PL_PIDSTATUS is only defined when neither
2918 waitpid() nor wait4() is available, or on OS/2, which
2919 doesn't appear to support waiting for a progress group
2920 member, so we can only treat a 0 pid as an unknown child.
2927 /* The keys in PL_pidstatus are now the raw 4 (or 8) bytes of the
2928 pid, rather than a string form. */
2929 SV * const * const svp = hv_fetch(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),FALSE);
2930 if (svp && *svp != &PL_sv_undef) {
2931 *statusp = SvIVX(*svp);
2932 (void)hv_delete(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),
2940 hv_iterinit(PL_pidstatus);
2941 if ((entry = hv_iternext(PL_pidstatus))) {
2942 SV * const sv = hv_iterval(PL_pidstatus,entry);
2944 const char * const spid = hv_iterkey(entry,&len);
2946 assert (len == sizeof(Pid_t));
2947 memcpy((char *)&pid, spid, len);
2948 *statusp = SvIVX(sv);
2949 /* The hash iterator is currently on this entry, so simply
2950 calling hv_delete would trigger the lazy delete, which on
2951 aggregate does more work, beacuse next call to hv_iterinit()
2952 would spot the flag, and have to call the delete routine,
2953 while in the meantime any new entries can't re-use that
2955 hv_iterinit(PL_pidstatus);
2956 (void)hv_delete(PL_pidstatus,spid,len,G_DISCARD);
2963 # ifdef HAS_WAITPID_RUNTIME
2964 if (!HAS_WAITPID_RUNTIME)
2967 result = PerlProc_waitpid(pid,statusp,flags);
2970 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
2971 result = wait4(pid,statusp,flags,NULL);
2974 #ifdef PERL_USES_PL_PIDSTATUS
2975 #if defined(HAS_WAITPID) && defined(HAS_WAITPID_RUNTIME)
2980 Perl_croak(aTHX_ "Can't do waitpid with flags");
2982 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
2983 pidgone(result,*statusp);
2989 #if defined(HAS_WAITPID) || defined(HAS_WAIT4)
2992 if (result < 0 && errno == EINTR) {
2994 errno = EINTR; /* reset in case a signal handler changed $! */
2998 #endif /* !DOSISH || OS2 || WIN32 || NETWARE */
3000 #ifdef PERL_USES_PL_PIDSTATUS
3002 S_pidgone(pTHX_ Pid_t pid, int status)
3006 sv = *hv_fetch(PL_pidstatus,(const char*)&pid,sizeof(Pid_t),TRUE);
3007 SvUPGRADE(sv,SVt_IV);
3008 SvIV_set(sv, status);
3016 int /* Cannot prototype with I32
3018 my_syspclose(PerlIO *ptr)
3021 Perl_my_pclose(pTHX_ PerlIO *ptr)
3024 /* Needs work for PerlIO ! */
3025 FILE * const f = PerlIO_findFILE(ptr);
3026 const I32 result = pclose(f);
3027 PerlIO_releaseFILE(ptr,f);
3035 Perl_my_pclose(pTHX_ PerlIO *ptr)
3037 /* Needs work for PerlIO ! */
3038 FILE * const f = PerlIO_findFILE(ptr);
3039 I32 result = djgpp_pclose(f);
3040 result = (result << 8) & 0xff00;
3041 PerlIO_releaseFILE(ptr,f);
3046 #define PERL_REPEATCPY_LINEAR 4
3048 Perl_repeatcpy(char *to, const char *from, I32 len, IV count)
3050 PERL_ARGS_ASSERT_REPEATCPY;
3055 croak_memory_wrap();
3058 memset(to, *from, count);
3061 IV items, linear, half;
3063 linear = count < PERL_REPEATCPY_LINEAR ? count : PERL_REPEATCPY_LINEAR;
3064 for (items = 0; items < linear; ++items) {
3065 const char *q = from;
3067 for (todo = len; todo > 0; todo--)
3072 while (items <= half) {
3073 IV size = items * len;
3074 memcpy(p, to, size);
3080 memcpy(p, to, (count - items) * len);
3086 Perl_same_dirent(pTHX_ const char *a, const char *b)
3088 char *fa = strrchr(a,'/');
3089 char *fb = strrchr(b,'/');
3092 SV * const tmpsv = sv_newmortal();
3094 PERL_ARGS_ASSERT_SAME_DIRENT;
3107 sv_setpvs(tmpsv, ".");
3109 sv_setpvn(tmpsv, a, fa - a);
3110 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf1) < 0)
3113 sv_setpvs(tmpsv, ".");
3115 sv_setpvn(tmpsv, b, fb - b);
3116 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf2) < 0)
3118 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
3119 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
3121 #endif /* !HAS_RENAME */
3124 Perl_find_script(pTHX_ const char *scriptname, bool dosearch,
3125 const char *const *const search_ext, I32 flags)
3127 const char *xfound = NULL;
3128 char *xfailed = NULL;
3129 char tmpbuf[MAXPATHLEN];
3134 #if defined(DOSISH) && !defined(OS2)
3135 # define SEARCH_EXTS ".bat", ".cmd", NULL
3136 # define MAX_EXT_LEN 4
3139 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
3140 # define MAX_EXT_LEN 4
3143 # define SEARCH_EXTS ".pl", ".com", NULL
3144 # define MAX_EXT_LEN 4
3146 /* additional extensions to try in each dir if scriptname not found */
3148 static const char *const exts[] = { SEARCH_EXTS };
3149 const char *const *const ext = search_ext ? search_ext : exts;
3150 int extidx = 0, i = 0;
3151 const char *curext = NULL;
3153 PERL_UNUSED_ARG(search_ext);
3154 # define MAX_EXT_LEN 0
3157 PERL_ARGS_ASSERT_FIND_SCRIPT;
3160 * If dosearch is true and if scriptname does not contain path
3161 * delimiters, search the PATH for scriptname.
3163 * If SEARCH_EXTS is also defined, will look for each
3164 * scriptname{SEARCH_EXTS} whenever scriptname is not found
3165 * while searching the PATH.
3167 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
3168 * proceeds as follows:
3169 * If DOSISH or VMSISH:
3170 * + look for ./scriptname{,.foo,.bar}
3171 * + search the PATH for scriptname{,.foo,.bar}
3174 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
3175 * this will not look in '.' if it's not in the PATH)
3180 # ifdef ALWAYS_DEFTYPES
3181 len = strlen(scriptname);
3182 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
3183 int idx = 0, deftypes = 1;
3186 const int hasdir = !dosearch || (strpbrk(scriptname,":[</") != NULL);
3189 int idx = 0, deftypes = 1;
3192 const int hasdir = (strpbrk(scriptname,":[</") != NULL);
3194 /* The first time through, just add SEARCH_EXTS to whatever we
3195 * already have, so we can check for default file types. */
3197 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
3203 if ((strlen(tmpbuf) + strlen(scriptname)
3204 + MAX_EXT_LEN) >= sizeof tmpbuf)
3205 continue; /* don't search dir with too-long name */
3206 my_strlcat(tmpbuf, scriptname, sizeof(tmpbuf));
3210 if (strEQ(scriptname, "-"))
3212 if (dosearch) { /* Look in '.' first. */
3213 const char *cur = scriptname;
3215 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
3217 if (strEQ(ext[i++],curext)) {
3218 extidx = -1; /* already has an ext */
3223 DEBUG_p(PerlIO_printf(Perl_debug_log,
3224 "Looking for %s\n",cur));
3225 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
3226 && !S_ISDIR(PL_statbuf.st_mode)) {
3234 if (cur == scriptname) {
3235 len = strlen(scriptname);
3236 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
3238 my_strlcpy(tmpbuf, scriptname, sizeof(tmpbuf));
3241 } while (extidx >= 0 && ext[extidx] /* try an extension? */
3242 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len));
3247 if (dosearch && !strchr(scriptname, '/')
3249 && !strchr(scriptname, '\\')
3251 && (s = PerlEnv_getenv("PATH")))
3255 bufend = s + strlen(s);
3256 while (s < bufend) {
3259 && *s != ';'; len++, s++) {
3260 if (len < sizeof tmpbuf)
3263 if (len < sizeof tmpbuf)
3266 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, bufend,
3272 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
3273 continue; /* don't search dir with too-long name */
3276 && tmpbuf[len - 1] != '/'
3277 && tmpbuf[len - 1] != '\\'
3280 tmpbuf[len++] = '/';
3281 if (len == 2 && tmpbuf[0] == '.')
3283 (void)my_strlcpy(tmpbuf + len, scriptname, sizeof(tmpbuf) - len);
3287 len = strlen(tmpbuf);
3288 if (extidx > 0) /* reset after previous loop */
3292 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
3293 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
3294 if (S_ISDIR(PL_statbuf.st_mode)) {
3298 } while ( retval < 0 /* not there */
3299 && extidx>=0 && ext[extidx] /* try an extension? */
3300 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len)
3305 if (S_ISREG(PL_statbuf.st_mode)
3306 && cando(S_IRUSR,TRUE,&PL_statbuf)
3307 #if !defined(DOSISH)
3308 && cando(S_IXUSR,TRUE,&PL_statbuf)
3312 xfound = tmpbuf; /* bingo! */
3316 xfailed = savepv(tmpbuf);
3319 if (!xfound && !seen_dot && !xfailed &&
3320 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
3321 || S_ISDIR(PL_statbuf.st_mode)))
3323 seen_dot = 1; /* Disable message. */
3325 if (flags & 1) { /* do or die? */
3326 /* diag_listed_as: Can't execute %s */
3327 Perl_croak(aTHX_ "Can't %s %s%s%s",
3328 (xfailed ? "execute" : "find"),
3329 (xfailed ? xfailed : scriptname),
3330 (xfailed ? "" : " on PATH"),
3331 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
3336 scriptname = xfound;
3338 return (scriptname ? savepv(scriptname) : NULL);
3341 #ifndef PERL_GET_CONTEXT_DEFINED
3344 Perl_get_context(void)
3346 #if defined(USE_ITHREADS)
3348 # ifdef OLD_PTHREADS_API
3350 int error = pthread_getspecific(PL_thr_key, &t)
3352 Perl_croak_nocontext("panic: pthread_getspecific, error=%d", error);
3355 # ifdef I_MACH_CTHREADS
3356 return (void*)cthread_data(cthread_self());
3358 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
3367 Perl_set_context(void *t)
3369 #if defined(USE_ITHREADS)
3372 PERL_ARGS_ASSERT_SET_CONTEXT;
3373 #if defined(USE_ITHREADS)
3374 # ifdef I_MACH_CTHREADS
3375 cthread_set_data(cthread_self(), t);
3378 const int error = pthread_setspecific(PL_thr_key, t);
3380 Perl_croak_nocontext("panic: pthread_setspecific, error=%d", error);
3388 #endif /* !PERL_GET_CONTEXT_DEFINED */
3390 #if defined(PERL_GLOBAL_STRUCT) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
3394 PERL_UNUSED_CONTEXT;
3400 Perl_get_op_names(pTHX)
3402 PERL_UNUSED_CONTEXT;
3403 return (char **)PL_op_name;
3407 Perl_get_op_descs(pTHX)
3409 PERL_UNUSED_CONTEXT;
3410 return (char **)PL_op_desc;
3414 Perl_get_no_modify(pTHX)
3416 PERL_UNUSED_CONTEXT;
3417 return PL_no_modify;
3421 Perl_get_opargs(pTHX)
3423 PERL_UNUSED_CONTEXT;
3424 return (U32 *)PL_opargs;
3428 Perl_get_ppaddr(pTHX)
3431 PERL_UNUSED_CONTEXT;
3432 return (PPADDR_t*)PL_ppaddr;
3435 #ifndef HAS_GETENV_LEN
3437 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3439 char * const env_trans = PerlEnv_getenv(env_elem);
3440 PERL_UNUSED_CONTEXT;
3441 PERL_ARGS_ASSERT_GETENV_LEN;
3443 *len = strlen(env_trans);
3450 Perl_get_vtbl(pTHX_ int vtbl_id)
3452 PERL_UNUSED_CONTEXT;
3454 return (vtbl_id < 0 || vtbl_id >= magic_vtable_max)
3455 ? NULL : (MGVTBL*)PL_magic_vtables + vtbl_id;
3459 Perl_my_fflush_all(pTHX)
3461 #if defined(USE_PERLIO) || defined(FFLUSH_NULL)
3462 return PerlIO_flush(NULL);
3464 # if defined(HAS__FWALK)
3465 extern int fflush(FILE *);
3466 /* undocumented, unprototyped, but very useful BSDism */
3467 extern void _fwalk(int (*)(FILE *));
3471 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3473 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3474 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3476 # if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3477 open_max = sysconf(_SC_OPEN_MAX);
3480 open_max = FOPEN_MAX;
3483 open_max = OPEN_MAX;
3494 for (i = 0; i < open_max; i++)
3495 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3496 STDIO_STREAM_ARRAY[i]._file < open_max &&
3497 STDIO_STREAM_ARRAY[i]._flag)
3498 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3502 SETERRNO(EBADF,RMS_IFI);
3509 Perl_report_wrongway_fh(pTHX_ const GV *gv, const char have)
3511 if (ckWARN(WARN_IO)) {
3513 = gv && (isGV_with_GP(gv))
3516 const char * const direction = have == '>' ? "out" : "in";
3518 if (name && HEK_LEN(name))
3519 Perl_warner(aTHX_ packWARN(WARN_IO),
3520 "Filehandle %"HEKf" opened only for %sput",
3521 HEKfARG(name), direction);
3523 Perl_warner(aTHX_ packWARN(WARN_IO),
3524 "Filehandle opened only for %sput", direction);
3529 Perl_report_evil_fh(pTHX_ const GV *gv)
3531 const IO *io = gv ? GvIO(gv) : NULL;
3532 const PERL_BITFIELD16 op = PL_op->op_type;
3536 if (io && IoTYPE(io) == IoTYPE_CLOSED) {
3538 warn_type = WARN_CLOSED;
3542 warn_type = WARN_UNOPENED;
3545 if (ckWARN(warn_type)) {
3547 = gv && isGV_with_GP(gv) && GvENAMELEN(gv) ?
3548 sv_2mortal(newSVhek(GvENAME_HEK(gv))) : NULL;
3549 const char * const pars =
3550 (const char *)(OP_IS_FILETEST(op) ? "" : "()");
3551 const char * const func =
3553 (op == OP_READLINE || op == OP_RCATLINE
3554 ? "readline" : /* "<HANDLE>" not nice */
3555 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
3557 const char * const type =
3559 (OP_IS_SOCKET(op) || (io && IoTYPE(io) == IoTYPE_SOCKET)
3560 ? "socket" : "filehandle");
3561 const bool have_name = name && SvCUR(name);
3562 Perl_warner(aTHX_ packWARN(warn_type),
3563 "%s%s on %s %s%s%"SVf, func, pars, vile, type,
3564 have_name ? " " : "",
3565 SVfARG(have_name ? name : &PL_sv_no));
3566 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3568 aTHX_ packWARN(warn_type),
3569 "\t(Are you trying to call %s%s on dirhandle%s%"SVf"?)\n",
3570 func, pars, have_name ? " " : "",
3571 SVfARG(have_name ? name : &PL_sv_no)
3576 /* To workaround core dumps from the uninitialised tm_zone we get the
3577 * system to give us a reasonable struct to copy. This fix means that
3578 * strftime uses the tm_zone and tm_gmtoff values returned by
3579 * localtime(time()). That should give the desired result most of the
3580 * time. But probably not always!
3582 * This does not address tzname aspects of NETaa14816.
3587 # ifndef STRUCT_TM_HASZONE
3588 # define STRUCT_TM_HASZONE
3592 #ifdef STRUCT_TM_HASZONE /* Backward compat */
3593 # ifndef HAS_TM_TM_ZONE
3594 # define HAS_TM_TM_ZONE
3599 Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
3601 #ifdef HAS_TM_TM_ZONE
3603 const struct tm* my_tm;
3604 PERL_UNUSED_CONTEXT;
3605 PERL_ARGS_ASSERT_INIT_TM;
3607 my_tm = localtime(&now);
3609 Copy(my_tm, ptm, 1, struct tm);
3611 PERL_UNUSED_CONTEXT;
3612 PERL_ARGS_ASSERT_INIT_TM;
3613 PERL_UNUSED_ARG(ptm);
3618 * mini_mktime - normalise struct tm values without the localtime()
3619 * semantics (and overhead) of mktime().
3622 Perl_mini_mktime(struct tm *ptm)
3626 int month, mday, year, jday;
3627 int odd_cent, odd_year;
3629 PERL_ARGS_ASSERT_MINI_MKTIME;
3631 #define DAYS_PER_YEAR 365
3632 #define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
3633 #define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
3634 #define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
3635 #define SECS_PER_HOUR (60*60)
3636 #define SECS_PER_DAY (24*SECS_PER_HOUR)
3637 /* parentheses deliberately absent on these two, otherwise they don't work */
3638 #define MONTH_TO_DAYS 153/5
3639 #define DAYS_TO_MONTH 5/153
3640 /* offset to bias by March (month 4) 1st between month/mday & year finding */
3641 #define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
3642 /* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
3643 #define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
3646 * Year/day algorithm notes:
3648 * With a suitable offset for numeric value of the month, one can find
3649 * an offset into the year by considering months to have 30.6 (153/5) days,
3650 * using integer arithmetic (i.e., with truncation). To avoid too much
3651 * messing about with leap days, we consider January and February to be
3652 * the 13th and 14th month of the previous year. After that transformation,
3653 * we need the month index we use to be high by 1 from 'normal human' usage,
3654 * so the month index values we use run from 4 through 15.
3656 * Given that, and the rules for the Gregorian calendar (leap years are those
3657 * divisible by 4 unless also divisible by 100, when they must be divisible
3658 * by 400 instead), we can simply calculate the number of days since some
3659 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
3660 * the days we derive from our month index, and adding in the day of the
3661 * month. The value used here is not adjusted for the actual origin which
3662 * it normally would use (1 January A.D. 1), since we're not exposing it.
3663 * We're only building the value so we can turn around and get the
3664 * normalised values for the year, month, day-of-month, and day-of-year.
3666 * For going backward, we need to bias the value we're using so that we find
3667 * the right year value. (Basically, we don't want the contribution of
3668 * March 1st to the number to apply while deriving the year). Having done
3669 * that, we 'count up' the contribution to the year number by accounting for
3670 * full quadracenturies (400-year periods) with their extra leap days, plus
3671 * the contribution from full centuries (to avoid counting in the lost leap
3672 * days), plus the contribution from full quad-years (to count in the normal
3673 * leap days), plus the leftover contribution from any non-leap years.
3674 * At this point, if we were working with an actual leap day, we'll have 0
3675 * days left over. This is also true for March 1st, however. So, we have
3676 * to special-case that result, and (earlier) keep track of the 'odd'
3677 * century and year contributions. If we got 4 extra centuries in a qcent,
3678 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
3679 * Otherwise, we add back in the earlier bias we removed (the 123 from
3680 * figuring in March 1st), find the month index (integer division by 30.6),
3681 * and the remainder is the day-of-month. We then have to convert back to
3682 * 'real' months (including fixing January and February from being 14/15 in
3683 * the previous year to being in the proper year). After that, to get
3684 * tm_yday, we work with the normalised year and get a new yearday value for
3685 * January 1st, which we subtract from the yearday value we had earlier,
3686 * representing the date we've re-built. This is done from January 1
3687 * because tm_yday is 0-origin.
3689 * Since POSIX time routines are only guaranteed to work for times since the
3690 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
3691 * applies Gregorian calendar rules even to dates before the 16th century
3692 * doesn't bother me. Besides, you'd need cultural context for a given
3693 * date to know whether it was Julian or Gregorian calendar, and that's
3694 * outside the scope for this routine. Since we convert back based on the
3695 * same rules we used to build the yearday, you'll only get strange results
3696 * for input which needed normalising, or for the 'odd' century years which
3697 * were leap years in the Julian calendar but not in the Gregorian one.
3698 * I can live with that.
3700 * This algorithm also fails to handle years before A.D. 1 gracefully, but
3701 * that's still outside the scope for POSIX time manipulation, so I don't
3705 year = 1900 + ptm->tm_year;
3706 month = ptm->tm_mon;
3707 mday = ptm->tm_mday;
3713 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
3714 yearday += month*MONTH_TO_DAYS + mday + jday;
3716 * Note that we don't know when leap-seconds were or will be,
3717 * so we have to trust the user if we get something which looks
3718 * like a sensible leap-second. Wild values for seconds will
3719 * be rationalised, however.
3721 if ((unsigned) ptm->tm_sec <= 60) {
3728 secs += 60 * ptm->tm_min;
3729 secs += SECS_PER_HOUR * ptm->tm_hour;
3731 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
3732 /* got negative remainder, but need positive time */
3733 /* back off an extra day to compensate */
3734 yearday += (secs/SECS_PER_DAY)-1;
3735 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
3738 yearday += (secs/SECS_PER_DAY);
3739 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
3742 else if (secs >= SECS_PER_DAY) {
3743 yearday += (secs/SECS_PER_DAY);
3744 secs %= SECS_PER_DAY;
3746 ptm->tm_hour = secs/SECS_PER_HOUR;
3747 secs %= SECS_PER_HOUR;
3748 ptm->tm_min = secs/60;
3750 ptm->tm_sec += secs;
3751 /* done with time of day effects */
3753 * The algorithm for yearday has (so far) left it high by 428.
3754 * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
3755 * bias it by 123 while trying to figure out what year it
3756 * really represents. Even with this tweak, the reverse
3757 * translation fails for years before A.D. 0001.
3758 * It would still fail for Feb 29, but we catch that one below.
3760 jday = yearday; /* save for later fixup vis-a-vis Jan 1 */
3761 yearday -= YEAR_ADJUST;
3762 year = (yearday / DAYS_PER_QCENT) * 400;
3763 yearday %= DAYS_PER_QCENT;
3764 odd_cent = yearday / DAYS_PER_CENT;
3765 year += odd_cent * 100;
3766 yearday %= DAYS_PER_CENT;
3767 year += (yearday / DAYS_PER_QYEAR) * 4;
3768 yearday %= DAYS_PER_QYEAR;
3769 odd_year = yearday / DAYS_PER_YEAR;
3771 yearday %= DAYS_PER_YEAR;
3772 if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
3777 yearday += YEAR_ADJUST; /* recover March 1st crock */
3778 month = yearday*DAYS_TO_MONTH;
3779 yearday -= month*MONTH_TO_DAYS;
3780 /* recover other leap-year adjustment */
3789 ptm->tm_year = year - 1900;
3791 ptm->tm_mday = yearday;
3792 ptm->tm_mon = month;
3796 ptm->tm_mon = month - 1;
3798 /* re-build yearday based on Jan 1 to get tm_yday */
3800 yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
3801 yearday += 14*MONTH_TO_DAYS + 1;
3802 ptm->tm_yday = jday - yearday;
3803 ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
3807 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)
3811 /* Note that yday and wday effectively are ignored by this function, as mini_mktime() overwrites them */
3818 PERL_ARGS_ASSERT_MY_STRFTIME;
3820 init_tm(&mytm); /* XXX workaround - see init_tm() above */
3823 mytm.tm_hour = hour;
3824 mytm.tm_mday = mday;
3826 mytm.tm_year = year;
3827 mytm.tm_wday = wday;
3828 mytm.tm_yday = yday;
3829 mytm.tm_isdst = isdst;
3831 /* use libc to get the values for tm_gmtoff and tm_zone [perl #18238] */
3832 #if defined(HAS_MKTIME) && (defined(HAS_TM_TM_GMTOFF) || defined(HAS_TM_TM_ZONE))
3837 #ifdef HAS_TM_TM_GMTOFF
3838 mytm.tm_gmtoff = mytm2.tm_gmtoff;
3840 #ifdef HAS_TM_TM_ZONE
3841 mytm.tm_zone = mytm2.tm_zone;
3846 Newx(buf, buflen, char);
3848 GCC_DIAG_IGNORE(-Wformat-nonliteral); /* fmt checked by caller */
3849 len = strftime(buf, buflen, fmt, &mytm);
3853 ** The following is needed to handle to the situation where
3854 ** tmpbuf overflows. Basically we want to allocate a buffer
3855 ** and try repeatedly. The reason why it is so complicated
3856 ** is that getting a return value of 0 from strftime can indicate
3857 ** one of the following:
3858 ** 1. buffer overflowed,
3859 ** 2. illegal conversion specifier, or
3860 ** 3. the format string specifies nothing to be returned(not
3861 ** an error). This could be because format is an empty string
3862 ** or it specifies %p that yields an empty string in some locale.
3863 ** If there is a better way to make it portable, go ahead by
3866 if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
3869 /* Possibly buf overflowed - try again with a bigger buf */
3870 const int fmtlen = strlen(fmt);
3871 int bufsize = fmtlen + buflen;
3873 Renew(buf, bufsize, char);
3876 GCC_DIAG_IGNORE(-Wformat-nonliteral); /* fmt checked by caller */
3877 buflen = strftime(buf, bufsize, fmt, &mytm);
3880 if (buflen > 0 && buflen < bufsize)
3882 /* heuristic to prevent out-of-memory errors */
3883 if (bufsize > 100*fmtlen) {
3889 Renew(buf, bufsize, char);
3894 Perl_croak(aTHX_ "panic: no strftime");
3900 #define SV_CWD_RETURN_UNDEF \
3901 sv_setsv(sv, &PL_sv_undef); \
3904 #define SV_CWD_ISDOT(dp) \
3905 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
3906 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
3909 =head1 Miscellaneous Functions
3911 =for apidoc getcwd_sv
3913 Fill the sv with current working directory
3918 /* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
3919 * rewritten again by dougm, optimized for use with xs TARG, and to prefer
3920 * getcwd(3) if available
3921 * Comments from the orignal:
3922 * This is a faster version of getcwd. It's also more dangerous
3923 * because you might chdir out of a directory that you can't chdir
3927 Perl_getcwd_sv(pTHX_ SV *sv)
3932 PERL_ARGS_ASSERT_GETCWD_SV;
3936 char buf[MAXPATHLEN];
3938 /* Some getcwd()s automatically allocate a buffer of the given
3939 * size from the heap if they are given a NULL buffer pointer.
3940 * The problem is that this behaviour is not portable. */
3941 if (getcwd(buf, sizeof(buf) - 1)) {
3946 sv_setsv(sv, &PL_sv_undef);
3954 int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
3958 SvUPGRADE(sv, SVt_PV);
3960 if (PerlLIO_lstat(".", &statbuf) < 0) {
3961 SV_CWD_RETURN_UNDEF;
3964 orig_cdev = statbuf.st_dev;
3965 orig_cino = statbuf.st_ino;
3975 if (PerlDir_chdir("..") < 0) {
3976 SV_CWD_RETURN_UNDEF;
3978 if (PerlLIO_stat(".", &statbuf) < 0) {
3979 SV_CWD_RETURN_UNDEF;
3982 cdev = statbuf.st_dev;
3983 cino = statbuf.st_ino;
3985 if (odev == cdev && oino == cino) {
3988 if (!(dir = PerlDir_open("."))) {
3989 SV_CWD_RETURN_UNDEF;
3992 while ((dp = PerlDir_read(dir)) != NULL) {
3994 namelen = dp->d_namlen;
3996 namelen = strlen(dp->d_name);
3999 if (SV_CWD_ISDOT(dp)) {
4003 if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
4004 SV_CWD_RETURN_UNDEF;
4007 tdev = statbuf.st_dev;
4008 tino = statbuf.st_ino;
4009 if (tino == oino && tdev == odev) {
4015 SV_CWD_RETURN_UNDEF;
4018 if (pathlen + namelen + 1 >= MAXPATHLEN) {
4019 SV_CWD_RETURN_UNDEF;
4022 SvGROW(sv, pathlen + namelen + 1);
4026 Move(SvPVX_const(sv), SvPVX(sv) + namelen + 1, pathlen, char);
4029 /* prepend current directory to the front */
4031 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
4032 pathlen += (namelen + 1);
4034 #ifdef VOID_CLOSEDIR
4037 if (PerlDir_close(dir) < 0) {
4038 SV_CWD_RETURN_UNDEF;
4044 SvCUR_set(sv, pathlen);
4048 if (PerlDir_chdir(SvPVX_const(sv)) < 0) {
4049 SV_CWD_RETURN_UNDEF;
4052 if (PerlLIO_stat(".", &statbuf) < 0) {
4053 SV_CWD_RETURN_UNDEF;
4056 cdev = statbuf.st_dev;
4057 cino = statbuf.st_ino;
4059 if (cdev != orig_cdev || cino != orig_cino) {
4060 Perl_croak(aTHX_ "Unstable directory path, "
4061 "current directory changed unexpectedly");
4074 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET) && defined(SOCK_DGRAM) && defined(HAS_SELECT)
4075 # define EMULATE_SOCKETPAIR_UDP
4078 #ifdef EMULATE_SOCKETPAIR_UDP
4080 S_socketpair_udp (int fd[2]) {
4082 /* Fake a datagram socketpair using UDP to localhost. */
4083 int sockets[2] = {-1, -1};
4084 struct sockaddr_in addresses[2];
4086 Sock_size_t size = sizeof(struct sockaddr_in);
4087 unsigned short port;
4090 memset(&addresses, 0, sizeof(addresses));
4093 sockets[i] = PerlSock_socket(AF_INET, SOCK_DGRAM, PF_INET);
4094 if (sockets[i] == -1)
4095 goto tidy_up_and_fail;
4097 addresses[i].sin_family = AF_INET;
4098 addresses[i].sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4099 addresses[i].sin_port = 0; /* kernel choses port. */
4100 if (PerlSock_bind(sockets[i], (struct sockaddr *) &addresses[i],
4101 sizeof(struct sockaddr_in)) == -1)
4102 goto tidy_up_and_fail;
4105 /* Now have 2 UDP sockets. Find out which port each is connected to, and
4106 for each connect the other socket to it. */
4109 if (PerlSock_getsockname(sockets[i], (struct sockaddr *) &addresses[i],
4111 goto tidy_up_and_fail;
4112 if (size != sizeof(struct sockaddr_in))
4113 goto abort_tidy_up_and_fail;
4114 /* !1 is 0, !0 is 1 */
4115 if (PerlSock_connect(sockets[!i], (struct sockaddr *) &addresses[i],
4116 sizeof(struct sockaddr_in)) == -1)
4117 goto tidy_up_and_fail;
4120 /* Now we have 2 sockets connected to each other. I don't trust some other
4121 process not to have already sent a packet to us (by random) so send
4122 a packet from each to the other. */
4125 /* I'm going to send my own port number. As a short.
4126 (Who knows if someone somewhere has sin_port as a bitfield and needs
4127 this routine. (I'm assuming crays have socketpair)) */
4128 port = addresses[i].sin_port;
4129 got = PerlLIO_write(sockets[i], &port, sizeof(port));
4130 if (got != sizeof(port)) {
4132 goto tidy_up_and_fail;
4133 goto abort_tidy_up_and_fail;
4137 /* Packets sent. I don't trust them to have arrived though.
4138 (As I understand it Solaris TCP stack is multithreaded. Non-blocking
4139 connect to localhost will use a second kernel thread. In 2.6 the
4140 first thread running the connect() returns before the second completes,
4141 so EINPROGRESS> In 2.7 the improved stack is faster and connect()
4142 returns 0. Poor programs have tripped up. One poor program's authors'
4143 had a 50-1 reverse stock split. Not sure how connected these were.)
4144 So I don't trust someone not to have an unpredictable UDP stack.
4148 struct timeval waitfor = {0, 100000}; /* You have 0.1 seconds */
4149 int max = sockets[1] > sockets[0] ? sockets[1] : sockets[0];
4153 FD_SET((unsigned int)sockets[0], &rset);
4154 FD_SET((unsigned int)sockets[1], &rset);
4156 got = PerlSock_select(max + 1, &rset, NULL, NULL, &waitfor);
4157 if (got != 2 || !FD_ISSET(sockets[0], &rset)
4158 || !FD_ISSET(sockets[1], &rset)) {
4159 /* I hope this is portable and appropriate. */
4161 goto tidy_up_and_fail;
4162 goto abort_tidy_up_and_fail;
4166 /* And the paranoia department even now doesn't trust it to have arrive
4167 (hence MSG_DONTWAIT). Or that what arrives was sent by us. */
4169 struct sockaddr_in readfrom;
4170 unsigned short buffer[2];
4175 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4176 sizeof(buffer), MSG_DONTWAIT,
4177 (struct sockaddr *) &readfrom, &size);
4179 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4181 (struct sockaddr *) &readfrom, &size);
4185 goto tidy_up_and_fail;
4186 if (got != sizeof(port)
4187 || size != sizeof(struct sockaddr_in)
4188 /* Check other socket sent us its port. */
4189 || buffer[0] != (unsigned short) addresses[!i].sin_port
4190 /* Check kernel says we got the datagram from that socket */
4191 || readfrom.sin_family != addresses[!i].sin_family
4192 || readfrom.sin_addr.s_addr != addresses[!i].sin_addr.s_addr
4193 || readfrom.sin_port != addresses[!i].sin_port)
4194 goto abort_tidy_up_and_fail;
4197 /* My caller (my_socketpair) has validated that this is non-NULL */
4200 /* I hereby declare this connection open. May God bless all who cross
4204 abort_tidy_up_and_fail:
4205 errno = ECONNABORTED;
4209 if (sockets[0] != -1)
4210 PerlLIO_close(sockets[0]);
4211 if (sockets[1] != -1)
4212 PerlLIO_close(sockets[1]);
4217 #endif /* EMULATE_SOCKETPAIR_UDP */
4219 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET)
4221 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4222 /* Stevens says that family must be AF_LOCAL, protocol 0.
4223 I'm going to enforce that, then ignore it, and use TCP (or UDP). */
4228 struct sockaddr_in listen_addr;
4229 struct sockaddr_in connect_addr;
4234 || family != AF_UNIX
4237 errno = EAFNOSUPPORT;
4245 #ifdef EMULATE_SOCKETPAIR_UDP
4246 if (type == SOCK_DGRAM)
4247 return S_socketpair_udp(fd);
4250 aTHXa(PERL_GET_THX);
4251 listener = PerlSock_socket(AF_INET, type, 0);
4254 memset(&listen_addr, 0, sizeof(listen_addr));
4255 listen_addr.sin_family = AF_INET;
4256 listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4257 listen_addr.sin_port = 0; /* kernel choses port. */
4258 if (PerlSock_bind(listener, (struct sockaddr *) &listen_addr,
4259 sizeof(listen_addr)) == -1)
4260 goto tidy_up_and_fail;
4261 if (PerlSock_listen(listener, 1) == -1)
4262 goto tidy_up_and_fail;
4264 connector = PerlSock_socket(AF_INET, type, 0);
4265 if (connector == -1)
4266 goto tidy_up_and_fail;
4267 /* We want to find out the port number to connect to. */
4268 size = sizeof(connect_addr);
4269 if (PerlSock_getsockname(listener, (struct sockaddr *) &connect_addr,
4271 goto tidy_up_and_fail;
4272 if (size != sizeof(connect_addr))
4273 goto abort_tidy_up_and_fail;
4274 if (PerlSock_connect(connector, (struct sockaddr *) &connect_addr,
4275 sizeof(connect_addr)) == -1)
4276 goto tidy_up_and_fail;
4278 size = sizeof(listen_addr);
4279 acceptor = PerlSock_accept(listener, (struct sockaddr *) &listen_addr,
4282 goto tidy_up_and_fail;
4283 if (size != sizeof(listen_addr))
4284 goto abort_tidy_up_and_fail;
4285 PerlLIO_close(listener);
4286 /* Now check we are talking to ourself by matching port and host on the
4288 if (PerlSock_getsockname(connector, (struct sockaddr *) &connect_addr,
4290 goto tidy_up_and_fail;
4291 if (size != sizeof(connect_addr)
4292 || listen_addr.sin_family != connect_addr.sin_family
4293 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
4294 || listen_addr.sin_port != connect_addr.sin_port) {
4295 goto abort_tidy_up_and_fail;
4301 abort_tidy_up_and_fail:
4303 errno = ECONNABORTED; /* This would be the standard thing to do. */
4305 # ifdef ECONNREFUSED
4306 errno = ECONNREFUSED; /* E.g. Symbian does not have ECONNABORTED. */
4308 errno = ETIMEDOUT; /* Desperation time. */
4315 PerlLIO_close(listener);
4316 if (connector != -1)
4317 PerlLIO_close(connector);
4319 PerlLIO_close(acceptor);
4325 /* In any case have a stub so that there's code corresponding
4326 * to the my_socketpair in embed.fnc. */
4328 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4329 #ifdef HAS_SOCKETPAIR
4330 return socketpair(family, type, protocol, fd);
4339 =for apidoc sv_nosharing
4341 Dummy routine which "shares" an SV when there is no sharing module present.
4342 Or "locks" it. Or "unlocks" it. In other
4343 words, ignores its single SV argument.
4344 Exists to avoid test for a NULL function pointer and because it could
4345 potentially warn under some level of strict-ness.
4351 Perl_sv_nosharing(pTHX_ SV *sv)
4353 PERL_UNUSED_CONTEXT;
4354 PERL_UNUSED_ARG(sv);
4359 =for apidoc sv_destroyable
4361 Dummy routine which reports that object can be destroyed when there is no
4362 sharing module present. It ignores its single SV argument, and returns
4363 'true'. Exists to avoid test for a NULL function pointer and because it
4364 could potentially warn under some level of strict-ness.
4370 Perl_sv_destroyable(pTHX_ SV *sv)
4372 PERL_UNUSED_CONTEXT;
4373 PERL_UNUSED_ARG(sv);
4378 Perl_parse_unicode_opts(pTHX_ const char **popt)
4380 const char *p = *popt;
4383 PERL_ARGS_ASSERT_PARSE_UNICODE_OPTS;
4388 opt = (U32) grok_atou(p, &endptr);
4390 if (*p && *p != '\n' && *p != '\r') {
4391 if(isSPACE(*p)) goto the_end_of_the_opts_parser;
4393 Perl_croak(aTHX_ "Unknown Unicode option letter '%c'", *p);
4399 case PERL_UNICODE_STDIN:
4400 opt |= PERL_UNICODE_STDIN_FLAG; break;
4401 case PERL_UNICODE_STDOUT:
4402 opt |= PERL_UNICODE_STDOUT_FLAG; break;
4403 case PERL_UNICODE_STDERR:
4404 opt |= PERL_UNICODE_STDERR_FLAG; break;
4405 case PERL_UNICODE_STD:
4406 opt |= PERL_UNICODE_STD_FLAG; break;
4407 case PERL_UNICODE_IN:
4408 opt |= PERL_UNICODE_IN_FLAG; break;
4409 case PERL_UNICODE_OUT:
4410 opt |= PERL_UNICODE_OUT_FLAG; break;
4411 case PERL_UNICODE_INOUT:
4412 opt |= PERL_UNICODE_INOUT_FLAG; break;
4413 case PERL_UNICODE_LOCALE:
4414 opt |= PERL_UNICODE_LOCALE_FLAG; break;
4415 case PERL_UNICODE_ARGV:
4416 opt |= PERL_UNICODE_ARGV_FLAG; break;
4417 case PERL_UNICODE_UTF8CACHEASSERT:
4418 opt |= PERL_UNICODE_UTF8CACHEASSERT_FLAG; break;
4420 if (*p != '\n' && *p != '\r') {
4421 if(isSPACE(*p)) goto the_end_of_the_opts_parser;
4424 "Unknown Unicode option letter '%c'", *p);
4431 opt = PERL_UNICODE_DEFAULT_FLAGS;
4433 the_end_of_the_opts_parser:
4435 if (opt & ~PERL_UNICODE_ALL_FLAGS)
4436 Perl_croak(aTHX_ "Unknown Unicode option value %"UVuf,
4437 (UV) (opt & ~PERL_UNICODE_ALL_FLAGS));
4445 # include <starlet.h>
4452 * This is really just a quick hack which grabs various garbage
4453 * values. It really should be a real hash algorithm which
4454 * spreads the effect of every input bit onto every output bit,
4455 * if someone who knows about such things would bother to write it.
4456 * Might be a good idea to add that function to CORE as well.
4457 * No numbers below come from careful analysis or anything here,
4458 * except they are primes and SEED_C1 > 1E6 to get a full-width
4459 * value from (tv_sec * SEED_C1 + tv_usec). The multipliers should
4460 * probably be bigger too.
4463 # define SEED_C1 1000003
4464 #define SEED_C4 73819
4466 # define SEED_C1 25747
4467 #define SEED_C4 20639
4471 #define SEED_C5 26107
4473 #ifndef PERL_NO_DEV_RANDOM
4478 /* when[] = (low 32 bits, high 32 bits) of time since epoch
4479 * in 100-ns units, typically incremented ever 10 ms. */
4480 unsigned int when[2];
4482 # ifdef HAS_GETTIMEOFDAY
4483 struct timeval when;
4489 /* This test is an escape hatch, this symbol isn't set by Configure. */
4490 #ifndef PERL_NO_DEV_RANDOM
4491 #ifndef PERL_RANDOM_DEVICE
4492 /* /dev/random isn't used by default because reads from it will block
4493 * if there isn't enough entropy available. You can compile with
4494 * PERL_RANDOM_DEVICE to it if you'd prefer Perl to block until there
4495 * is enough real entropy to fill the seed. */
4496 # define PERL_RANDOM_DEVICE "/dev/urandom"
4498 fd = PerlLIO_open(PERL_RANDOM_DEVICE, 0);
4500 if (PerlLIO_read(fd, (void*)&u, sizeof u) != sizeof u)
4509 _ckvmssts(sys$gettim(when));
4510 u = (U32)SEED_C1 * when[0] + (U32)SEED_C2 * when[1];
4512 # ifdef HAS_GETTIMEOFDAY
4513 PerlProc_gettimeofday(&when,NULL);
4514 u = (U32)SEED_C1 * when.tv_sec + (U32)SEED_C2 * when.tv_usec;
4517 u = (U32)SEED_C1 * when;
4520 u += SEED_C3 * (U32)PerlProc_getpid();
4521 u += SEED_C4 * (U32)PTR2UV(PL_stack_sp);
4522 #ifndef PLAN9 /* XXX Plan9 assembler chokes on this; fix needed */
4523 u += SEED_C5 * (U32)PTR2UV(&when);
4529 Perl_get_hash_seed(pTHX_ unsigned char * const seed_buffer)
4534 PERL_ARGS_ASSERT_GET_HASH_SEED;
4536 env_pv= PerlEnv_getenv("PERL_HASH_SEED");
4539 #ifndef USE_HASH_SEED_EXPLICIT
4541 /* ignore leading spaces */
4542 while (isSPACE(*env_pv))
4544 #ifdef USE_PERL_PERTURB_KEYS
4545 /* if they set it to "0" we disable key traversal randomization completely */
4546 if (strEQ(env_pv,"0")) {
4547 PL_hash_rand_bits_enabled= 0;
4549 /* otherwise switch to deterministic mode */
4550 PL_hash_rand_bits_enabled= 2;
4553 /* ignore a leading 0x... if it is there */
4554 if (env_pv[0] == '0' && env_pv[1] == 'x')
4557 for( i = 0; isXDIGIT(*env_pv) && i < PERL_HASH_SEED_BYTES; i++ ) {
4558 seed_buffer[i] = READ_XDIGIT(env_pv) << 4;
4559 if ( isXDIGIT(*env_pv)) {
4560 seed_buffer[i] |= READ_XDIGIT(env_pv);
4563 while (isSPACE(*env_pv))
4566 if (*env_pv && !isXDIGIT(*env_pv)) {
4567 Perl_warn(aTHX_ "perl: warning: Non hex character in '$ENV{PERL_HASH_SEED}', seed only partially set\n");
4569 /* should we check for unparsed crap? */
4570 /* should we warn about unused hex? */
4571 /* should we warn about insufficient hex? */
4576 (void)seedDrand01((Rand_seed_t)seed());
4578 for( i = 0; i < PERL_HASH_SEED_BYTES; i++ ) {
4579 seed_buffer[i] = (unsigned char)(Drand01() * (U8_MAX+1));
4582 #ifdef USE_PERL_PERTURB_KEYS
4583 { /* initialize PL_hash_rand_bits from the hash seed.
4584 * This value is highly volatile, it is updated every
4585 * hash insert, and is used as part of hash bucket chain
4586 * randomization and hash iterator randomization. */
4587 PL_hash_rand_bits= 0xbe49d17f; /* I just picked a number */
4588 for( i = 0; i < sizeof(UV) ; i++ ) {
4589 PL_hash_rand_bits += seed_buffer[i % PERL_HASH_SEED_BYTES];
4590 PL_hash_rand_bits = ROTL_UV(PL_hash_rand_bits,8);
4593 env_pv= PerlEnv_getenv("PERL_PERTURB_KEYS");
4595 if (strEQ(env_pv,"0") || strEQ(env_pv,"NO")) {
4596 PL_hash_rand_bits_enabled= 0;
4597 } else if (strEQ(env_pv,"1") || strEQ(env_pv,"RANDOM")) {
4598 PL_hash_rand_bits_enabled= 1;
4599 } else if (strEQ(env_pv,"2") || strEQ(env_pv,"DETERMINISTIC")) {
4600 PL_hash_rand_bits_enabled= 2;
4602 Perl_warn(aTHX_ "perl: warning: strange setting in '$ENV{PERL_PERTURB_KEYS}': '%s'\n", env_pv);
4608 #ifdef PERL_GLOBAL_STRUCT
4610 #define PERL_GLOBAL_STRUCT_INIT
4611 #include "opcode.h" /* the ppaddr and check */
4614 Perl_init_global_struct(pTHX)
4616 struct perl_vars *plvarsp = NULL;
4617 # ifdef PERL_GLOBAL_STRUCT
4618 const IV nppaddr = C_ARRAY_LENGTH(Gppaddr);
4619 const IV ncheck = C_ARRAY_LENGTH(Gcheck);
4620 PERL_UNUSED_CONTEXT;
4621 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
4622 /* PerlMem_malloc() because can't use even safesysmalloc() this early. */
4623 plvarsp = (struct perl_vars*)PerlMem_malloc(sizeof(struct perl_vars));
4627 plvarsp = PL_VarsPtr;
4628 # endif /* PERL_GLOBAL_STRUCT_PRIVATE */
4633 # define PERLVAR(prefix,var,type) /**/
4634 # define PERLVARA(prefix,var,n,type) /**/
4635 # define PERLVARI(prefix,var,type,init) plvarsp->prefix##var = init;
4636 # define PERLVARIC(prefix,var,type,init) plvarsp->prefix##var = init;
4637 # include "perlvars.h"
4642 # ifdef PERL_GLOBAL_STRUCT
4645 PerlMem_malloc(nppaddr * sizeof(Perl_ppaddr_t));
4646 if (!plvarsp->Gppaddr)
4650 PerlMem_malloc(ncheck * sizeof(Perl_check_t));
4651 if (!plvarsp->Gcheck)
4653 Copy(Gppaddr, plvarsp->Gppaddr, nppaddr, Perl_ppaddr_t);
4654 Copy(Gcheck, plvarsp->Gcheck, ncheck, Perl_check_t);
4656 # ifdef PERL_SET_VARS
4657 PERL_SET_VARS(plvarsp);
4659 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
4660 plvarsp->Gsv_placeholder.sv_flags = 0;
4661 memset(plvarsp->Ghash_seed, 0, sizeof(plvarsp->Ghash_seed));
4663 # undef PERL_GLOBAL_STRUCT_INIT
4668 #endif /* PERL_GLOBAL_STRUCT */
4670 #ifdef PERL_GLOBAL_STRUCT
4673 Perl_free_global_struct(pTHX_ struct perl_vars *plvarsp)
4675 int veto = plvarsp->Gveto_cleanup;
4677 PERL_ARGS_ASSERT_FREE_GLOBAL_STRUCT;
4678 PERL_UNUSED_CONTEXT;
4679 # ifdef PERL_GLOBAL_STRUCT
4680 # ifdef PERL_UNSET_VARS
4681 PERL_UNSET_VARS(plvarsp);
4685 free(plvarsp->Gppaddr);
4686 free(plvarsp->Gcheck);
4687 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
4693 #endif /* PERL_GLOBAL_STRUCT */
4697 /* -DPERL_MEM_LOG: the Perl_mem_log_..() is compiled, including the
4698 * the default implementation, unless -DPERL_MEM_LOG_NOIMPL is also
4699 * given, and you supply your own implementation.
4701 * The default implementation reads a single env var, PERL_MEM_LOG,
4702 * expecting one or more of the following:
4704 * \d+ - fd fd to write to : must be 1st (grok_atou)
4705 * 'm' - memlog was PERL_MEM_LOG=1
4706 * 's' - svlog was PERL_SV_LOG=1
4707 * 't' - timestamp was PERL_MEM_LOG_TIMESTAMP=1
4709 * This makes the logger controllable enough that it can reasonably be
4710 * added to the system perl.
4713 /* -DPERL_MEM_LOG_SPRINTF_BUF_SIZE=X: size of a (stack-allocated) buffer
4714 * the Perl_mem_log_...() will use (either via sprintf or snprintf).
4716 #define PERL_MEM_LOG_SPRINTF_BUF_SIZE 128
4718 /* -DPERL_MEM_LOG_FD=N: the file descriptor the Perl_mem_log_...()
4719 * writes to. In the default logger, this is settable at runtime.
4721 #ifndef PERL_MEM_LOG_FD
4722 # define PERL_MEM_LOG_FD 2 /* If STDERR is too boring for you. */
4725 #ifndef PERL_MEM_LOG_NOIMPL
4727 # ifdef DEBUG_LEAKING_SCALARS
4728 # define SV_LOG_SERIAL_FMT " [%lu]"
4729 # define _SV_LOG_SERIAL_ARG(sv) , (unsigned long) (sv)->sv_debug_serial
4731 # define SV_LOG_SERIAL_FMT
4732 # define _SV_LOG_SERIAL_ARG(sv)
4736 S_mem_log_common(enum mem_log_type mlt, const UV n,
4737 const UV typesize, const char *type_name, const SV *sv,
4738 Malloc_t oldalloc, Malloc_t newalloc,
4739 const char *filename, const int linenumber,
4740 const char *funcname)
4744 PERL_ARGS_ASSERT_MEM_LOG_COMMON;
4746 pmlenv = PerlEnv_getenv("PERL_MEM_LOG");
4749 if (mlt < MLT_NEW_SV ? strchr(pmlenv,'m') : strchr(pmlenv,'s'))
4751 /* We can't use SVs or PerlIO for obvious reasons,
4752 * so we'll use stdio and low-level IO instead. */
4753 char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
4755 # ifdef HAS_GETTIMEOFDAY
4756 # define MEM_LOG_TIME_FMT "%10d.%06d: "
4757 # define MEM_LOG_TIME_ARG (int)tv.tv_sec, (int)tv.tv_usec
4759 gettimeofday(&tv, 0);
4761 # define MEM_LOG_TIME_FMT "%10d: "
4762 # define MEM_LOG_TIME_ARG (int)when
4766 /* If there are other OS specific ways of hires time than
4767 * gettimeofday() (see ext/Time-HiRes), the easiest way is
4768 * probably that they would be used to fill in the struct
4773 int fd = grok_atou(pmlenv, &endptr); /* Ignore endptr. */
4775 fd = PERL_MEM_LOG_FD;
4777 if (strchr(pmlenv, 't')) {
4778 len = my_snprintf(buf, sizeof(buf),
4779 MEM_LOG_TIME_FMT, MEM_LOG_TIME_ARG);
4780 PERL_UNUSED_RESULT(PerlLIO_write(fd, buf, len));
4784 len = my_snprintf(buf, sizeof(buf),
4785 "alloc: %s:%d:%s: %"IVdf" %"UVuf
4786 " %s = %"IVdf": %"UVxf"\n",
4787 filename, linenumber, funcname, n, typesize,
4788 type_name, n * typesize, PTR2UV(newalloc));
4791 len = my_snprintf(buf, sizeof(buf),
4792 "realloc: %s:%d:%s: %"IVdf" %"UVuf
4793 " %s = %"IVdf": %"UVxf" -> %"UVxf"\n",
4794 filename, linenumber, funcname, n, typesize,
4795 type_name, n * typesize, PTR2UV(oldalloc),
4799 len = my_snprintf(buf, sizeof(buf),
4800 "free: %s:%d:%s: %"UVxf"\n",
4801 filename, linenumber, funcname,
4806 len = my_snprintf(buf, sizeof(buf),
4807 "%s_SV: %s:%d:%s: %"UVxf SV_LOG_SERIAL_FMT "\n",
4808 mlt == MLT_NEW_SV ? "new" : "del",
4809 filename, linenumber, funcname,
4810 PTR2UV(sv) _SV_LOG_SERIAL_ARG(sv));
4815 PERL_UNUSED_RESULT(PerlLIO_write(fd, buf, len));
4819 #endif /* !PERL_MEM_LOG_NOIMPL */
4821 #ifndef PERL_MEM_LOG_NOIMPL
4823 mem_log_common_if(alty, num, tysz, tynm, sv, oal, nal, flnm, ln, fnnm) \
4824 mem_log_common (alty, num, tysz, tynm, sv, oal, nal, flnm, ln, fnnm)
4826 /* this is suboptimal, but bug compatible. User is providing their
4827 own implementation, but is getting these functions anyway, and they
4828 do nothing. But _NOIMPL users should be able to cope or fix */
4830 mem_log_common_if(alty, num, tysz, tynm, u, oal, nal, flnm, ln, fnnm) \
4831 /* mem_log_common_if_PERL_MEM_LOG_NOIMPL */
4835 Perl_mem_log_alloc(const UV n, const UV typesize, const char *type_name,
4837 const char *filename, const int linenumber,
4838 const char *funcname)
4840 mem_log_common_if(MLT_ALLOC, n, typesize, type_name,
4841 NULL, NULL, newalloc,
4842 filename, linenumber, funcname);
4847 Perl_mem_log_realloc(const UV n, const UV typesize, const char *type_name,
4848 Malloc_t oldalloc, Malloc_t newalloc,
4849 const char *filename, const int linenumber,
4850 const char *funcname)
4852 mem_log_common_if(MLT_REALLOC, n, typesize, type_name,
4853 NULL, oldalloc, newalloc,
4854 filename, linenumber, funcname);
4859 Perl_mem_log_free(Malloc_t oldalloc,
4860 const char *filename, const int linenumber,
4861 const char *funcname)
4863 mem_log_common_if(MLT_FREE, 0, 0, "", NULL, oldalloc, NULL,
4864 filename, linenumber, funcname);
4869 Perl_mem_log_new_sv(const SV *sv,
4870 const char *filename, const int linenumber,
4871 const char *funcname)
4873 mem_log_common_if(MLT_NEW_SV, 0, 0, "", sv, NULL, NULL,
4874 filename, linenumber, funcname);
4878 Perl_mem_log_del_sv(const SV *sv,
4879 const char *filename, const int linenumber,
4880 const char *funcname)
4882 mem_log_common_if(MLT_DEL_SV, 0, 0, "", sv, NULL, NULL,
4883 filename, linenumber, funcname);
4886 #endif /* PERL_MEM_LOG */
4889 =for apidoc my_sprintf
4891 The C library C<sprintf>, wrapped if necessary, to ensure that it will return
4892 the length of the string written to the buffer. Only rare pre-ANSI systems
4893 need the wrapper function - usually this is a direct call to C<sprintf>.
4897 #ifndef SPRINTF_RETURNS_STRLEN
4899 Perl_my_sprintf(char *buffer, const char* pat, ...)
4902 PERL_ARGS_ASSERT_MY_SPRINTF;
4903 va_start(args, pat);
4904 vsprintf(buffer, pat, args);
4906 return strlen(buffer);
4911 =for apidoc my_snprintf
4913 The C library C<snprintf> functionality, if available and
4914 standards-compliant (uses C<vsnprintf>, actually). However, if the
4915 C<vsnprintf> is not available, will unfortunately use the unsafe
4916 C<vsprintf> which can overrun the buffer (there is an overrun check,
4917 but that may be too late). Consider using C<sv_vcatpvf> instead, or
4918 getting C<vsnprintf>.
4923 Perl_my_snprintf(char *buffer, const Size_t len, const char *format, ...)
4927 PERL_ARGS_ASSERT_MY_SNPRINTF;
4928 #ifndef HAS_VSNPRINTF
4929 PERL_UNUSED_VAR(len);
4931 va_start(ap, format);
4932 #ifdef HAS_VSNPRINTF
4933 retval = vsnprintf(buffer, len, format, ap);
4935 retval = vsprintf(buffer, format, ap);
4938 /* vsprintf() shows failure with < 0 */
4940 #ifdef HAS_VSNPRINTF
4941 /* vsnprintf() shows failure with >= len */
4943 (len > 0 && (Size_t)retval >= len)
4946 Perl_croak_nocontext("panic: my_snprintf buffer overflow");
4951 =for apidoc my_vsnprintf
4953 The C library C<vsnprintf> if available and standards-compliant.
4954 However, if if the C<vsnprintf> is not available, will unfortunately
4955 use the unsafe C<vsprintf> which can overrun the buffer (there is an
4956 overrun check, but that may be too late). Consider using
4957 C<sv_vcatpvf> instead, or getting C<vsnprintf>.
4962 Perl_my_vsnprintf(char *buffer, const Size_t len, const char *format, va_list ap)
4968 PERL_ARGS_ASSERT_MY_VSNPRINTF;
4969 #ifndef HAS_VSNPRINTF
4970 PERL_UNUSED_VAR(len);
4972 Perl_va_copy(ap, apc);
4973 # ifdef HAS_VSNPRINTF
4974 retval = vsnprintf(buffer, len, format, apc);
4976 retval = vsprintf(buffer, format, apc);
4980 # ifdef HAS_VSNPRINTF
4981 retval = vsnprintf(buffer, len, format, ap);
4983 retval = vsprintf(buffer, format, ap);
4985 #endif /* #ifdef NEED_VA_COPY */
4986 /* vsprintf() shows failure with < 0 */
4988 #ifdef HAS_VSNPRINTF
4989 /* vsnprintf() shows failure with >= len */
4991 (len > 0 && (Size_t)retval >= len)
4994 Perl_croak_nocontext("panic: my_vsnprintf buffer overflow");
4999 Perl_my_clearenv(pTHX)
5002 #if ! defined(PERL_MICRO)
5003 # if defined(PERL_IMPLICIT_SYS) || defined(WIN32)
5005 # else /* ! (PERL_IMPLICIT_SYS || WIN32) */
5006 # if defined(USE_ENVIRON_ARRAY)
5007 # if defined(USE_ITHREADS)
5008 /* only the parent thread can clobber the process environment */
5009 if (PL_curinterp == aTHX)
5010 # endif /* USE_ITHREADS */
5012 # if ! defined(PERL_USE_SAFE_PUTENV)
5013 if ( !PL_use_safe_putenv) {
5015 if (environ == PL_origenviron)
5016 environ = (char**)safesysmalloc(sizeof(char*));
5018 for (i = 0; environ[i]; i++)
5019 (void)safesysfree(environ[i]);
5022 # else /* PERL_USE_SAFE_PUTENV */
5023 # if defined(HAS_CLEARENV)
5025 # elif defined(HAS_UNSETENV)
5026 int bsiz = 80; /* Most envvar names will be shorter than this. */
5027 char *buf = (char*)safesysmalloc(bsiz);
5028 while (*environ != NULL) {
5029 char *e = strchr(*environ, '=');
5030 int l = e ? e - *environ : (int)strlen(*environ);
5032 (void)safesysfree(buf);
5033 bsiz = l + 1; /* + 1 for the \0. */
5034 buf = (char*)safesysmalloc(bsiz);
5036 memcpy(buf, *environ, l);
5038 (void)unsetenv(buf);
5040 (void)safesysfree(buf);
5041 # else /* ! HAS_CLEARENV && ! HAS_UNSETENV */
5042 /* Just null environ and accept the leakage. */
5044 # endif /* HAS_CLEARENV || HAS_UNSETENV */
5045 # endif /* ! PERL_USE_SAFE_PUTENV */
5047 # endif /* USE_ENVIRON_ARRAY */
5048 # endif /* PERL_IMPLICIT_SYS || WIN32 */
5049 #endif /* PERL_MICRO */
5052 #ifdef PERL_IMPLICIT_CONTEXT
5054 /* Implements the MY_CXT_INIT macro. The first time a module is loaded,
5055 the global PL_my_cxt_index is incremented, and that value is assigned to
5056 that module's static my_cxt_index (who's address is passed as an arg).
5057 Then, for each interpreter this function is called for, it makes sure a
5058 void* slot is available to hang the static data off, by allocating or
5059 extending the interpreter's PL_my_cxt_list array */
5061 #ifndef PERL_GLOBAL_STRUCT_PRIVATE
5063 Perl_my_cxt_init(pTHX_ int *index, size_t size)
5067 PERL_ARGS_ASSERT_MY_CXT_INIT;
5069 /* this module hasn't been allocated an index yet */
5070 #if defined(USE_ITHREADS)
5071 MUTEX_LOCK(&PL_my_ctx_mutex);
5073 *index = PL_my_cxt_index++;
5074 #if defined(USE_ITHREADS)
5075 MUTEX_UNLOCK(&PL_my_ctx_mutex);
5079 /* make sure the array is big enough */
5080 if (PL_my_cxt_size <= *index) {
5081 if (PL_my_cxt_size) {
5082 while (PL_my_cxt_size <= *index)
5083 PL_my_cxt_size *= 2;
5084 Renew(PL_my_cxt_list, PL_my_cxt_size, void *);
5087 PL_my_cxt_size = 16;
5088 Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
5091 /* newSV() allocates one more than needed */
5092 p = (void*)SvPVX(newSV(size-1));
5093 PL_my_cxt_list[*index] = p;
5094 Zero(p, size, char);
5098 #else /* #ifndef PERL_GLOBAL_STRUCT_PRIVATE */
5101 Perl_my_cxt_index(pTHX_ const char *my_cxt_key)
5106 PERL_ARGS_ASSERT_MY_CXT_INDEX;
5108 for (index = 0; index < PL_my_cxt_index; index++) {
5109 const char *key = PL_my_cxt_keys[index];
5110 /* try direct pointer compare first - there are chances to success,
5111 * and it's much faster.
5113 if ((key == my_cxt_key) || strEQ(key, my_cxt_key))
5120 Perl_my_cxt_init(pTHX_ const char *my_cxt_key, size_t size)
5126 PERL_ARGS_ASSERT_MY_CXT_INIT;
5128 index = Perl_my_cxt_index(aTHX_ my_cxt_key);
5130 /* this module hasn't been allocated an index yet */
5131 #if defined(USE_ITHREADS)
5132 MUTEX_LOCK(&PL_my_ctx_mutex);
5134 index = PL_my_cxt_index++;
5135 #if defined(USE_ITHREADS)
5136 MUTEX_UNLOCK(&PL_my_ctx_mutex);
5140 /* make sure the array is big enough */
5141 if (PL_my_cxt_size <= index) {
5142 int old_size = PL_my_cxt_size;
5144 if (PL_my_cxt_size) {
5145 while (PL_my_cxt_size <= index)
5146 PL_my_cxt_size *= 2;
5147 Renew(PL_my_cxt_list, PL_my_cxt_size, void *);
5148 Renew(PL_my_cxt_keys, PL_my_cxt_size, const char *);
5151 PL_my_cxt_size = 16;
5152 Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
5153 Newx(PL_my_cxt_keys, PL_my_cxt_size, const char *);
5155 for (i = old_size; i < PL_my_cxt_size; i++) {
5156 PL_my_cxt_keys[i] = 0;
5157 PL_my_cxt_list[i] = 0;
5160 PL_my_cxt_keys[index] = my_cxt_key;
5161 /* newSV() allocates one more than needed */
5162 p = (void*)SvPVX(newSV(size-1));
5163 PL_my_cxt_list[index] = p;
5164 Zero(p, size, char);
5167 #endif /* #ifndef PERL_GLOBAL_STRUCT_PRIVATE */
5168 #endif /* PERL_IMPLICIT_CONTEXT */
5171 Perl_xs_version_bootcheck(pTHX_ U32 items, U32 ax, const char *xs_p,
5175 const char *vn = NULL;
5176 SV *const module = PL_stack_base[ax];
5178 PERL_ARGS_ASSERT_XS_VERSION_BOOTCHECK;
5180 if (items >= 2) /* version supplied as bootstrap arg */
5181 sv = PL_stack_base[ax + 1];
5183 /* XXX GV_ADDWARN */
5185 sv = get_sv(Perl_form(aTHX_ "%"SVf"::%s", SVfARG(module), vn), 0);
5186 if (!sv || !SvOK(sv)) {
5188 sv = get_sv(Perl_form(aTHX_ "%"SVf"::%s", SVfARG(module), vn), 0);
5192 SV *xssv = Perl_newSVpvn_flags(aTHX_ xs_p, xs_len, SVs_TEMP);
5193 SV *pmsv = sv_isobject(sv) && sv_derived_from(sv, "version")
5194 ? sv : sv_2mortal(new_version(sv));
5195 xssv = upg_version(xssv, 0);
5196 if ( vcmp(pmsv,xssv) ) {
5197 SV *string = vstringify(xssv);
5198 SV *xpt = Perl_newSVpvf(aTHX_ "%"SVf" object version %"SVf
5199 " does not match ", SVfARG(module), SVfARG(string));
5201 SvREFCNT_dec(string);
5202 string = vstringify(pmsv);
5205 Perl_sv_catpvf(aTHX_ xpt, "$%"SVf"::%s %"SVf, SVfARG(module), vn,
5208 Perl_sv_catpvf(aTHX_ xpt, "bootstrap parameter %"SVf, SVfARG(string));
5210 SvREFCNT_dec(string);
5212 Perl_sv_2mortal(aTHX_ xpt);
5213 Perl_croak_sv(aTHX_ xpt);
5219 Perl_xs_apiversion_bootcheck(pTHX_ SV *module, const char *api_p,
5223 SV *compver = Perl_newSVpvn_flags(aTHX_ api_p, api_len, SVs_TEMP);
5226 PERL_ARGS_ASSERT_XS_APIVERSION_BOOTCHECK;
5228 /* This might croak */
5229 compver = upg_version(compver, 0);
5230 /* This should never croak */
5231 runver = new_version(PL_apiversion);
5232 if (vcmp(compver, runver)) {
5233 SV *compver_string = vstringify(compver);
5234 SV *runver_string = vstringify(runver);
5235 xpt = Perl_newSVpvf(aTHX_ "Perl API version %"SVf
5236 " of %"SVf" does not match %"SVf,
5237 SVfARG(compver_string), SVfARG(module),
5238 SVfARG(runver_string));
5239 Perl_sv_2mortal(aTHX_ xpt);
5241 SvREFCNT_dec(compver_string);
5242 SvREFCNT_dec(runver_string);
5244 SvREFCNT_dec(runver);
5246 Perl_croak_sv(aTHX_ xpt);
5250 =for apidoc my_strlcat
5252 The C library C<strlcat> if available, or a Perl implementation of it.
5253 This operates on C C<NUL>-terminated strings.
5255 C<my_strlcat()> appends string C<src> to the end of C<dst>. It will append at
5256 most S<C<size - strlen(dst) - 1>> characters. It will then C<NUL>-terminate,
5257 unless C<size> is 0 or the original C<dst> string was longer than C<size> (in
5258 practice this should not happen as it means that either C<size> is incorrect or
5259 that C<dst> is not a proper C<NUL>-terminated string).
5261 Note that C<size> is the full size of the destination buffer and
5262 the result is guaranteed to be C<NUL>-terminated if there is room. Note that
5263 room for the C<NUL> should be included in C<size>.
5267 Description stolen from http://www.openbsd.org/cgi-bin/man.cgi?query=strlcat
5271 Perl_my_strlcat(char *dst, const char *src, Size_t size)
5273 Size_t used, length, copy;
5276 length = strlen(src);
5277 if (size > 0 && used < size - 1) {
5278 copy = (length >= size - used) ? size - used - 1 : length;
5279 memcpy(dst + used, src, copy);
5280 dst[used + copy] = '\0';
5282 return used + length;
5288 =for apidoc my_strlcpy
5290 The C library C<strlcpy> if available, or a Perl implementation of it.
5291 This operates on C C<NUL>-terminated strings.
5293 C<my_strlcpy()> copies up to S<C<size - 1>> characters from the string C<src>
5294 to C<dst>, C<NUL>-terminating the result if C<size> is not 0.
5298 Description stolen from http://www.openbsd.org/cgi-bin/man.cgi?query=strlcpy
5302 Perl_my_strlcpy(char *dst, const char *src, Size_t size)
5304 Size_t length, copy;
5306 length = strlen(src);
5308 copy = (length >= size) ? size - 1 : length;
5309 memcpy(dst, src, copy);
5316 #if defined(_MSC_VER) && (_MSC_VER >= 1300) && (_MSC_VER < 1400) && (WINVER < 0x0500)
5317 /* VC7 or 7.1, building with pre-VC7 runtime libraries. */
5318 long _ftol( double ); /* Defined by VC6 C libs. */
5319 long _ftol2( double dblSource ) { return _ftol( dblSource ); }
5322 PERL_STATIC_INLINE bool
5323 S_gv_has_usable_name(pTHX_ GV *gv)
5327 && HvENAME(GvSTASH(gv))
5328 && (gvp = (GV **)hv_fetchhek(
5329 GvSTASH(gv), GvNAME_HEK(gv), 0
5335 Perl_get_db_sub(pTHX_ SV **svp, CV *cv)
5337 SV * const dbsv = GvSVn(PL_DBsub);
5338 const bool save_taint = TAINT_get;
5340 /* When we are called from pp_goto (svp is null),
5341 * we do not care about using dbsv to call CV;
5342 * it's for informational purposes only.
5345 PERL_ARGS_ASSERT_GET_DB_SUB;
5349 if (!PERLDB_SUB_NN) {
5353 gv_efullname3(dbsv, gv, NULL);
5355 else if ( (CvFLAGS(cv) & (CVf_ANON | CVf_CLONED)) || !gv
5356 || strEQ(GvNAME(gv), "END")
5357 || ( /* Could be imported, and old sub redefined. */
5358 (GvCV(gv) != cv || !S_gv_has_usable_name(aTHX_ gv))
5360 !( (SvTYPE(*svp) == SVt_PVGV)
5361 && (GvCV((const GV *)*svp) == cv)
5362 /* Use GV from the stack as a fallback. */
5363 && S_gv_has_usable_name(aTHX_ gv = (GV *)*svp)
5367 /* GV is potentially non-unique, or contain different CV. */
5368 SV * const tmp = newRV(MUTABLE_SV(cv));
5369 sv_setsv(dbsv, tmp);
5373 sv_sethek(dbsv, HvENAME_HEK(GvSTASH(gv)));
5374 sv_catpvs(dbsv, "::");
5375 sv_cathek(dbsv, GvNAME_HEK(gv));
5379 const int type = SvTYPE(dbsv);
5380 if (type < SVt_PVIV && type != SVt_IV)
5381 sv_upgrade(dbsv, SVt_PVIV);
5382 (void)SvIOK_on(dbsv);
5383 SvIV_set(dbsv, PTR2IV(cv)); /* Do it the quickest way */
5386 TAINT_IF(save_taint);
5387 #ifdef NO_TAINT_SUPPORT
5388 PERL_UNUSED_VAR(save_taint);
5393 Perl_my_dirfd(DIR * dir) {
5395 /* Most dirfd implementations have problems when passed NULL. */
5400 #elif defined(HAS_DIR_DD_FD)
5403 Perl_croak_nocontext(PL_no_func, "dirfd");
5404 assert(0); /* NOT REACHED */
5410 Perl_get_re_arg(pTHX_ SV *sv) {
5416 sv = MUTABLE_SV(SvRV(sv));
5417 if (SvTYPE(sv) == SVt_REGEXP)
5418 return (REGEXP*) sv;
5425 * This code is derived from drand48() implementation from FreeBSD,
5426 * found in lib/libc/gen/_rand48.c.
5428 * The U64 implementation is original, based on the POSIX
5429 * specification for drand48().
5433 * Copyright (c) 1993 Martin Birgmeier
5434 * All rights reserved.
5436 * You may redistribute unmodified or modified versions of this source
5437 * code provided that the above copyright notice and this and the
5438 * following conditions are retained.
5440 * This software is provided ``as is'', and comes with no warranties
5441 * of any kind. I shall in no event be liable for anything that happens
5442 * to anyone/anything when using this software.
5445 #define FREEBSD_DRAND48_SEED_0 (0x330e)
5447 #ifdef PERL_DRAND48_QUAD
5449 #define DRAND48_MULT U64_CONST(0x5deece66d)
5450 #define DRAND48_ADD 0xb
5451 #define DRAND48_MASK U64_CONST(0xffffffffffff)
5455 #define FREEBSD_DRAND48_SEED_1 (0xabcd)
5456 #define FREEBSD_DRAND48_SEED_2 (0x1234)
5457 #define FREEBSD_DRAND48_MULT_0 (0xe66d)
5458 #define FREEBSD_DRAND48_MULT_1 (0xdeec)
5459 #define FREEBSD_DRAND48_MULT_2 (0x0005)
5460 #define FREEBSD_DRAND48_ADD (0x000b)
5462 const unsigned short _rand48_mult[3] = {
5463 FREEBSD_DRAND48_MULT_0,
5464 FREEBSD_DRAND48_MULT_1,
5465 FREEBSD_DRAND48_MULT_2
5467 const unsigned short _rand48_add = FREEBSD_DRAND48_ADD;
5472 Perl_drand48_init_r(perl_drand48_t *random_state, U32 seed)
5474 PERL_ARGS_ASSERT_DRAND48_INIT_R;
5476 #ifdef PERL_DRAND48_QUAD
5477 *random_state = FREEBSD_DRAND48_SEED_0 + ((U64TYPE)seed << 16);
5479 random_state->seed[0] = FREEBSD_DRAND48_SEED_0;
5480 random_state->seed[1] = (U16) seed;
5481 random_state->seed[2] = (U16) (seed >> 16);
5486 Perl_drand48_r(perl_drand48_t *random_state)
5488 PERL_ARGS_ASSERT_DRAND48_R;
5490 #ifdef PERL_DRAND48_QUAD
5491 *random_state = (*random_state * DRAND48_MULT + DRAND48_ADD)
5494 return ldexp((double)*random_state, -48);
5500 accu = (U32) _rand48_mult[0] * (U32) random_state->seed[0]
5501 + (U32) _rand48_add;
5502 temp[0] = (U16) accu; /* lower 16 bits */
5503 accu >>= sizeof(U16) * 8;
5504 accu += (U32) _rand48_mult[0] * (U32) random_state->seed[1]
5505 + (U32) _rand48_mult[1] * (U32) random_state->seed[0];
5506 temp[1] = (U16) accu; /* middle 16 bits */
5507 accu >>= sizeof(U16) * 8;
5508 accu += _rand48_mult[0] * random_state->seed[2]
5509 + _rand48_mult[1] * random_state->seed[1]
5510 + _rand48_mult[2] * random_state->seed[0];
5511 random_state->seed[0] = temp[0];
5512 random_state->seed[1] = temp[1];
5513 random_state->seed[2] = (U16) accu;
5515 return ldexp((double) random_state->seed[0], -48) +
5516 ldexp((double) random_state->seed[1], -32) +
5517 ldexp((double) random_state->seed[2], -16);
5522 #ifdef USE_C_BACKTRACE
5524 /* Possibly move all this USE_C_BACKTRACE code into a new file. */
5529 /* abfd is the BFD handle. */
5531 /* bfd_syms is the BFD symbol table. */
5533 /* bfd_text is handle to the the ".text" section of the object file. */
5535 /* Since opening the executable and scanning its symbols is quite
5536 * heavy operation, we remember the filename we used the last time,
5537 * and do the opening and scanning only if the filename changes.
5538 * This removes most (but not all) open+scan cycles. */
5539 const char* fname_prev;
5542 /* Given a dl_info, update the BFD context if necessary. */
5543 static void bfd_update(bfd_context* ctx, Dl_info* dl_info)
5545 /* BFD open and scan only if the filename changed. */
5546 if (ctx->fname_prev == NULL ||
5547 strNE(dl_info->dli_fname, ctx->fname_prev)) {
5548 ctx->abfd = bfd_openr(dl_info->dli_fname, 0);
5550 if (bfd_check_format(ctx->abfd, bfd_object)) {
5551 IV symbol_size = bfd_get_symtab_upper_bound(ctx->abfd);
5552 if (symbol_size > 0) {
5553 Safefree(ctx->bfd_syms);
5554 Newx(ctx->bfd_syms, symbol_size, asymbol*);
5556 bfd_get_section_by_name(ctx->abfd, ".text");
5564 ctx->fname_prev = dl_info->dli_fname;
5568 /* Given a raw frame, try to symbolize it and store
5569 * symbol information (source file, line number) away. */
5570 static void bfd_symbolize(bfd_context* ctx,
5573 STRLEN* symbol_name_size,
5575 STRLEN* source_name_size,
5576 STRLEN* source_line)
5578 *symbol_name = NULL;
5579 *symbol_name_size = 0;
5581 IV offset = PTR2IV(raw_frame) - PTR2IV(ctx->bfd_text->vma);
5583 bfd_canonicalize_symtab(ctx->abfd, ctx->bfd_syms) > 0) {
5586 unsigned int line = 0;
5587 if (bfd_find_nearest_line(ctx->abfd, ctx->bfd_text,
5588 ctx->bfd_syms, offset,
5589 &file, &func, &line) &&
5590 file && func && line > 0) {
5591 /* Size and copy the source file, use only
5592 * the basename of the source file.
5594 * NOTE: the basenames are fine for the
5595 * Perl source files, but may not always
5596 * be the best idea for XS files. */
5597 const char *p, *b = NULL;
5598 /* Look for the last slash. */
5599 for (p = file; *p; p++) {
5603 if (b == NULL || *b == 0) {
5606 *source_name_size = p - b + 1;
5607 Newx(*source_name, *source_name_size + 1, char);
5608 Copy(b, *source_name, *source_name_size + 1, char);
5610 *symbol_name_size = strlen(func);
5611 Newx(*symbol_name, *symbol_name_size + 1, char);
5612 Copy(func, *symbol_name, *symbol_name_size + 1, char);
5614 *source_line = line;
5620 #endif /* #ifdef USE_BFD */
5624 /* OS X has no public API for for 'symbolicating' (Apple official term)
5625 * stack addresses to {function_name, source_file, line_number}.
5626 * Good news: there is command line utility atos(1) which does that.
5627 * Bad news 1: it's a command line utility.
5628 * Bad news 2: one needs to have the Developer Tools installed.
5629 * Bad news 3: in newer releases it needs to be run as 'xcrun atos'.
5631 * To recap: we need to open a pipe for reading for a utility which
5632 * might not exist, or exists in different locations, and then parse
5633 * the output. And since this is all for a low-level API, we cannot
5634 * use high-level stuff. Thanks, Apple. */
5637 /* tool is set to the absolute pathname of the tool to use:
5640 /* format is set to a printf format string used for building
5641 * the external command to run. */
5643 /* unavail is set if e.g. xcrun cannot be found, or something
5644 * else happens that makes getting the backtrace dubious. Note,
5645 * however, that the context isn't persistent, the next call to
5646 * get_c_backtrace() will start from scratch. */
5648 /* fname is the current object file name. */
5650 /* object_base_addr is the base address of the shared object. */
5651 void* object_base_addr;
5654 /* Given |dl_info|, updates the context. If the context has been
5655 * marked unavailable, return immediately. If not but the tool has
5656 * not been set, set it to either "xcrun atos" or "atos" (also set the
5657 * format to use for creating commands for piping), or if neither is
5658 * unavailable (one needs the Developer Tools installed), mark the context
5659 * an unavailable. Finally, update the filename (object name),
5660 * and its base address. */
5662 static void atos_update(atos_context* ctx,
5667 if (ctx->tool == NULL) {
5668 const char* tools[] = {
5672 const char* formats[] = {
5673 "/usr/bin/xcrun atos -o '%s' -l %08x %08x 2>&1",
5674 "/usr/bin/atos -d -o '%s' -l %08x %08x 2>&1"
5678 for (i = 0; i < C_ARRAY_LENGTH(tools); i++) {
5679 if (stat(tools[i], &st) == 0 && S_ISREG(st.st_mode)) {
5680 ctx->tool = tools[i];
5681 ctx->format = formats[i];
5685 if (ctx->tool == NULL) {
5686 ctx->unavail = TRUE;
5690 if (ctx->fname == NULL ||
5691 strNE(dl_info->dli_fname, ctx->fname)) {
5692 ctx->fname = dl_info->dli_fname;
5693 ctx->object_base_addr = dl_info->dli_fbase;
5697 /* Given an output buffer end |p| and its |start|, matches
5698 * for the atos output, extracting the source code location
5699 * and returning non-NULL if possible, returning NULL otherwise. */
5700 static const char* atos_parse(const char* p,
5702 STRLEN* source_name_size,
5703 STRLEN* source_line) {
5704 /* atos() output is something like:
5705 * perl_parse (in miniperl) (perl.c:2314)\n\n".
5706 * We cannot use Perl regular expressions, because we need to
5707 * stay low-level. Therefore here we have a rolled-out version
5708 * of a state machine which matches _backwards_from_the_end_ and
5709 * if there's a success, returns the starts of the filename,
5710 * also setting the filename size and the source line number.
5711 * The matched regular expression is roughly "\(.*:\d+\)\s*$" */
5712 const char* source_number_start;
5713 const char* source_name_end;
5714 const char* source_line_end;
5715 const char* close_paren;
5716 /* Skip trailing whitespace. */
5717 while (p > start && isspace(*p)) p--;
5718 /* Now we should be at the close paren. */
5719 if (p == start || *p != ')')
5723 /* Now we should be in the line number. */
5724 if (p == start || !isdigit(*p))
5726 /* Skip over the digits. */
5727 while (p > start && isdigit(*p))
5729 /* Now we should be at the colon. */
5730 if (p == start || *p != ':')
5732 source_number_start = p + 1;
5733 source_name_end = p; /* Just beyond the end. */
5735 /* Look for the open paren. */
5736 while (p > start && *p != '(')
5741 *source_name_size = source_name_end - p;
5742 *source_line = grok_atou(source_number_start, &source_line_end);
5743 if (source_line_end != close_paren)
5748 /* Given a raw frame, read a pipe from the symbolicator (that's the
5749 * technical term) atos, reads the result, and parses the source code
5750 * location. We must stay low-level, so we use snprintf(), pipe(),
5751 * and fread(), and then also parse the output ourselves. */
5752 static void atos_symbolize(atos_context* ctx,
5755 STRLEN* source_name_size,
5756 STRLEN* source_line)
5764 /* Simple security measure: if there's any funny business with
5765 * the object name (used as "-o '%s'" ), leave since at least
5766 * partially the user controls it. */
5767 for (p = ctx->fname; *p; p++) {
5768 if (*p == '\'' || iscntrl(*p)) {
5769 ctx->unavail = TRUE;
5773 cnt = snprintf(cmd, sizeof(cmd), ctx->format,
5774 ctx->fname, ctx->object_base_addr, raw_frame);
5775 if (cnt < sizeof(cmd)) {
5776 /* Undo nostdio.h #defines that disable stdio.
5777 * This is somewhat naughty, but is used elsewhere
5778 * in the core, and affects only OS X. */
5783 FILE* fp = popen(cmd, "r");
5784 /* At the moment we open a new pipe for each stack frame.
5785 * This is naturally somewhat slow, but hopefully generating
5786 * stack traces is never going to in a performance critical path.
5788 * We could play tricks with atos by batching the stack
5789 * addresses to be resolved: atos can either take multiple
5790 * addresses from the command line, or read addresses from
5791 * a file (though the mess of creating temporary files would
5792 * probably negate much of any possible speedup).
5794 * Normally there are only two objects present in the backtrace:
5795 * perl itself, and the libdyld.dylib. (Note that the object
5796 * filenames contain the full pathname, so perl may not always
5797 * be in the same place.) Whenever the object in the
5798 * backtrace changes, the base address also changes.
5800 * The problem with batching the addresses, though, would be
5801 * matching the results with the addresses: the parsing of
5802 * the results is already painful enough with a single address. */
5805 UV cnt = fread(out, 1, sizeof(out), fp);
5806 if (cnt < sizeof(out)) {
5807 const char* p = atos_parse(out + cnt, out,
5812 *source_name_size + 1, char);
5813 Copy(p, *source_name,
5814 *source_name_size + 1, char);
5822 #endif /* #ifdef PERL_DARWIN */
5825 =for apidoc get_c_backtrace
5827 Collects the backtrace (aka "stacktrace") into a single linear
5828 malloced buffer, which the caller B<must> Perl_free_c_backtrace().
5830 Scans the frames back by depth + skip, then drops the skip innermost,
5831 returning at most depth frames.
5837 Perl_get_c_backtrace(pTHX_ int depth, int skip)
5839 /* Note that here we must stay as low-level as possible: Newx(),
5840 * Copy(), Safefree(); since we may be called from anywhere,
5841 * so we should avoid higher level constructs like SVs or AVs.
5843 * Since we are using safesysmalloc() via Newx(), don't try
5844 * getting backtrace() there, unless you like deep recursion. */
5846 /* Currently only implemented with backtrace() and dladdr(),
5847 * for other platforms NULL is returned. */
5849 #if defined(HAS_BACKTRACE) && defined(HAS_DLADDR)
5850 /* backtrace() is available via <execinfo.h> in glibc and in most
5851 * modern BSDs; dladdr() is available via <dlfcn.h>. */
5853 /* We try fetching this many frames total, but then discard
5854 * the |skip| first ones. For the remaining ones we will try
5855 * retrieving more information with dladdr(). */
5856 int try_depth = skip + depth;
5858 /* The addresses (program counters) returned by backtrace(). */
5861 /* Retrieved with dladdr() from the addresses returned by backtrace(). */
5864 /* Sizes _including_ the terminating \0 of the object name
5865 * and symbol name strings. */
5866 STRLEN* object_name_sizes;
5867 STRLEN* symbol_name_sizes;
5870 /* The symbol names comes either from dli_sname,
5871 * or if using BFD, they can come from BFD. */
5872 char** symbol_names;
5875 /* The source code location information. Dug out with e.g. BFD. */
5876 char** source_names;
5877 STRLEN* source_name_sizes;
5878 STRLEN* source_lines;
5880 Perl_c_backtrace* bt = NULL; /* This is what will be returned. */
5881 int got_depth; /* How many frames were returned from backtrace(). */
5882 UV frame_count = 0; /* How many frames we return. */
5883 UV total_bytes = 0; /* The size of the whole returned backtrace. */
5886 bfd_context bfd_ctx;
5889 atos_context atos_ctx;
5892 /* Here are probably possibilities for optimizing. We could for
5893 * example have a struct that contains most of these and then
5894 * allocate |try_depth| of them, saving a bunch of malloc calls.
5895 * Note, however, that |frames| could not be part of that struct
5896 * because backtrace() will want an array of just them. Also be
5897 * careful about the name strings. */
5898 Newx(raw_frames, try_depth, void*);
5899 Newx(dl_infos, try_depth, Dl_info);
5900 Newx(object_name_sizes, try_depth, STRLEN);
5901 Newx(symbol_name_sizes, try_depth, STRLEN);
5902 Newx(source_names, try_depth, char*);
5903 Newx(source_name_sizes, try_depth, STRLEN);
5904 Newx(source_lines, try_depth, STRLEN);
5906 Newx(symbol_names, try_depth, char*);
5909 /* Get the raw frames. */
5910 got_depth = (int)backtrace(raw_frames, try_depth);
5912 /* We use dladdr() instead of backtrace_symbols() because we want
5913 * the full details instead of opaque strings. This is useful for
5914 * two reasons: () the details are needed for further symbolic
5915 * digging, for example in OS X (2) by having the details we fully
5916 * control the output, which in turn is useful when more platforms
5917 * are added: we can keep out output "portable". */
5919 /* We want a single linear allocation, which can then be freed
5920 * with a single swoop. We will do the usual trick of first
5921 * walking over the structure and seeing how much we need to
5922 * allocate, then allocating, and then walking over the structure
5923 * the second time and populating it. */
5925 /* First we must compute the total size of the buffer. */
5926 total_bytes = sizeof(Perl_c_backtrace_header);
5927 if (got_depth > skip) {
5930 bfd_init(); /* Is this safe to call multiple times? */
5931 Zero(&bfd_ctx, 1, bfd_context);
5934 Zero(&atos_ctx, 1, atos_context);
5936 for (i = skip; i < try_depth; i++) {
5937 Dl_info* dl_info = &dl_infos[i];
5939 total_bytes += sizeof(Perl_c_backtrace_frame);
5941 source_names[i] = NULL;
5942 source_name_sizes[i] = 0;
5943 source_lines[i] = 0;
5945 /* Yes, zero from dladdr() is failure. */
5946 if (dladdr(raw_frames[i], dl_info)) {
5947 object_name_sizes[i] =
5948 dl_info->dli_fname ? strlen(dl_info->dli_fname) : 0;
5949 symbol_name_sizes[i] =
5950 dl_info->dli_sname ? strlen(dl_info->dli_sname) : 0;
5952 bfd_update(&bfd_ctx, dl_info);
5953 bfd_symbolize(&bfd_ctx, raw_frames[i],
5955 &symbol_name_sizes[i],
5957 &source_name_sizes[i],
5961 atos_update(&atos_ctx, dl_info);
5962 atos_symbolize(&atos_ctx,
5965 &source_name_sizes[i],
5969 /* Plus ones for the terminating \0. */
5970 total_bytes += object_name_sizes[i] + 1;
5971 total_bytes += symbol_name_sizes[i] + 1;
5972 total_bytes += source_name_sizes[i] + 1;
5980 Safefree(bfd_ctx.bfd_syms);
5984 /* Now we can allocate and populate the result buffer. */
5985 Newxc(bt, total_bytes, char, Perl_c_backtrace);
5986 Zero(bt, total_bytes, char);
5987 bt->header.frame_count = frame_count;
5988 bt->header.total_bytes = total_bytes;
5989 if (frame_count > 0) {
5990 Perl_c_backtrace_frame* frame = bt->frame_info;
5991 char* name_base = (char *)(frame + frame_count);
5992 char* name_curr = name_base; /* Outputting the name strings here. */
5994 for (i = skip; i < skip + frame_count; i++) {
5995 Dl_info* dl_info = &dl_infos[i];
5997 frame->addr = raw_frames[i];
5998 frame->object_base_addr = dl_info->dli_fbase;
5999 frame->symbol_addr = dl_info->dli_saddr;
6001 /* Copies a string, including the \0, and advances the name_curr.
6002 * Also copies the start and the size to the frame. */
6003 #define PERL_C_BACKTRACE_STRCPY(frame, doffset, src, dsize, size) \
6005 Copy(src, name_curr, size, char); \
6006 frame->doffset = name_curr - (char*)bt; \
6007 frame->dsize = size; \
6008 name_curr += size; \
6011 PERL_C_BACKTRACE_STRCPY(frame, object_name_offset,
6013 object_name_size, object_name_sizes[i]);
6016 PERL_C_BACKTRACE_STRCPY(frame, symbol_name_offset,
6018 symbol_name_size, symbol_name_sizes[i]);
6019 Safefree(symbol_names[i]);
6021 PERL_C_BACKTRACE_STRCPY(frame, symbol_name_offset,
6023 symbol_name_size, symbol_name_sizes[i]);
6026 PERL_C_BACKTRACE_STRCPY(frame, source_name_offset,
6028 source_name_size, source_name_sizes[i]);
6029 Safefree(source_names[i]);
6031 #undef PERL_C_BACKTRACE_STRCPY
6033 frame->source_line_number = source_lines[i];
6037 assert(total_bytes ==
6038 (UV)(sizeof(Perl_c_backtrace_header) +
6039 frame_count * sizeof(Perl_c_backtrace_frame) +
6040 name_curr - name_base));
6043 Safefree(symbol_names);
6045 Safefree(source_lines);
6046 Safefree(source_name_sizes);
6047 Safefree(source_names);
6048 Safefree(symbol_name_sizes);
6049 Safefree(object_name_sizes);
6050 /* Assuming the strings returned by dladdr() are pointers
6051 * to read-only static memory (the object file), so that
6052 * they do not need freeing (and cannot be). */
6054 Safefree(raw_frames);
6057 PERL_UNUSED_ARGV(depth);
6058 PERL_UNUSED_ARGV(skip);
6064 =for apidoc free_c_backtrace
6066 Deallocates a backtrace received from get_c_bracktrace.
6072 =for apidoc get_c_backtrace_dump
6074 Returns a SV a dump of |depth| frames of the call stack, skipping
6075 the |skip| innermost ones. depth of 20 is usually enough.
6077 The appended output looks like:
6080 1 10e004812:0082 Perl_croak util.c:1716 /usr/bin/perl
6081 2 10df8d6d2:1d72 perl_parse perl.c:3975 /usr/bin/perl
6084 The fields are tab-separated. The first column is the depth (zero
6085 being the innermost non-skipped frame). In the hex:offset, the hex is
6086 where the program counter was in S_parse_body, and the :offset (might
6087 be missing) tells how much inside the S_parse_body the program counter was.
6089 The util.c:1716 is the source code file and line number.
6091 The /usr/bin/perl is obvious (hopefully).
6093 Unknowns are C<"-">. Unknowns can happen unfortunately quite easily:
6094 if the platform doesn't support retrieving the information;
6095 if the binary is missing the debug information;
6096 if the optimizer has transformed the code by for example inlining.
6102 Perl_get_c_backtrace_dump(pTHX_ int depth, int skip)
6104 Perl_c_backtrace* bt;
6106 bt = get_c_backtrace(depth, skip + 1 /* Hide ourselves. */);
6108 Perl_c_backtrace_frame* frame;
6109 SV* dsv = newSVpvs("");
6111 for (i = 0, frame = bt->frame_info;
6112 i < bt->header.frame_count; i++, frame++) {
6113 Perl_sv_catpvf(aTHX_ dsv, "%d", (int)i);
6114 Perl_sv_catpvf(aTHX_ dsv, "\t%p", frame->addr ? frame->addr : "-");
6115 /* Symbol (function) names might disappear without debug info.
6117 * The source code location might disappear in case of the
6118 * optimizer inlining or otherwise rearranging the code. */
6119 if (frame->symbol_addr) {
6120 Perl_sv_catpvf(aTHX_ dsv, ":%04x",
6122 ((char*)frame->addr - (char*)frame->symbol_addr));
6124 Perl_sv_catpvf(aTHX_ dsv, "\t%s",
6125 frame->symbol_name_size &&
6126 frame->symbol_name_offset ?
6127 (char*)bt + frame->symbol_name_offset : "-");
6128 if (frame->source_name_size &&
6129 frame->source_name_offset &&
6130 frame->source_line_number) {
6131 Perl_sv_catpvf(aTHX_ dsv, "\t%s:%"UVuf,
6132 (char*)bt + frame->source_name_offset,
6133 (UV)frame->source_line_number);
6135 Perl_sv_catpvf(aTHX_ dsv, "\t-");
6137 Perl_sv_catpvf(aTHX_ dsv, "\t%s",
6138 frame->object_name_size &&
6139 frame->object_name_offset ?
6140 (char*)bt + frame->object_name_offset : "-");
6141 /* The frame->object_base_addr is not output,
6142 * but it is used for symbolizing/symbolicating. */
6143 sv_catpvs(dsv, "\n");
6146 Perl_free_c_backtrace(aTHX_ bt);
6155 =for apidoc dump_c_backtrace
6157 Dumps the C backtrace to the given fp.
6159 Returns true if a backtrace could be retrieved, false if not.
6165 Perl_dump_c_backtrace(pTHX_ PerlIO* fp, int depth, int skip)
6169 PERL_ARGS_ASSERT_DUMP_C_BACKTRACE;
6171 sv = Perl_get_c_backtrace_dump(aTHX_ depth, skip);
6174 PerlIO_printf(fp, "%s", SvPV_nolen(sv));
6180 #endif /* #ifdef USE_C_BACKTRACE */
6184 * c-indentation-style: bsd
6186 * indent-tabs-mode: nil
6189 * ex: set ts=8 sts=4 sw=4 et: