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
133 if (size + PERL_MEMORY_DEBUG_HEADER_SIZE < size)
135 size += PERL_MEMORY_DEBUG_HEADER_SIZE;
138 if ((SSize_t)size < 0)
139 Perl_croak_nocontext("panic: malloc, size=%"UVuf, (UV) size);
141 if (!size) size = 1; /* malloc(0) is NASTY on our system */
142 #ifdef PERL_DEBUG_READONLY_COW
143 if ((ptr = mmap(0, size, PROT_READ|PROT_WRITE,
144 MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED) {
145 perror("mmap failed");
149 ptr = (Malloc_t)PerlMem_malloc(size?size:1);
151 PERL_ALLOC_CHECK(ptr);
154 struct perl_memory_debug_header *const header
155 = (struct perl_memory_debug_header *)ptr;
159 PoisonNew(((char *)ptr), size, char);
162 #ifdef PERL_TRACK_MEMPOOL
163 header->interpreter = aTHX;
164 /* Link us into the list. */
165 header->prev = &PL_memory_debug_header;
166 header->next = PL_memory_debug_header.next;
167 PL_memory_debug_header.next = header;
168 maybe_protect_rw(header->next);
169 header->next->prev = header;
170 maybe_protect_ro(header->next);
171 # ifdef PERL_DEBUG_READONLY_COW
172 header->readonly = 0;
178 ptr = (Malloc_t)((char*)ptr+PERL_MEMORY_DEBUG_HEADER_SIZE);
179 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) malloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
187 #ifndef ALWAYS_NEED_THX
199 /* paranoid version of system's realloc() */
202 Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
204 #ifdef ALWAYS_NEED_THX
208 #ifdef PERL_DEBUG_READONLY_COW
209 const MEM_SIZE oldsize = where
210 ? ((struct perl_memory_debug_header *)((char *)where - PERL_MEMORY_DEBUG_HEADER_SIZE))->size
213 #if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) && !defined(PERL_MICRO)
214 Malloc_t PerlMem_realloc();
215 #endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
222 ptr = safesysmalloc(size);
226 where = (Malloc_t)((char*)where-PERL_MEMORY_DEBUG_HEADER_SIZE);
227 if (size + PERL_MEMORY_DEBUG_HEADER_SIZE < size)
229 size += PERL_MEMORY_DEBUG_HEADER_SIZE;
231 struct perl_memory_debug_header *const header
232 = (struct perl_memory_debug_header *)where;
234 # ifdef PERL_TRACK_MEMPOOL
235 if (header->interpreter != aTHX) {
236 Perl_croak_nocontext("panic: realloc from wrong pool, %p!=%p",
237 header->interpreter, aTHX);
239 assert(header->next->prev == header);
240 assert(header->prev->next == header);
242 if (header->size > size) {
243 const MEM_SIZE freed_up = header->size - size;
244 char *start_of_freed = ((char *)where) + size;
245 PoisonFree(start_of_freed, freed_up, char);
255 if ((SSize_t)size < 0)
256 Perl_croak_nocontext("panic: realloc, size=%"UVuf, (UV)size);
258 #ifdef PERL_DEBUG_READONLY_COW
259 if ((ptr = mmap(0, size, PROT_READ|PROT_WRITE,
260 MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED) {
261 perror("mmap failed");
264 Copy(where,ptr,oldsize < size ? oldsize : size,char);
265 if (munmap(where, oldsize)) {
266 perror("munmap failed");
270 ptr = (Malloc_t)PerlMem_realloc(where,size);
272 PERL_ALLOC_CHECK(ptr);
274 /* MUST do this fixup first, before doing ANYTHING else, as anything else
275 might allocate memory/free/move memory, and until we do the fixup, it
276 may well be chasing (and writing to) free memory. */
278 #ifdef PERL_TRACK_MEMPOOL
279 struct perl_memory_debug_header *const header
280 = (struct perl_memory_debug_header *)ptr;
283 if (header->size < size) {
284 const MEM_SIZE fresh = size - header->size;
285 char *start_of_fresh = ((char *)ptr) + size;
286 PoisonNew(start_of_fresh, fresh, char);
290 maybe_protect_rw(header->next);
291 header->next->prev = header;
292 maybe_protect_ro(header->next);
293 maybe_protect_rw(header->prev);
294 header->prev->next = header;
295 maybe_protect_ro(header->prev);
297 ptr = (Malloc_t)((char*)ptr+PERL_MEMORY_DEBUG_HEADER_SIZE);
300 /* In particular, must do that fixup above before logging anything via
301 *printf(), as it can reallocate memory, which can cause SEGVs. */
303 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) rfree\n",PTR2UV(where),(long)PL_an++));
304 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) realloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
311 #ifndef ALWAYS_NEED_THX
324 /* safe version of system's free() */
327 Perl_safesysfree(Malloc_t where)
329 #ifdef ALWAYS_NEED_THX
332 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) free\n",PTR2UV(where),(long)PL_an++));
335 Malloc_t where_intrn = (Malloc_t)((char*)where-PERL_MEMORY_DEBUG_HEADER_SIZE);
337 struct perl_memory_debug_header *const header
338 = (struct perl_memory_debug_header *)where_intrn;
341 const MEM_SIZE size = header->size;
343 # ifdef PERL_TRACK_MEMPOOL
344 if (header->interpreter != aTHX) {
345 Perl_croak_nocontext("panic: free from wrong pool, %p!=%p",
346 header->interpreter, aTHX);
349 Perl_croak_nocontext("panic: duplicate free");
352 Perl_croak_nocontext("panic: bad free, header->next==NULL");
353 if (header->next->prev != header || header->prev->next != header) {
354 Perl_croak_nocontext("panic: bad free, ->next->prev=%p, "
355 "header=%p, ->prev->next=%p",
356 header->next->prev, header,
359 /* Unlink us from the chain. */
360 maybe_protect_rw(header->next);
361 header->next->prev = header->prev;
362 maybe_protect_ro(header->next);
363 maybe_protect_rw(header->prev);
364 header->prev->next = header->next;
365 maybe_protect_ro(header->prev);
366 maybe_protect_rw(header);
368 PoisonNew(where_intrn, size, char);
370 /* Trigger the duplicate free warning. */
373 # ifdef PERL_DEBUG_READONLY_COW
374 if (munmap(where_intrn, size)) {
375 perror("munmap failed");
381 Malloc_t where_intrn = where;
383 #ifndef PERL_DEBUG_READONLY_COW
384 PerlMem_free(where_intrn);
389 /* safe version of system's calloc() */
392 Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
394 #ifdef ALWAYS_NEED_THX
398 #if defined(USE_MDH) || defined(DEBUGGING)
399 MEM_SIZE total_size = 0;
402 /* Even though calloc() for zero bytes is strange, be robust. */
403 if (size && (count <= MEM_SIZE_MAX / size)) {
404 #if defined(USE_MDH) || defined(DEBUGGING)
405 total_size = size * count;
411 if (PERL_MEMORY_DEBUG_HEADER_SIZE <= MEM_SIZE_MAX - (MEM_SIZE)total_size)
412 total_size += PERL_MEMORY_DEBUG_HEADER_SIZE;
417 if ((SSize_t)size < 0 || (SSize_t)count < 0)
418 Perl_croak_nocontext("panic: calloc, size=%"UVuf", count=%"UVuf,
419 (UV)size, (UV)count);
421 #ifdef PERL_DEBUG_READONLY_COW
422 if ((ptr = mmap(0, total_size ? total_size : 1, PROT_READ|PROT_WRITE,
423 MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED) {
424 perror("mmap failed");
427 #elif defined(PERL_TRACK_MEMPOOL)
428 /* Have to use malloc() because we've added some space for our tracking
430 /* malloc(0) is non-portable. */
431 ptr = (Malloc_t)PerlMem_malloc(total_size ? total_size : 1);
433 /* Use calloc() because it might save a memset() if the memory is fresh
434 and clean from the OS. */
436 ptr = (Malloc_t)PerlMem_calloc(count, size);
437 else /* calloc(0) is non-portable. */
438 ptr = (Malloc_t)PerlMem_calloc(count ? count : 1, size ? size : 1);
440 PERL_ALLOC_CHECK(ptr);
441 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));
445 struct perl_memory_debug_header *const header
446 = (struct perl_memory_debug_header *)ptr;
448 # ifndef PERL_DEBUG_READONLY_COW
449 memset((void*)ptr, 0, total_size);
451 # ifdef PERL_TRACK_MEMPOOL
452 header->interpreter = aTHX;
453 /* Link us into the list. */
454 header->prev = &PL_memory_debug_header;
455 header->next = PL_memory_debug_header.next;
456 PL_memory_debug_header.next = header;
457 maybe_protect_rw(header->next);
458 header->next->prev = header;
459 maybe_protect_ro(header->next);
460 # ifdef PERL_DEBUG_READONLY_COW
461 header->readonly = 0;
465 header->size = total_size;
467 ptr = (Malloc_t)((char*)ptr+PERL_MEMORY_DEBUG_HEADER_SIZE);
473 #ifndef ALWAYS_NEED_THX
482 /* These must be defined when not using Perl's malloc for binary
487 Malloc_t Perl_malloc (MEM_SIZE nbytes)
489 #ifdef PERL_IMPLICIT_SYS
492 return (Malloc_t)PerlMem_malloc(nbytes);
495 Malloc_t Perl_calloc (MEM_SIZE elements, MEM_SIZE size)
497 #ifdef PERL_IMPLICIT_SYS
500 return (Malloc_t)PerlMem_calloc(elements, size);
503 Malloc_t Perl_realloc (Malloc_t where, MEM_SIZE nbytes)
505 #ifdef PERL_IMPLICIT_SYS
508 return (Malloc_t)PerlMem_realloc(where, nbytes);
511 Free_t Perl_mfree (Malloc_t where)
513 #ifdef PERL_IMPLICIT_SYS
521 /* copy a string up to some (non-backslashed) delimiter, if any */
524 Perl_delimcpy(char *to, const char *toend, const char *from, const char *fromend, int delim, I32 *retlen)
528 PERL_ARGS_ASSERT_DELIMCPY;
530 for (tolen = 0; from < fromend; from++, tolen++) {
532 if (from[1] != delim) {
539 else if (*from == delim)
550 /* return ptr to little string in big string, NULL if not found */
551 /* This routine was donated by Corey Satten. */
554 Perl_instr(const char *big, const char *little)
557 PERL_ARGS_ASSERT_INSTR;
559 return strstr((char*)big, (char*)little);
562 /* same as instr but allow embedded nulls. The end pointers point to 1 beyond
563 * the final character desired to be checked */
566 Perl_ninstr(const char *big, const char *bigend, const char *little, const char *lend)
568 PERL_ARGS_ASSERT_NINSTR;
572 const char first = *little;
574 bigend -= lend - little++;
576 while (big <= bigend) {
577 if (*big++ == first) {
578 for (x=big,s=little; s < lend; x++,s++) {
582 return (char*)(big-1);
589 /* reverse of the above--find last substring */
592 Perl_rninstr(const char *big, const char *bigend, const char *little, const char *lend)
595 const I32 first = *little;
596 const char * const littleend = lend;
598 PERL_ARGS_ASSERT_RNINSTR;
600 if (little >= littleend)
601 return (char*)bigend;
603 big = bigend - (littleend - little++);
604 while (big >= bigbeg) {
608 for (x=big+2,s=little; s < littleend; /**/ ) {
617 return (char*)(big+1);
622 /* As a space optimization, we do not compile tables for strings of length
623 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
624 special-cased in fbm_instr().
626 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
629 =head1 Miscellaneous Functions
631 =for apidoc fbm_compile
633 Analyses the string in order to make fast searches on it using fbm_instr()
634 -- the Boyer-Moore algorithm.
640 Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
647 PERL_DEB( STRLEN rarest = 0 );
649 PERL_ARGS_ASSERT_FBM_COMPILE;
651 if (isGV_with_GP(sv) || SvROK(sv))
657 if (flags & FBMcf_TAIL) {
658 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL;
659 sv_catpvs(sv, "\n"); /* Taken into account in fbm_instr() */
660 if (mg && mg->mg_len >= 0)
663 if (!SvPOK(sv) || SvNIOKp(sv))
664 s = (U8*)SvPV_force_mutable(sv, len);
665 else s = (U8 *)SvPV_mutable(sv, len);
666 if (len == 0) /* TAIL might be on a zero-length string. */
668 SvUPGRADE(sv, SVt_PVMG);
673 /* "deep magic", the comment used to add. The use of MAGIC itself isn't
674 really. MAGIC was originally added in 79072805bf63abe5 (perl 5.0 alpha 2)
675 to call SvVALID_off() if the scalar was assigned to.
677 The comment itself (and "deeper magic" below) date back to
678 378cc40b38293ffc (perl 2.0). "deep magic" was an annotation on
680 where the magic (presumably) was that the scalar had a BM table hidden
683 As MAGIC is always present on BMs [in Perl 5 :-)], we can use it to store
684 the table instead of the previous (somewhat hacky) approach of co-opting
685 the string buffer and storing it after the string. */
687 assert(!mg_find(sv, PERL_MAGIC_bm));
688 mg = sv_magicext(sv, NULL, PERL_MAGIC_bm, &PL_vtbl_bm, NULL, 0);
692 /* Shorter strings are special-cased in Perl_fbm_instr(), and don't use
694 const U8 mlen = (len>255) ? 255 : (U8)len;
695 const unsigned char *const sb = s + len - mlen; /* first char (maybe) */
698 Newx(table, 256, U8);
699 memset((void*)table, mlen, 256);
700 mg->mg_ptr = (char *)table;
703 s += len - 1; /* last char */
706 if (table[*s] == mlen)
712 s = (const unsigned char*)(SvPVX_const(sv)); /* deeper magic */
713 for (i = 0; i < len; i++) {
714 if (PL_freq[s[i]] < frequency) {
715 PERL_DEB( rarest = i );
716 frequency = PL_freq[s[i]];
719 BmUSEFUL(sv) = 100; /* Initial value */
720 if (flags & FBMcf_TAIL)
722 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %"UVuf"\n",
723 s[rarest], (UV)rarest));
726 /* If SvTAIL(littlestr), it has a fake '\n' at end. */
727 /* If SvTAIL is actually due to \Z or \z, this gives false positives
731 =for apidoc fbm_instr
733 Returns the location of the SV in the string delimited by C<big> and
734 C<bigend>. It returns C<NULL> if the string can't be found. The C<sv>
735 does not have to be fbm_compiled, but the search will not be as fast
742 Perl_fbm_instr(pTHX_ unsigned char *big, unsigned char *bigend, SV *littlestr, U32 flags)
746 const unsigned char *little = (const unsigned char *)SvPV_const(littlestr,l);
747 STRLEN littlelen = l;
748 const I32 multiline = flags & FBMrf_MULTILINE;
750 PERL_ARGS_ASSERT_FBM_INSTR;
752 if ((STRLEN)(bigend - big) < littlelen) {
753 if ( SvTAIL(littlestr)
754 && ((STRLEN)(bigend - big) == littlelen - 1)
756 || (*big == *little &&
757 memEQ((char *)big, (char *)little, littlelen - 1))))
762 switch (littlelen) { /* Special cases for 0, 1 and 2 */
764 return (char*)big; /* Cannot be SvTAIL! */
766 if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
767 /* Know that bigend != big. */
768 if (bigend[-1] == '\n')
769 return (char *)(bigend - 1);
770 return (char *) bigend;
778 if (SvTAIL(littlestr))
779 return (char *) bigend;
782 if (SvTAIL(littlestr) && !multiline) {
783 if (bigend[-1] == '\n' && bigend[-2] == *little)
784 return (char*)bigend - 2;
785 if (bigend[-1] == *little)
786 return (char*)bigend - 1;
790 /* This should be better than FBM if c1 == c2, and almost
791 as good otherwise: maybe better since we do less indirection.
792 And we save a lot of memory by caching no table. */
793 const unsigned char c1 = little[0];
794 const unsigned char c2 = little[1];
799 while (s <= bigend) {
809 goto check_1char_anchor;
820 goto check_1char_anchor;
823 while (s <= bigend) {
828 goto check_1char_anchor;
837 check_1char_anchor: /* One char and anchor! */
838 if (SvTAIL(littlestr) && (*bigend == *little))
839 return (char *)bigend; /* bigend is already decremented. */
842 break; /* Only lengths 0 1 and 2 have special-case code. */
845 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
846 s = bigend - littlelen;
847 if (s >= big && bigend[-1] == '\n' && *s == *little
848 /* Automatically of length > 2 */
849 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
851 return (char*)s; /* how sweet it is */
854 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
856 return (char*)s + 1; /* how sweet it is */
860 if (!SvVALID(littlestr)) {
861 char * const b = ninstr((char*)big,(char*)bigend,
862 (char*)little, (char*)little + littlelen);
864 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
865 /* Chop \n from littlestr: */
866 s = bigend - littlelen + 1;
868 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
878 if (littlelen > (STRLEN)(bigend - big))
882 const MAGIC *const mg = mg_find(littlestr, PERL_MAGIC_bm);
883 const unsigned char *oldlittle;
887 --littlelen; /* Last char found by table lookup */
890 little += littlelen; /* last char */
893 const unsigned char * const table = (const unsigned char *) mg->mg_ptr;
897 if ((tmp = table[*s])) {
898 if ((s += tmp) < bigend)
902 else { /* less expensive than calling strncmp() */
903 unsigned char * const olds = s;
908 if (*--s == *--little)
910 s = olds + 1; /* here we pay the price for failure */
912 if (s < bigend) /* fake up continue to outer loop */
922 && memEQ((char *)(bigend - littlelen),
923 (char *)(oldlittle - littlelen), littlelen) )
924 return (char*)bigend - littlelen;
932 Returns true if the leading len bytes of the strings s1 and s2 are the same
933 case-insensitively; false otherwise. Uppercase and lowercase ASCII range bytes
934 match themselves and their opposite case counterparts. Non-cased and non-ASCII
935 range bytes match only themselves.
942 Perl_foldEQ(const char *s1, const char *s2, I32 len)
944 const U8 *a = (const U8 *)s1;
945 const U8 *b = (const U8 *)s2;
947 PERL_ARGS_ASSERT_FOLDEQ;
952 if (*a != *b && *a != PL_fold[*b])
959 Perl_foldEQ_latin1(const char *s1, const char *s2, I32 len)
961 /* Compare non-utf8 using Unicode (Latin1) semantics. Does not work on
962 * MICRO_SIGN, LATIN_SMALL_LETTER_SHARP_S, nor
963 * LATIN_SMALL_LETTER_Y_WITH_DIAERESIS, and does not check for these. Nor
964 * does it check that the strings each have at least 'len' characters */
966 const U8 *a = (const U8 *)s1;
967 const U8 *b = (const U8 *)s2;
969 PERL_ARGS_ASSERT_FOLDEQ_LATIN1;
974 if (*a != *b && *a != PL_fold_latin1[*b]) {
983 =for apidoc foldEQ_locale
985 Returns true if the leading len bytes of the strings s1 and s2 are the same
986 case-insensitively in the current locale; false otherwise.
992 Perl_foldEQ_locale(const char *s1, const char *s2, I32 len)
995 const U8 *a = (const U8 *)s1;
996 const U8 *b = (const U8 *)s2;
998 PERL_ARGS_ASSERT_FOLDEQ_LOCALE;
1003 if (*a != *b && *a != PL_fold_locale[*b])
1010 /* copy a string to a safe spot */
1013 =head1 Memory Management
1017 Perl's version of C<strdup()>. Returns a pointer to a newly allocated
1018 string which is a duplicate of C<pv>. The size of the string is
1019 determined by C<strlen()>, which means it may not contain embedded C<NUL>
1020 characters and must have a trailing C<NUL>. The memory allocated for the new
1021 string can be freed with the C<Safefree()> function.
1023 On some platforms, Windows for example, all allocated memory owned by a thread
1024 is deallocated when that thread ends. So if you need that not to happen, you
1025 need to use the shared memory functions, such as C<L</savesharedpv>>.
1031 Perl_savepv(pTHX_ const char *pv)
1033 PERL_UNUSED_CONTEXT;
1038 const STRLEN pvlen = strlen(pv)+1;
1039 Newx(newaddr, pvlen, char);
1040 return (char*)memcpy(newaddr, pv, pvlen);
1044 /* same thing but with a known length */
1049 Perl's version of what C<strndup()> would be if it existed. Returns a
1050 pointer to a newly allocated string which is a duplicate of the first
1051 C<len> bytes from C<pv>, plus a trailing
1052 C<NUL> byte. The memory allocated for
1053 the new string can be freed with the C<Safefree()> function.
1055 On some platforms, Windows for example, all allocated memory owned by a thread
1056 is deallocated when that thread ends. So if you need that not to happen, you
1057 need to use the shared memory functions, such as C<L</savesharedpvn>>.
1063 Perl_savepvn(pTHX_ const char *pv, I32 len)
1066 PERL_UNUSED_CONTEXT;
1070 Newx(newaddr,len+1,char);
1071 /* Give a meaning to NULL pointer mainly for the use in sv_magic() */
1073 /* might not be null terminated */
1074 newaddr[len] = '\0';
1075 return (char *) CopyD(pv,newaddr,len,char);
1078 return (char *) ZeroD(newaddr,len+1,char);
1083 =for apidoc savesharedpv
1085 A version of C<savepv()> which allocates the duplicate string in memory
1086 which is shared between threads.
1091 Perl_savesharedpv(pTHX_ const char *pv)
1096 PERL_UNUSED_CONTEXT;
1101 pvlen = strlen(pv)+1;
1102 newaddr = (char*)PerlMemShared_malloc(pvlen);
1106 return (char*)memcpy(newaddr, pv, pvlen);
1110 =for apidoc savesharedpvn
1112 A version of C<savepvn()> which allocates the duplicate string in memory
1113 which is shared between threads. (With the specific difference that a NULL
1114 pointer is not acceptable)
1119 Perl_savesharedpvn(pTHX_ const char *const pv, const STRLEN len)
1121 char *const newaddr = (char*)PerlMemShared_malloc(len + 1);
1123 PERL_UNUSED_CONTEXT;
1124 /* PERL_ARGS_ASSERT_SAVESHAREDPVN; */
1129 newaddr[len] = '\0';
1130 return (char*)memcpy(newaddr, pv, len);
1134 =for apidoc savesvpv
1136 A version of C<savepv()>/C<savepvn()> which gets the string to duplicate from
1137 the passed in SV using C<SvPV()>
1139 On some platforms, Windows for example, all allocated memory owned by a thread
1140 is deallocated when that thread ends. So if you need that not to happen, you
1141 need to use the shared memory functions, such as C<L</savesharedsvpv>>.
1147 Perl_savesvpv(pTHX_ SV *sv)
1150 const char * const pv = SvPV_const(sv, len);
1153 PERL_ARGS_ASSERT_SAVESVPV;
1156 Newx(newaddr,len,char);
1157 return (char *) CopyD(pv,newaddr,len,char);
1161 =for apidoc savesharedsvpv
1163 A version of C<savesharedpv()> which allocates the duplicate string in
1164 memory which is shared between threads.
1170 Perl_savesharedsvpv(pTHX_ SV *sv)
1173 const char * const pv = SvPV_const(sv, len);
1175 PERL_ARGS_ASSERT_SAVESHAREDSVPV;
1177 return savesharedpvn(pv, len);
1180 /* the SV for Perl_form() and mess() is not kept in an arena */
1188 if (PL_phase != PERL_PHASE_DESTRUCT)
1189 return newSVpvs_flags("", SVs_TEMP);
1194 /* Create as PVMG now, to avoid any upgrading later */
1196 Newxz(any, 1, XPVMG);
1197 SvFLAGS(sv) = SVt_PVMG;
1198 SvANY(sv) = (void*)any;
1200 SvREFCNT(sv) = 1 << 30; /* practically infinite */
1205 #if defined(PERL_IMPLICIT_CONTEXT)
1207 Perl_form_nocontext(const char* pat, ...)
1212 PERL_ARGS_ASSERT_FORM_NOCONTEXT;
1213 va_start(args, pat);
1214 retval = vform(pat, &args);
1218 #endif /* PERL_IMPLICIT_CONTEXT */
1221 =head1 Miscellaneous Functions
1224 Takes a sprintf-style format pattern and conventional
1225 (non-SV) arguments and returns the formatted string.
1227 (char *) Perl_form(pTHX_ const char* pat, ...)
1229 can be used any place a string (char *) is required:
1231 char * s = Perl_form("%d.%d",major,minor);
1233 Uses a single private buffer so if you want to format several strings you
1234 must explicitly copy the earlier strings away (and free the copies when you
1241 Perl_form(pTHX_ const char* pat, ...)
1245 PERL_ARGS_ASSERT_FORM;
1246 va_start(args, pat);
1247 retval = vform(pat, &args);
1253 Perl_vform(pTHX_ const char *pat, va_list *args)
1255 SV * const sv = mess_alloc();
1256 PERL_ARGS_ASSERT_VFORM;
1257 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1262 =for apidoc Am|SV *|mess|const char *pat|...
1264 Take a sprintf-style format pattern and argument list. These are used to
1265 generate a string message. If the message does not end with a newline,
1266 then it will be extended with some indication of the current location
1267 in the code, as described for L</mess_sv>.
1269 Normally, the resulting message is returned in a new mortal SV.
1270 During global destruction a single SV may be shared between uses of
1276 #if defined(PERL_IMPLICIT_CONTEXT)
1278 Perl_mess_nocontext(const char *pat, ...)
1283 PERL_ARGS_ASSERT_MESS_NOCONTEXT;
1284 va_start(args, pat);
1285 retval = vmess(pat, &args);
1289 #endif /* PERL_IMPLICIT_CONTEXT */
1292 Perl_mess(pTHX_ const char *pat, ...)
1296 PERL_ARGS_ASSERT_MESS;
1297 va_start(args, pat);
1298 retval = vmess(pat, &args);
1304 Perl_closest_cop(pTHX_ const COP *cop, const OP *o, const OP *curop,
1307 /* Look for curop starting from o. cop is the last COP we've seen. */
1308 /* opnext means that curop is actually the ->op_next of the op we are
1311 PERL_ARGS_ASSERT_CLOSEST_COP;
1313 if (!o || !curop || (
1314 opnext ? o->op_next == curop && o->op_type != OP_SCOPE : o == curop
1318 if (o->op_flags & OPf_KIDS) {
1320 for (kid = cUNOPo->op_first; kid; kid = OpSIBLING(kid)) {
1323 /* If the OP_NEXTSTATE has been optimised away we can still use it
1324 * the get the file and line number. */
1326 if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
1327 cop = (const COP *)kid;
1329 /* Keep searching, and return when we've found something. */
1331 new_cop = closest_cop(cop, kid, curop, opnext);
1337 /* Nothing found. */
1343 =for apidoc Am|SV *|mess_sv|SV *basemsg|bool consume
1345 Expands a message, intended for the user, to include an indication of
1346 the current location in the code, if the message does not already appear
1349 C<basemsg> is the initial message or object. If it is a reference, it
1350 will be used as-is and will be the result of this function. Otherwise it
1351 is used as a string, and if it already ends with a newline, it is taken
1352 to be complete, and the result of this function will be the same string.
1353 If the message does not end with a newline, then a segment such as C<at
1354 foo.pl line 37> will be appended, and possibly other clauses indicating
1355 the current state of execution. The resulting message will end with a
1358 Normally, the resulting message is returned in a new mortal SV.
1359 During global destruction a single SV may be shared between uses of this
1360 function. If C<consume> is true, then the function is permitted (but not
1361 required) to modify and return C<basemsg> instead of allocating a new SV.
1367 Perl_mess_sv(pTHX_ SV *basemsg, bool consume)
1371 #if defined(USE_C_BACKTRACE) && defined(USE_C_BACKTRACE_ON_ERROR)
1375 /* The PERL_C_BACKTRACE_ON_WARN must be an integer of one or more. */
1376 if ((ws = PerlEnv_getenv("PERL_C_BACKTRACE_ON_ERROR"))
1377 && grok_atoUV(ws, &wi, NULL)
1378 && wi <= PERL_INT_MAX
1380 Perl_dump_c_backtrace(aTHX_ Perl_debug_log, (int)wi, 1);
1385 PERL_ARGS_ASSERT_MESS_SV;
1387 if (SvROK(basemsg)) {
1393 sv_setsv(sv, basemsg);
1398 if (SvPOK(basemsg) && consume) {
1403 sv_copypv(sv, basemsg);
1406 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1408 * Try and find the file and line for PL_op. This will usually be
1409 * PL_curcop, but it might be a cop that has been optimised away. We
1410 * can try to find such a cop by searching through the optree starting
1411 * from the sibling of PL_curcop.
1415 closest_cop(PL_curcop, OpSIBLING(PL_curcop), PL_op, FALSE);
1420 Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
1421 OutCopFILE(cop), (IV)CopLINE(cop));
1422 /* Seems that GvIO() can be untrustworthy during global destruction. */
1423 if (GvIO(PL_last_in_gv) && (SvTYPE(GvIOp(PL_last_in_gv)) == SVt_PVIO)
1424 && IoLINES(GvIOp(PL_last_in_gv)))
1427 const bool line_mode = (RsSIMPLE(PL_rs) &&
1428 *SvPV_const(PL_rs,l) == '\n' && l == 1);
1429 Perl_sv_catpvf(aTHX_ sv, ", <%"SVf"> %s %"IVdf,
1430 SVfARG(PL_last_in_gv == PL_argvgv
1432 : sv_2mortal(newSVhek(GvNAME_HEK(PL_last_in_gv)))),
1433 line_mode ? "line" : "chunk",
1434 (IV)IoLINES(GvIOp(PL_last_in_gv)));
1436 if (PL_phase == PERL_PHASE_DESTRUCT)
1437 sv_catpvs(sv, " during global destruction");
1438 sv_catpvs(sv, ".\n");
1444 =for apidoc Am|SV *|vmess|const char *pat|va_list *args
1446 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1447 argument list. These are used to generate a string message. If the
1448 message does not end with a newline, then it will be extended with
1449 some indication of the current location in the code, as described for
1452 Normally, the resulting message is returned in a new mortal SV.
1453 During global destruction a single SV may be shared between uses of
1460 Perl_vmess(pTHX_ const char *pat, va_list *args)
1462 SV * const sv = mess_alloc();
1464 PERL_ARGS_ASSERT_VMESS;
1466 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1467 return mess_sv(sv, 1);
1471 Perl_write_to_stderr(pTHX_ SV* msv)
1476 PERL_ARGS_ASSERT_WRITE_TO_STDERR;
1478 if (PL_stderrgv && SvREFCNT(PL_stderrgv)
1479 && (io = GvIO(PL_stderrgv))
1480 && (mg = SvTIED_mg((const SV *)io, PERL_MAGIC_tiedscalar)))
1481 Perl_magic_methcall(aTHX_ MUTABLE_SV(io), mg, SV_CONST(PRINT),
1482 G_SCALAR | G_DISCARD | G_WRITING_TO_STDERR, 1, msv);
1484 PerlIO * const serr = Perl_error_log;
1486 do_print(msv, serr);
1487 (void)PerlIO_flush(serr);
1492 =head1 Warning and Dieing
1495 /* Common code used in dieing and warning */
1498 S_with_queued_errors(pTHX_ SV *ex)
1500 PERL_ARGS_ASSERT_WITH_QUEUED_ERRORS;
1501 if (PL_errors && SvCUR(PL_errors) && !SvROK(ex)) {
1502 sv_catsv(PL_errors, ex);
1503 ex = sv_mortalcopy(PL_errors);
1504 SvCUR_set(PL_errors, 0);
1510 S_invoke_exception_hook(pTHX_ SV *ex, bool warn)
1515 SV **const hook = warn ? &PL_warnhook : &PL_diehook;
1516 /* sv_2cv might call Perl_croak() or Perl_warner() */
1517 SV * const oldhook = *hook;
1525 cv = sv_2cv(oldhook, &stash, &gv, 0);
1527 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1537 exarg = newSVsv(ex);
1538 SvREADONLY_on(exarg);
1541 PUSHSTACKi(warn ? PERLSI_WARNHOOK : PERLSI_DIEHOOK);
1545 call_sv(MUTABLE_SV(cv), G_DISCARD);
1554 =for apidoc Am|OP *|die_sv|SV *baseex
1556 Behaves the same as L</croak_sv>, except for the return type.
1557 It should be used only where the C<OP *> return type is required.
1558 The function never actually returns.
1564 # pragma warning( push )
1565 # pragma warning( disable : 4646 ) /* warning C4646: function declared with
1566 __declspec(noreturn) has non-void return type */
1567 # pragma warning( disable : 4645 ) /* warning C4645: function declared with
1568 __declspec(noreturn) has a return statement */
1571 Perl_die_sv(pTHX_ SV *baseex)
1573 PERL_ARGS_ASSERT_DIE_SV;
1576 NORETURN_FUNCTION_END;
1579 # pragma warning( pop )
1583 =for apidoc Am|OP *|die|const char *pat|...
1585 Behaves the same as L</croak>, except for the return type.
1586 It should be used only where the C<OP *> return type is required.
1587 The function never actually returns.
1592 #if defined(PERL_IMPLICIT_CONTEXT)
1594 # pragma warning( push )
1595 # pragma warning( disable : 4646 ) /* warning C4646: function declared with
1596 __declspec(noreturn) has non-void return type */
1597 # pragma warning( disable : 4645 ) /* warning C4645: function declared with
1598 __declspec(noreturn) has a return statement */
1601 Perl_die_nocontext(const char* pat, ...)
1605 va_start(args, pat);
1607 NOT_REACHED; /* NOTREACHED */
1609 NORETURN_FUNCTION_END;
1612 # pragma warning( pop )
1614 #endif /* PERL_IMPLICIT_CONTEXT */
1617 # pragma warning( push )
1618 # pragma warning( disable : 4646 ) /* warning C4646: function declared with
1619 __declspec(noreturn) has non-void return type */
1620 # pragma warning( disable : 4645 ) /* warning C4645: function declared with
1621 __declspec(noreturn) has a return statement */
1624 Perl_die(pTHX_ const char* pat, ...)
1627 va_start(args, pat);
1629 NOT_REACHED; /* NOTREACHED */
1631 NORETURN_FUNCTION_END;
1634 # pragma warning( pop )
1638 =for apidoc Am|void|croak_sv|SV *baseex
1640 This is an XS interface to Perl's C<die> function.
1642 C<baseex> is the error message or object. If it is a reference, it
1643 will be used as-is. Otherwise it is used as a string, and if it does
1644 not end with a newline then it will be extended with some indication of
1645 the current location in the code, as described for L</mess_sv>.
1647 The error message or object will be used as an exception, by default
1648 returning control to the nearest enclosing C<eval>, but subject to
1649 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak_sv>
1650 function never returns normally.
1652 To die with a simple string message, the L</croak> function may be
1659 Perl_croak_sv(pTHX_ SV *baseex)
1661 SV *ex = with_queued_errors(mess_sv(baseex, 0));
1662 PERL_ARGS_ASSERT_CROAK_SV;
1663 invoke_exception_hook(ex, FALSE);
1668 =for apidoc Am|void|vcroak|const char *pat|va_list *args
1670 This is an XS interface to Perl's C<die> function.
1672 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1673 argument list. These are used to generate a string message. If the
1674 message does not end with a newline, then it will be extended with
1675 some indication of the current location in the code, as described for
1678 The error message will be used as an exception, by default
1679 returning control to the nearest enclosing C<eval>, but subject to
1680 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1681 function never returns normally.
1683 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1684 (C<$@>) will be used as an error message or object instead of building an
1685 error message from arguments. If you want to throw a non-string object,
1686 or build an error message in an SV yourself, it is preferable to use
1687 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1693 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1695 SV *ex = with_queued_errors(pat ? vmess(pat, args) : mess_sv(ERRSV, 0));
1696 invoke_exception_hook(ex, FALSE);
1701 =for apidoc Am|void|croak|const char *pat|...
1703 This is an XS interface to Perl's C<die> function.
1705 Take a sprintf-style format pattern and argument list. These are used to
1706 generate a string message. If the message does not end with a newline,
1707 then it will be extended with some indication of the current location
1708 in the code, as described for L</mess_sv>.
1710 The error message will be used as an exception, by default
1711 returning control to the nearest enclosing C<eval>, but subject to
1712 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1713 function never returns normally.
1715 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1716 (C<$@>) will be used as an error message or object instead of building an
1717 error message from arguments. If you want to throw a non-string object,
1718 or build an error message in an SV yourself, it is preferable to use
1719 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1724 #if defined(PERL_IMPLICIT_CONTEXT)
1726 Perl_croak_nocontext(const char *pat, ...)
1730 va_start(args, pat);
1732 NOT_REACHED; /* NOTREACHED */
1735 #endif /* PERL_IMPLICIT_CONTEXT */
1738 Perl_croak(pTHX_ const char *pat, ...)
1741 va_start(args, pat);
1743 NOT_REACHED; /* NOTREACHED */
1748 =for apidoc Am|void|croak_no_modify
1750 Exactly equivalent to C<Perl_croak(aTHX_ "%s", PL_no_modify)>, but generates
1751 terser object code than using C<Perl_croak>. Less code used on exception code
1752 paths reduces CPU cache pressure.
1758 Perl_croak_no_modify(void)
1760 Perl_croak_nocontext( "%s", PL_no_modify);
1763 /* does not return, used in util.c perlio.c and win32.c
1764 This is typically called when malloc returns NULL.
1767 Perl_croak_no_mem(void)
1771 int fd = PerlIO_fileno(Perl_error_log);
1773 SETERRNO(EBADF,RMS_IFI);
1775 /* Can't use PerlIO to write as it allocates memory */
1776 PERL_UNUSED_RESULT(PerlLIO_write(fd, PL_no_mem, sizeof(PL_no_mem)-1));
1781 /* does not return, used only in POPSTACK */
1783 Perl_croak_popstack(void)
1786 PerlIO_printf(Perl_error_log, "panic: POPSTACK\n");
1791 =for apidoc Am|void|warn_sv|SV *baseex
1793 This is an XS interface to Perl's C<warn> function.
1795 C<baseex> is the error message or object. If it is a reference, it
1796 will be used as-is. Otherwise it is used as a string, and if it does
1797 not end with a newline then it will be extended with some indication of
1798 the current location in the code, as described for L</mess_sv>.
1800 The error message or object will by default be written to standard error,
1801 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1803 To warn with a simple string message, the L</warn> function may be
1810 Perl_warn_sv(pTHX_ SV *baseex)
1812 SV *ex = mess_sv(baseex, 0);
1813 PERL_ARGS_ASSERT_WARN_SV;
1814 if (!invoke_exception_hook(ex, TRUE))
1815 write_to_stderr(ex);
1819 =for apidoc Am|void|vwarn|const char *pat|va_list *args
1821 This is an XS interface to Perl's C<warn> function.
1823 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1824 argument list. These are used to generate a string message. If the
1825 message does not end with a newline, then it will be extended with
1826 some indication of the current location in the code, as described for
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</vcroak>, C<pat> is not permitted to be null.
1838 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1840 SV *ex = vmess(pat, args);
1841 PERL_ARGS_ASSERT_VWARN;
1842 if (!invoke_exception_hook(ex, TRUE))
1843 write_to_stderr(ex);
1847 =for apidoc Am|void|warn|const char *pat|...
1849 This is an XS interface to Perl's C<warn> function.
1851 Take a sprintf-style format pattern and argument list. These are used to
1852 generate a string message. If the message does not end with a newline,
1853 then it will be extended with some indication of the current location
1854 in the code, as described for L</mess_sv>.
1856 The error message or object will by default be written to standard error,
1857 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1859 Unlike with L</croak>, C<pat> is not permitted to be null.
1864 #if defined(PERL_IMPLICIT_CONTEXT)
1866 Perl_warn_nocontext(const char *pat, ...)
1870 PERL_ARGS_ASSERT_WARN_NOCONTEXT;
1871 va_start(args, pat);
1875 #endif /* PERL_IMPLICIT_CONTEXT */
1878 Perl_warn(pTHX_ const char *pat, ...)
1881 PERL_ARGS_ASSERT_WARN;
1882 va_start(args, pat);
1887 #if defined(PERL_IMPLICIT_CONTEXT)
1889 Perl_warner_nocontext(U32 err, const char *pat, ...)
1893 PERL_ARGS_ASSERT_WARNER_NOCONTEXT;
1894 va_start(args, pat);
1895 vwarner(err, pat, &args);
1898 #endif /* PERL_IMPLICIT_CONTEXT */
1901 Perl_ck_warner_d(pTHX_ U32 err, const char* pat, ...)
1903 PERL_ARGS_ASSERT_CK_WARNER_D;
1905 if (Perl_ckwarn_d(aTHX_ err)) {
1907 va_start(args, pat);
1908 vwarner(err, pat, &args);
1914 Perl_ck_warner(pTHX_ U32 err, const char* pat, ...)
1916 PERL_ARGS_ASSERT_CK_WARNER;
1918 if (Perl_ckwarn(aTHX_ err)) {
1920 va_start(args, pat);
1921 vwarner(err, pat, &args);
1927 Perl_warner(pTHX_ U32 err, const char* pat,...)
1930 PERL_ARGS_ASSERT_WARNER;
1931 va_start(args, pat);
1932 vwarner(err, pat, &args);
1937 Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1940 PERL_ARGS_ASSERT_VWARNER;
1942 (PL_warnhook == PERL_WARNHOOK_FATAL || ckDEAD(err)) &&
1943 !(PL_in_eval & EVAL_KEEPERR)
1945 SV * const msv = vmess(pat, args);
1947 if (PL_parser && PL_parser->error_count) {
1951 invoke_exception_hook(msv, FALSE);
1956 Perl_vwarn(aTHX_ pat, args);
1960 /* implements the ckWARN? macros */
1963 Perl_ckwarn(pTHX_ U32 w)
1965 /* If lexical warnings have not been set, use $^W. */
1967 return PL_dowarn & G_WARN_ON;
1969 return ckwarn_common(w);
1972 /* implements the ckWARN?_d macro */
1975 Perl_ckwarn_d(pTHX_ U32 w)
1977 /* If lexical warnings have not been set then default classes warn. */
1981 return ckwarn_common(w);
1985 S_ckwarn_common(pTHX_ U32 w)
1987 if (PL_curcop->cop_warnings == pWARN_ALL)
1990 if (PL_curcop->cop_warnings == pWARN_NONE)
1993 /* Check the assumption that at least the first slot is non-zero. */
1994 assert(unpackWARN1(w));
1996 /* Check the assumption that it is valid to stop as soon as a zero slot is
1998 if (!unpackWARN2(w)) {
1999 assert(!unpackWARN3(w));
2000 assert(!unpackWARN4(w));
2001 } else if (!unpackWARN3(w)) {
2002 assert(!unpackWARN4(w));
2005 /* Right, dealt with all the special cases, which are implemented as non-
2006 pointers, so there is a pointer to a real warnings mask. */
2008 if (isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w)))
2010 } while (w >>= WARNshift);
2015 /* Set buffer=NULL to get a new one. */
2017 Perl_new_warnings_bitfield(pTHX_ STRLEN *buffer, const char *const bits,
2019 const MEM_SIZE len_wanted =
2020 sizeof(STRLEN) + (size > WARNsize ? size : WARNsize);
2021 PERL_UNUSED_CONTEXT;
2022 PERL_ARGS_ASSERT_NEW_WARNINGS_BITFIELD;
2025 (specialWARN(buffer) ?
2026 PerlMemShared_malloc(len_wanted) :
2027 PerlMemShared_realloc(buffer, len_wanted));
2029 Copy(bits, (buffer + 1), size, char);
2030 if (size < WARNsize)
2031 Zero((char *)(buffer + 1) + size, WARNsize - size, char);
2035 /* since we've already done strlen() for both nam and val
2036 * we can use that info to make things faster than
2037 * sprintf(s, "%s=%s", nam, val)
2039 #define my_setenv_format(s, nam, nlen, val, vlen) \
2040 Copy(nam, s, nlen, char); \
2042 Copy(val, s+(nlen+1), vlen, char); \
2043 *(s+(nlen+1+vlen)) = '\0'
2045 #ifdef USE_ENVIRON_ARRAY
2046 /* VMS' my_setenv() is in vms.c */
2047 #if !defined(WIN32) && !defined(NETWARE)
2049 Perl_my_setenv(pTHX_ const char *nam, const char *val)
2053 /* only parent thread can modify process environment */
2054 if (PL_curinterp == aTHX)
2057 #ifndef PERL_USE_SAFE_PUTENV
2058 if (!PL_use_safe_putenv) {
2059 /* most putenv()s leak, so we manipulate environ directly */
2061 const I32 len = strlen(nam);
2064 /* where does it go? */
2065 for (i = 0; environ[i]; i++) {
2066 if (strnEQ(environ[i],nam,len) && environ[i][len] == '=')
2070 if (environ == PL_origenviron) { /* need we copy environment? */
2076 while (environ[max])
2078 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
2079 for (j=0; j<max; j++) { /* copy environment */
2080 const int len = strlen(environ[j]);
2081 tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
2082 Copy(environ[j], tmpenv[j], len+1, char);
2085 environ = tmpenv; /* tell exec where it is now */
2088 safesysfree(environ[i]);
2089 while (environ[i]) {
2090 environ[i] = environ[i+1];
2095 if (!environ[i]) { /* does not exist yet */
2096 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
2097 environ[i+1] = NULL; /* make sure it's null terminated */
2100 safesysfree(environ[i]);
2104 environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
2105 /* all that work just for this */
2106 my_setenv_format(environ[i], nam, nlen, val, vlen);
2109 /* This next branch should only be called #if defined(HAS_SETENV), but
2110 Configure doesn't test for that yet. For Solaris, setenv() and unsetenv()
2111 were introduced in Solaris 9, so testing for HAS UNSETENV is sufficient.
2113 # if defined(__CYGWIN__)|| defined(__SYMBIAN32__) || defined(__riscos__) || (defined(__sun) && defined(HAS_UNSETENV))
2114 # if defined(HAS_UNSETENV)
2116 (void)unsetenv(nam);
2118 (void)setenv(nam, val, 1);
2120 # else /* ! HAS_UNSETENV */
2121 (void)setenv(nam, val, 1);
2122 # endif /* HAS_UNSETENV */
2124 # if defined(HAS_UNSETENV)
2126 if (environ) /* old glibc can crash with null environ */
2127 (void)unsetenv(nam);
2129 const int nlen = strlen(nam);
2130 const int vlen = strlen(val);
2131 char * const new_env =
2132 (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
2133 my_setenv_format(new_env, nam, nlen, val, vlen);
2134 (void)putenv(new_env);
2136 # else /* ! HAS_UNSETENV */
2138 const int nlen = strlen(nam);
2144 new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
2145 /* all that work just for this */
2146 my_setenv_format(new_env, nam, nlen, val, vlen);
2147 (void)putenv(new_env);
2148 # endif /* HAS_UNSETENV */
2149 # endif /* __CYGWIN__ */
2150 #ifndef PERL_USE_SAFE_PUTENV
2156 #else /* WIN32 || NETWARE */
2159 Perl_my_setenv(pTHX_ const char *nam, const char *val)
2163 const int nlen = strlen(nam);
2170 Newx(envstr, nlen+vlen+2, char);
2171 my_setenv_format(envstr, nam, nlen, val, vlen);
2172 (void)PerlEnv_putenv(envstr);
2176 #endif /* WIN32 || NETWARE */
2180 #ifdef UNLINK_ALL_VERSIONS
2182 Perl_unlnk(pTHX_ const char *f) /* unlink all versions of a file */
2186 PERL_ARGS_ASSERT_UNLNK;
2188 while (PerlLIO_unlink(f) >= 0)
2190 return retries ? 0 : -1;
2194 /* this is a drop-in replacement for bcopy() */
2195 #if (!defined(HAS_MEMCPY) && !defined(HAS_BCOPY)) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY) && !defined(HAS_SAFE_BCOPY))
2197 Perl_my_bcopy(const char *from, char *to, I32 len)
2199 char * const retval = to;
2201 PERL_ARGS_ASSERT_MY_BCOPY;
2205 if (from - to >= 0) {
2213 *(--to) = *(--from);
2219 /* this is a drop-in replacement for memset() */
2222 Perl_my_memset(char *loc, I32 ch, I32 len)
2224 char * const retval = loc;
2226 PERL_ARGS_ASSERT_MY_MEMSET;
2236 /* this is a drop-in replacement for bzero() */
2237 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
2239 Perl_my_bzero(char *loc, I32 len)
2241 char * const retval = loc;
2243 PERL_ARGS_ASSERT_MY_BZERO;
2253 /* this is a drop-in replacement for memcmp() */
2254 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
2256 Perl_my_memcmp(const char *s1, const char *s2, I32 len)
2258 const U8 *a = (const U8 *)s1;
2259 const U8 *b = (const U8 *)s2;
2262 PERL_ARGS_ASSERT_MY_MEMCMP;
2267 if ((tmp = *a++ - *b++))
2272 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
2275 /* This vsprintf replacement should generally never get used, since
2276 vsprintf was available in both System V and BSD 2.11. (There may
2277 be some cross-compilation or embedded set-ups where it is needed,
2280 If you encounter a problem in this function, it's probably a symptom
2281 that Configure failed to detect your system's vprintf() function.
2282 See the section on "item vsprintf" in the INSTALL file.
2284 This version may compile on systems with BSD-ish <stdio.h>,
2285 but probably won't on others.
2288 #ifdef USE_CHAR_VSPRINTF
2293 vsprintf(char *dest, const char *pat, void *args)
2297 #if defined(STDIO_PTR_LVALUE) && defined(STDIO_CNT_LVALUE)
2298 FILE_ptr(&fakebuf) = (STDCHAR *) dest;
2299 FILE_cnt(&fakebuf) = 32767;
2301 /* These probably won't compile -- If you really need
2302 this, you'll have to figure out some other method. */
2303 fakebuf._ptr = dest;
2304 fakebuf._cnt = 32767;
2309 fakebuf._flag = _IOWRT|_IOSTRG;
2310 _doprnt(pat, args, &fakebuf); /* what a kludge */
2311 #if defined(STDIO_PTR_LVALUE)
2312 *(FILE_ptr(&fakebuf)++) = '\0';
2314 /* PerlIO has probably #defined away fputc, but we want it here. */
2316 # undef fputc /* XXX Should really restore it later */
2318 (void)fputc('\0', &fakebuf);
2320 #ifdef USE_CHAR_VSPRINTF
2323 return 0; /* perl doesn't use return value */
2327 #endif /* HAS_VPRINTF */
2330 Perl_my_popen_list(pTHX_ const char *mode, int n, SV **args)
2332 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(OS2) && !defined(VMS) && !defined(NETWARE) && !defined(__LIBCATAMOUNT__)
2340 PERL_ARGS_ASSERT_MY_POPEN_LIST;
2342 PERL_FLUSHALL_FOR_CHILD;
2343 This = (*mode == 'w');
2347 taint_proper("Insecure %s%s", "EXEC");
2349 if (PerlProc_pipe(p) < 0)
2351 /* Try for another pipe pair for error return */
2352 if (PerlProc_pipe(pp) >= 0)
2354 while ((pid = PerlProc_fork()) < 0) {
2355 if (errno != EAGAIN) {
2356 PerlLIO_close(p[This]);
2357 PerlLIO_close(p[that]);
2359 PerlLIO_close(pp[0]);
2360 PerlLIO_close(pp[1]);
2364 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2373 /* Close parent's end of error status pipe (if any) */
2375 PerlLIO_close(pp[0]);
2376 #if defined(HAS_FCNTL) && defined(F_SETFD) && defined(FD_CLOEXEC)
2377 /* Close error pipe automatically if exec works */
2378 if (fcntl(pp[1], F_SETFD, FD_CLOEXEC) < 0)
2382 /* Now dup our end of _the_ pipe to right position */
2383 if (p[THIS] != (*mode == 'r')) {
2384 PerlLIO_dup2(p[THIS], *mode == 'r');
2385 PerlLIO_close(p[THIS]);
2386 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2387 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2390 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2391 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2392 /* No automatic close - do it by hand */
2399 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
2405 do_aexec5(NULL, args-1, args-1+n, pp[1], did_pipes);
2411 do_execfree(); /* free any memory malloced by child on fork */
2413 PerlLIO_close(pp[1]);
2414 /* Keep the lower of the two fd numbers */
2415 if (p[that] < p[This]) {
2416 PerlLIO_dup2(p[This], p[that]);
2417 PerlLIO_close(p[This]);
2421 PerlLIO_close(p[that]); /* close child's end of pipe */
2423 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2424 SvUPGRADE(sv,SVt_IV);
2426 PL_forkprocess = pid;
2427 /* If we managed to get status pipe check for exec fail */
2428 if (did_pipes && pid > 0) {
2433 while (n < sizeof(int)) {
2434 n1 = PerlLIO_read(pp[0],
2435 (void*)(((char*)&errkid)+n),
2441 PerlLIO_close(pp[0]);
2443 if (n) { /* Error */
2445 PerlLIO_close(p[This]);
2446 if (n != sizeof(int))
2447 Perl_croak(aTHX_ "panic: kid popen errno read, n=%u", n);
2449 pid2 = wait4pid(pid, &status, 0);
2450 } while (pid2 == -1 && errno == EINTR);
2451 errno = errkid; /* Propagate errno from kid */
2456 PerlLIO_close(pp[0]);
2457 return PerlIO_fdopen(p[This], mode);
2459 # if defined(OS2) /* Same, without fork()ing and all extra overhead... */
2460 return my_syspopen4(aTHX_ NULL, mode, n, args);
2461 # elif defined(WIN32)
2462 return win32_popenlist(mode, n, args);
2464 Perl_croak(aTHX_ "List form of piped open not implemented");
2465 return (PerlIO *) NULL;
2470 /* VMS' my_popen() is in VMS.c, same with OS/2. */
2471 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__LIBCATAMOUNT__)
2473 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2479 const I32 doexec = !(*cmd == '-' && cmd[1] == '\0');
2483 PERL_ARGS_ASSERT_MY_POPEN;
2485 PERL_FLUSHALL_FOR_CHILD;
2488 return my_syspopen(aTHX_ cmd,mode);
2491 This = (*mode == 'w');
2493 if (doexec && TAINTING_get) {
2495 taint_proper("Insecure %s%s", "EXEC");
2497 if (PerlProc_pipe(p) < 0)
2499 if (doexec && PerlProc_pipe(pp) >= 0)
2501 while ((pid = PerlProc_fork()) < 0) {
2502 if (errno != EAGAIN) {
2503 PerlLIO_close(p[This]);
2504 PerlLIO_close(p[that]);
2506 PerlLIO_close(pp[0]);
2507 PerlLIO_close(pp[1]);
2510 Perl_croak(aTHX_ "Can't fork: %s", Strerror(errno));
2513 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2523 PerlLIO_close(pp[0]);
2524 #if defined(HAS_FCNTL) && defined(F_SETFD)
2525 if (fcntl(pp[1], F_SETFD, FD_CLOEXEC) < 0)
2529 if (p[THIS] != (*mode == 'r')) {
2530 PerlLIO_dup2(p[THIS], *mode == 'r');
2531 PerlLIO_close(p[THIS]);
2532 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2533 PerlLIO_close(p[THAT]);
2536 PerlLIO_close(p[THAT]);
2539 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2546 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2551 /* may or may not use the shell */
2552 do_exec3(cmd, pp[1], did_pipes);
2555 #endif /* defined OS2 */
2557 #ifdef PERLIO_USING_CRLF
2558 /* Since we circumvent IO layers when we manipulate low-level
2559 filedescriptors directly, need to manually switch to the
2560 default, binary, low-level mode; see PerlIOBuf_open(). */
2561 PerlLIO_setmode((*mode == 'r'), O_BINARY);
2564 #ifdef PERL_USES_PL_PIDSTATUS
2565 hv_clear(PL_pidstatus); /* we have no children */
2571 do_execfree(); /* free any memory malloced by child on vfork */
2573 PerlLIO_close(pp[1]);
2574 if (p[that] < p[This]) {
2575 PerlLIO_dup2(p[This], p[that]);
2576 PerlLIO_close(p[This]);
2580 PerlLIO_close(p[that]);
2582 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2583 SvUPGRADE(sv,SVt_IV);
2585 PL_forkprocess = pid;
2586 if (did_pipes && pid > 0) {
2591 while (n < sizeof(int)) {
2592 n1 = PerlLIO_read(pp[0],
2593 (void*)(((char*)&errkid)+n),
2599 PerlLIO_close(pp[0]);
2601 if (n) { /* Error */
2603 PerlLIO_close(p[This]);
2604 if (n != sizeof(int))
2605 Perl_croak(aTHX_ "panic: kid popen errno read, n=%u", n);
2607 pid2 = wait4pid(pid, &status, 0);
2608 } while (pid2 == -1 && errno == EINTR);
2609 errno = errkid; /* Propagate errno from kid */
2614 PerlLIO_close(pp[0]);
2615 return PerlIO_fdopen(p[This], mode);
2619 FILE *djgpp_popen();
2621 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2623 PERL_FLUSHALL_FOR_CHILD;
2624 /* Call system's popen() to get a FILE *, then import it.
2625 used 0 for 2nd parameter to PerlIO_importFILE;
2628 return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2631 #if defined(__LIBCATAMOUNT__)
2633 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2640 #endif /* !DOSISH */
2642 /* this is called in parent before the fork() */
2644 Perl_atfork_lock(void)
2646 #if defined(USE_ITHREADS)
2648 /* locks must be held in locking order (if any) */
2650 MUTEX_LOCK(&PL_perlio_mutex);
2653 MUTEX_LOCK(&PL_malloc_mutex);
2659 /* this is called in both parent and child after the fork() */
2661 Perl_atfork_unlock(void)
2663 #if defined(USE_ITHREADS)
2665 /* locks must be released in same order as in atfork_lock() */
2667 MUTEX_UNLOCK(&PL_perlio_mutex);
2670 MUTEX_UNLOCK(&PL_malloc_mutex);
2679 #if defined(HAS_FORK)
2681 #if defined(USE_ITHREADS) && !defined(HAS_PTHREAD_ATFORK)
2686 /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2687 * handlers elsewhere in the code */
2692 /* this "canna happen" since nothing should be calling here if !HAS_FORK */
2693 Perl_croak_nocontext("fork() not available");
2695 #endif /* HAS_FORK */
2700 dup2(int oldfd, int newfd)
2702 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2705 PerlLIO_close(newfd);
2706 return fcntl(oldfd, F_DUPFD, newfd);
2708 #define DUP2_MAX_FDS 256
2709 int fdtmp[DUP2_MAX_FDS];
2715 PerlLIO_close(newfd);
2716 /* good enough for low fd's... */
2717 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2718 if (fdx >= DUP2_MAX_FDS) {
2726 PerlLIO_close(fdtmp[--fdx]);
2733 #ifdef HAS_SIGACTION
2736 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2738 struct sigaction act, oact;
2742 /* only "parent" interpreter can diddle signals */
2743 if (PL_curinterp != aTHX)
2744 return (Sighandler_t) SIG_ERR;
2747 act.sa_handler = (void(*)(int))handler;
2748 sigemptyset(&act.sa_mask);
2751 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2752 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2754 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2755 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2756 act.sa_flags |= SA_NOCLDWAIT;
2758 if (sigaction(signo, &act, &oact) == -1)
2759 return (Sighandler_t) SIG_ERR;
2761 return (Sighandler_t) oact.sa_handler;
2765 Perl_rsignal_state(pTHX_ int signo)
2767 struct sigaction oact;
2768 PERL_UNUSED_CONTEXT;
2770 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2771 return (Sighandler_t) SIG_ERR;
2773 return (Sighandler_t) oact.sa_handler;
2777 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2782 struct sigaction act;
2784 PERL_ARGS_ASSERT_RSIGNAL_SAVE;
2787 /* only "parent" interpreter can diddle signals */
2788 if (PL_curinterp != aTHX)
2792 act.sa_handler = (void(*)(int))handler;
2793 sigemptyset(&act.sa_mask);
2796 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2797 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2799 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2800 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2801 act.sa_flags |= SA_NOCLDWAIT;
2803 return sigaction(signo, &act, save);
2807 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2812 PERL_UNUSED_CONTEXT;
2814 /* only "parent" interpreter can diddle signals */
2815 if (PL_curinterp != aTHX)
2819 return sigaction(signo, save, (struct sigaction *)NULL);
2822 #else /* !HAS_SIGACTION */
2825 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2827 #if defined(USE_ITHREADS) && !defined(WIN32)
2828 /* only "parent" interpreter can diddle signals */
2829 if (PL_curinterp != aTHX)
2830 return (Sighandler_t) SIG_ERR;
2833 return PerlProc_signal(signo, handler);
2844 Perl_rsignal_state(pTHX_ int signo)
2847 Sighandler_t oldsig;
2849 #if defined(USE_ITHREADS) && !defined(WIN32)
2850 /* only "parent" interpreter can diddle signals */
2851 if (PL_curinterp != aTHX)
2852 return (Sighandler_t) SIG_ERR;
2856 oldsig = PerlProc_signal(signo, sig_trap);
2857 PerlProc_signal(signo, oldsig);
2859 PerlProc_kill(PerlProc_getpid(), signo);
2864 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2866 #if defined(USE_ITHREADS) && !defined(WIN32)
2867 /* only "parent" interpreter can diddle signals */
2868 if (PL_curinterp != aTHX)
2871 *save = PerlProc_signal(signo, handler);
2872 return (*save == (Sighandler_t) SIG_ERR) ? -1 : 0;
2876 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2878 #if defined(USE_ITHREADS) && !defined(WIN32)
2879 /* only "parent" interpreter can diddle signals */
2880 if (PL_curinterp != aTHX)
2883 return (PerlProc_signal(signo, *save) == (Sighandler_t) SIG_ERR) ? -1 : 0;
2886 #endif /* !HAS_SIGACTION */
2887 #endif /* !PERL_MICRO */
2889 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
2890 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__LIBCATAMOUNT__)
2892 Perl_my_pclose(pTHX_ PerlIO *ptr)
2900 const int fd = PerlIO_fileno(ptr);
2903 svp = av_fetch(PL_fdpid,fd,TRUE);
2904 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
2908 #if defined(USE_PERLIO)
2909 /* Find out whether the refcount is low enough for us to wait for the
2910 child proc without blocking. */
2911 should_wait = PerlIOUnix_refcnt(fd) == 1 && pid > 0;
2913 should_wait = pid > 0;
2917 if (pid == -1) { /* Opened by popen. */
2918 return my_syspclose(ptr);
2921 close_failed = (PerlIO_close(ptr) == EOF);
2923 if (should_wait) do {
2924 pid2 = wait4pid(pid, &status, 0);
2925 } while (pid2 == -1 && errno == EINTR);
2932 ? pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status)
2937 #if defined(__LIBCATAMOUNT__)
2939 Perl_my_pclose(pTHX_ PerlIO *ptr)
2944 #endif /* !DOSISH */
2946 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(__LIBCATAMOUNT__)
2948 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
2951 PERL_ARGS_ASSERT_WAIT4PID;
2952 #ifdef PERL_USES_PL_PIDSTATUS
2954 /* PERL_USES_PL_PIDSTATUS is only defined when neither
2955 waitpid() nor wait4() is available, or on OS/2, which
2956 doesn't appear to support waiting for a progress group
2957 member, so we can only treat a 0 pid as an unknown child.
2964 /* The keys in PL_pidstatus are now the raw 4 (or 8) bytes of the
2965 pid, rather than a string form. */
2966 SV * const * const svp = hv_fetch(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),FALSE);
2967 if (svp && *svp != &PL_sv_undef) {
2968 *statusp = SvIVX(*svp);
2969 (void)hv_delete(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),
2977 hv_iterinit(PL_pidstatus);
2978 if ((entry = hv_iternext(PL_pidstatus))) {
2979 SV * const sv = hv_iterval(PL_pidstatus,entry);
2981 const char * const spid = hv_iterkey(entry,&len);
2983 assert (len == sizeof(Pid_t));
2984 memcpy((char *)&pid, spid, len);
2985 *statusp = SvIVX(sv);
2986 /* The hash iterator is currently on this entry, so simply
2987 calling hv_delete would trigger the lazy delete, which on
2988 aggregate does more work, because next call to hv_iterinit()
2989 would spot the flag, and have to call the delete routine,
2990 while in the meantime any new entries can't re-use that
2992 hv_iterinit(PL_pidstatus);
2993 (void)hv_delete(PL_pidstatus,spid,len,G_DISCARD);
3000 # ifdef HAS_WAITPID_RUNTIME
3001 if (!HAS_WAITPID_RUNTIME)
3004 result = PerlProc_waitpid(pid,statusp,flags);
3007 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
3008 result = wait4(pid,statusp,flags,NULL);
3011 #ifdef PERL_USES_PL_PIDSTATUS
3012 #if defined(HAS_WAITPID) && defined(HAS_WAITPID_RUNTIME)
3017 Perl_croak(aTHX_ "Can't do waitpid with flags");
3019 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
3020 pidgone(result,*statusp);
3026 #if defined(HAS_WAITPID) || defined(HAS_WAIT4)
3029 if (result < 0 && errno == EINTR) {
3031 errno = EINTR; /* reset in case a signal handler changed $! */
3035 #endif /* !DOSISH || OS2 || WIN32 || NETWARE */
3037 #ifdef PERL_USES_PL_PIDSTATUS
3039 S_pidgone(pTHX_ Pid_t pid, int status)
3043 sv = *hv_fetch(PL_pidstatus,(const char*)&pid,sizeof(Pid_t),TRUE);
3044 SvUPGRADE(sv,SVt_IV);
3045 SvIV_set(sv, status);
3053 int /* Cannot prototype with I32
3055 my_syspclose(PerlIO *ptr)
3058 Perl_my_pclose(pTHX_ PerlIO *ptr)
3061 /* Needs work for PerlIO ! */
3062 FILE * const f = PerlIO_findFILE(ptr);
3063 const I32 result = pclose(f);
3064 PerlIO_releaseFILE(ptr,f);
3072 Perl_my_pclose(pTHX_ PerlIO *ptr)
3074 /* Needs work for PerlIO ! */
3075 FILE * const f = PerlIO_findFILE(ptr);
3076 I32 result = djgpp_pclose(f);
3077 result = (result << 8) & 0xff00;
3078 PerlIO_releaseFILE(ptr,f);
3083 #define PERL_REPEATCPY_LINEAR 4
3085 Perl_repeatcpy(char *to, const char *from, I32 len, IV count)
3087 PERL_ARGS_ASSERT_REPEATCPY;
3092 croak_memory_wrap();
3095 memset(to, *from, count);
3098 IV items, linear, half;
3100 linear = count < PERL_REPEATCPY_LINEAR ? count : PERL_REPEATCPY_LINEAR;
3101 for (items = 0; items < linear; ++items) {
3102 const char *q = from;
3104 for (todo = len; todo > 0; todo--)
3109 while (items <= half) {
3110 IV size = items * len;
3111 memcpy(p, to, size);
3117 memcpy(p, to, (count - items) * len);
3123 Perl_same_dirent(pTHX_ const char *a, const char *b)
3125 char *fa = strrchr(a,'/');
3126 char *fb = strrchr(b,'/');
3129 SV * const tmpsv = sv_newmortal();
3131 PERL_ARGS_ASSERT_SAME_DIRENT;
3144 sv_setpvs(tmpsv, ".");
3146 sv_setpvn(tmpsv, a, fa - a);
3147 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf1) < 0)
3150 sv_setpvs(tmpsv, ".");
3152 sv_setpvn(tmpsv, b, fb - b);
3153 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf2) < 0)
3155 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
3156 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
3158 #endif /* !HAS_RENAME */
3161 Perl_find_script(pTHX_ const char *scriptname, bool dosearch,
3162 const char *const *const search_ext, I32 flags)
3164 const char *xfound = NULL;
3165 char *xfailed = NULL;
3166 char tmpbuf[MAXPATHLEN];
3171 #if defined(DOSISH) && !defined(OS2)
3172 # define SEARCH_EXTS ".bat", ".cmd", NULL
3173 # define MAX_EXT_LEN 4
3176 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
3177 # define MAX_EXT_LEN 4
3180 # define SEARCH_EXTS ".pl", ".com", NULL
3181 # define MAX_EXT_LEN 4
3183 /* additional extensions to try in each dir if scriptname not found */
3185 static const char *const exts[] = { SEARCH_EXTS };
3186 const char *const *const ext = search_ext ? search_ext : exts;
3187 int extidx = 0, i = 0;
3188 const char *curext = NULL;
3190 PERL_UNUSED_ARG(search_ext);
3191 # define MAX_EXT_LEN 0
3194 PERL_ARGS_ASSERT_FIND_SCRIPT;
3197 * If dosearch is true and if scriptname does not contain path
3198 * delimiters, search the PATH for scriptname.
3200 * If SEARCH_EXTS is also defined, will look for each
3201 * scriptname{SEARCH_EXTS} whenever scriptname is not found
3202 * while searching the PATH.
3204 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
3205 * proceeds as follows:
3206 * If DOSISH or VMSISH:
3207 * + look for ./scriptname{,.foo,.bar}
3208 * + search the PATH for scriptname{,.foo,.bar}
3211 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
3212 * this will not look in '.' if it's not in the PATH)
3217 # ifdef ALWAYS_DEFTYPES
3218 len = strlen(scriptname);
3219 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
3220 int idx = 0, deftypes = 1;
3223 const int hasdir = !dosearch || (strpbrk(scriptname,":[</") != NULL);
3226 int idx = 0, deftypes = 1;
3229 const int hasdir = (strpbrk(scriptname,":[</") != NULL);
3231 /* The first time through, just add SEARCH_EXTS to whatever we
3232 * already have, so we can check for default file types. */
3234 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
3240 if ((strlen(tmpbuf) + strlen(scriptname)
3241 + MAX_EXT_LEN) >= sizeof tmpbuf)
3242 continue; /* don't search dir with too-long name */
3243 my_strlcat(tmpbuf, scriptname, sizeof(tmpbuf));
3247 if (strEQ(scriptname, "-"))
3249 if (dosearch) { /* Look in '.' first. */
3250 const char *cur = scriptname;
3252 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
3254 if (strEQ(ext[i++],curext)) {
3255 extidx = -1; /* already has an ext */
3260 DEBUG_p(PerlIO_printf(Perl_debug_log,
3261 "Looking for %s\n",cur));
3262 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
3263 && !S_ISDIR(PL_statbuf.st_mode)) {
3271 if (cur == scriptname) {
3272 len = strlen(scriptname);
3273 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
3275 my_strlcpy(tmpbuf, scriptname, sizeof(tmpbuf));
3278 } while (extidx >= 0 && ext[extidx] /* try an extension? */
3279 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len));
3284 if (dosearch && !strchr(scriptname, '/')
3286 && !strchr(scriptname, '\\')
3288 && (s = PerlEnv_getenv("PATH")))
3292 bufend = s + strlen(s);
3293 while (s < bufend) {
3296 && *s != ';'; len++, s++) {
3297 if (len < sizeof tmpbuf)
3300 if (len < sizeof tmpbuf)
3303 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, bufend,
3309 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
3310 continue; /* don't search dir with too-long name */
3313 && tmpbuf[len - 1] != '/'
3314 && tmpbuf[len - 1] != '\\'
3317 tmpbuf[len++] = '/';
3318 if (len == 2 && tmpbuf[0] == '.')
3320 (void)my_strlcpy(tmpbuf + len, scriptname, sizeof(tmpbuf) - len);
3324 len = strlen(tmpbuf);
3325 if (extidx > 0) /* reset after previous loop */
3329 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
3330 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
3331 if (S_ISDIR(PL_statbuf.st_mode)) {
3335 } while ( retval < 0 /* not there */
3336 && extidx>=0 && ext[extidx] /* try an extension? */
3337 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len)
3342 if (S_ISREG(PL_statbuf.st_mode)
3343 && cando(S_IRUSR,TRUE,&PL_statbuf)
3344 #if !defined(DOSISH)
3345 && cando(S_IXUSR,TRUE,&PL_statbuf)
3349 xfound = tmpbuf; /* bingo! */
3353 xfailed = savepv(tmpbuf);
3356 if (!xfound && !seen_dot && !xfailed &&
3357 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
3358 || S_ISDIR(PL_statbuf.st_mode)))
3360 seen_dot = 1; /* Disable message. */
3362 if (flags & 1) { /* do or die? */
3363 /* diag_listed_as: Can't execute %s */
3364 Perl_croak(aTHX_ "Can't %s %s%s%s",
3365 (xfailed ? "execute" : "find"),
3366 (xfailed ? xfailed : scriptname),
3367 (xfailed ? "" : " on PATH"),
3368 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
3373 scriptname = xfound;
3375 return (scriptname ? savepv(scriptname) : NULL);
3378 #ifndef PERL_GET_CONTEXT_DEFINED
3381 Perl_get_context(void)
3383 #if defined(USE_ITHREADS)
3385 # ifdef OLD_PTHREADS_API
3387 int error = pthread_getspecific(PL_thr_key, &t)
3389 Perl_croak_nocontext("panic: pthread_getspecific, error=%d", error);
3392 # ifdef I_MACH_CTHREADS
3393 return (void*)cthread_data(cthread_self());
3395 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
3404 Perl_set_context(void *t)
3406 #if defined(USE_ITHREADS)
3409 PERL_ARGS_ASSERT_SET_CONTEXT;
3410 #if defined(USE_ITHREADS)
3411 # ifdef I_MACH_CTHREADS
3412 cthread_set_data(cthread_self(), t);
3415 const int error = pthread_setspecific(PL_thr_key, t);
3417 Perl_croak_nocontext("panic: pthread_setspecific, error=%d", error);
3425 #endif /* !PERL_GET_CONTEXT_DEFINED */
3427 #if defined(PERL_GLOBAL_STRUCT) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
3431 PERL_UNUSED_CONTEXT;
3437 Perl_get_op_names(pTHX)
3439 PERL_UNUSED_CONTEXT;
3440 return (char **)PL_op_name;
3444 Perl_get_op_descs(pTHX)
3446 PERL_UNUSED_CONTEXT;
3447 return (char **)PL_op_desc;
3451 Perl_get_no_modify(pTHX)
3453 PERL_UNUSED_CONTEXT;
3454 return PL_no_modify;
3458 Perl_get_opargs(pTHX)
3460 PERL_UNUSED_CONTEXT;
3461 return (U32 *)PL_opargs;
3465 Perl_get_ppaddr(pTHX)
3468 PERL_UNUSED_CONTEXT;
3469 return (PPADDR_t*)PL_ppaddr;
3472 #ifndef HAS_GETENV_LEN
3474 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3476 char * const env_trans = PerlEnv_getenv(env_elem);
3477 PERL_UNUSED_CONTEXT;
3478 PERL_ARGS_ASSERT_GETENV_LEN;
3480 *len = strlen(env_trans);
3487 Perl_get_vtbl(pTHX_ int vtbl_id)
3489 PERL_UNUSED_CONTEXT;
3491 return (vtbl_id < 0 || vtbl_id >= magic_vtable_max)
3492 ? NULL : (MGVTBL*)PL_magic_vtables + vtbl_id;
3496 Perl_my_fflush_all(pTHX)
3498 #if defined(USE_PERLIO) || defined(FFLUSH_NULL)
3499 return PerlIO_flush(NULL);
3501 # if defined(HAS__FWALK)
3502 extern int fflush(FILE *);
3503 /* undocumented, unprototyped, but very useful BSDism */
3504 extern void _fwalk(int (*)(FILE *));
3508 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3510 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3511 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3513 # if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3514 open_max = sysconf(_SC_OPEN_MAX);
3517 open_max = FOPEN_MAX;
3520 open_max = OPEN_MAX;
3531 for (i = 0; i < open_max; i++)
3532 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3533 STDIO_STREAM_ARRAY[i]._file < open_max &&
3534 STDIO_STREAM_ARRAY[i]._flag)
3535 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3539 SETERRNO(EBADF,RMS_IFI);
3546 Perl_report_wrongway_fh(pTHX_ const GV *gv, const char have)
3548 if (ckWARN(WARN_IO)) {
3550 = gv && (isGV_with_GP(gv))
3553 const char * const direction = have == '>' ? "out" : "in";
3555 if (name && HEK_LEN(name))
3556 Perl_warner(aTHX_ packWARN(WARN_IO),
3557 "Filehandle %"HEKf" opened only for %sput",
3558 HEKfARG(name), direction);
3560 Perl_warner(aTHX_ packWARN(WARN_IO),
3561 "Filehandle opened only for %sput", direction);
3566 Perl_report_evil_fh(pTHX_ const GV *gv)
3568 const IO *io = gv ? GvIO(gv) : NULL;
3569 const PERL_BITFIELD16 op = PL_op->op_type;
3573 if (io && IoTYPE(io) == IoTYPE_CLOSED) {
3575 warn_type = WARN_CLOSED;
3579 warn_type = WARN_UNOPENED;
3582 if (ckWARN(warn_type)) {
3584 = gv && isGV_with_GP(gv) && GvENAMELEN(gv) ?
3585 sv_2mortal(newSVhek(GvENAME_HEK(gv))) : NULL;
3586 const char * const pars =
3587 (const char *)(OP_IS_FILETEST(op) ? "" : "()");
3588 const char * const func =
3590 (op == OP_READLINE || op == OP_RCATLINE
3591 ? "readline" : /* "<HANDLE>" not nice */
3592 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
3594 const char * const type =
3596 (OP_IS_SOCKET(op) || (io && IoTYPE(io) == IoTYPE_SOCKET)
3597 ? "socket" : "filehandle");
3598 const bool have_name = name && SvCUR(name);
3599 Perl_warner(aTHX_ packWARN(warn_type),
3600 "%s%s on %s %s%s%"SVf, func, pars, vile, type,
3601 have_name ? " " : "",
3602 SVfARG(have_name ? name : &PL_sv_no));
3603 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3605 aTHX_ packWARN(warn_type),
3606 "\t(Are you trying to call %s%s on dirhandle%s%"SVf"?)\n",
3607 func, pars, have_name ? " " : "",
3608 SVfARG(have_name ? name : &PL_sv_no)
3613 /* To workaround core dumps from the uninitialised tm_zone we get the
3614 * system to give us a reasonable struct to copy. This fix means that
3615 * strftime uses the tm_zone and tm_gmtoff values returned by
3616 * localtime(time()). That should give the desired result most of the
3617 * time. But probably not always!
3619 * This does not address tzname aspects of NETaa14816.
3624 # ifndef STRUCT_TM_HASZONE
3625 # define STRUCT_TM_HASZONE
3629 #ifdef STRUCT_TM_HASZONE /* Backward compat */
3630 # ifndef HAS_TM_TM_ZONE
3631 # define HAS_TM_TM_ZONE
3636 Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
3638 #ifdef HAS_TM_TM_ZONE
3640 const struct tm* my_tm;
3641 PERL_UNUSED_CONTEXT;
3642 PERL_ARGS_ASSERT_INIT_TM;
3644 my_tm = localtime(&now);
3646 Copy(my_tm, ptm, 1, struct tm);
3648 PERL_UNUSED_CONTEXT;
3649 PERL_ARGS_ASSERT_INIT_TM;
3650 PERL_UNUSED_ARG(ptm);
3655 * mini_mktime - normalise struct tm values without the localtime()
3656 * semantics (and overhead) of mktime().
3659 Perl_mini_mktime(struct tm *ptm)
3663 int month, mday, year, jday;
3664 int odd_cent, odd_year;
3666 PERL_ARGS_ASSERT_MINI_MKTIME;
3668 #define DAYS_PER_YEAR 365
3669 #define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
3670 #define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
3671 #define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
3672 #define SECS_PER_HOUR (60*60)
3673 #define SECS_PER_DAY (24*SECS_PER_HOUR)
3674 /* parentheses deliberately absent on these two, otherwise they don't work */
3675 #define MONTH_TO_DAYS 153/5
3676 #define DAYS_TO_MONTH 5/153
3677 /* offset to bias by March (month 4) 1st between month/mday & year finding */
3678 #define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
3679 /* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
3680 #define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
3683 * Year/day algorithm notes:
3685 * With a suitable offset for numeric value of the month, one can find
3686 * an offset into the year by considering months to have 30.6 (153/5) days,
3687 * using integer arithmetic (i.e., with truncation). To avoid too much
3688 * messing about with leap days, we consider January and February to be
3689 * the 13th and 14th month of the previous year. After that transformation,
3690 * we need the month index we use to be high by 1 from 'normal human' usage,
3691 * so the month index values we use run from 4 through 15.
3693 * Given that, and the rules for the Gregorian calendar (leap years are those
3694 * divisible by 4 unless also divisible by 100, when they must be divisible
3695 * by 400 instead), we can simply calculate the number of days since some
3696 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
3697 * the days we derive from our month index, and adding in the day of the
3698 * month. The value used here is not adjusted for the actual origin which
3699 * it normally would use (1 January A.D. 1), since we're not exposing it.
3700 * We're only building the value so we can turn around and get the
3701 * normalised values for the year, month, day-of-month, and day-of-year.
3703 * For going backward, we need to bias the value we're using so that we find
3704 * the right year value. (Basically, we don't want the contribution of
3705 * March 1st to the number to apply while deriving the year). Having done
3706 * that, we 'count up' the contribution to the year number by accounting for
3707 * full quadracenturies (400-year periods) with their extra leap days, plus
3708 * the contribution from full centuries (to avoid counting in the lost leap
3709 * days), plus the contribution from full quad-years (to count in the normal
3710 * leap days), plus the leftover contribution from any non-leap years.
3711 * At this point, if we were working with an actual leap day, we'll have 0
3712 * days left over. This is also true for March 1st, however. So, we have
3713 * to special-case that result, and (earlier) keep track of the 'odd'
3714 * century and year contributions. If we got 4 extra centuries in a qcent,
3715 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
3716 * Otherwise, we add back in the earlier bias we removed (the 123 from
3717 * figuring in March 1st), find the month index (integer division by 30.6),
3718 * and the remainder is the day-of-month. We then have to convert back to
3719 * 'real' months (including fixing January and February from being 14/15 in
3720 * the previous year to being in the proper year). After that, to get
3721 * tm_yday, we work with the normalised year and get a new yearday value for
3722 * January 1st, which we subtract from the yearday value we had earlier,
3723 * representing the date we've re-built. This is done from January 1
3724 * because tm_yday is 0-origin.
3726 * Since POSIX time routines are only guaranteed to work for times since the
3727 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
3728 * applies Gregorian calendar rules even to dates before the 16th century
3729 * doesn't bother me. Besides, you'd need cultural context for a given
3730 * date to know whether it was Julian or Gregorian calendar, and that's
3731 * outside the scope for this routine. Since we convert back based on the
3732 * same rules we used to build the yearday, you'll only get strange results
3733 * for input which needed normalising, or for the 'odd' century years which
3734 * were leap years in the Julian calendar but not in the Gregorian one.
3735 * I can live with that.
3737 * This algorithm also fails to handle years before A.D. 1 gracefully, but
3738 * that's still outside the scope for POSIX time manipulation, so I don't
3742 year = 1900 + ptm->tm_year;
3743 month = ptm->tm_mon;
3744 mday = ptm->tm_mday;
3750 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
3751 yearday += month*MONTH_TO_DAYS + mday + jday;
3753 * Note that we don't know when leap-seconds were or will be,
3754 * so we have to trust the user if we get something which looks
3755 * like a sensible leap-second. Wild values for seconds will
3756 * be rationalised, however.
3758 if ((unsigned) ptm->tm_sec <= 60) {
3765 secs += 60 * ptm->tm_min;
3766 secs += SECS_PER_HOUR * ptm->tm_hour;
3768 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
3769 /* got negative remainder, but need positive time */
3770 /* back off an extra day to compensate */
3771 yearday += (secs/SECS_PER_DAY)-1;
3772 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
3775 yearday += (secs/SECS_PER_DAY);
3776 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
3779 else if (secs >= SECS_PER_DAY) {
3780 yearday += (secs/SECS_PER_DAY);
3781 secs %= SECS_PER_DAY;
3783 ptm->tm_hour = secs/SECS_PER_HOUR;
3784 secs %= SECS_PER_HOUR;
3785 ptm->tm_min = secs/60;
3787 ptm->tm_sec += secs;
3788 /* done with time of day effects */
3790 * The algorithm for yearday has (so far) left it high by 428.
3791 * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
3792 * bias it by 123 while trying to figure out what year it
3793 * really represents. Even with this tweak, the reverse
3794 * translation fails for years before A.D. 0001.
3795 * It would still fail for Feb 29, but we catch that one below.
3797 jday = yearday; /* save for later fixup vis-a-vis Jan 1 */
3798 yearday -= YEAR_ADJUST;
3799 year = (yearday / DAYS_PER_QCENT) * 400;
3800 yearday %= DAYS_PER_QCENT;
3801 odd_cent = yearday / DAYS_PER_CENT;
3802 year += odd_cent * 100;
3803 yearday %= DAYS_PER_CENT;
3804 year += (yearday / DAYS_PER_QYEAR) * 4;
3805 yearday %= DAYS_PER_QYEAR;
3806 odd_year = yearday / DAYS_PER_YEAR;
3808 yearday %= DAYS_PER_YEAR;
3809 if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
3814 yearday += YEAR_ADJUST; /* recover March 1st crock */
3815 month = yearday*DAYS_TO_MONTH;
3816 yearday -= month*MONTH_TO_DAYS;
3817 /* recover other leap-year adjustment */
3826 ptm->tm_year = year - 1900;
3828 ptm->tm_mday = yearday;
3829 ptm->tm_mon = month;
3833 ptm->tm_mon = month - 1;
3835 /* re-build yearday based on Jan 1 to get tm_yday */
3837 yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
3838 yearday += 14*MONTH_TO_DAYS + 1;
3839 ptm->tm_yday = jday - yearday;
3840 ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
3844 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)
3848 /* Note that yday and wday effectively are ignored by this function, as mini_mktime() overwrites them */
3855 PERL_ARGS_ASSERT_MY_STRFTIME;
3857 init_tm(&mytm); /* XXX workaround - see init_tm() above */
3860 mytm.tm_hour = hour;
3861 mytm.tm_mday = mday;
3863 mytm.tm_year = year;
3864 mytm.tm_wday = wday;
3865 mytm.tm_yday = yday;
3866 mytm.tm_isdst = isdst;
3868 /* use libc to get the values for tm_gmtoff and tm_zone [perl #18238] */
3869 #if defined(HAS_MKTIME) && (defined(HAS_TM_TM_GMTOFF) || defined(HAS_TM_TM_ZONE))
3874 #ifdef HAS_TM_TM_GMTOFF
3875 mytm.tm_gmtoff = mytm2.tm_gmtoff;
3877 #ifdef HAS_TM_TM_ZONE
3878 mytm.tm_zone = mytm2.tm_zone;
3883 Newx(buf, buflen, char);
3885 GCC_DIAG_IGNORE(-Wformat-nonliteral); /* fmt checked by caller */
3886 len = strftime(buf, buflen, fmt, &mytm);
3890 ** The following is needed to handle to the situation where
3891 ** tmpbuf overflows. Basically we want to allocate a buffer
3892 ** and try repeatedly. The reason why it is so complicated
3893 ** is that getting a return value of 0 from strftime can indicate
3894 ** one of the following:
3895 ** 1. buffer overflowed,
3896 ** 2. illegal conversion specifier, or
3897 ** 3. the format string specifies nothing to be returned(not
3898 ** an error). This could be because format is an empty string
3899 ** or it specifies %p that yields an empty string in some locale.
3900 ** If there is a better way to make it portable, go ahead by
3903 if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
3906 /* Possibly buf overflowed - try again with a bigger buf */
3907 const int fmtlen = strlen(fmt);
3908 int bufsize = fmtlen + buflen;
3910 Renew(buf, bufsize, char);
3913 GCC_DIAG_IGNORE(-Wformat-nonliteral); /* fmt checked by caller */
3914 buflen = strftime(buf, bufsize, fmt, &mytm);
3917 if (buflen > 0 && buflen < bufsize)
3919 /* heuristic to prevent out-of-memory errors */
3920 if (bufsize > 100*fmtlen) {
3926 Renew(buf, bufsize, char);
3931 Perl_croak(aTHX_ "panic: no strftime");
3937 #define SV_CWD_RETURN_UNDEF \
3938 sv_setsv(sv, &PL_sv_undef); \
3941 #define SV_CWD_ISDOT(dp) \
3942 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
3943 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
3946 =head1 Miscellaneous Functions
3948 =for apidoc getcwd_sv
3950 Fill the sv with current working directory
3955 /* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
3956 * rewritten again by dougm, optimized for use with xs TARG, and to prefer
3957 * getcwd(3) if available
3958 * Comments from the original:
3959 * This is a faster version of getcwd. It's also more dangerous
3960 * because you might chdir out of a directory that you can't chdir
3964 Perl_getcwd_sv(pTHX_ SV *sv)
3969 PERL_ARGS_ASSERT_GETCWD_SV;
3973 char buf[MAXPATHLEN];
3975 /* Some getcwd()s automatically allocate a buffer of the given
3976 * size from the heap if they are given a NULL buffer pointer.
3977 * The problem is that this behaviour is not portable. */
3978 if (getcwd(buf, sizeof(buf) - 1)) {
3983 sv_setsv(sv, &PL_sv_undef);
3991 int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
3995 SvUPGRADE(sv, SVt_PV);
3997 if (PerlLIO_lstat(".", &statbuf) < 0) {
3998 SV_CWD_RETURN_UNDEF;
4001 orig_cdev = statbuf.st_dev;
4002 orig_cino = statbuf.st_ino;
4012 if (PerlDir_chdir("..") < 0) {
4013 SV_CWD_RETURN_UNDEF;
4015 if (PerlLIO_stat(".", &statbuf) < 0) {
4016 SV_CWD_RETURN_UNDEF;
4019 cdev = statbuf.st_dev;
4020 cino = statbuf.st_ino;
4022 if (odev == cdev && oino == cino) {
4025 if (!(dir = PerlDir_open("."))) {
4026 SV_CWD_RETURN_UNDEF;
4029 while ((dp = PerlDir_read(dir)) != NULL) {
4031 namelen = dp->d_namlen;
4033 namelen = strlen(dp->d_name);
4036 if (SV_CWD_ISDOT(dp)) {
4040 if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
4041 SV_CWD_RETURN_UNDEF;
4044 tdev = statbuf.st_dev;
4045 tino = statbuf.st_ino;
4046 if (tino == oino && tdev == odev) {
4052 SV_CWD_RETURN_UNDEF;
4055 if (pathlen + namelen + 1 >= MAXPATHLEN) {
4056 SV_CWD_RETURN_UNDEF;
4059 SvGROW(sv, pathlen + namelen + 1);
4063 Move(SvPVX_const(sv), SvPVX(sv) + namelen + 1, pathlen, char);
4066 /* prepend current directory to the front */
4068 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
4069 pathlen += (namelen + 1);
4071 #ifdef VOID_CLOSEDIR
4074 if (PerlDir_close(dir) < 0) {
4075 SV_CWD_RETURN_UNDEF;
4081 SvCUR_set(sv, pathlen);
4085 if (PerlDir_chdir(SvPVX_const(sv)) < 0) {
4086 SV_CWD_RETURN_UNDEF;
4089 if (PerlLIO_stat(".", &statbuf) < 0) {
4090 SV_CWD_RETURN_UNDEF;
4093 cdev = statbuf.st_dev;
4094 cino = statbuf.st_ino;
4096 if (cdev != orig_cdev || cino != orig_cino) {
4097 Perl_croak(aTHX_ "Unstable directory path, "
4098 "current directory changed unexpectedly");
4111 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET) && defined(SOCK_DGRAM) && defined(HAS_SELECT)
4112 # define EMULATE_SOCKETPAIR_UDP
4115 #ifdef EMULATE_SOCKETPAIR_UDP
4117 S_socketpair_udp (int fd[2]) {
4119 /* Fake a datagram socketpair using UDP to localhost. */
4120 int sockets[2] = {-1, -1};
4121 struct sockaddr_in addresses[2];
4123 Sock_size_t size = sizeof(struct sockaddr_in);
4124 unsigned short port;
4127 memset(&addresses, 0, sizeof(addresses));
4130 sockets[i] = PerlSock_socket(AF_INET, SOCK_DGRAM, PF_INET);
4131 if (sockets[i] == -1)
4132 goto tidy_up_and_fail;
4134 addresses[i].sin_family = AF_INET;
4135 addresses[i].sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4136 addresses[i].sin_port = 0; /* kernel choses port. */
4137 if (PerlSock_bind(sockets[i], (struct sockaddr *) &addresses[i],
4138 sizeof(struct sockaddr_in)) == -1)
4139 goto tidy_up_and_fail;
4142 /* Now have 2 UDP sockets. Find out which port each is connected to, and
4143 for each connect the other socket to it. */
4146 if (PerlSock_getsockname(sockets[i], (struct sockaddr *) &addresses[i],
4148 goto tidy_up_and_fail;
4149 if (size != sizeof(struct sockaddr_in))
4150 goto abort_tidy_up_and_fail;
4151 /* !1 is 0, !0 is 1 */
4152 if (PerlSock_connect(sockets[!i], (struct sockaddr *) &addresses[i],
4153 sizeof(struct sockaddr_in)) == -1)
4154 goto tidy_up_and_fail;
4157 /* Now we have 2 sockets connected to each other. I don't trust some other
4158 process not to have already sent a packet to us (by random) so send
4159 a packet from each to the other. */
4162 /* I'm going to send my own port number. As a short.
4163 (Who knows if someone somewhere has sin_port as a bitfield and needs
4164 this routine. (I'm assuming crays have socketpair)) */
4165 port = addresses[i].sin_port;
4166 got = PerlLIO_write(sockets[i], &port, sizeof(port));
4167 if (got != sizeof(port)) {
4169 goto tidy_up_and_fail;
4170 goto abort_tidy_up_and_fail;
4174 /* Packets sent. I don't trust them to have arrived though.
4175 (As I understand it Solaris TCP stack is multithreaded. Non-blocking
4176 connect to localhost will use a second kernel thread. In 2.6 the
4177 first thread running the connect() returns before the second completes,
4178 so EINPROGRESS> In 2.7 the improved stack is faster and connect()
4179 returns 0. Poor programs have tripped up. One poor program's authors'
4180 had a 50-1 reverse stock split. Not sure how connected these were.)
4181 So I don't trust someone not to have an unpredictable UDP stack.
4185 struct timeval waitfor = {0, 100000}; /* You have 0.1 seconds */
4186 int max = sockets[1] > sockets[0] ? sockets[1] : sockets[0];
4190 FD_SET((unsigned int)sockets[0], &rset);
4191 FD_SET((unsigned int)sockets[1], &rset);
4193 got = PerlSock_select(max + 1, &rset, NULL, NULL, &waitfor);
4194 if (got != 2 || !FD_ISSET(sockets[0], &rset)
4195 || !FD_ISSET(sockets[1], &rset)) {
4196 /* I hope this is portable and appropriate. */
4198 goto tidy_up_and_fail;
4199 goto abort_tidy_up_and_fail;
4203 /* And the paranoia department even now doesn't trust it to have arrive
4204 (hence MSG_DONTWAIT). Or that what arrives was sent by us. */
4206 struct sockaddr_in readfrom;
4207 unsigned short buffer[2];
4212 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4213 sizeof(buffer), MSG_DONTWAIT,
4214 (struct sockaddr *) &readfrom, &size);
4216 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4218 (struct sockaddr *) &readfrom, &size);
4222 goto tidy_up_and_fail;
4223 if (got != sizeof(port)
4224 || size != sizeof(struct sockaddr_in)
4225 /* Check other socket sent us its port. */
4226 || buffer[0] != (unsigned short) addresses[!i].sin_port
4227 /* Check kernel says we got the datagram from that socket */
4228 || readfrom.sin_family != addresses[!i].sin_family
4229 || readfrom.sin_addr.s_addr != addresses[!i].sin_addr.s_addr
4230 || readfrom.sin_port != addresses[!i].sin_port)
4231 goto abort_tidy_up_and_fail;
4234 /* My caller (my_socketpair) has validated that this is non-NULL */
4237 /* I hereby declare this connection open. May God bless all who cross
4241 abort_tidy_up_and_fail:
4242 errno = ECONNABORTED;
4246 if (sockets[0] != -1)
4247 PerlLIO_close(sockets[0]);
4248 if (sockets[1] != -1)
4249 PerlLIO_close(sockets[1]);
4254 #endif /* EMULATE_SOCKETPAIR_UDP */
4256 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET)
4258 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4259 /* Stevens says that family must be AF_LOCAL, protocol 0.
4260 I'm going to enforce that, then ignore it, and use TCP (or UDP). */
4265 struct sockaddr_in listen_addr;
4266 struct sockaddr_in connect_addr;
4271 || family != AF_UNIX
4274 errno = EAFNOSUPPORT;
4282 #ifdef EMULATE_SOCKETPAIR_UDP
4283 if (type == SOCK_DGRAM)
4284 return S_socketpair_udp(fd);
4287 aTHXa(PERL_GET_THX);
4288 listener = PerlSock_socket(AF_INET, type, 0);
4291 memset(&listen_addr, 0, sizeof(listen_addr));
4292 listen_addr.sin_family = AF_INET;
4293 listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4294 listen_addr.sin_port = 0; /* kernel choses port. */
4295 if (PerlSock_bind(listener, (struct sockaddr *) &listen_addr,
4296 sizeof(listen_addr)) == -1)
4297 goto tidy_up_and_fail;
4298 if (PerlSock_listen(listener, 1) == -1)
4299 goto tidy_up_and_fail;
4301 connector = PerlSock_socket(AF_INET, type, 0);
4302 if (connector == -1)
4303 goto tidy_up_and_fail;
4304 /* We want to find out the port number to connect to. */
4305 size = sizeof(connect_addr);
4306 if (PerlSock_getsockname(listener, (struct sockaddr *) &connect_addr,
4308 goto tidy_up_and_fail;
4309 if (size != sizeof(connect_addr))
4310 goto abort_tidy_up_and_fail;
4311 if (PerlSock_connect(connector, (struct sockaddr *) &connect_addr,
4312 sizeof(connect_addr)) == -1)
4313 goto tidy_up_and_fail;
4315 size = sizeof(listen_addr);
4316 acceptor = PerlSock_accept(listener, (struct sockaddr *) &listen_addr,
4319 goto tidy_up_and_fail;
4320 if (size != sizeof(listen_addr))
4321 goto abort_tidy_up_and_fail;
4322 PerlLIO_close(listener);
4323 /* Now check we are talking to ourself by matching port and host on the
4325 if (PerlSock_getsockname(connector, (struct sockaddr *) &connect_addr,
4327 goto tidy_up_and_fail;
4328 if (size != sizeof(connect_addr)
4329 || listen_addr.sin_family != connect_addr.sin_family
4330 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
4331 || listen_addr.sin_port != connect_addr.sin_port) {
4332 goto abort_tidy_up_and_fail;
4338 abort_tidy_up_and_fail:
4340 errno = ECONNABORTED; /* This would be the standard thing to do. */
4342 # ifdef ECONNREFUSED
4343 errno = ECONNREFUSED; /* E.g. Symbian does not have ECONNABORTED. */
4345 errno = ETIMEDOUT; /* Desperation time. */
4352 PerlLIO_close(listener);
4353 if (connector != -1)
4354 PerlLIO_close(connector);
4356 PerlLIO_close(acceptor);
4362 /* In any case have a stub so that there's code corresponding
4363 * to the my_socketpair in embed.fnc. */
4365 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4366 #ifdef HAS_SOCKETPAIR
4367 return socketpair(family, type, protocol, fd);
4376 =for apidoc sv_nosharing
4378 Dummy routine which "shares" an SV when there is no sharing module present.
4379 Or "locks" it. Or "unlocks" it. In other
4380 words, ignores its single SV argument.
4381 Exists to avoid test for a NULL function pointer and because it could
4382 potentially warn under some level of strict-ness.
4388 Perl_sv_nosharing(pTHX_ SV *sv)
4390 PERL_UNUSED_CONTEXT;
4391 PERL_UNUSED_ARG(sv);
4396 =for apidoc sv_destroyable
4398 Dummy routine which reports that object can be destroyed when there is no
4399 sharing module present. It ignores its single SV argument, and returns
4400 'true'. Exists to avoid test for a NULL function pointer and because it
4401 could potentially warn under some level of strict-ness.
4407 Perl_sv_destroyable(pTHX_ SV *sv)
4409 PERL_UNUSED_CONTEXT;
4410 PERL_UNUSED_ARG(sv);
4415 Perl_parse_unicode_opts(pTHX_ const char **popt)
4417 const char *p = *popt;
4420 PERL_ARGS_ASSERT_PARSE_UNICODE_OPTS;
4426 if (grok_atoUV(p, &uv, &endptr) && uv <= U32_MAX) {
4429 if (p && *p && *p != '\n' && *p != '\r') {
4431 goto the_end_of_the_opts_parser;
4433 Perl_croak(aTHX_ "Unknown Unicode option letter '%c'", *p);
4440 case PERL_UNICODE_STDIN:
4441 opt |= PERL_UNICODE_STDIN_FLAG; break;
4442 case PERL_UNICODE_STDOUT:
4443 opt |= PERL_UNICODE_STDOUT_FLAG; break;
4444 case PERL_UNICODE_STDERR:
4445 opt |= PERL_UNICODE_STDERR_FLAG; break;
4446 case PERL_UNICODE_STD:
4447 opt |= PERL_UNICODE_STD_FLAG; break;
4448 case PERL_UNICODE_IN:
4449 opt |= PERL_UNICODE_IN_FLAG; break;
4450 case PERL_UNICODE_OUT:
4451 opt |= PERL_UNICODE_OUT_FLAG; break;
4452 case PERL_UNICODE_INOUT:
4453 opt |= PERL_UNICODE_INOUT_FLAG; break;
4454 case PERL_UNICODE_LOCALE:
4455 opt |= PERL_UNICODE_LOCALE_FLAG; break;
4456 case PERL_UNICODE_ARGV:
4457 opt |= PERL_UNICODE_ARGV_FLAG; break;
4458 case PERL_UNICODE_UTF8CACHEASSERT:
4459 opt |= PERL_UNICODE_UTF8CACHEASSERT_FLAG; break;
4461 if (*p != '\n' && *p != '\r') {
4462 if(isSPACE(*p)) goto the_end_of_the_opts_parser;
4465 "Unknown Unicode option letter '%c'", *p);
4472 opt = PERL_UNICODE_DEFAULT_FLAGS;
4474 the_end_of_the_opts_parser:
4476 if (opt & ~PERL_UNICODE_ALL_FLAGS)
4477 Perl_croak(aTHX_ "Unknown Unicode option value %"UVuf,
4478 (UV) (opt & ~PERL_UNICODE_ALL_FLAGS));
4486 # include <starlet.h>
4493 * This is really just a quick hack which grabs various garbage
4494 * values. It really should be a real hash algorithm which
4495 * spreads the effect of every input bit onto every output bit,
4496 * if someone who knows about such things would bother to write it.
4497 * Might be a good idea to add that function to CORE as well.
4498 * No numbers below come from careful analysis or anything here,
4499 * except they are primes and SEED_C1 > 1E6 to get a full-width
4500 * value from (tv_sec * SEED_C1 + tv_usec). The multipliers should
4501 * probably be bigger too.
4504 # define SEED_C1 1000003
4505 #define SEED_C4 73819
4507 # define SEED_C1 25747
4508 #define SEED_C4 20639
4512 #define SEED_C5 26107
4514 #ifndef PERL_NO_DEV_RANDOM
4518 #ifdef HAS_GETTIMEOFDAY
4519 struct timeval when;
4524 /* This test is an escape hatch, this symbol isn't set by Configure. */
4525 #ifndef PERL_NO_DEV_RANDOM
4526 #ifndef PERL_RANDOM_DEVICE
4527 /* /dev/random isn't used by default because reads from it will block
4528 * if there isn't enough entropy available. You can compile with
4529 * PERL_RANDOM_DEVICE to it if you'd prefer Perl to block until there
4530 * is enough real entropy to fill the seed. */
4531 # define PERL_RANDOM_DEVICE "/dev/urandom"
4533 fd = PerlLIO_open(PERL_RANDOM_DEVICE, 0);
4535 if (PerlLIO_read(fd, (void*)&u, sizeof u) != sizeof u)
4543 #ifdef HAS_GETTIMEOFDAY
4544 PerlProc_gettimeofday(&when,NULL);
4545 u = (U32)SEED_C1 * when.tv_sec + (U32)SEED_C2 * when.tv_usec;
4548 u = (U32)SEED_C1 * when;
4550 u += SEED_C3 * (U32)PerlProc_getpid();
4551 u += SEED_C4 * (U32)PTR2UV(PL_stack_sp);
4552 #ifndef PLAN9 /* XXX Plan9 assembler chokes on this; fix needed */
4553 u += SEED_C5 * (U32)PTR2UV(&when);
4559 Perl_get_hash_seed(pTHX_ unsigned char * const seed_buffer)
4564 PERL_ARGS_ASSERT_GET_HASH_SEED;
4566 env_pv= PerlEnv_getenv("PERL_HASH_SEED");
4569 #ifndef USE_HASH_SEED_EXPLICIT
4571 /* ignore leading spaces */
4572 while (isSPACE(*env_pv))
4574 #ifdef USE_PERL_PERTURB_KEYS
4575 /* if they set it to "0" we disable key traversal randomization completely */
4576 if (strEQ(env_pv,"0")) {
4577 PL_hash_rand_bits_enabled= 0;
4579 /* otherwise switch to deterministic mode */
4580 PL_hash_rand_bits_enabled= 2;
4583 /* ignore a leading 0x... if it is there */
4584 if (env_pv[0] == '0' && env_pv[1] == 'x')
4587 for( i = 0; isXDIGIT(*env_pv) && i < PERL_HASH_SEED_BYTES; i++ ) {
4588 seed_buffer[i] = READ_XDIGIT(env_pv) << 4;
4589 if ( isXDIGIT(*env_pv)) {
4590 seed_buffer[i] |= READ_XDIGIT(env_pv);
4593 while (isSPACE(*env_pv))
4596 if (*env_pv && !isXDIGIT(*env_pv)) {
4597 Perl_warn(aTHX_ "perl: warning: Non hex character in '$ENV{PERL_HASH_SEED}', seed only partially set\n");
4599 /* should we check for unparsed crap? */
4600 /* should we warn about unused hex? */
4601 /* should we warn about insufficient hex? */
4606 (void)seedDrand01((Rand_seed_t)seed());
4608 for( i = 0; i < PERL_HASH_SEED_BYTES; i++ ) {
4609 seed_buffer[i] = (unsigned char)(Drand01() * (U8_MAX+1));
4612 #ifdef USE_PERL_PERTURB_KEYS
4613 { /* initialize PL_hash_rand_bits from the hash seed.
4614 * This value is highly volatile, it is updated every
4615 * hash insert, and is used as part of hash bucket chain
4616 * randomization and hash iterator randomization. */
4617 PL_hash_rand_bits= 0xbe49d17f; /* I just picked a number */
4618 for( i = 0; i < sizeof(UV) ; i++ ) {
4619 PL_hash_rand_bits += seed_buffer[i % PERL_HASH_SEED_BYTES];
4620 PL_hash_rand_bits = ROTL_UV(PL_hash_rand_bits,8);
4623 env_pv= PerlEnv_getenv("PERL_PERTURB_KEYS");
4625 if (strEQ(env_pv,"0") || strEQ(env_pv,"NO")) {
4626 PL_hash_rand_bits_enabled= 0;
4627 } else if (strEQ(env_pv,"1") || strEQ(env_pv,"RANDOM")) {
4628 PL_hash_rand_bits_enabled= 1;
4629 } else if (strEQ(env_pv,"2") || strEQ(env_pv,"DETERMINISTIC")) {
4630 PL_hash_rand_bits_enabled= 2;
4632 Perl_warn(aTHX_ "perl: warning: strange setting in '$ENV{PERL_PERTURB_KEYS}': '%s'\n", env_pv);
4638 #ifdef PERL_GLOBAL_STRUCT
4640 #define PERL_GLOBAL_STRUCT_INIT
4641 #include "opcode.h" /* the ppaddr and check */
4644 Perl_init_global_struct(pTHX)
4646 struct perl_vars *plvarsp = NULL;
4647 # ifdef PERL_GLOBAL_STRUCT
4648 const IV nppaddr = C_ARRAY_LENGTH(Gppaddr);
4649 const IV ncheck = C_ARRAY_LENGTH(Gcheck);
4650 PERL_UNUSED_CONTEXT;
4651 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
4652 /* PerlMem_malloc() because can't use even safesysmalloc() this early. */
4653 plvarsp = (struct perl_vars*)PerlMem_malloc(sizeof(struct perl_vars));
4657 plvarsp = PL_VarsPtr;
4658 # endif /* PERL_GLOBAL_STRUCT_PRIVATE */
4663 # define PERLVAR(prefix,var,type) /**/
4664 # define PERLVARA(prefix,var,n,type) /**/
4665 # define PERLVARI(prefix,var,type,init) plvarsp->prefix##var = init;
4666 # define PERLVARIC(prefix,var,type,init) plvarsp->prefix##var = init;
4667 # include "perlvars.h"
4672 # ifdef PERL_GLOBAL_STRUCT
4675 PerlMem_malloc(nppaddr * sizeof(Perl_ppaddr_t));
4676 if (!plvarsp->Gppaddr)
4680 PerlMem_malloc(ncheck * sizeof(Perl_check_t));
4681 if (!plvarsp->Gcheck)
4683 Copy(Gppaddr, plvarsp->Gppaddr, nppaddr, Perl_ppaddr_t);
4684 Copy(Gcheck, plvarsp->Gcheck, ncheck, Perl_check_t);
4686 # ifdef PERL_SET_VARS
4687 PERL_SET_VARS(plvarsp);
4689 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
4690 plvarsp->Gsv_placeholder.sv_flags = 0;
4691 memset(plvarsp->Ghash_seed, 0, sizeof(plvarsp->Ghash_seed));
4693 # undef PERL_GLOBAL_STRUCT_INIT
4698 #endif /* PERL_GLOBAL_STRUCT */
4700 #ifdef PERL_GLOBAL_STRUCT
4703 Perl_free_global_struct(pTHX_ struct perl_vars *plvarsp)
4705 int veto = plvarsp->Gveto_cleanup;
4707 PERL_ARGS_ASSERT_FREE_GLOBAL_STRUCT;
4708 PERL_UNUSED_CONTEXT;
4709 # ifdef PERL_GLOBAL_STRUCT
4710 # ifdef PERL_UNSET_VARS
4711 PERL_UNSET_VARS(plvarsp);
4715 free(plvarsp->Gppaddr);
4716 free(plvarsp->Gcheck);
4717 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
4723 #endif /* PERL_GLOBAL_STRUCT */
4727 /* -DPERL_MEM_LOG: the Perl_mem_log_..() is compiled, including
4728 * the default implementation, unless -DPERL_MEM_LOG_NOIMPL is also
4729 * given, and you supply your own implementation.
4731 * The default implementation reads a single env var, PERL_MEM_LOG,
4732 * expecting one or more of the following:
4734 * \d+ - fd fd to write to : must be 1st (grok_atoUV)
4735 * 'm' - memlog was PERL_MEM_LOG=1
4736 * 's' - svlog was PERL_SV_LOG=1
4737 * 't' - timestamp was PERL_MEM_LOG_TIMESTAMP=1
4739 * This makes the logger controllable enough that it can reasonably be
4740 * added to the system perl.
4743 /* -DPERL_MEM_LOG_SPRINTF_BUF_SIZE=X: size of a (stack-allocated) buffer
4744 * the Perl_mem_log_...() will use (either via sprintf or snprintf).
4746 #define PERL_MEM_LOG_SPRINTF_BUF_SIZE 128
4748 /* -DPERL_MEM_LOG_FD=N: the file descriptor the Perl_mem_log_...()
4749 * writes to. In the default logger, this is settable at runtime.
4751 #ifndef PERL_MEM_LOG_FD
4752 # define PERL_MEM_LOG_FD 2 /* If STDERR is too boring for you. */
4755 #ifndef PERL_MEM_LOG_NOIMPL
4757 # ifdef DEBUG_LEAKING_SCALARS
4758 # define SV_LOG_SERIAL_FMT " [%lu]"
4759 # define _SV_LOG_SERIAL_ARG(sv) , (unsigned long) (sv)->sv_debug_serial
4761 # define SV_LOG_SERIAL_FMT
4762 # define _SV_LOG_SERIAL_ARG(sv)
4766 S_mem_log_common(enum mem_log_type mlt, const UV n,
4767 const UV typesize, const char *type_name, const SV *sv,
4768 Malloc_t oldalloc, Malloc_t newalloc,
4769 const char *filename, const int linenumber,
4770 const char *funcname)
4774 PERL_ARGS_ASSERT_MEM_LOG_COMMON;
4776 pmlenv = PerlEnv_getenv("PERL_MEM_LOG");
4779 if (mlt < MLT_NEW_SV ? strchr(pmlenv,'m') : strchr(pmlenv,'s'))
4781 /* We can't use SVs or PerlIO for obvious reasons,
4782 * so we'll use stdio and low-level IO instead. */
4783 char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
4785 # ifdef HAS_GETTIMEOFDAY
4786 # define MEM_LOG_TIME_FMT "%10d.%06d: "
4787 # define MEM_LOG_TIME_ARG (int)tv.tv_sec, (int)tv.tv_usec
4789 gettimeofday(&tv, 0);
4791 # define MEM_LOG_TIME_FMT "%10d: "
4792 # define MEM_LOG_TIME_ARG (int)when
4796 /* If there are other OS specific ways of hires time than
4797 * gettimeofday() (see ext/Time-HiRes), the easiest way is
4798 * probably that they would be used to fill in the struct
4805 if (grok_atoUV(pmlenv, &uv, &endptr) /* Ignore endptr. */
4806 && uv && uv <= PERL_INT_MAX
4810 fd = PERL_MEM_LOG_FD;
4813 if (strchr(pmlenv, 't')) {
4814 len = my_snprintf(buf, sizeof(buf),
4815 MEM_LOG_TIME_FMT, MEM_LOG_TIME_ARG);
4816 PERL_UNUSED_RESULT(PerlLIO_write(fd, buf, len));
4820 len = my_snprintf(buf, sizeof(buf),
4821 "alloc: %s:%d:%s: %"IVdf" %"UVuf
4822 " %s = %"IVdf": %"UVxf"\n",
4823 filename, linenumber, funcname, n, typesize,
4824 type_name, n * typesize, PTR2UV(newalloc));
4827 len = my_snprintf(buf, sizeof(buf),
4828 "realloc: %s:%d:%s: %"IVdf" %"UVuf
4829 " %s = %"IVdf": %"UVxf" -> %"UVxf"\n",
4830 filename, linenumber, funcname, n, typesize,
4831 type_name, n * typesize, PTR2UV(oldalloc),
4835 len = my_snprintf(buf, sizeof(buf),
4836 "free: %s:%d:%s: %"UVxf"\n",
4837 filename, linenumber, funcname,
4842 len = my_snprintf(buf, sizeof(buf),
4843 "%s_SV: %s:%d:%s: %"UVxf SV_LOG_SERIAL_FMT "\n",
4844 mlt == MLT_NEW_SV ? "new" : "del",
4845 filename, linenumber, funcname,
4846 PTR2UV(sv) _SV_LOG_SERIAL_ARG(sv));
4851 PERL_UNUSED_RESULT(PerlLIO_write(fd, buf, len));
4855 #endif /* !PERL_MEM_LOG_NOIMPL */
4857 #ifndef PERL_MEM_LOG_NOIMPL
4859 mem_log_common_if(alty, num, tysz, tynm, sv, oal, nal, flnm, ln, fnnm) \
4860 mem_log_common (alty, num, tysz, tynm, sv, oal, nal, flnm, ln, fnnm)
4862 /* this is suboptimal, but bug compatible. User is providing their
4863 own implementation, but is getting these functions anyway, and they
4864 do nothing. But _NOIMPL users should be able to cope or fix */
4866 mem_log_common_if(alty, num, tysz, tynm, u, oal, nal, flnm, ln, fnnm) \
4867 /* mem_log_common_if_PERL_MEM_LOG_NOIMPL */
4871 Perl_mem_log_alloc(const UV n, const UV typesize, const char *type_name,
4873 const char *filename, const int linenumber,
4874 const char *funcname)
4876 mem_log_common_if(MLT_ALLOC, n, typesize, type_name,
4877 NULL, NULL, newalloc,
4878 filename, linenumber, funcname);
4883 Perl_mem_log_realloc(const UV n, const UV typesize, const char *type_name,
4884 Malloc_t oldalloc, Malloc_t newalloc,
4885 const char *filename, const int linenumber,
4886 const char *funcname)
4888 mem_log_common_if(MLT_REALLOC, n, typesize, type_name,
4889 NULL, oldalloc, newalloc,
4890 filename, linenumber, funcname);
4895 Perl_mem_log_free(Malloc_t oldalloc,
4896 const char *filename, const int linenumber,
4897 const char *funcname)
4899 mem_log_common_if(MLT_FREE, 0, 0, "", NULL, oldalloc, NULL,
4900 filename, linenumber, funcname);
4905 Perl_mem_log_new_sv(const SV *sv,
4906 const char *filename, const int linenumber,
4907 const char *funcname)
4909 mem_log_common_if(MLT_NEW_SV, 0, 0, "", sv, NULL, NULL,
4910 filename, linenumber, funcname);
4914 Perl_mem_log_del_sv(const SV *sv,
4915 const char *filename, const int linenumber,
4916 const char *funcname)
4918 mem_log_common_if(MLT_DEL_SV, 0, 0, "", sv, NULL, NULL,
4919 filename, linenumber, funcname);
4922 #endif /* PERL_MEM_LOG */
4925 =for apidoc my_sprintf
4927 The C library C<sprintf>, wrapped if necessary, to ensure that it will return
4928 the length of the string written to the buffer. Only rare pre-ANSI systems
4929 need the wrapper function - usually this is a direct call to C<sprintf>.
4933 #ifndef SPRINTF_RETURNS_STRLEN
4935 Perl_my_sprintf(char *buffer, const char* pat, ...)
4938 PERL_ARGS_ASSERT_MY_SPRINTF;
4939 va_start(args, pat);
4940 vsprintf(buffer, pat, args);
4942 return strlen(buffer);
4947 =for apidoc quadmath_format_single
4949 quadmath_snprintf() is very strict about its format string and will
4950 fail, returning -1, if the format is invalid. It acccepts exactly
4953 quadmath_format_single() checks that the intended single spec looks
4954 sane: begins with C<%>, has only one C<%>, ends with C<[efgaEFGA]>,
4955 and has C<Q> before it. This is not a full "printf syntax check",
4958 Returns the format if it is valid, NULL if not.
4960 quadmath_format_single() can and will actually patch in the missing
4961 C<Q>, if necessary. In this case it will return the modified copy of
4962 the format, B<which the caller will need to free.>
4964 See also L</quadmath_format_needed>.
4970 Perl_quadmath_format_single(const char* format)
4974 PERL_ARGS_ASSERT_QUADMATH_FORMAT_SINGLE;
4976 if (format[0] != '%' || strchr(format + 1, '%'))
4978 len = strlen(format);
4979 /* minimum length three: %Qg */
4980 if (len < 3 || strchr("efgaEFGA", format[len - 1]) == NULL)
4982 if (format[len - 2] != 'Q') {
4984 Newx(fixed, len + 1, char);
4985 memcpy(fixed, format, len - 1);
4986 fixed[len - 1] = 'Q';
4987 fixed[len ] = format[len - 1];
4989 return (const char*)fixed;
4996 =for apidoc quadmath_format_needed
4998 quadmath_format_needed() returns true if the format string seems to
4999 contain at least one non-Q-prefixed %[efgaEFGA] format specifier,
5000 or returns false otherwise.
5002 The format specifier detection is not complete printf-syntax detection,
5003 but it should catch most common cases.
5005 If true is returned, those arguments B<should> in theory be processed
5006 with quadmath_snprintf(), but in case there is more than one such
5007 format specifier (see L</quadmath_format_single>), and if there is
5008 anything else beyond that one (even just a single byte), they
5009 B<cannot> be processed because quadmath_snprintf() is very strict,
5010 accepting only one format spec, and nothing else.
5011 In this case, the code should probably fail.
5017 Perl_quadmath_format_needed(const char* format)
5019 const char *p = format;
5022 PERL_ARGS_ASSERT_QUADMATH_FORMAT_NEEDED;
5024 while ((q = strchr(p, '%'))) {
5026 if (*q == '+') /* plus */
5028 if (*q == '#') /* alt */
5030 if (*q == '*') /* width */
5034 while (isDIGIT(*q)) q++;
5037 if (*q == '.' && (q[1] == '*' || isDIGIT(q[1]))) { /* prec */
5042 while (isDIGIT(*q)) q++;
5044 if (strchr("efgaEFGA", *q)) /* Would have needed 'Q' in front. */
5053 =for apidoc my_snprintf
5055 The C library C<snprintf> functionality, if available and
5056 standards-compliant (uses C<vsnprintf>, actually). However, if the
5057 C<vsnprintf> is not available, will unfortunately use the unsafe
5058 C<vsprintf> which can overrun the buffer (there is an overrun check,
5059 but that may be too late). Consider using C<sv_vcatpvf> instead, or
5060 getting C<vsnprintf>.
5065 Perl_my_snprintf(char *buffer, const Size_t len, const char *format, ...)
5069 PERL_ARGS_ASSERT_MY_SNPRINTF;
5070 #ifndef HAS_VSNPRINTF
5071 PERL_UNUSED_VAR(len);
5073 va_start(ap, format);
5076 const char* qfmt = quadmath_format_single(format);
5077 bool quadmath_valid = FALSE;
5079 /* If the format looked promising, use it as quadmath. */
5080 retval = quadmath_snprintf(buffer, len, qfmt, va_arg(ap, NV));
5082 Perl_croak_nocontext("panic: quadmath_snprintf failed, format \"%s\"", qfmt);
5083 quadmath_valid = TRUE;
5088 assert(qfmt == NULL);
5089 /* quadmath_format_single() will return false for example for
5090 * "foo = %g", or simply "%g". We could handle the %g by
5091 * using quadmath for the NV args. More complex cases of
5092 * course exist: "foo = %g, bar = %g", or "foo=%Qg" (otherwise
5093 * quadmath-valid but has stuff in front).
5095 * Handling the "Q-less" cases right would require walking
5096 * through the va_list and rewriting the format, calling
5097 * quadmath for the NVs, building a new va_list, and then
5098 * letting vsnprintf/vsprintf to take care of the other
5099 * arguments. This may be doable.
5101 * We do not attempt that now. But for paranoia, we here try
5102 * to detect some common (but not all) cases where the
5103 * "Q-less" %[efgaEFGA] formats are present, and die if
5104 * detected. This doesn't fix the problem, but it stops the
5105 * vsnprintf/vsprintf pulling doubles off the va_list when
5106 * __float128 NVs should be pulled off instead.
5108 * If quadmath_format_needed() returns false, we are reasonably
5109 * certain that we can call vnsprintf() or vsprintf() safely. */
5110 if (!quadmath_valid && quadmath_format_needed(format))
5111 Perl_croak_nocontext("panic: quadmath_snprintf failed, format \"%s\"", format);
5116 #ifdef HAS_VSNPRINTF
5117 retval = vsnprintf(buffer, len, format, ap);
5119 retval = vsprintf(buffer, format, ap);
5122 /* vsprintf() shows failure with < 0 */
5124 #ifdef HAS_VSNPRINTF
5125 /* vsnprintf() shows failure with >= len */
5127 (len > 0 && (Size_t)retval >= len)
5130 Perl_croak_nocontext("panic: my_snprintf buffer overflow");
5135 =for apidoc my_vsnprintf
5137 The C library C<vsnprintf> if available and standards-compliant.
5138 However, if if the C<vsnprintf> is not available, will unfortunately
5139 use the unsafe C<vsprintf> which can overrun the buffer (there is an
5140 overrun check, but that may be too late). Consider using
5141 C<sv_vcatpvf> instead, or getting C<vsnprintf>.
5146 Perl_my_vsnprintf(char *buffer, const Size_t len, const char *format, va_list ap)
5149 PERL_UNUSED_ARG(buffer);
5150 PERL_UNUSED_ARG(len);
5151 PERL_UNUSED_ARG(format);
5152 PERL_UNUSED_ARG(ap);
5153 Perl_croak_nocontext("panic: my_vsnprintf not available with quadmath");
5160 PERL_ARGS_ASSERT_MY_VSNPRINTF;
5161 #ifndef HAS_VSNPRINTF
5162 PERL_UNUSED_VAR(len);
5164 Perl_va_copy(ap, apc);
5165 # ifdef HAS_VSNPRINTF
5166 retval = vsnprintf(buffer, len, format, apc);
5168 retval = vsprintf(buffer, format, apc);
5172 # ifdef HAS_VSNPRINTF
5173 retval = vsnprintf(buffer, len, format, ap);
5175 retval = vsprintf(buffer, format, ap);
5177 #endif /* #ifdef NEED_VA_COPY */
5178 /* vsprintf() shows failure with < 0 */
5180 #ifdef HAS_VSNPRINTF
5181 /* vsnprintf() shows failure with >= len */
5183 (len > 0 && (Size_t)retval >= len)
5186 Perl_croak_nocontext("panic: my_vsnprintf buffer overflow");
5192 Perl_my_clearenv(pTHX)
5195 #if ! defined(PERL_MICRO)
5196 # if defined(PERL_IMPLICIT_SYS) || defined(WIN32)
5198 # else /* ! (PERL_IMPLICIT_SYS || WIN32) */
5199 # if defined(USE_ENVIRON_ARRAY)
5200 # if defined(USE_ITHREADS)
5201 /* only the parent thread can clobber the process environment */
5202 if (PL_curinterp == aTHX)
5203 # endif /* USE_ITHREADS */
5205 # if ! defined(PERL_USE_SAFE_PUTENV)
5206 if ( !PL_use_safe_putenv) {
5208 if (environ == PL_origenviron)
5209 environ = (char**)safesysmalloc(sizeof(char*));
5211 for (i = 0; environ[i]; i++)
5212 (void)safesysfree(environ[i]);
5215 # else /* PERL_USE_SAFE_PUTENV */
5216 # if defined(HAS_CLEARENV)
5218 # elif defined(HAS_UNSETENV)
5219 int bsiz = 80; /* Most envvar names will be shorter than this. */
5220 char *buf = (char*)safesysmalloc(bsiz);
5221 while (*environ != NULL) {
5222 char *e = strchr(*environ, '=');
5223 int l = e ? e - *environ : (int)strlen(*environ);
5225 (void)safesysfree(buf);
5226 bsiz = l + 1; /* + 1 for the \0. */
5227 buf = (char*)safesysmalloc(bsiz);
5229 memcpy(buf, *environ, l);
5231 (void)unsetenv(buf);
5233 (void)safesysfree(buf);
5234 # else /* ! HAS_CLEARENV && ! HAS_UNSETENV */
5235 /* Just null environ and accept the leakage. */
5237 # endif /* HAS_CLEARENV || HAS_UNSETENV */
5238 # endif /* ! PERL_USE_SAFE_PUTENV */
5240 # endif /* USE_ENVIRON_ARRAY */
5241 # endif /* PERL_IMPLICIT_SYS || WIN32 */
5242 #endif /* PERL_MICRO */
5245 #ifdef PERL_IMPLICIT_CONTEXT
5247 /* Implements the MY_CXT_INIT macro. The first time a module is loaded,
5248 the global PL_my_cxt_index is incremented, and that value is assigned to
5249 that module's static my_cxt_index (who's address is passed as an arg).
5250 Then, for each interpreter this function is called for, it makes sure a
5251 void* slot is available to hang the static data off, by allocating or
5252 extending the interpreter's PL_my_cxt_list array */
5254 #ifndef PERL_GLOBAL_STRUCT_PRIVATE
5256 Perl_my_cxt_init(pTHX_ int *index, size_t size)
5260 PERL_ARGS_ASSERT_MY_CXT_INIT;
5262 /* this module hasn't been allocated an index yet */
5263 #if defined(USE_ITHREADS)
5264 MUTEX_LOCK(&PL_my_ctx_mutex);
5266 *index = PL_my_cxt_index++;
5267 #if defined(USE_ITHREADS)
5268 MUTEX_UNLOCK(&PL_my_ctx_mutex);
5272 /* make sure the array is big enough */
5273 if (PL_my_cxt_size <= *index) {
5274 if (PL_my_cxt_size) {
5275 while (PL_my_cxt_size <= *index)
5276 PL_my_cxt_size *= 2;
5277 Renew(PL_my_cxt_list, PL_my_cxt_size, void *);
5280 PL_my_cxt_size = 16;
5281 Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
5284 /* newSV() allocates one more than needed */
5285 p = (void*)SvPVX(newSV(size-1));
5286 PL_my_cxt_list[*index] = p;
5287 Zero(p, size, char);
5291 #else /* #ifndef PERL_GLOBAL_STRUCT_PRIVATE */
5294 Perl_my_cxt_index(pTHX_ const char *my_cxt_key)
5299 PERL_ARGS_ASSERT_MY_CXT_INDEX;
5301 for (index = 0; index < PL_my_cxt_index; index++) {
5302 const char *key = PL_my_cxt_keys[index];
5303 /* try direct pointer compare first - there are chances to success,
5304 * and it's much faster.
5306 if ((key == my_cxt_key) || strEQ(key, my_cxt_key))
5313 Perl_my_cxt_init(pTHX_ const char *my_cxt_key, size_t size)
5319 PERL_ARGS_ASSERT_MY_CXT_INIT;
5321 index = Perl_my_cxt_index(aTHX_ my_cxt_key);
5323 /* this module hasn't been allocated an index yet */
5324 #if defined(USE_ITHREADS)
5325 MUTEX_LOCK(&PL_my_ctx_mutex);
5327 index = PL_my_cxt_index++;
5328 #if defined(USE_ITHREADS)
5329 MUTEX_UNLOCK(&PL_my_ctx_mutex);
5333 /* make sure the array is big enough */
5334 if (PL_my_cxt_size <= index) {
5335 int old_size = PL_my_cxt_size;
5337 if (PL_my_cxt_size) {
5338 while (PL_my_cxt_size <= index)
5339 PL_my_cxt_size *= 2;
5340 Renew(PL_my_cxt_list, PL_my_cxt_size, void *);
5341 Renew(PL_my_cxt_keys, PL_my_cxt_size, const char *);
5344 PL_my_cxt_size = 16;
5345 Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
5346 Newx(PL_my_cxt_keys, PL_my_cxt_size, const char *);
5348 for (i = old_size; i < PL_my_cxt_size; i++) {
5349 PL_my_cxt_keys[i] = 0;
5350 PL_my_cxt_list[i] = 0;
5353 PL_my_cxt_keys[index] = my_cxt_key;
5354 /* newSV() allocates one more than needed */
5355 p = (void*)SvPVX(newSV(size-1));
5356 PL_my_cxt_list[index] = p;
5357 Zero(p, size, char);
5360 #endif /* #ifndef PERL_GLOBAL_STRUCT_PRIVATE */
5361 #endif /* PERL_IMPLICIT_CONTEXT */
5364 /* Perl_xs_handshake():
5365 implement the various XS_*_BOOTCHECK macros, which are added to .c
5366 files by ExtUtils::ParseXS, to check that the perl the module was built
5367 with is binary compatible with the running perl.
5370 Perl_xs_handshake(U32 key, void * v_my_perl, const char * file,
5371 [U32 items, U32 ax], [char * api_version], [char * xs_version])
5373 The meaning of the varargs is determined the U32 key arg (which is not
5374 a format string). The fields of key are assembled by using HS_KEY().
5376 Under PERL_IMPLICIT_CONTEX, the v_my_perl arg is of type
5377 "PerlInterpreter *" and represents the callers context; otherwise it is
5378 of type "CV *", and is the boot xsub's CV.
5380 v_my_perl will catch where a threaded future perl526.dll calling IO.dll
5381 for example, and IO.dll was linked with threaded perl524.dll, and both
5382 perl526.dll and perl524.dll are in %PATH and the Win32 DLL loader
5383 successfully can load IO.dll into the process but simultaneously it
5384 loaded an interpreter of a different version into the process, and XS
5385 code will naturally pass SV*s created by perl524.dll for perl526.dll to
5386 use through perl526.dll's my_perl->Istack_base.
5388 v_my_perl cannot be the first arg, since then 'key' will be out of
5389 place in a threaded vs non-threaded mixup; and analyzing the key
5390 number's bitfields won't reveal the problem, since it will be a valid
5391 key (unthreaded perl) on interp side, but croak will report the XS mod's
5392 key as gibberish (it is really a my_perl ptr) (threaded XS mod); or if
5393 it's a threaded perl and an unthreaded XS module, threaded perl will
5394 look at an uninit C stack or an uninit register to get 'key'
5395 (remember that it assumes that the 1st arg is the interp cxt).
5397 'file' is the source filename of the caller.
5401 Perl_xs_handshake(const U32 key, void * v_my_perl, const char * file, ...)
5407 #ifdef PERL_IMPLICIT_CONTEXT
5414 PERL_ARGS_ASSERT_XS_HANDSHAKE;
5415 va_start(args, file);
5417 got = INT2PTR(void*, (UV)(key & HSm_KEY_MATCH));
5418 need = (void *)(HS_KEY(FALSE, FALSE, "", "") & HSm_KEY_MATCH);
5419 if (UNLIKELY(got != need))
5421 /* try to catch where a 2nd threaded perl interp DLL is loaded into a process
5422 by a XS DLL compiled against the wrong interl DLL b/c of bad @INC, and the
5423 2nd threaded perl interp DLL never initialized its TLS/PERL_SYS_INIT3 so
5424 dTHX call from 2nd interp DLL can't return the my_perl that pp_entersub
5425 passed to the XS DLL */
5426 #ifdef PERL_IMPLICIT_CONTEXT
5427 xs_interp = (tTHX)v_my_perl;
5431 /* try to catch where an unthreaded perl interp DLL (for ex. perl522.dll) is
5432 loaded into a process by a XS DLL built by an unthreaded perl522.dll perl,
5433 but the DynaLoder/Perl that started the process and loaded the XS DLL is
5434 unthreaded perl524.dll, since unthreadeds don't pass my_perl (a unique *)
5435 through pp_entersub, use a unique value (which is a pointer to PL_stack_sp's
5436 location in the unthreaded perl binary) stored in CV * to figure out if this
5437 Perl_xs_handshake was called by the same pp_entersub */
5438 cv = (CV*)v_my_perl;
5439 xs_spp = (SV***)CvHSCXT(cv);
5441 need = &PL_stack_sp;
5443 if(UNLIKELY(got != need)) {
5444 bad_handshake:/* recycle branch and string from above */
5445 if(got != (void *)HSf_NOCHK)
5446 noperl_die("%s: loadable library and perl binaries are mismatched"
5447 " (got handshake key %p, needed %p)\n",
5451 if(key & HSf_SETXSUBFN) { /* this might be called from a module bootstrap */
5452 SAVEPPTR(PL_xsubfilename);/* which was require'd from a XSUB BEGIN */
5453 PL_xsubfilename = file; /* so the old name must be restored for
5454 additional XSUBs to register themselves */
5455 /* XSUBs can't be perl lang/perl5db.pl debugged
5456 if (PERLDB_LINE_OR_SAVESRC)
5457 (void)gv_fetchfile(file); */
5460 if(key & HSf_POPMARK) {
5462 { SV **mark = PL_stack_base + ax++;
5464 items = (I32)(SP - MARK);
5468 items = va_arg(args, U32);
5469 ax = va_arg(args, U32);
5473 assert(HS_GETAPIVERLEN(key) <= UCHAR_MAX);
5474 if((apiverlen = HS_GETAPIVERLEN(key))) {
5475 char * api_p = va_arg(args, char*);
5476 if(apiverlen != sizeof("v" PERL_API_VERSION_STRING)-1
5477 || memNE(api_p, "v" PERL_API_VERSION_STRING,
5478 sizeof("v" PERL_API_VERSION_STRING)-1))
5479 Perl_croak_nocontext("Perl API version %s of %"SVf" does not match %s",
5480 api_p, SVfARG(PL_stack_base[ax + 0]),
5481 "v" PERL_API_VERSION_STRING);
5486 assert(HS_GETXSVERLEN(key) <= UCHAR_MAX && HS_GETXSVERLEN(key) <= HS_APIVERLEN_MAX);
5487 if((xsverlen = HS_GETXSVERLEN(key)))
5488 S_xs_version_bootcheck(aTHX_
5489 items, ax, va_arg(args, char*), xsverlen);
5497 S_xs_version_bootcheck(pTHX_ U32 items, U32 ax, const char *xs_p,
5501 const char *vn = NULL;
5502 SV *const module = PL_stack_base[ax];
5504 PERL_ARGS_ASSERT_XS_VERSION_BOOTCHECK;
5506 if (items >= 2) /* version supplied as bootstrap arg */
5507 sv = PL_stack_base[ax + 1];
5509 /* XXX GV_ADDWARN */
5511 sv = get_sv(Perl_form(aTHX_ "%"SVf"::%s", SVfARG(module), vn), 0);
5512 if (!sv || !SvOK(sv)) {
5514 sv = get_sv(Perl_form(aTHX_ "%"SVf"::%s", SVfARG(module), vn), 0);
5518 SV *xssv = Perl_newSVpvn_flags(aTHX_ xs_p, xs_len, SVs_TEMP);
5519 SV *pmsv = sv_isobject(sv) && sv_derived_from(sv, "version")
5520 ? sv : sv_2mortal(new_version(sv));
5521 xssv = upg_version(xssv, 0);
5522 if ( vcmp(pmsv,xssv) ) {
5523 SV *string = vstringify(xssv);
5524 SV *xpt = Perl_newSVpvf(aTHX_ "%"SVf" object version %"SVf
5525 " does not match ", SVfARG(module), SVfARG(string));
5527 SvREFCNT_dec(string);
5528 string = vstringify(pmsv);
5531 Perl_sv_catpvf(aTHX_ xpt, "$%"SVf"::%s %"SVf, SVfARG(module), vn,
5534 Perl_sv_catpvf(aTHX_ xpt, "bootstrap parameter %"SVf, SVfARG(string));
5536 SvREFCNT_dec(string);
5538 Perl_sv_2mortal(aTHX_ xpt);
5539 Perl_croak_sv(aTHX_ xpt);
5545 =for apidoc my_strlcat
5547 The C library C<strlcat> if available, or a Perl implementation of it.
5548 This operates on C C<NUL>-terminated strings.
5550 C<my_strlcat()> appends string C<src> to the end of C<dst>. It will append at
5551 most S<C<size - strlen(dst) - 1>> characters. It will then C<NUL>-terminate,
5552 unless C<size> is 0 or the original C<dst> string was longer than C<size> (in
5553 practice this should not happen as it means that either C<size> is incorrect or
5554 that C<dst> is not a proper C<NUL>-terminated string).
5556 Note that C<size> is the full size of the destination buffer and
5557 the result is guaranteed to be C<NUL>-terminated if there is room. Note that
5558 room for the C<NUL> should be included in C<size>.
5562 Description stolen from http://www.openbsd.org/cgi-bin/man.cgi?query=strlcat
5566 Perl_my_strlcat(char *dst, const char *src, Size_t size)
5568 Size_t used, length, copy;
5571 length = strlen(src);
5572 if (size > 0 && used < size - 1) {
5573 copy = (length >= size - used) ? size - used - 1 : length;
5574 memcpy(dst + used, src, copy);
5575 dst[used + copy] = '\0';
5577 return used + length;
5583 =for apidoc my_strlcpy
5585 The C library C<strlcpy> if available, or a Perl implementation of it.
5586 This operates on C C<NUL>-terminated strings.
5588 C<my_strlcpy()> copies up to S<C<size - 1>> characters from the string C<src>
5589 to C<dst>, C<NUL>-terminating the result if C<size> is not 0.
5593 Description stolen from http://www.openbsd.org/cgi-bin/man.cgi?query=strlcpy
5597 Perl_my_strlcpy(char *dst, const char *src, Size_t size)
5599 Size_t length, copy;
5601 length = strlen(src);
5603 copy = (length >= size) ? size - 1 : length;
5604 memcpy(dst, src, copy);
5611 #if defined(_MSC_VER) && (_MSC_VER >= 1300) && (_MSC_VER < 1400) && (WINVER < 0x0500)
5612 /* VC7 or 7.1, building with pre-VC7 runtime libraries. */
5613 long _ftol( double ); /* Defined by VC6 C libs. */
5614 long _ftol2( double dblSource ) { return _ftol( dblSource ); }
5617 PERL_STATIC_INLINE bool
5618 S_gv_has_usable_name(pTHX_ GV *gv)
5622 && HvENAME(GvSTASH(gv))
5623 && (gvp = (GV **)hv_fetchhek(
5624 GvSTASH(gv), GvNAME_HEK(gv), 0
5630 Perl_get_db_sub(pTHX_ SV **svp, CV *cv)
5632 SV * const dbsv = GvSVn(PL_DBsub);
5633 const bool save_taint = TAINT_get;
5635 /* When we are called from pp_goto (svp is null),
5636 * we do not care about using dbsv to call CV;
5637 * it's for informational purposes only.
5640 PERL_ARGS_ASSERT_GET_DB_SUB;
5644 if (!PERLDB_SUB_NN) {
5647 if (!svp && !CvLEXICAL(cv)) {
5648 gv_efullname3(dbsv, gv, NULL);
5650 else if ( (CvFLAGS(cv) & (CVf_ANON | CVf_CLONED)) || CvLEXICAL(cv)
5651 || strEQ(GvNAME(gv), "END")
5652 || ( /* Could be imported, and old sub redefined. */
5653 (GvCV(gv) != cv || !S_gv_has_usable_name(aTHX_ gv))
5655 !( (SvTYPE(*svp) == SVt_PVGV)
5656 && (GvCV((const GV *)*svp) == cv)
5657 /* Use GV from the stack as a fallback. */
5658 && S_gv_has_usable_name(aTHX_ gv = (GV *)*svp)
5662 /* GV is potentially non-unique, or contain different CV. */
5663 SV * const tmp = newRV(MUTABLE_SV(cv));
5664 sv_setsv(dbsv, tmp);
5668 sv_sethek(dbsv, HvENAME_HEK(GvSTASH(gv)));
5669 sv_catpvs(dbsv, "::");
5670 sv_cathek(dbsv, GvNAME_HEK(gv));
5674 const int type = SvTYPE(dbsv);
5675 if (type < SVt_PVIV && type != SVt_IV)
5676 sv_upgrade(dbsv, SVt_PVIV);
5677 (void)SvIOK_on(dbsv);
5678 SvIV_set(dbsv, PTR2IV(cv)); /* Do it the quickest way */
5681 TAINT_IF(save_taint);
5682 #ifdef NO_TAINT_SUPPORT
5683 PERL_UNUSED_VAR(save_taint);
5688 Perl_my_dirfd(DIR * dir) {
5690 /* Most dirfd implementations have problems when passed NULL. */
5695 #elif defined(HAS_DIR_DD_FD)
5698 Perl_croak_nocontext(PL_no_func, "dirfd");
5699 NOT_REACHED; /* NOTREACHED */
5705 Perl_get_re_arg(pTHX_ SV *sv) {
5711 sv = MUTABLE_SV(SvRV(sv));
5712 if (SvTYPE(sv) == SVt_REGEXP)
5713 return (REGEXP*) sv;
5720 * This code is derived from drand48() implementation from FreeBSD,
5721 * found in lib/libc/gen/_rand48.c.
5723 * The U64 implementation is original, based on the POSIX
5724 * specification for drand48().
5728 * Copyright (c) 1993 Martin Birgmeier
5729 * All rights reserved.
5731 * You may redistribute unmodified or modified versions of this source
5732 * code provided that the above copyright notice and this and the
5733 * following conditions are retained.
5735 * This software is provided ``as is'', and comes with no warranties
5736 * of any kind. I shall in no event be liable for anything that happens
5737 * to anyone/anything when using this software.
5740 #define FREEBSD_DRAND48_SEED_0 (0x330e)
5742 #ifdef PERL_DRAND48_QUAD
5744 #define DRAND48_MULT U64_CONST(0x5deece66d)
5745 #define DRAND48_ADD 0xb
5746 #define DRAND48_MASK U64_CONST(0xffffffffffff)
5750 #define FREEBSD_DRAND48_SEED_1 (0xabcd)
5751 #define FREEBSD_DRAND48_SEED_2 (0x1234)
5752 #define FREEBSD_DRAND48_MULT_0 (0xe66d)
5753 #define FREEBSD_DRAND48_MULT_1 (0xdeec)
5754 #define FREEBSD_DRAND48_MULT_2 (0x0005)
5755 #define FREEBSD_DRAND48_ADD (0x000b)
5757 const unsigned short _rand48_mult[3] = {
5758 FREEBSD_DRAND48_MULT_0,
5759 FREEBSD_DRAND48_MULT_1,
5760 FREEBSD_DRAND48_MULT_2
5762 const unsigned short _rand48_add = FREEBSD_DRAND48_ADD;
5767 Perl_drand48_init_r(perl_drand48_t *random_state, U32 seed)
5769 PERL_ARGS_ASSERT_DRAND48_INIT_R;
5771 #ifdef PERL_DRAND48_QUAD
5772 *random_state = FREEBSD_DRAND48_SEED_0 + ((U64)seed << 16);
5774 random_state->seed[0] = FREEBSD_DRAND48_SEED_0;
5775 random_state->seed[1] = (U16) seed;
5776 random_state->seed[2] = (U16) (seed >> 16);
5781 Perl_drand48_r(perl_drand48_t *random_state)
5783 PERL_ARGS_ASSERT_DRAND48_R;
5785 #ifdef PERL_DRAND48_QUAD
5786 *random_state = (*random_state * DRAND48_MULT + DRAND48_ADD)
5789 return ldexp((double)*random_state, -48);
5795 accu = (U32) _rand48_mult[0] * (U32) random_state->seed[0]
5796 + (U32) _rand48_add;
5797 temp[0] = (U16) accu; /* lower 16 bits */
5798 accu >>= sizeof(U16) * 8;
5799 accu += (U32) _rand48_mult[0] * (U32) random_state->seed[1]
5800 + (U32) _rand48_mult[1] * (U32) random_state->seed[0];
5801 temp[1] = (U16) accu; /* middle 16 bits */
5802 accu >>= sizeof(U16) * 8;
5803 accu += _rand48_mult[0] * random_state->seed[2]
5804 + _rand48_mult[1] * random_state->seed[1]
5805 + _rand48_mult[2] * random_state->seed[0];
5806 random_state->seed[0] = temp[0];
5807 random_state->seed[1] = temp[1];
5808 random_state->seed[2] = (U16) accu;
5810 return ldexp((double) random_state->seed[0], -48) +
5811 ldexp((double) random_state->seed[1], -32) +
5812 ldexp((double) random_state->seed[2], -16);
5817 #ifdef USE_C_BACKTRACE
5819 /* Possibly move all this USE_C_BACKTRACE code into a new file. */
5824 /* abfd is the BFD handle. */
5826 /* bfd_syms is the BFD symbol table. */
5828 /* bfd_text is handle to the the ".text" section of the object file. */
5830 /* Since opening the executable and scanning its symbols is quite
5831 * heavy operation, we remember the filename we used the last time,
5832 * and do the opening and scanning only if the filename changes.
5833 * This removes most (but not all) open+scan cycles. */
5834 const char* fname_prev;
5837 /* Given a dl_info, update the BFD context if necessary. */
5838 static void bfd_update(bfd_context* ctx, Dl_info* dl_info)
5840 /* BFD open and scan only if the filename changed. */
5841 if (ctx->fname_prev == NULL ||
5842 strNE(dl_info->dli_fname, ctx->fname_prev)) {
5844 bfd_close(ctx->abfd);
5846 ctx->abfd = bfd_openr(dl_info->dli_fname, 0);
5848 if (bfd_check_format(ctx->abfd, bfd_object)) {
5849 IV symbol_size = bfd_get_symtab_upper_bound(ctx->abfd);
5850 if (symbol_size > 0) {
5851 Safefree(ctx->bfd_syms);
5852 Newx(ctx->bfd_syms, symbol_size, asymbol*);
5854 bfd_get_section_by_name(ctx->abfd, ".text");
5862 ctx->fname_prev = dl_info->dli_fname;
5866 /* Given a raw frame, try to symbolize it and store
5867 * symbol information (source file, line number) away. */
5868 static void bfd_symbolize(bfd_context* ctx,
5871 STRLEN* symbol_name_size,
5873 STRLEN* source_name_size,
5874 STRLEN* source_line)
5876 *symbol_name = NULL;
5877 *symbol_name_size = 0;
5879 IV offset = PTR2IV(raw_frame) - PTR2IV(ctx->bfd_text->vma);
5881 bfd_canonicalize_symtab(ctx->abfd, ctx->bfd_syms) > 0) {
5884 unsigned int line = 0;
5885 if (bfd_find_nearest_line(ctx->abfd, ctx->bfd_text,
5886 ctx->bfd_syms, offset,
5887 &file, &func, &line) &&
5888 file && func && line > 0) {
5889 /* Size and copy the source file, use only
5890 * the basename of the source file.
5892 * NOTE: the basenames are fine for the
5893 * Perl source files, but may not always
5894 * be the best idea for XS files. */
5895 const char *p, *b = NULL;
5896 /* Look for the last slash. */
5897 for (p = file; *p; p++) {
5901 if (b == NULL || *b == 0) {
5904 *source_name_size = p - b + 1;
5905 Newx(*source_name, *source_name_size + 1, char);
5906 Copy(b, *source_name, *source_name_size + 1, char);
5908 *symbol_name_size = strlen(func);
5909 Newx(*symbol_name, *symbol_name_size + 1, char);
5910 Copy(func, *symbol_name, *symbol_name_size + 1, char);
5912 *source_line = line;
5918 #endif /* #ifdef USE_BFD */
5922 /* OS X has no public API for for 'symbolicating' (Apple official term)
5923 * stack addresses to {function_name, source_file, line_number}.
5924 * Good news: there is command line utility atos(1) which does that.
5925 * Bad news 1: it's a command line utility.
5926 * Bad news 2: one needs to have the Developer Tools installed.
5927 * Bad news 3: in newer releases it needs to be run as 'xcrun atos'.
5929 * To recap: we need to open a pipe for reading for a utility which
5930 * might not exist, or exists in different locations, and then parse
5931 * the output. And since this is all for a low-level API, we cannot
5932 * use high-level stuff. Thanks, Apple. */
5935 /* tool is set to the absolute pathname of the tool to use:
5938 /* format is set to a printf format string used for building
5939 * the external command to run. */
5941 /* unavail is set if e.g. xcrun cannot be found, or something
5942 * else happens that makes getting the backtrace dubious. Note,
5943 * however, that the context isn't persistent, the next call to
5944 * get_c_backtrace() will start from scratch. */
5946 /* fname is the current object file name. */
5948 /* object_base_addr is the base address of the shared object. */
5949 void* object_base_addr;
5952 /* Given |dl_info|, updates the context. If the context has been
5953 * marked unavailable, return immediately. If not but the tool has
5954 * not been set, set it to either "xcrun atos" or "atos" (also set the
5955 * format to use for creating commands for piping), or if neither is
5956 * unavailable (one needs the Developer Tools installed), mark the context
5957 * an unavailable. Finally, update the filename (object name),
5958 * and its base address. */
5960 static void atos_update(atos_context* ctx,
5965 if (ctx->tool == NULL) {
5966 const char* tools[] = {
5970 const char* formats[] = {
5971 "/usr/bin/xcrun atos -o '%s' -l %08x %08x 2>&1",
5972 "/usr/bin/atos -d -o '%s' -l %08x %08x 2>&1"
5976 for (i = 0; i < C_ARRAY_LENGTH(tools); i++) {
5977 if (stat(tools[i], &st) == 0 && S_ISREG(st.st_mode)) {
5978 ctx->tool = tools[i];
5979 ctx->format = formats[i];
5983 if (ctx->tool == NULL) {
5984 ctx->unavail = TRUE;
5988 if (ctx->fname == NULL ||
5989 strNE(dl_info->dli_fname, ctx->fname)) {
5990 ctx->fname = dl_info->dli_fname;
5991 ctx->object_base_addr = dl_info->dli_fbase;
5995 /* Given an output buffer end |p| and its |start|, matches
5996 * for the atos output, extracting the source code location
5997 * and returning non-NULL if possible, returning NULL otherwise. */
5998 static const char* atos_parse(const char* p,
6000 STRLEN* source_name_size,
6001 STRLEN* source_line) {
6002 /* atos() output is something like:
6003 * perl_parse (in miniperl) (perl.c:2314)\n\n".
6004 * We cannot use Perl regular expressions, because we need to
6005 * stay low-level. Therefore here we have a rolled-out version
6006 * of a state machine which matches _backwards_from_the_end_ and
6007 * if there's a success, returns the starts of the filename,
6008 * also setting the filename size and the source line number.
6009 * The matched regular expression is roughly "\(.*:\d+\)\s*$" */
6010 const char* source_number_start;
6011 const char* source_name_end;
6012 const char* source_line_end;
6013 const char* close_paren;
6016 /* Skip trailing whitespace. */
6017 while (p > start && isspace(*p)) p--;
6018 /* Now we should be at the close paren. */
6019 if (p == start || *p != ')')
6023 /* Now we should be in the line number. */
6024 if (p == start || !isdigit(*p))
6026 /* Skip over the digits. */
6027 while (p > start && isdigit(*p))
6029 /* Now we should be at the colon. */
6030 if (p == start || *p != ':')
6032 source_number_start = p + 1;
6033 source_name_end = p; /* Just beyond the end. */
6035 /* Look for the open paren. */
6036 while (p > start && *p != '(')
6041 *source_name_size = source_name_end - p;
6042 if (grok_atoUV(source_number_start, &uv, &source_line_end)
6043 && source_line_end == close_paren
6046 *source_line = (STRLEN)uv;
6052 /* Given a raw frame, read a pipe from the symbolicator (that's the
6053 * technical term) atos, reads the result, and parses the source code
6054 * location. We must stay low-level, so we use snprintf(), pipe(),
6055 * and fread(), and then also parse the output ourselves. */
6056 static void atos_symbolize(atos_context* ctx,
6059 STRLEN* source_name_size,
6060 STRLEN* source_line)
6068 /* Simple security measure: if there's any funny business with
6069 * the object name (used as "-o '%s'" ), leave since at least
6070 * partially the user controls it. */
6071 for (p = ctx->fname; *p; p++) {
6072 if (*p == '\'' || iscntrl(*p)) {
6073 ctx->unavail = TRUE;
6077 cnt = snprintf(cmd, sizeof(cmd), ctx->format,
6078 ctx->fname, ctx->object_base_addr, raw_frame);
6079 if (cnt < sizeof(cmd)) {
6080 /* Undo nostdio.h #defines that disable stdio.
6081 * This is somewhat naughty, but is used elsewhere
6082 * in the core, and affects only OS X. */
6087 FILE* fp = popen(cmd, "r");
6088 /* At the moment we open a new pipe for each stack frame.
6089 * This is naturally somewhat slow, but hopefully generating
6090 * stack traces is never going to in a performance critical path.
6092 * We could play tricks with atos by batching the stack
6093 * addresses to be resolved: atos can either take multiple
6094 * addresses from the command line, or read addresses from
6095 * a file (though the mess of creating temporary files would
6096 * probably negate much of any possible speedup).
6098 * Normally there are only two objects present in the backtrace:
6099 * perl itself, and the libdyld.dylib. (Note that the object
6100 * filenames contain the full pathname, so perl may not always
6101 * be in the same place.) Whenever the object in the
6102 * backtrace changes, the base address also changes.
6104 * The problem with batching the addresses, though, would be
6105 * matching the results with the addresses: the parsing of
6106 * the results is already painful enough with a single address. */
6109 UV cnt = fread(out, 1, sizeof(out), fp);
6110 if (cnt < sizeof(out)) {
6111 const char* p = atos_parse(out + cnt, out,
6116 *source_name_size + 1, char);
6117 Copy(p, *source_name,
6118 *source_name_size + 1, char);
6126 #endif /* #ifdef PERL_DARWIN */
6129 =for apidoc get_c_backtrace
6131 Collects the backtrace (aka "stacktrace") into a single linear
6132 malloced buffer, which the caller B<must> Perl_free_c_backtrace().
6134 Scans the frames back by depth + skip, then drops the skip innermost,
6135 returning at most depth frames.
6141 Perl_get_c_backtrace(pTHX_ int depth, int skip)
6143 /* Note that here we must stay as low-level as possible: Newx(),
6144 * Copy(), Safefree(); since we may be called from anywhere,
6145 * so we should avoid higher level constructs like SVs or AVs.
6147 * Since we are using safesysmalloc() via Newx(), don't try
6148 * getting backtrace() there, unless you like deep recursion. */
6150 /* Currently only implemented with backtrace() and dladdr(),
6151 * for other platforms NULL is returned. */
6153 #if defined(HAS_BACKTRACE) && defined(HAS_DLADDR)
6154 /* backtrace() is available via <execinfo.h> in glibc and in most
6155 * modern BSDs; dladdr() is available via <dlfcn.h>. */
6157 /* We try fetching this many frames total, but then discard
6158 * the |skip| first ones. For the remaining ones we will try
6159 * retrieving more information with dladdr(). */
6160 int try_depth = skip + depth;
6162 /* The addresses (program counters) returned by backtrace(). */
6165 /* Retrieved with dladdr() from the addresses returned by backtrace(). */
6168 /* Sizes _including_ the terminating \0 of the object name
6169 * and symbol name strings. */
6170 STRLEN* object_name_sizes;
6171 STRLEN* symbol_name_sizes;
6174 /* The symbol names comes either from dli_sname,
6175 * or if using BFD, they can come from BFD. */
6176 char** symbol_names;
6179 /* The source code location information. Dug out with e.g. BFD. */
6180 char** source_names;
6181 STRLEN* source_name_sizes;
6182 STRLEN* source_lines;
6184 Perl_c_backtrace* bt = NULL; /* This is what will be returned. */
6185 int got_depth; /* How many frames were returned from backtrace(). */
6186 UV frame_count = 0; /* How many frames we return. */
6187 UV total_bytes = 0; /* The size of the whole returned backtrace. */
6190 bfd_context bfd_ctx;
6193 atos_context atos_ctx;
6196 /* Here are probably possibilities for optimizing. We could for
6197 * example have a struct that contains most of these and then
6198 * allocate |try_depth| of them, saving a bunch of malloc calls.
6199 * Note, however, that |frames| could not be part of that struct
6200 * because backtrace() will want an array of just them. Also be
6201 * careful about the name strings. */
6202 Newx(raw_frames, try_depth, void*);
6203 Newx(dl_infos, try_depth, Dl_info);
6204 Newx(object_name_sizes, try_depth, STRLEN);
6205 Newx(symbol_name_sizes, try_depth, STRLEN);
6206 Newx(source_names, try_depth, char*);
6207 Newx(source_name_sizes, try_depth, STRLEN);
6208 Newx(source_lines, try_depth, STRLEN);
6210 Newx(symbol_names, try_depth, char*);
6213 /* Get the raw frames. */
6214 got_depth = (int)backtrace(raw_frames, try_depth);
6216 /* We use dladdr() instead of backtrace_symbols() because we want
6217 * the full details instead of opaque strings. This is useful for
6218 * two reasons: () the details are needed for further symbolic
6219 * digging, for example in OS X (2) by having the details we fully
6220 * control the output, which in turn is useful when more platforms
6221 * are added: we can keep out output "portable". */
6223 /* We want a single linear allocation, which can then be freed
6224 * with a single swoop. We will do the usual trick of first
6225 * walking over the structure and seeing how much we need to
6226 * allocate, then allocating, and then walking over the structure
6227 * the second time and populating it. */
6229 /* First we must compute the total size of the buffer. */
6230 total_bytes = sizeof(Perl_c_backtrace_header);
6231 if (got_depth > skip) {
6234 bfd_init(); /* Is this safe to call multiple times? */
6235 Zero(&bfd_ctx, 1, bfd_context);
6238 Zero(&atos_ctx, 1, atos_context);
6240 for (i = skip; i < try_depth; i++) {
6241 Dl_info* dl_info = &dl_infos[i];
6243 total_bytes += sizeof(Perl_c_backtrace_frame);
6245 source_names[i] = NULL;
6246 source_name_sizes[i] = 0;
6247 source_lines[i] = 0;
6249 /* Yes, zero from dladdr() is failure. */
6250 if (dladdr(raw_frames[i], dl_info)) {
6251 object_name_sizes[i] =
6252 dl_info->dli_fname ? strlen(dl_info->dli_fname) : 0;
6253 symbol_name_sizes[i] =
6254 dl_info->dli_sname ? strlen(dl_info->dli_sname) : 0;
6256 bfd_update(&bfd_ctx, dl_info);
6257 bfd_symbolize(&bfd_ctx, raw_frames[i],
6259 &symbol_name_sizes[i],
6261 &source_name_sizes[i],
6265 atos_update(&atos_ctx, dl_info);
6266 atos_symbolize(&atos_ctx,
6269 &source_name_sizes[i],
6273 /* Plus ones for the terminating \0. */
6274 total_bytes += object_name_sizes[i] + 1;
6275 total_bytes += symbol_name_sizes[i] + 1;
6276 total_bytes += source_name_sizes[i] + 1;
6284 Safefree(bfd_ctx.bfd_syms);
6288 /* Now we can allocate and populate the result buffer. */
6289 Newxc(bt, total_bytes, char, Perl_c_backtrace);
6290 Zero(bt, total_bytes, char);
6291 bt->header.frame_count = frame_count;
6292 bt->header.total_bytes = total_bytes;
6293 if (frame_count > 0) {
6294 Perl_c_backtrace_frame* frame = bt->frame_info;
6295 char* name_base = (char *)(frame + frame_count);
6296 char* name_curr = name_base; /* Outputting the name strings here. */
6298 for (i = skip; i < skip + frame_count; i++) {
6299 Dl_info* dl_info = &dl_infos[i];
6301 frame->addr = raw_frames[i];
6302 frame->object_base_addr = dl_info->dli_fbase;
6303 frame->symbol_addr = dl_info->dli_saddr;
6305 /* Copies a string, including the \0, and advances the name_curr.
6306 * Also copies the start and the size to the frame. */
6307 #define PERL_C_BACKTRACE_STRCPY(frame, doffset, src, dsize, size) \
6309 Copy(src, name_curr, size, char); \
6310 frame->doffset = name_curr - (char*)bt; \
6311 frame->dsize = size; \
6312 name_curr += size; \
6315 PERL_C_BACKTRACE_STRCPY(frame, object_name_offset,
6317 object_name_size, object_name_sizes[i]);
6320 PERL_C_BACKTRACE_STRCPY(frame, symbol_name_offset,
6322 symbol_name_size, symbol_name_sizes[i]);
6323 Safefree(symbol_names[i]);
6325 PERL_C_BACKTRACE_STRCPY(frame, symbol_name_offset,
6327 symbol_name_size, symbol_name_sizes[i]);
6330 PERL_C_BACKTRACE_STRCPY(frame, source_name_offset,
6332 source_name_size, source_name_sizes[i]);
6333 Safefree(source_names[i]);
6335 #undef PERL_C_BACKTRACE_STRCPY
6337 frame->source_line_number = source_lines[i];
6341 assert(total_bytes ==
6342 (UV)(sizeof(Perl_c_backtrace_header) +
6343 frame_count * sizeof(Perl_c_backtrace_frame) +
6344 name_curr - name_base));
6347 Safefree(symbol_names);
6349 bfd_close(bfd_ctx.abfd);
6352 Safefree(source_lines);
6353 Safefree(source_name_sizes);
6354 Safefree(source_names);
6355 Safefree(symbol_name_sizes);
6356 Safefree(object_name_sizes);
6357 /* Assuming the strings returned by dladdr() are pointers
6358 * to read-only static memory (the object file), so that
6359 * they do not need freeing (and cannot be). */
6361 Safefree(raw_frames);
6364 PERL_UNUSED_ARGV(depth);
6365 PERL_UNUSED_ARGV(skip);
6371 =for apidoc free_c_backtrace
6373 Deallocates a backtrace received from get_c_bracktrace.
6379 =for apidoc get_c_backtrace_dump
6381 Returns a SV a dump of |depth| frames of the call stack, skipping
6382 the |skip| innermost ones. depth of 20 is usually enough.
6384 The appended output looks like:
6387 1 10e004812:0082 Perl_croak util.c:1716 /usr/bin/perl
6388 2 10df8d6d2:1d72 perl_parse perl.c:3975 /usr/bin/perl
6391 The fields are tab-separated. The first column is the depth (zero
6392 being the innermost non-skipped frame). In the hex:offset, the hex is
6393 where the program counter was in S_parse_body, and the :offset (might
6394 be missing) tells how much inside the S_parse_body the program counter was.
6396 The util.c:1716 is the source code file and line number.
6398 The F</usr/bin/perl> is obvious (hopefully).
6400 Unknowns are C<"-">. Unknowns can happen unfortunately quite easily:
6401 if the platform doesn't support retrieving the information;
6402 if the binary is missing the debug information;
6403 if the optimizer has transformed the code by for example inlining.
6409 Perl_get_c_backtrace_dump(pTHX_ int depth, int skip)
6411 Perl_c_backtrace* bt;
6413 bt = get_c_backtrace(depth, skip + 1 /* Hide ourselves. */);
6415 Perl_c_backtrace_frame* frame;
6416 SV* dsv = newSVpvs("");
6418 for (i = 0, frame = bt->frame_info;
6419 i < bt->header.frame_count; i++, frame++) {
6420 Perl_sv_catpvf(aTHX_ dsv, "%d", (int)i);
6421 Perl_sv_catpvf(aTHX_ dsv, "\t%p", frame->addr ? frame->addr : "-");
6422 /* Symbol (function) names might disappear without debug info.
6424 * The source code location might disappear in case of the
6425 * optimizer inlining or otherwise rearranging the code. */
6426 if (frame->symbol_addr) {
6427 Perl_sv_catpvf(aTHX_ dsv, ":%04x",
6429 ((char*)frame->addr - (char*)frame->symbol_addr));
6431 Perl_sv_catpvf(aTHX_ dsv, "\t%s",
6432 frame->symbol_name_size &&
6433 frame->symbol_name_offset ?
6434 (char*)bt + frame->symbol_name_offset : "-");
6435 if (frame->source_name_size &&
6436 frame->source_name_offset &&
6437 frame->source_line_number) {
6438 Perl_sv_catpvf(aTHX_ dsv, "\t%s:%"UVuf,
6439 (char*)bt + frame->source_name_offset,
6440 (UV)frame->source_line_number);
6442 Perl_sv_catpvf(aTHX_ dsv, "\t-");
6444 Perl_sv_catpvf(aTHX_ dsv, "\t%s",
6445 frame->object_name_size &&
6446 frame->object_name_offset ?
6447 (char*)bt + frame->object_name_offset : "-");
6448 /* The frame->object_base_addr is not output,
6449 * but it is used for symbolizing/symbolicating. */
6450 sv_catpvs(dsv, "\n");
6453 Perl_free_c_backtrace(aTHX_ bt);
6462 =for apidoc dump_c_backtrace
6464 Dumps the C backtrace to the given fp.
6466 Returns true if a backtrace could be retrieved, false if not.
6472 Perl_dump_c_backtrace(pTHX_ PerlIO* fp, int depth, int skip)
6476 PERL_ARGS_ASSERT_DUMP_C_BACKTRACE;
6478 sv = Perl_get_c_backtrace_dump(aTHX_ depth, skip);
6481 PerlIO_printf(fp, "%s", SvPV_nolen(sv));
6487 #endif /* #ifdef USE_C_BACKTRACE */
6490 * ex: set ts=8 sts=4 sw=4 et: