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 /* libc prior to 4.6.27 (late 1994) did not work properly on a NULL
563 return strstr((char*)big, (char*)little);
566 /* same as instr but allow embedded nulls. The end pointers point to 1 beyond
567 * the final character desired to be checked */
570 Perl_ninstr(const char *big, const char *bigend, const char *little, const char *lend)
572 PERL_ARGS_ASSERT_NINSTR;
576 const char first = *little;
578 bigend -= lend - little++;
580 while (big <= bigend) {
581 if (*big++ == first) {
582 for (x=big,s=little; s < lend; x++,s++) {
586 return (char*)(big-1);
593 /* reverse of the above--find last substring */
596 Perl_rninstr(const char *big, const char *bigend, const char *little, const char *lend)
599 const I32 first = *little;
600 const char * const littleend = lend;
602 PERL_ARGS_ASSERT_RNINSTR;
604 if (little >= littleend)
605 return (char*)bigend;
607 big = bigend - (littleend - little++);
608 while (big >= bigbeg) {
612 for (x=big+2,s=little; s < littleend; /**/ ) {
621 return (char*)(big+1);
626 /* As a space optimization, we do not compile tables for strings of length
627 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
628 special-cased in fbm_instr().
630 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
633 =head1 Miscellaneous Functions
635 =for apidoc fbm_compile
637 Analyses the string in order to make fast searches on it using fbm_instr()
638 -- the Boyer-Moore algorithm.
644 Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
651 PERL_DEB( STRLEN rarest = 0 );
653 PERL_ARGS_ASSERT_FBM_COMPILE;
655 if (isGV_with_GP(sv) || SvROK(sv))
661 if (flags & FBMcf_TAIL) {
662 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL;
663 sv_catpvs(sv, "\n"); /* Taken into account in fbm_instr() */
664 if (mg && mg->mg_len >= 0)
667 if (!SvPOK(sv) || SvNIOKp(sv))
668 s = (U8*)SvPV_force_mutable(sv, len);
669 else s = (U8 *)SvPV_mutable(sv, len);
670 if (len == 0) /* TAIL might be on a zero-length string. */
672 SvUPGRADE(sv, SVt_PVMG);
677 /* "deep magic", the comment used to add. The use of MAGIC itself isn't
678 really. MAGIC was originally added in 79072805bf63abe5 (perl 5.0 alpha 2)
679 to call SvVALID_off() if the scalar was assigned to.
681 The comment itself (and "deeper magic" below) date back to
682 378cc40b38293ffc (perl 2.0). "deep magic" was an annotation on
684 where the magic (presumably) was that the scalar had a BM table hidden
687 As MAGIC is always present on BMs [in Perl 5 :-)], we can use it to store
688 the table instead of the previous (somewhat hacky) approach of co-opting
689 the string buffer and storing it after the string. */
691 assert(!mg_find(sv, PERL_MAGIC_bm));
692 mg = sv_magicext(sv, NULL, PERL_MAGIC_bm, &PL_vtbl_bm, NULL, 0);
696 /* Shorter strings are special-cased in Perl_fbm_instr(), and don't use
698 const U8 mlen = (len>255) ? 255 : (U8)len;
699 const unsigned char *const sb = s + len - mlen; /* first char (maybe) */
702 Newx(table, 256, U8);
703 memset((void*)table, mlen, 256);
704 mg->mg_ptr = (char *)table;
707 s += len - 1; /* last char */
710 if (table[*s] == mlen)
716 s = (const unsigned char*)(SvPVX_const(sv)); /* deeper magic */
717 for (i = 0; i < len; i++) {
718 if (PL_freq[s[i]] < frequency) {
719 PERL_DEB( rarest = i );
720 frequency = PL_freq[s[i]];
723 BmUSEFUL(sv) = 100; /* Initial value */
724 if (flags & FBMcf_TAIL)
726 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %"UVuf"\n",
727 s[rarest], (UV)rarest));
730 /* If SvTAIL(littlestr), it has a fake '\n' at end. */
731 /* If SvTAIL is actually due to \Z or \z, this gives false positives
735 =for apidoc fbm_instr
737 Returns the location of the SV in the string delimited by C<big> and
738 C<bigend>. It returns C<NULL> if the string can't be found. The C<sv>
739 does not have to be fbm_compiled, but the search will not be as fast
746 Perl_fbm_instr(pTHX_ unsigned char *big, unsigned char *bigend, SV *littlestr, U32 flags)
750 const unsigned char *little = (const unsigned char *)SvPV_const(littlestr,l);
751 STRLEN littlelen = l;
752 const I32 multiline = flags & FBMrf_MULTILINE;
754 PERL_ARGS_ASSERT_FBM_INSTR;
756 if ((STRLEN)(bigend - big) < littlelen) {
757 if ( SvTAIL(littlestr)
758 && ((STRLEN)(bigend - big) == littlelen - 1)
760 || (*big == *little &&
761 memEQ((char *)big, (char *)little, littlelen - 1))))
766 switch (littlelen) { /* Special cases for 0, 1 and 2 */
768 return (char*)big; /* Cannot be SvTAIL! */
770 if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
771 /* Know that bigend != big. */
772 if (bigend[-1] == '\n')
773 return (char *)(bigend - 1);
774 return (char *) bigend;
782 if (SvTAIL(littlestr))
783 return (char *) bigend;
786 if (SvTAIL(littlestr) && !multiline) {
787 if (bigend[-1] == '\n' && bigend[-2] == *little)
788 return (char*)bigend - 2;
789 if (bigend[-1] == *little)
790 return (char*)bigend - 1;
794 /* This should be better than FBM if c1 == c2, and almost
795 as good otherwise: maybe better since we do less indirection.
796 And we save a lot of memory by caching no table. */
797 const unsigned char c1 = little[0];
798 const unsigned char c2 = little[1];
803 while (s <= bigend) {
813 goto check_1char_anchor;
824 goto check_1char_anchor;
827 while (s <= bigend) {
832 goto check_1char_anchor;
841 check_1char_anchor: /* One char and anchor! */
842 if (SvTAIL(littlestr) && (*bigend == *little))
843 return (char *)bigend; /* bigend is already decremented. */
846 break; /* Only lengths 0 1 and 2 have special-case code. */
849 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
850 s = bigend - littlelen;
851 if (s >= big && bigend[-1] == '\n' && *s == *little
852 /* Automatically of length > 2 */
853 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
855 return (char*)s; /* how sweet it is */
858 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
860 return (char*)s + 1; /* how sweet it is */
864 if (!SvVALID(littlestr)) {
865 char * const b = ninstr((char*)big,(char*)bigend,
866 (char*)little, (char*)little + littlelen);
868 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
869 /* Chop \n from littlestr: */
870 s = bigend - littlelen + 1;
872 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
882 if (littlelen > (STRLEN)(bigend - big))
886 const MAGIC *const mg = mg_find(littlestr, PERL_MAGIC_bm);
887 const unsigned char *oldlittle;
891 --littlelen; /* Last char found by table lookup */
894 little += littlelen; /* last char */
897 const unsigned char * const table = (const unsigned char *) mg->mg_ptr;
901 if ((tmp = table[*s])) {
902 if ((s += tmp) < bigend)
906 else { /* less expensive than calling strncmp() */
907 unsigned char * const olds = s;
912 if (*--s == *--little)
914 s = olds + 1; /* here we pay the price for failure */
916 if (s < bigend) /* fake up continue to outer loop */
926 && memEQ((char *)(bigend - littlelen),
927 (char *)(oldlittle - littlelen), littlelen) )
928 return (char*)bigend - littlelen;
936 Returns true if the leading len bytes of the strings s1 and s2 are the same
937 case-insensitively; false otherwise. Uppercase and lowercase ASCII range bytes
938 match themselves and their opposite case counterparts. Non-cased and non-ASCII
939 range bytes match only themselves.
946 Perl_foldEQ(const char *s1, const char *s2, I32 len)
948 const U8 *a = (const U8 *)s1;
949 const U8 *b = (const U8 *)s2;
951 PERL_ARGS_ASSERT_FOLDEQ;
956 if (*a != *b && *a != PL_fold[*b])
963 Perl_foldEQ_latin1(const char *s1, const char *s2, I32 len)
965 /* Compare non-utf8 using Unicode (Latin1) semantics. Does not work on
966 * MICRO_SIGN, LATIN_SMALL_LETTER_SHARP_S, nor
967 * LATIN_SMALL_LETTER_Y_WITH_DIAERESIS, and does not check for these. Nor
968 * does it check that the strings each have at least 'len' characters */
970 const U8 *a = (const U8 *)s1;
971 const U8 *b = (const U8 *)s2;
973 PERL_ARGS_ASSERT_FOLDEQ_LATIN1;
978 if (*a != *b && *a != PL_fold_latin1[*b]) {
987 =for apidoc foldEQ_locale
989 Returns true if the leading len bytes of the strings s1 and s2 are the same
990 case-insensitively in the current locale; false otherwise.
996 Perl_foldEQ_locale(const char *s1, const char *s2, I32 len)
999 const U8 *a = (const U8 *)s1;
1000 const U8 *b = (const U8 *)s2;
1002 PERL_ARGS_ASSERT_FOLDEQ_LOCALE;
1007 if (*a != *b && *a != PL_fold_locale[*b])
1014 /* copy a string to a safe spot */
1017 =head1 Memory Management
1021 Perl's version of C<strdup()>. Returns a pointer to a newly allocated
1022 string which is a duplicate of C<pv>. The size of the string is
1023 determined by C<strlen()>, which means it may not contain embedded C<NUL>
1024 characters and must have a trailing C<NUL>. The memory allocated for the new
1025 string can be freed with the C<Safefree()> function.
1027 On some platforms, Windows for example, all allocated memory owned by a thread
1028 is deallocated when that thread ends. So if you need that not to happen, you
1029 need to use the shared memory functions, such as C<L</savesharedpv>>.
1035 Perl_savepv(pTHX_ const char *pv)
1037 PERL_UNUSED_CONTEXT;
1042 const STRLEN pvlen = strlen(pv)+1;
1043 Newx(newaddr, pvlen, char);
1044 return (char*)memcpy(newaddr, pv, pvlen);
1048 /* same thing but with a known length */
1053 Perl's version of what C<strndup()> would be if it existed. Returns a
1054 pointer to a newly allocated string which is a duplicate of the first
1055 C<len> bytes from C<pv>, plus a trailing
1056 C<NUL> byte. The memory allocated for
1057 the new string can be freed with the C<Safefree()> function.
1059 On some platforms, Windows for example, all allocated memory owned by a thread
1060 is deallocated when that thread ends. So if you need that not to happen, you
1061 need to use the shared memory functions, such as C<L</savesharedpvn>>.
1067 Perl_savepvn(pTHX_ const char *pv, I32 len)
1070 PERL_UNUSED_CONTEXT;
1074 Newx(newaddr,len+1,char);
1075 /* Give a meaning to NULL pointer mainly for the use in sv_magic() */
1077 /* might not be null terminated */
1078 newaddr[len] = '\0';
1079 return (char *) CopyD(pv,newaddr,len,char);
1082 return (char *) ZeroD(newaddr,len+1,char);
1087 =for apidoc savesharedpv
1089 A version of C<savepv()> which allocates the duplicate string in memory
1090 which is shared between threads.
1095 Perl_savesharedpv(pTHX_ const char *pv)
1100 PERL_UNUSED_CONTEXT;
1105 pvlen = strlen(pv)+1;
1106 newaddr = (char*)PerlMemShared_malloc(pvlen);
1110 return (char*)memcpy(newaddr, pv, pvlen);
1114 =for apidoc savesharedpvn
1116 A version of C<savepvn()> which allocates the duplicate string in memory
1117 which is shared between threads. (With the specific difference that a NULL
1118 pointer is not acceptable)
1123 Perl_savesharedpvn(pTHX_ const char *const pv, const STRLEN len)
1125 char *const newaddr = (char*)PerlMemShared_malloc(len + 1);
1127 PERL_UNUSED_CONTEXT;
1128 /* PERL_ARGS_ASSERT_SAVESHAREDPVN; */
1133 newaddr[len] = '\0';
1134 return (char*)memcpy(newaddr, pv, len);
1138 =for apidoc savesvpv
1140 A version of C<savepv()>/C<savepvn()> which gets the string to duplicate from
1141 the passed in SV using C<SvPV()>
1143 On some platforms, Windows for example, all allocated memory owned by a thread
1144 is deallocated when that thread ends. So if you need that not to happen, you
1145 need to use the shared memory functions, such as C<L</savesharedsvpv>>.
1151 Perl_savesvpv(pTHX_ SV *sv)
1154 const char * const pv = SvPV_const(sv, len);
1157 PERL_ARGS_ASSERT_SAVESVPV;
1160 Newx(newaddr,len,char);
1161 return (char *) CopyD(pv,newaddr,len,char);
1165 =for apidoc savesharedsvpv
1167 A version of C<savesharedpv()> which allocates the duplicate string in
1168 memory which is shared between threads.
1174 Perl_savesharedsvpv(pTHX_ SV *sv)
1177 const char * const pv = SvPV_const(sv, len);
1179 PERL_ARGS_ASSERT_SAVESHAREDSVPV;
1181 return savesharedpvn(pv, len);
1184 /* the SV for Perl_form() and mess() is not kept in an arena */
1192 if (PL_phase != PERL_PHASE_DESTRUCT)
1193 return newSVpvs_flags("", SVs_TEMP);
1198 /* Create as PVMG now, to avoid any upgrading later */
1200 Newxz(any, 1, XPVMG);
1201 SvFLAGS(sv) = SVt_PVMG;
1202 SvANY(sv) = (void*)any;
1204 SvREFCNT(sv) = 1 << 30; /* practically infinite */
1209 #if defined(PERL_IMPLICIT_CONTEXT)
1211 Perl_form_nocontext(const char* pat, ...)
1216 PERL_ARGS_ASSERT_FORM_NOCONTEXT;
1217 va_start(args, pat);
1218 retval = vform(pat, &args);
1222 #endif /* PERL_IMPLICIT_CONTEXT */
1225 =head1 Miscellaneous Functions
1228 Takes a sprintf-style format pattern and conventional
1229 (non-SV) arguments and returns the formatted string.
1231 (char *) Perl_form(pTHX_ const char* pat, ...)
1233 can be used any place a string (char *) is required:
1235 char * s = Perl_form("%d.%d",major,minor);
1237 Uses a single private buffer so if you want to format several strings you
1238 must explicitly copy the earlier strings away (and free the copies when you
1245 Perl_form(pTHX_ const char* pat, ...)
1249 PERL_ARGS_ASSERT_FORM;
1250 va_start(args, pat);
1251 retval = vform(pat, &args);
1257 Perl_vform(pTHX_ const char *pat, va_list *args)
1259 SV * const sv = mess_alloc();
1260 PERL_ARGS_ASSERT_VFORM;
1261 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1266 =for apidoc Am|SV *|mess|const char *pat|...
1268 Take a sprintf-style format pattern and argument list. These are used to
1269 generate a string message. If the message does not end with a newline,
1270 then it will be extended with some indication of the current location
1271 in the code, as described for L</mess_sv>.
1273 Normally, the resulting message is returned in a new mortal SV.
1274 During global destruction a single SV may be shared between uses of
1280 #if defined(PERL_IMPLICIT_CONTEXT)
1282 Perl_mess_nocontext(const char *pat, ...)
1287 PERL_ARGS_ASSERT_MESS_NOCONTEXT;
1288 va_start(args, pat);
1289 retval = vmess(pat, &args);
1293 #endif /* PERL_IMPLICIT_CONTEXT */
1296 Perl_mess(pTHX_ const char *pat, ...)
1300 PERL_ARGS_ASSERT_MESS;
1301 va_start(args, pat);
1302 retval = vmess(pat, &args);
1308 Perl_closest_cop(pTHX_ const COP *cop, const OP *o, const OP *curop,
1311 /* Look for curop starting from o. cop is the last COP we've seen. */
1312 /* opnext means that curop is actually the ->op_next of the op we are
1315 PERL_ARGS_ASSERT_CLOSEST_COP;
1317 if (!o || !curop || (
1318 opnext ? o->op_next == curop && o->op_type != OP_SCOPE : o == curop
1322 if (o->op_flags & OPf_KIDS) {
1324 for (kid = cUNOPo->op_first; kid; kid = OpSIBLING(kid)) {
1327 /* If the OP_NEXTSTATE has been optimised away we can still use it
1328 * the get the file and line number. */
1330 if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
1331 cop = (const COP *)kid;
1333 /* Keep searching, and return when we've found something. */
1335 new_cop = closest_cop(cop, kid, curop, opnext);
1341 /* Nothing found. */
1347 =for apidoc Am|SV *|mess_sv|SV *basemsg|bool consume
1349 Expands a message, intended for the user, to include an indication of
1350 the current location in the code, if the message does not already appear
1353 C<basemsg> is the initial message or object. If it is a reference, it
1354 will be used as-is and will be the result of this function. Otherwise it
1355 is used as a string, and if it already ends with a newline, it is taken
1356 to be complete, and the result of this function will be the same string.
1357 If the message does not end with a newline, then a segment such as C<at
1358 foo.pl line 37> will be appended, and possibly other clauses indicating
1359 the current state of execution. The resulting message will end with a
1362 Normally, the resulting message is returned in a new mortal SV.
1363 During global destruction a single SV may be shared between uses of this
1364 function. If C<consume> is true, then the function is permitted (but not
1365 required) to modify and return C<basemsg> instead of allocating a new SV.
1371 Perl_mess_sv(pTHX_ SV *basemsg, bool consume)
1375 #if defined(USE_C_BACKTRACE) && defined(USE_C_BACKTRACE_ON_ERROR)
1379 /* The PERL_C_BACKTRACE_ON_WARN must be an integer of one or more. */
1380 if ((ws = PerlEnv_getenv("PERL_C_BACKTRACE_ON_ERROR")) &&
1381 (wi = grok_atou(ws, NULL)) > 0) {
1382 Perl_dump_c_backtrace(aTHX_ Perl_debug_log, wi, 1);
1387 PERL_ARGS_ASSERT_MESS_SV;
1389 if (SvROK(basemsg)) {
1395 sv_setsv(sv, basemsg);
1400 if (SvPOK(basemsg) && consume) {
1405 sv_copypv(sv, basemsg);
1408 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1410 * Try and find the file and line for PL_op. This will usually be
1411 * PL_curcop, but it might be a cop that has been optimised away. We
1412 * can try to find such a cop by searching through the optree starting
1413 * from the sibling of PL_curcop.
1417 closest_cop(PL_curcop, OpSIBLING(PL_curcop), PL_op, FALSE);
1422 Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
1423 OutCopFILE(cop), (IV)CopLINE(cop));
1424 /* Seems that GvIO() can be untrustworthy during global destruction. */
1425 if (GvIO(PL_last_in_gv) && (SvTYPE(GvIOp(PL_last_in_gv)) == SVt_PVIO)
1426 && IoLINES(GvIOp(PL_last_in_gv)))
1429 const bool line_mode = (RsSIMPLE(PL_rs) &&
1430 *SvPV_const(PL_rs,l) == '\n' && l == 1);
1431 Perl_sv_catpvf(aTHX_ sv, ", <%"SVf"> %s %"IVdf,
1432 SVfARG(PL_last_in_gv == PL_argvgv
1434 : sv_2mortal(newSVhek(GvNAME_HEK(PL_last_in_gv)))),
1435 line_mode ? "line" : "chunk",
1436 (IV)IoLINES(GvIOp(PL_last_in_gv)));
1438 if (PL_phase == PERL_PHASE_DESTRUCT)
1439 sv_catpvs(sv, " during global destruction");
1440 sv_catpvs(sv, ".\n");
1446 =for apidoc Am|SV *|vmess|const char *pat|va_list *args
1448 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1449 argument list. These are used to generate a string message. If the
1450 message does not end with a newline, then it will be extended with
1451 some indication of the current location in the code, as described for
1454 Normally, the resulting message is returned in a new mortal SV.
1455 During global destruction a single SV may be shared between uses of
1462 Perl_vmess(pTHX_ const char *pat, va_list *args)
1464 SV * const sv = mess_alloc();
1466 PERL_ARGS_ASSERT_VMESS;
1468 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1469 return mess_sv(sv, 1);
1473 Perl_write_to_stderr(pTHX_ SV* msv)
1478 PERL_ARGS_ASSERT_WRITE_TO_STDERR;
1480 if (PL_stderrgv && SvREFCNT(PL_stderrgv)
1481 && (io = GvIO(PL_stderrgv))
1482 && (mg = SvTIED_mg((const SV *)io, PERL_MAGIC_tiedscalar)))
1483 Perl_magic_methcall(aTHX_ MUTABLE_SV(io), mg, SV_CONST(PRINT),
1484 G_SCALAR | G_DISCARD | G_WRITING_TO_STDERR, 1, msv);
1486 PerlIO * const serr = Perl_error_log;
1488 do_print(msv, serr);
1489 (void)PerlIO_flush(serr);
1494 =head1 Warning and Dieing
1497 /* Common code used in dieing and warning */
1500 S_with_queued_errors(pTHX_ SV *ex)
1502 PERL_ARGS_ASSERT_WITH_QUEUED_ERRORS;
1503 if (PL_errors && SvCUR(PL_errors) && !SvROK(ex)) {
1504 sv_catsv(PL_errors, ex);
1505 ex = sv_mortalcopy(PL_errors);
1506 SvCUR_set(PL_errors, 0);
1512 S_invoke_exception_hook(pTHX_ SV *ex, bool warn)
1517 SV **const hook = warn ? &PL_warnhook : &PL_diehook;
1518 /* sv_2cv might call Perl_croak() or Perl_warner() */
1519 SV * const oldhook = *hook;
1527 cv = sv_2cv(oldhook, &stash, &gv, 0);
1529 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1538 exarg = newSVsv(ex);
1539 SvREADONLY_on(exarg);
1542 PUSHSTACKi(warn ? PERLSI_WARNHOOK : PERLSI_DIEHOOK);
1546 call_sv(MUTABLE_SV(cv), G_DISCARD);
1555 =for apidoc Am|OP *|die_sv|SV *baseex
1557 Behaves the same as L</croak_sv>, except for the return type.
1558 It should be used only where the C<OP *> return type is required.
1559 The function never actually returns.
1565 # pragma warning( push )
1566 # pragma warning( disable : 4646 ) /* warning C4646: function declared with
1567 __declspec(noreturn) has non-void return type */
1568 # pragma warning( disable : 4645 ) /* warning C4645: function declared with
1569 __declspec(noreturn) has a return statement */
1572 Perl_die_sv(pTHX_ SV *baseex)
1574 PERL_ARGS_ASSERT_DIE_SV;
1577 NORETURN_FUNCTION_END;
1580 # pragma warning( pop )
1584 =for apidoc Am|OP *|die|const char *pat|...
1586 Behaves the same as L</croak>, except for the return type.
1587 It should be used only where the C<OP *> return type is required.
1588 The function never actually returns.
1593 #if defined(PERL_IMPLICIT_CONTEXT)
1595 # pragma warning( push )
1596 # pragma warning( disable : 4646 ) /* warning C4646: function declared with
1597 __declspec(noreturn) has non-void return type */
1598 # pragma warning( disable : 4645 ) /* warning C4645: function declared with
1599 __declspec(noreturn) has a return statement */
1602 Perl_die_nocontext(const char* pat, ...)
1606 va_start(args, pat);
1608 NOT_REACHED; /* NOTREACHED */
1610 NORETURN_FUNCTION_END;
1613 # pragma warning( pop )
1615 #endif /* PERL_IMPLICIT_CONTEXT */
1618 # pragma warning( push )
1619 # pragma warning( disable : 4646 ) /* warning C4646: function declared with
1620 __declspec(noreturn) has non-void return type */
1621 # pragma warning( disable : 4645 ) /* warning C4645: function declared with
1622 __declspec(noreturn) has a return statement */
1625 Perl_die(pTHX_ const char* pat, ...)
1628 va_start(args, pat);
1630 NOT_REACHED; /* NOTREACHED */
1632 NORETURN_FUNCTION_END;
1635 # pragma warning( pop )
1639 =for apidoc Am|void|croak_sv|SV *baseex
1641 This is an XS interface to Perl's C<die> function.
1643 C<baseex> is the error message or object. If it is a reference, it
1644 will be used as-is. Otherwise it is used as a string, and if it does
1645 not end with a newline then it will be extended with some indication of
1646 the current location in the code, as described for L</mess_sv>.
1648 The error message or object will be used as an exception, by default
1649 returning control to the nearest enclosing C<eval>, but subject to
1650 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak_sv>
1651 function never returns normally.
1653 To die with a simple string message, the L</croak> function may be
1660 Perl_croak_sv(pTHX_ SV *baseex)
1662 SV *ex = with_queued_errors(mess_sv(baseex, 0));
1663 PERL_ARGS_ASSERT_CROAK_SV;
1664 invoke_exception_hook(ex, FALSE);
1669 =for apidoc Am|void|vcroak|const char *pat|va_list *args
1671 This is an XS interface to Perl's C<die> function.
1673 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1674 argument list. These are used to generate a string message. If the
1675 message does not end with a newline, then it will be extended with
1676 some indication of the current location in the code, as described for
1679 The error message will be used as an exception, by default
1680 returning control to the nearest enclosing C<eval>, but subject to
1681 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1682 function never returns normally.
1684 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1685 (C<$@>) will be used as an error message or object instead of building an
1686 error message from arguments. If you want to throw a non-string object,
1687 or build an error message in an SV yourself, it is preferable to use
1688 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1694 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1696 SV *ex = with_queued_errors(pat ? vmess(pat, args) : mess_sv(ERRSV, 0));
1697 invoke_exception_hook(ex, FALSE);
1702 =for apidoc Am|void|croak|const char *pat|...
1704 This is an XS interface to Perl's C<die> function.
1706 Take a sprintf-style format pattern and argument list. These are used to
1707 generate a string message. If the message does not end with a newline,
1708 then it will be extended with some indication of the current location
1709 in the code, as described for L</mess_sv>.
1711 The error message will be used as an exception, by default
1712 returning control to the nearest enclosing C<eval>, but subject to
1713 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1714 function never returns normally.
1716 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1717 (C<$@>) will be used as an error message or object instead of building an
1718 error message from arguments. If you want to throw a non-string object,
1719 or build an error message in an SV yourself, it is preferable to use
1720 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1725 #if defined(PERL_IMPLICIT_CONTEXT)
1727 Perl_croak_nocontext(const char *pat, ...)
1731 va_start(args, pat);
1733 NOT_REACHED; /* NOTREACHED */
1736 #endif /* PERL_IMPLICIT_CONTEXT */
1739 Perl_croak(pTHX_ const char *pat, ...)
1742 va_start(args, pat);
1744 NOT_REACHED; /* NOTREACHED */
1749 =for apidoc Am|void|croak_no_modify
1751 Exactly equivalent to C<Perl_croak(aTHX_ "%s", PL_no_modify)>, but generates
1752 terser object code than using C<Perl_croak>. Less code used on exception code
1753 paths reduces CPU cache pressure.
1759 Perl_croak_no_modify(void)
1761 Perl_croak_nocontext( "%s", PL_no_modify);
1764 /* does not return, used in util.c perlio.c and win32.c
1765 This is typically called when malloc returns NULL.
1768 Perl_croak_no_mem(void)
1772 int fd = PerlIO_fileno(Perl_error_log);
1774 SETERRNO(EBADF,RMS_IFI);
1776 /* Can't use PerlIO to write as it allocates memory */
1777 PERL_UNUSED_RESULT(PerlLIO_write(fd, PL_no_mem, sizeof(PL_no_mem)-1));
1782 /* does not return, used only in POPSTACK */
1784 Perl_croak_popstack(void)
1787 PerlIO_printf(Perl_error_log, "panic: POPSTACK\n");
1792 =for apidoc Am|void|warn_sv|SV *baseex
1794 This is an XS interface to Perl's C<warn> function.
1796 C<baseex> is the error message or object. If it is a reference, it
1797 will be used as-is. Otherwise it is used as a string, and if it does
1798 not end with a newline then it will be extended with some indication of
1799 the current location in the code, as described for L</mess_sv>.
1801 The error message or object will by default be written to standard error,
1802 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1804 To warn with a simple string message, the L</warn> function may be
1811 Perl_warn_sv(pTHX_ SV *baseex)
1813 SV *ex = mess_sv(baseex, 0);
1814 PERL_ARGS_ASSERT_WARN_SV;
1815 if (!invoke_exception_hook(ex, TRUE))
1816 write_to_stderr(ex);
1820 =for apidoc Am|void|vwarn|const char *pat|va_list *args
1822 This is an XS interface to Perl's C<warn> function.
1824 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1825 argument list. These are used to generate a string message. If the
1826 message does not end with a newline, then it will be extended with
1827 some indication of the current location in the code, as described for
1830 The error message or object will by default be written to standard error,
1831 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1833 Unlike with L</vcroak>, C<pat> is not permitted to be null.
1839 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1841 SV *ex = vmess(pat, args);
1842 PERL_ARGS_ASSERT_VWARN;
1843 if (!invoke_exception_hook(ex, TRUE))
1844 write_to_stderr(ex);
1848 =for apidoc Am|void|warn|const char *pat|...
1850 This is an XS interface to Perl's C<warn> function.
1852 Take a sprintf-style format pattern and argument list. These are used to
1853 generate a string message. If the message does not end with a newline,
1854 then it will be extended with some indication of the current location
1855 in the code, as described for L</mess_sv>.
1857 The error message or object will by default be written to standard error,
1858 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1860 Unlike with L</croak>, C<pat> is not permitted to be null.
1865 #if defined(PERL_IMPLICIT_CONTEXT)
1867 Perl_warn_nocontext(const char *pat, ...)
1871 PERL_ARGS_ASSERT_WARN_NOCONTEXT;
1872 va_start(args, pat);
1876 #endif /* PERL_IMPLICIT_CONTEXT */
1879 Perl_warn(pTHX_ const char *pat, ...)
1882 PERL_ARGS_ASSERT_WARN;
1883 va_start(args, pat);
1888 #if defined(PERL_IMPLICIT_CONTEXT)
1890 Perl_warner_nocontext(U32 err, const char *pat, ...)
1894 PERL_ARGS_ASSERT_WARNER_NOCONTEXT;
1895 va_start(args, pat);
1896 vwarner(err, pat, &args);
1899 #endif /* PERL_IMPLICIT_CONTEXT */
1902 Perl_ck_warner_d(pTHX_ U32 err, const char* pat, ...)
1904 PERL_ARGS_ASSERT_CK_WARNER_D;
1906 if (Perl_ckwarn_d(aTHX_ err)) {
1908 va_start(args, pat);
1909 vwarner(err, pat, &args);
1915 Perl_ck_warner(pTHX_ U32 err, const char* pat, ...)
1917 PERL_ARGS_ASSERT_CK_WARNER;
1919 if (Perl_ckwarn(aTHX_ err)) {
1921 va_start(args, pat);
1922 vwarner(err, pat, &args);
1928 Perl_warner(pTHX_ U32 err, const char* pat,...)
1931 PERL_ARGS_ASSERT_WARNER;
1932 va_start(args, pat);
1933 vwarner(err, pat, &args);
1938 Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1941 PERL_ARGS_ASSERT_VWARNER;
1942 if (PL_warnhook == PERL_WARNHOOK_FATAL || ckDEAD(err)) {
1943 SV * const msv = vmess(pat, args);
1945 if (PL_parser && PL_parser->error_count) {
1949 invoke_exception_hook(msv, FALSE);
1954 Perl_vwarn(aTHX_ pat, args);
1958 /* implements the ckWARN? macros */
1961 Perl_ckwarn(pTHX_ U32 w)
1963 /* If lexical warnings have not been set, use $^W. */
1965 return PL_dowarn & G_WARN_ON;
1967 return ckwarn_common(w);
1970 /* implements the ckWARN?_d macro */
1973 Perl_ckwarn_d(pTHX_ U32 w)
1975 /* If lexical warnings have not been set then default classes warn. */
1979 return ckwarn_common(w);
1983 S_ckwarn_common(pTHX_ U32 w)
1985 if (PL_curcop->cop_warnings == pWARN_ALL)
1988 if (PL_curcop->cop_warnings == pWARN_NONE)
1991 /* Check the assumption that at least the first slot is non-zero. */
1992 assert(unpackWARN1(w));
1994 /* Check the assumption that it is valid to stop as soon as a zero slot is
1996 if (!unpackWARN2(w)) {
1997 assert(!unpackWARN3(w));
1998 assert(!unpackWARN4(w));
1999 } else if (!unpackWARN3(w)) {
2000 assert(!unpackWARN4(w));
2003 /* Right, dealt with all the special cases, which are implemented as non-
2004 pointers, so there is a pointer to a real warnings mask. */
2006 if (isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w)))
2008 } while (w >>= WARNshift);
2013 /* Set buffer=NULL to get a new one. */
2015 Perl_new_warnings_bitfield(pTHX_ STRLEN *buffer, const char *const bits,
2017 const MEM_SIZE len_wanted =
2018 sizeof(STRLEN) + (size > WARNsize ? size : WARNsize);
2019 PERL_UNUSED_CONTEXT;
2020 PERL_ARGS_ASSERT_NEW_WARNINGS_BITFIELD;
2023 (specialWARN(buffer) ?
2024 PerlMemShared_malloc(len_wanted) :
2025 PerlMemShared_realloc(buffer, len_wanted));
2027 Copy(bits, (buffer + 1), size, char);
2028 if (size < WARNsize)
2029 Zero((char *)(buffer + 1) + size, WARNsize - size, char);
2033 /* since we've already done strlen() for both nam and val
2034 * we can use that info to make things faster than
2035 * sprintf(s, "%s=%s", nam, val)
2037 #define my_setenv_format(s, nam, nlen, val, vlen) \
2038 Copy(nam, s, nlen, char); \
2040 Copy(val, s+(nlen+1), vlen, char); \
2041 *(s+(nlen+1+vlen)) = '\0'
2043 #ifdef USE_ENVIRON_ARRAY
2044 /* VMS' my_setenv() is in vms.c */
2045 #if !defined(WIN32) && !defined(NETWARE)
2047 Perl_my_setenv(pTHX_ const char *nam, const char *val)
2051 /* only parent thread can modify process environment */
2052 if (PL_curinterp == aTHX)
2055 #ifndef PERL_USE_SAFE_PUTENV
2056 if (!PL_use_safe_putenv) {
2057 /* most putenv()s leak, so we manipulate environ directly */
2059 const I32 len = strlen(nam);
2062 /* where does it go? */
2063 for (i = 0; environ[i]; i++) {
2064 if (strnEQ(environ[i],nam,len) && environ[i][len] == '=')
2068 if (environ == PL_origenviron) { /* need we copy environment? */
2074 while (environ[max])
2076 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
2077 for (j=0; j<max; j++) { /* copy environment */
2078 const int len = strlen(environ[j]);
2079 tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
2080 Copy(environ[j], tmpenv[j], len+1, char);
2083 environ = tmpenv; /* tell exec where it is now */
2086 safesysfree(environ[i]);
2087 while (environ[i]) {
2088 environ[i] = environ[i+1];
2093 if (!environ[i]) { /* does not exist yet */
2094 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
2095 environ[i+1] = NULL; /* make sure it's null terminated */
2098 safesysfree(environ[i]);
2102 environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
2103 /* all that work just for this */
2104 my_setenv_format(environ[i], nam, nlen, val, vlen);
2107 /* This next branch should only be called #if defined(HAS_SETENV), but
2108 Configure doesn't test for that yet. For Solaris, setenv() and unsetenv()
2109 were introduced in Solaris 9, so testing for HAS UNSETENV is sufficient.
2111 # if defined(__CYGWIN__)|| defined(__SYMBIAN32__) || defined(__riscos__) || (defined(__sun) && defined(HAS_UNSETENV))
2112 # if defined(HAS_UNSETENV)
2114 (void)unsetenv(nam);
2116 (void)setenv(nam, val, 1);
2118 # else /* ! HAS_UNSETENV */
2119 (void)setenv(nam, val, 1);
2120 # endif /* HAS_UNSETENV */
2122 # if defined(HAS_UNSETENV)
2124 if (environ) /* old glibc can crash with null environ */
2125 (void)unsetenv(nam);
2127 const int nlen = strlen(nam);
2128 const int vlen = strlen(val);
2129 char * const new_env =
2130 (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
2131 my_setenv_format(new_env, nam, nlen, val, vlen);
2132 (void)putenv(new_env);
2134 # else /* ! HAS_UNSETENV */
2136 const int nlen = strlen(nam);
2142 new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
2143 /* all that work just for this */
2144 my_setenv_format(new_env, nam, nlen, val, vlen);
2145 (void)putenv(new_env);
2146 # endif /* HAS_UNSETENV */
2147 # endif /* __CYGWIN__ */
2148 #ifndef PERL_USE_SAFE_PUTENV
2154 #else /* WIN32 || NETWARE */
2157 Perl_my_setenv(pTHX_ const char *nam, const char *val)
2161 const int nlen = strlen(nam);
2168 Newx(envstr, nlen+vlen+2, char);
2169 my_setenv_format(envstr, nam, nlen, val, vlen);
2170 (void)PerlEnv_putenv(envstr);
2174 #endif /* WIN32 || NETWARE */
2178 #ifdef UNLINK_ALL_VERSIONS
2180 Perl_unlnk(pTHX_ const char *f) /* unlink all versions of a file */
2184 PERL_ARGS_ASSERT_UNLNK;
2186 while (PerlLIO_unlink(f) >= 0)
2188 return retries ? 0 : -1;
2192 /* this is a drop-in replacement for bcopy() */
2193 #if (!defined(HAS_MEMCPY) && !defined(HAS_BCOPY)) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY) && !defined(HAS_SAFE_BCOPY))
2195 Perl_my_bcopy(const char *from, char *to, I32 len)
2197 char * const retval = to;
2199 PERL_ARGS_ASSERT_MY_BCOPY;
2203 if (from - to >= 0) {
2211 *(--to) = *(--from);
2217 /* this is a drop-in replacement for memset() */
2220 Perl_my_memset(char *loc, I32 ch, I32 len)
2222 char * const retval = loc;
2224 PERL_ARGS_ASSERT_MY_MEMSET;
2234 /* this is a drop-in replacement for bzero() */
2235 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
2237 Perl_my_bzero(char *loc, I32 len)
2239 char * const retval = loc;
2241 PERL_ARGS_ASSERT_MY_BZERO;
2251 /* this is a drop-in replacement for memcmp() */
2252 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
2254 Perl_my_memcmp(const char *s1, const char *s2, I32 len)
2256 const U8 *a = (const U8 *)s1;
2257 const U8 *b = (const U8 *)s2;
2260 PERL_ARGS_ASSERT_MY_MEMCMP;
2265 if ((tmp = *a++ - *b++))
2270 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
2273 /* This vsprintf replacement should generally never get used, since
2274 vsprintf was available in both System V and BSD 2.11. (There may
2275 be some cross-compilation or embedded set-ups where it is needed,
2278 If you encounter a problem in this function, it's probably a symptom
2279 that Configure failed to detect your system's vprintf() function.
2280 See the section on "item vsprintf" in the INSTALL file.
2282 This version may compile on systems with BSD-ish <stdio.h>,
2283 but probably won't on others.
2286 #ifdef USE_CHAR_VSPRINTF
2291 vsprintf(char *dest, const char *pat, void *args)
2295 #if defined(STDIO_PTR_LVALUE) && defined(STDIO_CNT_LVALUE)
2296 FILE_ptr(&fakebuf) = (STDCHAR *) dest;
2297 FILE_cnt(&fakebuf) = 32767;
2299 /* These probably won't compile -- If you really need
2300 this, you'll have to figure out some other method. */
2301 fakebuf._ptr = dest;
2302 fakebuf._cnt = 32767;
2307 fakebuf._flag = _IOWRT|_IOSTRG;
2308 _doprnt(pat, args, &fakebuf); /* what a kludge */
2309 #if defined(STDIO_PTR_LVALUE)
2310 *(FILE_ptr(&fakebuf)++) = '\0';
2312 /* PerlIO has probably #defined away fputc, but we want it here. */
2314 # undef fputc /* XXX Should really restore it later */
2316 (void)fputc('\0', &fakebuf);
2318 #ifdef USE_CHAR_VSPRINTF
2321 return 0; /* perl doesn't use return value */
2325 #endif /* HAS_VPRINTF */
2328 Perl_my_popen_list(pTHX_ const char *mode, int n, SV **args)
2330 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(OS2) && !defined(VMS) && !defined(NETWARE) && !defined(__LIBCATAMOUNT__)
2338 PERL_ARGS_ASSERT_MY_POPEN_LIST;
2340 PERL_FLUSHALL_FOR_CHILD;
2341 This = (*mode == 'w');
2345 taint_proper("Insecure %s%s", "EXEC");
2347 if (PerlProc_pipe(p) < 0)
2349 /* Try for another pipe pair for error return */
2350 if (PerlProc_pipe(pp) >= 0)
2352 while ((pid = PerlProc_fork()) < 0) {
2353 if (errno != EAGAIN) {
2354 PerlLIO_close(p[This]);
2355 PerlLIO_close(p[that]);
2357 PerlLIO_close(pp[0]);
2358 PerlLIO_close(pp[1]);
2362 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2371 /* Close parent's end of error status pipe (if any) */
2373 PerlLIO_close(pp[0]);
2374 #if defined(HAS_FCNTL) && defined(F_SETFD)
2375 /* Close error pipe automatically if exec works */
2376 if (fcntl(pp[1], F_SETFD, FD_CLOEXEC) < 0)
2380 /* Now dup our end of _the_ pipe to right position */
2381 if (p[THIS] != (*mode == 'r')) {
2382 PerlLIO_dup2(p[THIS], *mode == 'r');
2383 PerlLIO_close(p[THIS]);
2384 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2385 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2388 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2389 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2390 /* No automatic close - do it by hand */
2397 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
2403 do_aexec5(NULL, args-1, args-1+n, pp[1], did_pipes);
2409 do_execfree(); /* free any memory malloced by child on fork */
2411 PerlLIO_close(pp[1]);
2412 /* Keep the lower of the two fd numbers */
2413 if (p[that] < p[This]) {
2414 PerlLIO_dup2(p[This], p[that]);
2415 PerlLIO_close(p[This]);
2419 PerlLIO_close(p[that]); /* close child's end of pipe */
2421 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2422 SvUPGRADE(sv,SVt_IV);
2424 PL_forkprocess = pid;
2425 /* If we managed to get status pipe check for exec fail */
2426 if (did_pipes && pid > 0) {
2431 while (n < sizeof(int)) {
2432 n1 = PerlLIO_read(pp[0],
2433 (void*)(((char*)&errkid)+n),
2439 PerlLIO_close(pp[0]);
2441 if (n) { /* Error */
2443 PerlLIO_close(p[This]);
2444 if (n != sizeof(int))
2445 Perl_croak(aTHX_ "panic: kid popen errno read, n=%u", n);
2447 pid2 = wait4pid(pid, &status, 0);
2448 } while (pid2 == -1 && errno == EINTR);
2449 errno = errkid; /* Propagate errno from kid */
2454 PerlLIO_close(pp[0]);
2455 return PerlIO_fdopen(p[This], mode);
2457 # if defined(OS2) /* Same, without fork()ing and all extra overhead... */
2458 return my_syspopen4(aTHX_ NULL, mode, n, args);
2459 # elif defined(WIN32)
2460 return win32_popenlist(mode, n, args);
2462 Perl_croak(aTHX_ "List form of piped open not implemented");
2463 return (PerlIO *) NULL;
2468 /* VMS' my_popen() is in VMS.c, same with OS/2. */
2469 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__LIBCATAMOUNT__)
2471 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2477 const I32 doexec = !(*cmd == '-' && cmd[1] == '\0');
2481 PERL_ARGS_ASSERT_MY_POPEN;
2483 PERL_FLUSHALL_FOR_CHILD;
2486 return my_syspopen(aTHX_ cmd,mode);
2489 This = (*mode == 'w');
2491 if (doexec && TAINTING_get) {
2493 taint_proper("Insecure %s%s", "EXEC");
2495 if (PerlProc_pipe(p) < 0)
2497 if (doexec && PerlProc_pipe(pp) >= 0)
2499 while ((pid = PerlProc_fork()) < 0) {
2500 if (errno != EAGAIN) {
2501 PerlLIO_close(p[This]);
2502 PerlLIO_close(p[that]);
2504 PerlLIO_close(pp[0]);
2505 PerlLIO_close(pp[1]);
2508 Perl_croak(aTHX_ "Can't fork: %s", Strerror(errno));
2511 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2521 PerlLIO_close(pp[0]);
2522 #if defined(HAS_FCNTL) && defined(F_SETFD)
2523 if (fcntl(pp[1], F_SETFD, FD_CLOEXEC) < 0)
2527 if (p[THIS] != (*mode == 'r')) {
2528 PerlLIO_dup2(p[THIS], *mode == 'r');
2529 PerlLIO_close(p[THIS]);
2530 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2531 PerlLIO_close(p[THAT]);
2534 PerlLIO_close(p[THAT]);
2537 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2544 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2549 /* may or may not use the shell */
2550 do_exec3(cmd, pp[1], did_pipes);
2553 #endif /* defined OS2 */
2555 #ifdef PERLIO_USING_CRLF
2556 /* Since we circumvent IO layers when we manipulate low-level
2557 filedescriptors directly, need to manually switch to the
2558 default, binary, low-level mode; see PerlIOBuf_open(). */
2559 PerlLIO_setmode((*mode == 'r'), O_BINARY);
2562 #ifdef PERL_USES_PL_PIDSTATUS
2563 hv_clear(PL_pidstatus); /* we have no children */
2569 do_execfree(); /* free any memory malloced by child on vfork */
2571 PerlLIO_close(pp[1]);
2572 if (p[that] < p[This]) {
2573 PerlLIO_dup2(p[This], p[that]);
2574 PerlLIO_close(p[This]);
2578 PerlLIO_close(p[that]);
2580 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2581 SvUPGRADE(sv,SVt_IV);
2583 PL_forkprocess = pid;
2584 if (did_pipes && pid > 0) {
2589 while (n < sizeof(int)) {
2590 n1 = PerlLIO_read(pp[0],
2591 (void*)(((char*)&errkid)+n),
2597 PerlLIO_close(pp[0]);
2599 if (n) { /* Error */
2601 PerlLIO_close(p[This]);
2602 if (n != sizeof(int))
2603 Perl_croak(aTHX_ "panic: kid popen errno read, n=%u", n);
2605 pid2 = wait4pid(pid, &status, 0);
2606 } while (pid2 == -1 && errno == EINTR);
2607 errno = errkid; /* Propagate errno from kid */
2612 PerlLIO_close(pp[0]);
2613 return PerlIO_fdopen(p[This], mode);
2617 FILE *djgpp_popen();
2619 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2621 PERL_FLUSHALL_FOR_CHILD;
2622 /* Call system's popen() to get a FILE *, then import it.
2623 used 0 for 2nd parameter to PerlIO_importFILE;
2626 return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2629 #if defined(__LIBCATAMOUNT__)
2631 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2638 #endif /* !DOSISH */
2640 /* this is called in parent before the fork() */
2642 Perl_atfork_lock(void)
2644 #if defined(USE_ITHREADS)
2646 /* locks must be held in locking order (if any) */
2648 MUTEX_LOCK(&PL_perlio_mutex);
2651 MUTEX_LOCK(&PL_malloc_mutex);
2657 /* this is called in both parent and child after the fork() */
2659 Perl_atfork_unlock(void)
2661 #if defined(USE_ITHREADS)
2663 /* locks must be released in same order as in atfork_lock() */
2665 MUTEX_UNLOCK(&PL_perlio_mutex);
2668 MUTEX_UNLOCK(&PL_malloc_mutex);
2677 #if defined(HAS_FORK)
2679 #if defined(USE_ITHREADS) && !defined(HAS_PTHREAD_ATFORK)
2684 /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2685 * handlers elsewhere in the code */
2690 /* this "canna happen" since nothing should be calling here if !HAS_FORK */
2691 Perl_croak_nocontext("fork() not available");
2693 #endif /* HAS_FORK */
2698 dup2(int oldfd, int newfd)
2700 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2703 PerlLIO_close(newfd);
2704 return fcntl(oldfd, F_DUPFD, newfd);
2706 #define DUP2_MAX_FDS 256
2707 int fdtmp[DUP2_MAX_FDS];
2713 PerlLIO_close(newfd);
2714 /* good enough for low fd's... */
2715 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2716 if (fdx >= DUP2_MAX_FDS) {
2724 PerlLIO_close(fdtmp[--fdx]);
2731 #ifdef HAS_SIGACTION
2734 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2736 struct sigaction act, oact;
2740 /* only "parent" interpreter can diddle signals */
2741 if (PL_curinterp != aTHX)
2742 return (Sighandler_t) SIG_ERR;
2745 act.sa_handler = (void(*)(int))handler;
2746 sigemptyset(&act.sa_mask);
2749 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2750 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2752 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2753 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2754 act.sa_flags |= SA_NOCLDWAIT;
2756 if (sigaction(signo, &act, &oact) == -1)
2757 return (Sighandler_t) SIG_ERR;
2759 return (Sighandler_t) oact.sa_handler;
2763 Perl_rsignal_state(pTHX_ int signo)
2765 struct sigaction oact;
2766 PERL_UNUSED_CONTEXT;
2768 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2769 return (Sighandler_t) SIG_ERR;
2771 return (Sighandler_t) oact.sa_handler;
2775 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2780 struct sigaction act;
2782 PERL_ARGS_ASSERT_RSIGNAL_SAVE;
2785 /* only "parent" interpreter can diddle signals */
2786 if (PL_curinterp != aTHX)
2790 act.sa_handler = (void(*)(int))handler;
2791 sigemptyset(&act.sa_mask);
2794 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2795 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2797 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2798 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2799 act.sa_flags |= SA_NOCLDWAIT;
2801 return sigaction(signo, &act, save);
2805 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2810 PERL_UNUSED_CONTEXT;
2812 /* only "parent" interpreter can diddle signals */
2813 if (PL_curinterp != aTHX)
2817 return sigaction(signo, save, (struct sigaction *)NULL);
2820 #else /* !HAS_SIGACTION */
2823 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2825 #if defined(USE_ITHREADS) && !defined(WIN32)
2826 /* only "parent" interpreter can diddle signals */
2827 if (PL_curinterp != aTHX)
2828 return (Sighandler_t) SIG_ERR;
2831 return PerlProc_signal(signo, handler);
2842 Perl_rsignal_state(pTHX_ int signo)
2845 Sighandler_t oldsig;
2847 #if defined(USE_ITHREADS) && !defined(WIN32)
2848 /* only "parent" interpreter can diddle signals */
2849 if (PL_curinterp != aTHX)
2850 return (Sighandler_t) SIG_ERR;
2854 oldsig = PerlProc_signal(signo, sig_trap);
2855 PerlProc_signal(signo, oldsig);
2857 PerlProc_kill(PerlProc_getpid(), signo);
2862 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2864 #if defined(USE_ITHREADS) && !defined(WIN32)
2865 /* only "parent" interpreter can diddle signals */
2866 if (PL_curinterp != aTHX)
2869 *save = PerlProc_signal(signo, handler);
2870 return (*save == (Sighandler_t) SIG_ERR) ? -1 : 0;
2874 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2876 #if defined(USE_ITHREADS) && !defined(WIN32)
2877 /* only "parent" interpreter can diddle signals */
2878 if (PL_curinterp != aTHX)
2881 return (PerlProc_signal(signo, *save) == (Sighandler_t) SIG_ERR) ? -1 : 0;
2884 #endif /* !HAS_SIGACTION */
2885 #endif /* !PERL_MICRO */
2887 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
2888 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__LIBCATAMOUNT__)
2890 Perl_my_pclose(pTHX_ PerlIO *ptr)
2898 const int fd = PerlIO_fileno(ptr);
2901 svp = av_fetch(PL_fdpid,fd,TRUE);
2902 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
2906 #if defined(USE_PERLIO)
2907 /* Find out whether the refcount is low enough for us to wait for the
2908 child proc without blocking. */
2909 should_wait = PerlIOUnix_refcnt(fd) == 1 && pid > 0;
2911 should_wait = pid > 0;
2915 if (pid == -1) { /* Opened by popen. */
2916 return my_syspclose(ptr);
2919 close_failed = (PerlIO_close(ptr) == EOF);
2921 if (should_wait) do {
2922 pid2 = wait4pid(pid, &status, 0);
2923 } while (pid2 == -1 && errno == EINTR);
2930 ? pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status)
2935 #if defined(__LIBCATAMOUNT__)
2937 Perl_my_pclose(pTHX_ PerlIO *ptr)
2942 #endif /* !DOSISH */
2944 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(__LIBCATAMOUNT__)
2946 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
2949 PERL_ARGS_ASSERT_WAIT4PID;
2950 #ifdef PERL_USES_PL_PIDSTATUS
2952 /* PERL_USES_PL_PIDSTATUS is only defined when neither
2953 waitpid() nor wait4() is available, or on OS/2, which
2954 doesn't appear to support waiting for a progress group
2955 member, so we can only treat a 0 pid as an unknown child.
2962 /* The keys in PL_pidstatus are now the raw 4 (or 8) bytes of the
2963 pid, rather than a string form. */
2964 SV * const * const svp = hv_fetch(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),FALSE);
2965 if (svp && *svp != &PL_sv_undef) {
2966 *statusp = SvIVX(*svp);
2967 (void)hv_delete(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),
2975 hv_iterinit(PL_pidstatus);
2976 if ((entry = hv_iternext(PL_pidstatus))) {
2977 SV * const sv = hv_iterval(PL_pidstatus,entry);
2979 const char * const spid = hv_iterkey(entry,&len);
2981 assert (len == sizeof(Pid_t));
2982 memcpy((char *)&pid, spid, len);
2983 *statusp = SvIVX(sv);
2984 /* The hash iterator is currently on this entry, so simply
2985 calling hv_delete would trigger the lazy delete, which on
2986 aggregate does more work, because next call to hv_iterinit()
2987 would spot the flag, and have to call the delete routine,
2988 while in the meantime any new entries can't re-use that
2990 hv_iterinit(PL_pidstatus);
2991 (void)hv_delete(PL_pidstatus,spid,len,G_DISCARD);
2998 # ifdef HAS_WAITPID_RUNTIME
2999 if (!HAS_WAITPID_RUNTIME)
3002 result = PerlProc_waitpid(pid,statusp,flags);
3005 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
3006 result = wait4(pid,statusp,flags,NULL);
3009 #ifdef PERL_USES_PL_PIDSTATUS
3010 #if defined(HAS_WAITPID) && defined(HAS_WAITPID_RUNTIME)
3015 Perl_croak(aTHX_ "Can't do waitpid with flags");
3017 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
3018 pidgone(result,*statusp);
3024 #if defined(HAS_WAITPID) || defined(HAS_WAIT4)
3027 if (result < 0 && errno == EINTR) {
3029 errno = EINTR; /* reset in case a signal handler changed $! */
3033 #endif /* !DOSISH || OS2 || WIN32 || NETWARE */
3035 #ifdef PERL_USES_PL_PIDSTATUS
3037 S_pidgone(pTHX_ Pid_t pid, int status)
3041 sv = *hv_fetch(PL_pidstatus,(const char*)&pid,sizeof(Pid_t),TRUE);
3042 SvUPGRADE(sv,SVt_IV);
3043 SvIV_set(sv, status);
3051 int /* Cannot prototype with I32
3053 my_syspclose(PerlIO *ptr)
3056 Perl_my_pclose(pTHX_ PerlIO *ptr)
3059 /* Needs work for PerlIO ! */
3060 FILE * const f = PerlIO_findFILE(ptr);
3061 const I32 result = pclose(f);
3062 PerlIO_releaseFILE(ptr,f);
3070 Perl_my_pclose(pTHX_ PerlIO *ptr)
3072 /* Needs work for PerlIO ! */
3073 FILE * const f = PerlIO_findFILE(ptr);
3074 I32 result = djgpp_pclose(f);
3075 result = (result << 8) & 0xff00;
3076 PerlIO_releaseFILE(ptr,f);
3081 #define PERL_REPEATCPY_LINEAR 4
3083 Perl_repeatcpy(char *to, const char *from, I32 len, IV count)
3085 PERL_ARGS_ASSERT_REPEATCPY;
3090 croak_memory_wrap();
3093 memset(to, *from, count);
3096 IV items, linear, half;
3098 linear = count < PERL_REPEATCPY_LINEAR ? count : PERL_REPEATCPY_LINEAR;
3099 for (items = 0; items < linear; ++items) {
3100 const char *q = from;
3102 for (todo = len; todo > 0; todo--)
3107 while (items <= half) {
3108 IV size = items * len;
3109 memcpy(p, to, size);
3115 memcpy(p, to, (count - items) * len);
3121 Perl_same_dirent(pTHX_ const char *a, const char *b)
3123 char *fa = strrchr(a,'/');
3124 char *fb = strrchr(b,'/');
3127 SV * const tmpsv = sv_newmortal();
3129 PERL_ARGS_ASSERT_SAME_DIRENT;
3142 sv_setpvs(tmpsv, ".");
3144 sv_setpvn(tmpsv, a, fa - a);
3145 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf1) < 0)
3148 sv_setpvs(tmpsv, ".");
3150 sv_setpvn(tmpsv, b, fb - b);
3151 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf2) < 0)
3153 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
3154 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
3156 #endif /* !HAS_RENAME */
3159 Perl_find_script(pTHX_ const char *scriptname, bool dosearch,
3160 const char *const *const search_ext, I32 flags)
3162 const char *xfound = NULL;
3163 char *xfailed = NULL;
3164 char tmpbuf[MAXPATHLEN];
3169 #if defined(DOSISH) && !defined(OS2)
3170 # define SEARCH_EXTS ".bat", ".cmd", NULL
3171 # define MAX_EXT_LEN 4
3174 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
3175 # define MAX_EXT_LEN 4
3178 # define SEARCH_EXTS ".pl", ".com", NULL
3179 # define MAX_EXT_LEN 4
3181 /* additional extensions to try in each dir if scriptname not found */
3183 static const char *const exts[] = { SEARCH_EXTS };
3184 const char *const *const ext = search_ext ? search_ext : exts;
3185 int extidx = 0, i = 0;
3186 const char *curext = NULL;
3188 PERL_UNUSED_ARG(search_ext);
3189 # define MAX_EXT_LEN 0
3192 PERL_ARGS_ASSERT_FIND_SCRIPT;
3195 * If dosearch is true and if scriptname does not contain path
3196 * delimiters, search the PATH for scriptname.
3198 * If SEARCH_EXTS is also defined, will look for each
3199 * scriptname{SEARCH_EXTS} whenever scriptname is not found
3200 * while searching the PATH.
3202 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
3203 * proceeds as follows:
3204 * If DOSISH or VMSISH:
3205 * + look for ./scriptname{,.foo,.bar}
3206 * + search the PATH for scriptname{,.foo,.bar}
3209 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
3210 * this will not look in '.' if it's not in the PATH)
3215 # ifdef ALWAYS_DEFTYPES
3216 len = strlen(scriptname);
3217 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
3218 int idx = 0, deftypes = 1;
3221 const int hasdir = !dosearch || (strpbrk(scriptname,":[</") != NULL);
3224 int idx = 0, deftypes = 1;
3227 const int hasdir = (strpbrk(scriptname,":[</") != NULL);
3229 /* The first time through, just add SEARCH_EXTS to whatever we
3230 * already have, so we can check for default file types. */
3232 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
3238 if ((strlen(tmpbuf) + strlen(scriptname)
3239 + MAX_EXT_LEN) >= sizeof tmpbuf)
3240 continue; /* don't search dir with too-long name */
3241 my_strlcat(tmpbuf, scriptname, sizeof(tmpbuf));
3245 if (strEQ(scriptname, "-"))
3247 if (dosearch) { /* Look in '.' first. */
3248 const char *cur = scriptname;
3250 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
3252 if (strEQ(ext[i++],curext)) {
3253 extidx = -1; /* already has an ext */
3258 DEBUG_p(PerlIO_printf(Perl_debug_log,
3259 "Looking for %s\n",cur));
3260 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
3261 && !S_ISDIR(PL_statbuf.st_mode)) {
3269 if (cur == scriptname) {
3270 len = strlen(scriptname);
3271 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
3273 my_strlcpy(tmpbuf, scriptname, sizeof(tmpbuf));
3276 } while (extidx >= 0 && ext[extidx] /* try an extension? */
3277 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len));
3282 if (dosearch && !strchr(scriptname, '/')
3284 && !strchr(scriptname, '\\')
3286 && (s = PerlEnv_getenv("PATH")))
3290 bufend = s + strlen(s);
3291 while (s < bufend) {
3294 && *s != ';'; len++, s++) {
3295 if (len < sizeof tmpbuf)
3298 if (len < sizeof tmpbuf)
3301 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, bufend,
3307 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
3308 continue; /* don't search dir with too-long name */
3311 && tmpbuf[len - 1] != '/'
3312 && tmpbuf[len - 1] != '\\'
3315 tmpbuf[len++] = '/';
3316 if (len == 2 && tmpbuf[0] == '.')
3318 (void)my_strlcpy(tmpbuf + len, scriptname, sizeof(tmpbuf) - len);
3322 len = strlen(tmpbuf);
3323 if (extidx > 0) /* reset after previous loop */
3327 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
3328 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
3329 if (S_ISDIR(PL_statbuf.st_mode)) {
3333 } while ( retval < 0 /* not there */
3334 && extidx>=0 && ext[extidx] /* try an extension? */
3335 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len)
3340 if (S_ISREG(PL_statbuf.st_mode)
3341 && cando(S_IRUSR,TRUE,&PL_statbuf)
3342 #if !defined(DOSISH)
3343 && cando(S_IXUSR,TRUE,&PL_statbuf)
3347 xfound = tmpbuf; /* bingo! */
3351 xfailed = savepv(tmpbuf);
3354 if (!xfound && !seen_dot && !xfailed &&
3355 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
3356 || S_ISDIR(PL_statbuf.st_mode)))
3358 seen_dot = 1; /* Disable message. */
3360 if (flags & 1) { /* do or die? */
3361 /* diag_listed_as: Can't execute %s */
3362 Perl_croak(aTHX_ "Can't %s %s%s%s",
3363 (xfailed ? "execute" : "find"),
3364 (xfailed ? xfailed : scriptname),
3365 (xfailed ? "" : " on PATH"),
3366 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
3371 scriptname = xfound;
3373 return (scriptname ? savepv(scriptname) : NULL);
3376 #ifndef PERL_GET_CONTEXT_DEFINED
3379 Perl_get_context(void)
3381 #if defined(USE_ITHREADS)
3383 # ifdef OLD_PTHREADS_API
3385 int error = pthread_getspecific(PL_thr_key, &t)
3387 Perl_croak_nocontext("panic: pthread_getspecific, error=%d", error);
3390 # ifdef I_MACH_CTHREADS
3391 return (void*)cthread_data(cthread_self());
3393 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
3402 Perl_set_context(void *t)
3404 #if defined(USE_ITHREADS)
3407 PERL_ARGS_ASSERT_SET_CONTEXT;
3408 #if defined(USE_ITHREADS)
3409 # ifdef I_MACH_CTHREADS
3410 cthread_set_data(cthread_self(), t);
3413 const int error = pthread_setspecific(PL_thr_key, t);
3415 Perl_croak_nocontext("panic: pthread_setspecific, error=%d", error);
3423 #endif /* !PERL_GET_CONTEXT_DEFINED */
3425 #if defined(PERL_GLOBAL_STRUCT) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
3429 PERL_UNUSED_CONTEXT;
3435 Perl_get_op_names(pTHX)
3437 PERL_UNUSED_CONTEXT;
3438 return (char **)PL_op_name;
3442 Perl_get_op_descs(pTHX)
3444 PERL_UNUSED_CONTEXT;
3445 return (char **)PL_op_desc;
3449 Perl_get_no_modify(pTHX)
3451 PERL_UNUSED_CONTEXT;
3452 return PL_no_modify;
3456 Perl_get_opargs(pTHX)
3458 PERL_UNUSED_CONTEXT;
3459 return (U32 *)PL_opargs;
3463 Perl_get_ppaddr(pTHX)
3466 PERL_UNUSED_CONTEXT;
3467 return (PPADDR_t*)PL_ppaddr;
3470 #ifndef HAS_GETENV_LEN
3472 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3474 char * const env_trans = PerlEnv_getenv(env_elem);
3475 PERL_UNUSED_CONTEXT;
3476 PERL_ARGS_ASSERT_GETENV_LEN;
3478 *len = strlen(env_trans);
3485 Perl_get_vtbl(pTHX_ int vtbl_id)
3487 PERL_UNUSED_CONTEXT;
3489 return (vtbl_id < 0 || vtbl_id >= magic_vtable_max)
3490 ? NULL : (MGVTBL*)PL_magic_vtables + vtbl_id;
3494 Perl_my_fflush_all(pTHX)
3496 #if defined(USE_PERLIO) || defined(FFLUSH_NULL)
3497 return PerlIO_flush(NULL);
3499 # if defined(HAS__FWALK)
3500 extern int fflush(FILE *);
3501 /* undocumented, unprototyped, but very useful BSDism */
3502 extern void _fwalk(int (*)(FILE *));
3506 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3508 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3509 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3511 # if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3512 open_max = sysconf(_SC_OPEN_MAX);
3515 open_max = FOPEN_MAX;
3518 open_max = OPEN_MAX;
3529 for (i = 0; i < open_max; i++)
3530 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3531 STDIO_STREAM_ARRAY[i]._file < open_max &&
3532 STDIO_STREAM_ARRAY[i]._flag)
3533 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3537 SETERRNO(EBADF,RMS_IFI);
3544 Perl_report_wrongway_fh(pTHX_ const GV *gv, const char have)
3546 if (ckWARN(WARN_IO)) {
3548 = gv && (isGV_with_GP(gv))
3551 const char * const direction = have == '>' ? "out" : "in";
3553 if (name && HEK_LEN(name))
3554 Perl_warner(aTHX_ packWARN(WARN_IO),
3555 "Filehandle %"HEKf" opened only for %sput",
3556 HEKfARG(name), direction);
3558 Perl_warner(aTHX_ packWARN(WARN_IO),
3559 "Filehandle opened only for %sput", direction);
3564 Perl_report_evil_fh(pTHX_ const GV *gv)
3566 const IO *io = gv ? GvIO(gv) : NULL;
3567 const PERL_BITFIELD16 op = PL_op->op_type;
3571 if (io && IoTYPE(io) == IoTYPE_CLOSED) {
3573 warn_type = WARN_CLOSED;
3577 warn_type = WARN_UNOPENED;
3580 if (ckWARN(warn_type)) {
3582 = gv && isGV_with_GP(gv) && GvENAMELEN(gv) ?
3583 sv_2mortal(newSVhek(GvENAME_HEK(gv))) : NULL;
3584 const char * const pars =
3585 (const char *)(OP_IS_FILETEST(op) ? "" : "()");
3586 const char * const func =
3588 (op == OP_READLINE || op == OP_RCATLINE
3589 ? "readline" : /* "<HANDLE>" not nice */
3590 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
3592 const char * const type =
3594 (OP_IS_SOCKET(op) || (io && IoTYPE(io) == IoTYPE_SOCKET)
3595 ? "socket" : "filehandle");
3596 const bool have_name = name && SvCUR(name);
3597 Perl_warner(aTHX_ packWARN(warn_type),
3598 "%s%s on %s %s%s%"SVf, func, pars, vile, type,
3599 have_name ? " " : "",
3600 SVfARG(have_name ? name : &PL_sv_no));
3601 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3603 aTHX_ packWARN(warn_type),
3604 "\t(Are you trying to call %s%s on dirhandle%s%"SVf"?)\n",
3605 func, pars, have_name ? " " : "",
3606 SVfARG(have_name ? name : &PL_sv_no)
3611 /* To workaround core dumps from the uninitialised tm_zone we get the
3612 * system to give us a reasonable struct to copy. This fix means that
3613 * strftime uses the tm_zone and tm_gmtoff values returned by
3614 * localtime(time()). That should give the desired result most of the
3615 * time. But probably not always!
3617 * This does not address tzname aspects of NETaa14816.
3622 # ifndef STRUCT_TM_HASZONE
3623 # define STRUCT_TM_HASZONE
3627 #ifdef STRUCT_TM_HASZONE /* Backward compat */
3628 # ifndef HAS_TM_TM_ZONE
3629 # define HAS_TM_TM_ZONE
3634 Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
3636 #ifdef HAS_TM_TM_ZONE
3638 const struct tm* my_tm;
3639 PERL_UNUSED_CONTEXT;
3640 PERL_ARGS_ASSERT_INIT_TM;
3642 my_tm = localtime(&now);
3644 Copy(my_tm, ptm, 1, struct tm);
3646 PERL_UNUSED_CONTEXT;
3647 PERL_ARGS_ASSERT_INIT_TM;
3648 PERL_UNUSED_ARG(ptm);
3653 * mini_mktime - normalise struct tm values without the localtime()
3654 * semantics (and overhead) of mktime().
3657 Perl_mini_mktime(struct tm *ptm)
3661 int month, mday, year, jday;
3662 int odd_cent, odd_year;
3664 PERL_ARGS_ASSERT_MINI_MKTIME;
3666 #define DAYS_PER_YEAR 365
3667 #define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
3668 #define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
3669 #define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
3670 #define SECS_PER_HOUR (60*60)
3671 #define SECS_PER_DAY (24*SECS_PER_HOUR)
3672 /* parentheses deliberately absent on these two, otherwise they don't work */
3673 #define MONTH_TO_DAYS 153/5
3674 #define DAYS_TO_MONTH 5/153
3675 /* offset to bias by March (month 4) 1st between month/mday & year finding */
3676 #define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
3677 /* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
3678 #define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
3681 * Year/day algorithm notes:
3683 * With a suitable offset for numeric value of the month, one can find
3684 * an offset into the year by considering months to have 30.6 (153/5) days,
3685 * using integer arithmetic (i.e., with truncation). To avoid too much
3686 * messing about with leap days, we consider January and February to be
3687 * the 13th and 14th month of the previous year. After that transformation,
3688 * we need the month index we use to be high by 1 from 'normal human' usage,
3689 * so the month index values we use run from 4 through 15.
3691 * Given that, and the rules for the Gregorian calendar (leap years are those
3692 * divisible by 4 unless also divisible by 100, when they must be divisible
3693 * by 400 instead), we can simply calculate the number of days since some
3694 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
3695 * the days we derive from our month index, and adding in the day of the
3696 * month. The value used here is not adjusted for the actual origin which
3697 * it normally would use (1 January A.D. 1), since we're not exposing it.
3698 * We're only building the value so we can turn around and get the
3699 * normalised values for the year, month, day-of-month, and day-of-year.
3701 * For going backward, we need to bias the value we're using so that we find
3702 * the right year value. (Basically, we don't want the contribution of
3703 * March 1st to the number to apply while deriving the year). Having done
3704 * that, we 'count up' the contribution to the year number by accounting for
3705 * full quadracenturies (400-year periods) with their extra leap days, plus
3706 * the contribution from full centuries (to avoid counting in the lost leap
3707 * days), plus the contribution from full quad-years (to count in the normal
3708 * leap days), plus the leftover contribution from any non-leap years.
3709 * At this point, if we were working with an actual leap day, we'll have 0
3710 * days left over. This is also true for March 1st, however. So, we have
3711 * to special-case that result, and (earlier) keep track of the 'odd'
3712 * century and year contributions. If we got 4 extra centuries in a qcent,
3713 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
3714 * Otherwise, we add back in the earlier bias we removed (the 123 from
3715 * figuring in March 1st), find the month index (integer division by 30.6),
3716 * and the remainder is the day-of-month. We then have to convert back to
3717 * 'real' months (including fixing January and February from being 14/15 in
3718 * the previous year to being in the proper year). After that, to get
3719 * tm_yday, we work with the normalised year and get a new yearday value for
3720 * January 1st, which we subtract from the yearday value we had earlier,
3721 * representing the date we've re-built. This is done from January 1
3722 * because tm_yday is 0-origin.
3724 * Since POSIX time routines are only guaranteed to work for times since the
3725 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
3726 * applies Gregorian calendar rules even to dates before the 16th century
3727 * doesn't bother me. Besides, you'd need cultural context for a given
3728 * date to know whether it was Julian or Gregorian calendar, and that's
3729 * outside the scope for this routine. Since we convert back based on the
3730 * same rules we used to build the yearday, you'll only get strange results
3731 * for input which needed normalising, or for the 'odd' century years which
3732 * were leap years in the Julian calendar but not in the Gregorian one.
3733 * I can live with that.
3735 * This algorithm also fails to handle years before A.D. 1 gracefully, but
3736 * that's still outside the scope for POSIX time manipulation, so I don't
3740 year = 1900 + ptm->tm_year;
3741 month = ptm->tm_mon;
3742 mday = ptm->tm_mday;
3748 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
3749 yearday += month*MONTH_TO_DAYS + mday + jday;
3751 * Note that we don't know when leap-seconds were or will be,
3752 * so we have to trust the user if we get something which looks
3753 * like a sensible leap-second. Wild values for seconds will
3754 * be rationalised, however.
3756 if ((unsigned) ptm->tm_sec <= 60) {
3763 secs += 60 * ptm->tm_min;
3764 secs += SECS_PER_HOUR * ptm->tm_hour;
3766 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
3767 /* got negative remainder, but need positive time */
3768 /* back off an extra day to compensate */
3769 yearday += (secs/SECS_PER_DAY)-1;
3770 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
3773 yearday += (secs/SECS_PER_DAY);
3774 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
3777 else if (secs >= SECS_PER_DAY) {
3778 yearday += (secs/SECS_PER_DAY);
3779 secs %= SECS_PER_DAY;
3781 ptm->tm_hour = secs/SECS_PER_HOUR;
3782 secs %= SECS_PER_HOUR;
3783 ptm->tm_min = secs/60;
3785 ptm->tm_sec += secs;
3786 /* done with time of day effects */
3788 * The algorithm for yearday has (so far) left it high by 428.
3789 * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
3790 * bias it by 123 while trying to figure out what year it
3791 * really represents. Even with this tweak, the reverse
3792 * translation fails for years before A.D. 0001.
3793 * It would still fail for Feb 29, but we catch that one below.
3795 jday = yearday; /* save for later fixup vis-a-vis Jan 1 */
3796 yearday -= YEAR_ADJUST;
3797 year = (yearday / DAYS_PER_QCENT) * 400;
3798 yearday %= DAYS_PER_QCENT;
3799 odd_cent = yearday / DAYS_PER_CENT;
3800 year += odd_cent * 100;
3801 yearday %= DAYS_PER_CENT;
3802 year += (yearday / DAYS_PER_QYEAR) * 4;
3803 yearday %= DAYS_PER_QYEAR;
3804 odd_year = yearday / DAYS_PER_YEAR;
3806 yearday %= DAYS_PER_YEAR;
3807 if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
3812 yearday += YEAR_ADJUST; /* recover March 1st crock */
3813 month = yearday*DAYS_TO_MONTH;
3814 yearday -= month*MONTH_TO_DAYS;
3815 /* recover other leap-year adjustment */
3824 ptm->tm_year = year - 1900;
3826 ptm->tm_mday = yearday;
3827 ptm->tm_mon = month;
3831 ptm->tm_mon = month - 1;
3833 /* re-build yearday based on Jan 1 to get tm_yday */
3835 yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
3836 yearday += 14*MONTH_TO_DAYS + 1;
3837 ptm->tm_yday = jday - yearday;
3838 ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
3842 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)
3846 /* Note that yday and wday effectively are ignored by this function, as mini_mktime() overwrites them */
3853 PERL_ARGS_ASSERT_MY_STRFTIME;
3855 init_tm(&mytm); /* XXX workaround - see init_tm() above */
3858 mytm.tm_hour = hour;
3859 mytm.tm_mday = mday;
3861 mytm.tm_year = year;
3862 mytm.tm_wday = wday;
3863 mytm.tm_yday = yday;
3864 mytm.tm_isdst = isdst;
3866 /* use libc to get the values for tm_gmtoff and tm_zone [perl #18238] */
3867 #if defined(HAS_MKTIME) && (defined(HAS_TM_TM_GMTOFF) || defined(HAS_TM_TM_ZONE))
3872 #ifdef HAS_TM_TM_GMTOFF
3873 mytm.tm_gmtoff = mytm2.tm_gmtoff;
3875 #ifdef HAS_TM_TM_ZONE
3876 mytm.tm_zone = mytm2.tm_zone;
3881 Newx(buf, buflen, char);
3883 GCC_DIAG_IGNORE(-Wformat-nonliteral); /* fmt checked by caller */
3884 len = strftime(buf, buflen, fmt, &mytm);
3888 ** The following is needed to handle to the situation where
3889 ** tmpbuf overflows. Basically we want to allocate a buffer
3890 ** and try repeatedly. The reason why it is so complicated
3891 ** is that getting a return value of 0 from strftime can indicate
3892 ** one of the following:
3893 ** 1. buffer overflowed,
3894 ** 2. illegal conversion specifier, or
3895 ** 3. the format string specifies nothing to be returned(not
3896 ** an error). This could be because format is an empty string
3897 ** or it specifies %p that yields an empty string in some locale.
3898 ** If there is a better way to make it portable, go ahead by
3901 if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
3904 /* Possibly buf overflowed - try again with a bigger buf */
3905 const int fmtlen = strlen(fmt);
3906 int bufsize = fmtlen + buflen;
3908 Renew(buf, bufsize, char);
3911 GCC_DIAG_IGNORE(-Wformat-nonliteral); /* fmt checked by caller */
3912 buflen = strftime(buf, bufsize, fmt, &mytm);
3915 if (buflen > 0 && buflen < bufsize)
3917 /* heuristic to prevent out-of-memory errors */
3918 if (bufsize > 100*fmtlen) {
3924 Renew(buf, bufsize, char);
3929 Perl_croak(aTHX_ "panic: no strftime");
3935 #define SV_CWD_RETURN_UNDEF \
3936 sv_setsv(sv, &PL_sv_undef); \
3939 #define SV_CWD_ISDOT(dp) \
3940 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
3941 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
3944 =head1 Miscellaneous Functions
3946 =for apidoc getcwd_sv
3948 Fill the sv with current working directory
3953 /* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
3954 * rewritten again by dougm, optimized for use with xs TARG, and to prefer
3955 * getcwd(3) if available
3956 * Comments from the original:
3957 * This is a faster version of getcwd. It's also more dangerous
3958 * because you might chdir out of a directory that you can't chdir
3962 Perl_getcwd_sv(pTHX_ SV *sv)
3967 PERL_ARGS_ASSERT_GETCWD_SV;
3971 char buf[MAXPATHLEN];
3973 /* Some getcwd()s automatically allocate a buffer of the given
3974 * size from the heap if they are given a NULL buffer pointer.
3975 * The problem is that this behaviour is not portable. */
3976 if (getcwd(buf, sizeof(buf) - 1)) {
3981 sv_setsv(sv, &PL_sv_undef);
3989 int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
3993 SvUPGRADE(sv, SVt_PV);
3995 if (PerlLIO_lstat(".", &statbuf) < 0) {
3996 SV_CWD_RETURN_UNDEF;
3999 orig_cdev = statbuf.st_dev;
4000 orig_cino = statbuf.st_ino;
4010 if (PerlDir_chdir("..") < 0) {
4011 SV_CWD_RETURN_UNDEF;
4013 if (PerlLIO_stat(".", &statbuf) < 0) {
4014 SV_CWD_RETURN_UNDEF;
4017 cdev = statbuf.st_dev;
4018 cino = statbuf.st_ino;
4020 if (odev == cdev && oino == cino) {
4023 if (!(dir = PerlDir_open("."))) {
4024 SV_CWD_RETURN_UNDEF;
4027 while ((dp = PerlDir_read(dir)) != NULL) {
4029 namelen = dp->d_namlen;
4031 namelen = strlen(dp->d_name);
4034 if (SV_CWD_ISDOT(dp)) {
4038 if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
4039 SV_CWD_RETURN_UNDEF;
4042 tdev = statbuf.st_dev;
4043 tino = statbuf.st_ino;
4044 if (tino == oino && tdev == odev) {
4050 SV_CWD_RETURN_UNDEF;
4053 if (pathlen + namelen + 1 >= MAXPATHLEN) {
4054 SV_CWD_RETURN_UNDEF;
4057 SvGROW(sv, pathlen + namelen + 1);
4061 Move(SvPVX_const(sv), SvPVX(sv) + namelen + 1, pathlen, char);
4064 /* prepend current directory to the front */
4066 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
4067 pathlen += (namelen + 1);
4069 #ifdef VOID_CLOSEDIR
4072 if (PerlDir_close(dir) < 0) {
4073 SV_CWD_RETURN_UNDEF;
4079 SvCUR_set(sv, pathlen);
4083 if (PerlDir_chdir(SvPVX_const(sv)) < 0) {
4084 SV_CWD_RETURN_UNDEF;
4087 if (PerlLIO_stat(".", &statbuf) < 0) {
4088 SV_CWD_RETURN_UNDEF;
4091 cdev = statbuf.st_dev;
4092 cino = statbuf.st_ino;
4094 if (cdev != orig_cdev || cino != orig_cino) {
4095 Perl_croak(aTHX_ "Unstable directory path, "
4096 "current directory changed unexpectedly");
4109 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET) && defined(SOCK_DGRAM) && defined(HAS_SELECT)
4110 # define EMULATE_SOCKETPAIR_UDP
4113 #ifdef EMULATE_SOCKETPAIR_UDP
4115 S_socketpair_udp (int fd[2]) {
4117 /* Fake a datagram socketpair using UDP to localhost. */
4118 int sockets[2] = {-1, -1};
4119 struct sockaddr_in addresses[2];
4121 Sock_size_t size = sizeof(struct sockaddr_in);
4122 unsigned short port;
4125 memset(&addresses, 0, sizeof(addresses));
4128 sockets[i] = PerlSock_socket(AF_INET, SOCK_DGRAM, PF_INET);
4129 if (sockets[i] == -1)
4130 goto tidy_up_and_fail;
4132 addresses[i].sin_family = AF_INET;
4133 addresses[i].sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4134 addresses[i].sin_port = 0; /* kernel choses port. */
4135 if (PerlSock_bind(sockets[i], (struct sockaddr *) &addresses[i],
4136 sizeof(struct sockaddr_in)) == -1)
4137 goto tidy_up_and_fail;
4140 /* Now have 2 UDP sockets. Find out which port each is connected to, and
4141 for each connect the other socket to it. */
4144 if (PerlSock_getsockname(sockets[i], (struct sockaddr *) &addresses[i],
4146 goto tidy_up_and_fail;
4147 if (size != sizeof(struct sockaddr_in))
4148 goto abort_tidy_up_and_fail;
4149 /* !1 is 0, !0 is 1 */
4150 if (PerlSock_connect(sockets[!i], (struct sockaddr *) &addresses[i],
4151 sizeof(struct sockaddr_in)) == -1)
4152 goto tidy_up_and_fail;
4155 /* Now we have 2 sockets connected to each other. I don't trust some other
4156 process not to have already sent a packet to us (by random) so send
4157 a packet from each to the other. */
4160 /* I'm going to send my own port number. As a short.
4161 (Who knows if someone somewhere has sin_port as a bitfield and needs
4162 this routine. (I'm assuming crays have socketpair)) */
4163 port = addresses[i].sin_port;
4164 got = PerlLIO_write(sockets[i], &port, sizeof(port));
4165 if (got != sizeof(port)) {
4167 goto tidy_up_and_fail;
4168 goto abort_tidy_up_and_fail;
4172 /* Packets sent. I don't trust them to have arrived though.
4173 (As I understand it Solaris TCP stack is multithreaded. Non-blocking
4174 connect to localhost will use a second kernel thread. In 2.6 the
4175 first thread running the connect() returns before the second completes,
4176 so EINPROGRESS> In 2.7 the improved stack is faster and connect()
4177 returns 0. Poor programs have tripped up. One poor program's authors'
4178 had a 50-1 reverse stock split. Not sure how connected these were.)
4179 So I don't trust someone not to have an unpredictable UDP stack.
4183 struct timeval waitfor = {0, 100000}; /* You have 0.1 seconds */
4184 int max = sockets[1] > sockets[0] ? sockets[1] : sockets[0];
4188 FD_SET((unsigned int)sockets[0], &rset);
4189 FD_SET((unsigned int)sockets[1], &rset);
4191 got = PerlSock_select(max + 1, &rset, NULL, NULL, &waitfor);
4192 if (got != 2 || !FD_ISSET(sockets[0], &rset)
4193 || !FD_ISSET(sockets[1], &rset)) {
4194 /* I hope this is portable and appropriate. */
4196 goto tidy_up_and_fail;
4197 goto abort_tidy_up_and_fail;
4201 /* And the paranoia department even now doesn't trust it to have arrive
4202 (hence MSG_DONTWAIT). Or that what arrives was sent by us. */
4204 struct sockaddr_in readfrom;
4205 unsigned short buffer[2];
4210 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4211 sizeof(buffer), MSG_DONTWAIT,
4212 (struct sockaddr *) &readfrom, &size);
4214 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4216 (struct sockaddr *) &readfrom, &size);
4220 goto tidy_up_and_fail;
4221 if (got != sizeof(port)
4222 || size != sizeof(struct sockaddr_in)
4223 /* Check other socket sent us its port. */
4224 || buffer[0] != (unsigned short) addresses[!i].sin_port
4225 /* Check kernel says we got the datagram from that socket */
4226 || readfrom.sin_family != addresses[!i].sin_family
4227 || readfrom.sin_addr.s_addr != addresses[!i].sin_addr.s_addr
4228 || readfrom.sin_port != addresses[!i].sin_port)
4229 goto abort_tidy_up_and_fail;
4232 /* My caller (my_socketpair) has validated that this is non-NULL */
4235 /* I hereby declare this connection open. May God bless all who cross
4239 abort_tidy_up_and_fail:
4240 errno = ECONNABORTED;
4244 if (sockets[0] != -1)
4245 PerlLIO_close(sockets[0]);
4246 if (sockets[1] != -1)
4247 PerlLIO_close(sockets[1]);
4252 #endif /* EMULATE_SOCKETPAIR_UDP */
4254 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET)
4256 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4257 /* Stevens says that family must be AF_LOCAL, protocol 0.
4258 I'm going to enforce that, then ignore it, and use TCP (or UDP). */
4263 struct sockaddr_in listen_addr;
4264 struct sockaddr_in connect_addr;
4269 || family != AF_UNIX
4272 errno = EAFNOSUPPORT;
4280 #ifdef EMULATE_SOCKETPAIR_UDP
4281 if (type == SOCK_DGRAM)
4282 return S_socketpair_udp(fd);
4285 aTHXa(PERL_GET_THX);
4286 listener = PerlSock_socket(AF_INET, type, 0);
4289 memset(&listen_addr, 0, sizeof(listen_addr));
4290 listen_addr.sin_family = AF_INET;
4291 listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4292 listen_addr.sin_port = 0; /* kernel choses port. */
4293 if (PerlSock_bind(listener, (struct sockaddr *) &listen_addr,
4294 sizeof(listen_addr)) == -1)
4295 goto tidy_up_and_fail;
4296 if (PerlSock_listen(listener, 1) == -1)
4297 goto tidy_up_and_fail;
4299 connector = PerlSock_socket(AF_INET, type, 0);
4300 if (connector == -1)
4301 goto tidy_up_and_fail;
4302 /* We want to find out the port number to connect to. */
4303 size = sizeof(connect_addr);
4304 if (PerlSock_getsockname(listener, (struct sockaddr *) &connect_addr,
4306 goto tidy_up_and_fail;
4307 if (size != sizeof(connect_addr))
4308 goto abort_tidy_up_and_fail;
4309 if (PerlSock_connect(connector, (struct sockaddr *) &connect_addr,
4310 sizeof(connect_addr)) == -1)
4311 goto tidy_up_and_fail;
4313 size = sizeof(listen_addr);
4314 acceptor = PerlSock_accept(listener, (struct sockaddr *) &listen_addr,
4317 goto tidy_up_and_fail;
4318 if (size != sizeof(listen_addr))
4319 goto abort_tidy_up_and_fail;
4320 PerlLIO_close(listener);
4321 /* Now check we are talking to ourself by matching port and host on the
4323 if (PerlSock_getsockname(connector, (struct sockaddr *) &connect_addr,
4325 goto tidy_up_and_fail;
4326 if (size != sizeof(connect_addr)
4327 || listen_addr.sin_family != connect_addr.sin_family
4328 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
4329 || listen_addr.sin_port != connect_addr.sin_port) {
4330 goto abort_tidy_up_and_fail;
4336 abort_tidy_up_and_fail:
4338 errno = ECONNABORTED; /* This would be the standard thing to do. */
4340 # ifdef ECONNREFUSED
4341 errno = ECONNREFUSED; /* E.g. Symbian does not have ECONNABORTED. */
4343 errno = ETIMEDOUT; /* Desperation time. */
4350 PerlLIO_close(listener);
4351 if (connector != -1)
4352 PerlLIO_close(connector);
4354 PerlLIO_close(acceptor);
4360 /* In any case have a stub so that there's code corresponding
4361 * to the my_socketpair in embed.fnc. */
4363 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4364 #ifdef HAS_SOCKETPAIR
4365 return socketpair(family, type, protocol, fd);
4374 =for apidoc sv_nosharing
4376 Dummy routine which "shares" an SV when there is no sharing module present.
4377 Or "locks" it. Or "unlocks" it. In other
4378 words, ignores its single SV argument.
4379 Exists to avoid test for a NULL function pointer and because it could
4380 potentially warn under some level of strict-ness.
4386 Perl_sv_nosharing(pTHX_ SV *sv)
4388 PERL_UNUSED_CONTEXT;
4389 PERL_UNUSED_ARG(sv);
4394 =for apidoc sv_destroyable
4396 Dummy routine which reports that object can be destroyed when there is no
4397 sharing module present. It ignores its single SV argument, and returns
4398 'true'. Exists to avoid test for a NULL function pointer and because it
4399 could potentially warn under some level of strict-ness.
4405 Perl_sv_destroyable(pTHX_ SV *sv)
4407 PERL_UNUSED_CONTEXT;
4408 PERL_UNUSED_ARG(sv);
4413 Perl_parse_unicode_opts(pTHX_ const char **popt)
4415 const char *p = *popt;
4418 PERL_ARGS_ASSERT_PARSE_UNICODE_OPTS;
4423 opt = (U32) grok_atou(p, &endptr);
4425 if (*p && *p != '\n' && *p != '\r') {
4426 if(isSPACE(*p)) goto the_end_of_the_opts_parser;
4428 Perl_croak(aTHX_ "Unknown Unicode option letter '%c'", *p);
4434 case PERL_UNICODE_STDIN:
4435 opt |= PERL_UNICODE_STDIN_FLAG; break;
4436 case PERL_UNICODE_STDOUT:
4437 opt |= PERL_UNICODE_STDOUT_FLAG; break;
4438 case PERL_UNICODE_STDERR:
4439 opt |= PERL_UNICODE_STDERR_FLAG; break;
4440 case PERL_UNICODE_STD:
4441 opt |= PERL_UNICODE_STD_FLAG; break;
4442 case PERL_UNICODE_IN:
4443 opt |= PERL_UNICODE_IN_FLAG; break;
4444 case PERL_UNICODE_OUT:
4445 opt |= PERL_UNICODE_OUT_FLAG; break;
4446 case PERL_UNICODE_INOUT:
4447 opt |= PERL_UNICODE_INOUT_FLAG; break;
4448 case PERL_UNICODE_LOCALE:
4449 opt |= PERL_UNICODE_LOCALE_FLAG; break;
4450 case PERL_UNICODE_ARGV:
4451 opt |= PERL_UNICODE_ARGV_FLAG; break;
4452 case PERL_UNICODE_UTF8CACHEASSERT:
4453 opt |= PERL_UNICODE_UTF8CACHEASSERT_FLAG; break;
4455 if (*p != '\n' && *p != '\r') {
4456 if(isSPACE(*p)) goto the_end_of_the_opts_parser;
4459 "Unknown Unicode option letter '%c'", *p);
4466 opt = PERL_UNICODE_DEFAULT_FLAGS;
4468 the_end_of_the_opts_parser:
4470 if (opt & ~PERL_UNICODE_ALL_FLAGS)
4471 Perl_croak(aTHX_ "Unknown Unicode option value %"UVuf,
4472 (UV) (opt & ~PERL_UNICODE_ALL_FLAGS));
4480 # include <starlet.h>
4487 * This is really just a quick hack which grabs various garbage
4488 * values. It really should be a real hash algorithm which
4489 * spreads the effect of every input bit onto every output bit,
4490 * if someone who knows about such things would bother to write it.
4491 * Might be a good idea to add that function to CORE as well.
4492 * No numbers below come from careful analysis or anything here,
4493 * except they are primes and SEED_C1 > 1E6 to get a full-width
4494 * value from (tv_sec * SEED_C1 + tv_usec). The multipliers should
4495 * probably be bigger too.
4498 # define SEED_C1 1000003
4499 #define SEED_C4 73819
4501 # define SEED_C1 25747
4502 #define SEED_C4 20639
4506 #define SEED_C5 26107
4508 #ifndef PERL_NO_DEV_RANDOM
4513 /* when[] = (low 32 bits, high 32 bits) of time since epoch
4514 * in 100-ns units, typically incremented ever 10 ms. */
4515 unsigned int when[2];
4517 # ifdef HAS_GETTIMEOFDAY
4518 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)
4544 _ckvmssts(sys$gettim(when));
4545 u = (U32)SEED_C1 * when[0] + (U32)SEED_C2 * when[1];
4547 # ifdef HAS_GETTIMEOFDAY
4548 PerlProc_gettimeofday(&when,NULL);
4549 u = (U32)SEED_C1 * when.tv_sec + (U32)SEED_C2 * when.tv_usec;
4552 u = (U32)SEED_C1 * when;
4555 u += SEED_C3 * (U32)PerlProc_getpid();
4556 u += SEED_C4 * (U32)PTR2UV(PL_stack_sp);
4557 #ifndef PLAN9 /* XXX Plan9 assembler chokes on this; fix needed */
4558 u += SEED_C5 * (U32)PTR2UV(&when);
4564 Perl_get_hash_seed(pTHX_ unsigned char * const seed_buffer)
4569 PERL_ARGS_ASSERT_GET_HASH_SEED;
4571 env_pv= PerlEnv_getenv("PERL_HASH_SEED");
4574 #ifndef USE_HASH_SEED_EXPLICIT
4576 /* ignore leading spaces */
4577 while (isSPACE(*env_pv))
4579 #ifdef USE_PERL_PERTURB_KEYS
4580 /* if they set it to "0" we disable key traversal randomization completely */
4581 if (strEQ(env_pv,"0")) {
4582 PL_hash_rand_bits_enabled= 0;
4584 /* otherwise switch to deterministic mode */
4585 PL_hash_rand_bits_enabled= 2;
4588 /* ignore a leading 0x... if it is there */
4589 if (env_pv[0] == '0' && env_pv[1] == 'x')
4592 for( i = 0; isXDIGIT(*env_pv) && i < PERL_HASH_SEED_BYTES; i++ ) {
4593 seed_buffer[i] = READ_XDIGIT(env_pv) << 4;
4594 if ( isXDIGIT(*env_pv)) {
4595 seed_buffer[i] |= READ_XDIGIT(env_pv);
4598 while (isSPACE(*env_pv))
4601 if (*env_pv && !isXDIGIT(*env_pv)) {
4602 Perl_warn(aTHX_ "perl: warning: Non hex character in '$ENV{PERL_HASH_SEED}', seed only partially set\n");
4604 /* should we check for unparsed crap? */
4605 /* should we warn about unused hex? */
4606 /* should we warn about insufficient hex? */
4611 (void)seedDrand01((Rand_seed_t)seed());
4613 for( i = 0; i < PERL_HASH_SEED_BYTES; i++ ) {
4614 seed_buffer[i] = (unsigned char)(Drand01() * (U8_MAX+1));
4617 #ifdef USE_PERL_PERTURB_KEYS
4618 { /* initialize PL_hash_rand_bits from the hash seed.
4619 * This value is highly volatile, it is updated every
4620 * hash insert, and is used as part of hash bucket chain
4621 * randomization and hash iterator randomization. */
4622 PL_hash_rand_bits= 0xbe49d17f; /* I just picked a number */
4623 for( i = 0; i < sizeof(UV) ; i++ ) {
4624 PL_hash_rand_bits += seed_buffer[i % PERL_HASH_SEED_BYTES];
4625 PL_hash_rand_bits = ROTL_UV(PL_hash_rand_bits,8);
4628 env_pv= PerlEnv_getenv("PERL_PERTURB_KEYS");
4630 if (strEQ(env_pv,"0") || strEQ(env_pv,"NO")) {
4631 PL_hash_rand_bits_enabled= 0;
4632 } else if (strEQ(env_pv,"1") || strEQ(env_pv,"RANDOM")) {
4633 PL_hash_rand_bits_enabled= 1;
4634 } else if (strEQ(env_pv,"2") || strEQ(env_pv,"DETERMINISTIC")) {
4635 PL_hash_rand_bits_enabled= 2;
4637 Perl_warn(aTHX_ "perl: warning: strange setting in '$ENV{PERL_PERTURB_KEYS}': '%s'\n", env_pv);
4643 #ifdef PERL_GLOBAL_STRUCT
4645 #define PERL_GLOBAL_STRUCT_INIT
4646 #include "opcode.h" /* the ppaddr and check */
4649 Perl_init_global_struct(pTHX)
4651 struct perl_vars *plvarsp = NULL;
4652 # ifdef PERL_GLOBAL_STRUCT
4653 const IV nppaddr = C_ARRAY_LENGTH(Gppaddr);
4654 const IV ncheck = C_ARRAY_LENGTH(Gcheck);
4655 PERL_UNUSED_CONTEXT;
4656 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
4657 /* PerlMem_malloc() because can't use even safesysmalloc() this early. */
4658 plvarsp = (struct perl_vars*)PerlMem_malloc(sizeof(struct perl_vars));
4662 plvarsp = PL_VarsPtr;
4663 # endif /* PERL_GLOBAL_STRUCT_PRIVATE */
4668 # define PERLVAR(prefix,var,type) /**/
4669 # define PERLVARA(prefix,var,n,type) /**/
4670 # define PERLVARI(prefix,var,type,init) plvarsp->prefix##var = init;
4671 # define PERLVARIC(prefix,var,type,init) plvarsp->prefix##var = init;
4672 # include "perlvars.h"
4677 # ifdef PERL_GLOBAL_STRUCT
4680 PerlMem_malloc(nppaddr * sizeof(Perl_ppaddr_t));
4681 if (!plvarsp->Gppaddr)
4685 PerlMem_malloc(ncheck * sizeof(Perl_check_t));
4686 if (!plvarsp->Gcheck)
4688 Copy(Gppaddr, plvarsp->Gppaddr, nppaddr, Perl_ppaddr_t);
4689 Copy(Gcheck, plvarsp->Gcheck, ncheck, Perl_check_t);
4691 # ifdef PERL_SET_VARS
4692 PERL_SET_VARS(plvarsp);
4694 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
4695 plvarsp->Gsv_placeholder.sv_flags = 0;
4696 memset(plvarsp->Ghash_seed, 0, sizeof(plvarsp->Ghash_seed));
4698 # undef PERL_GLOBAL_STRUCT_INIT
4703 #endif /* PERL_GLOBAL_STRUCT */
4705 #ifdef PERL_GLOBAL_STRUCT
4708 Perl_free_global_struct(pTHX_ struct perl_vars *plvarsp)
4710 int veto = plvarsp->Gveto_cleanup;
4712 PERL_ARGS_ASSERT_FREE_GLOBAL_STRUCT;
4713 PERL_UNUSED_CONTEXT;
4714 # ifdef PERL_GLOBAL_STRUCT
4715 # ifdef PERL_UNSET_VARS
4716 PERL_UNSET_VARS(plvarsp);
4720 free(plvarsp->Gppaddr);
4721 free(plvarsp->Gcheck);
4722 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
4728 #endif /* PERL_GLOBAL_STRUCT */
4732 /* -DPERL_MEM_LOG: the Perl_mem_log_..() is compiled, including the
4733 * the default implementation, unless -DPERL_MEM_LOG_NOIMPL is also
4734 * given, and you supply your own implementation.
4736 * The default implementation reads a single env var, PERL_MEM_LOG,
4737 * expecting one or more of the following:
4739 * \d+ - fd fd to write to : must be 1st (grok_atou)
4740 * 'm' - memlog was PERL_MEM_LOG=1
4741 * 's' - svlog was PERL_SV_LOG=1
4742 * 't' - timestamp was PERL_MEM_LOG_TIMESTAMP=1
4744 * This makes the logger controllable enough that it can reasonably be
4745 * added to the system perl.
4748 /* -DPERL_MEM_LOG_SPRINTF_BUF_SIZE=X: size of a (stack-allocated) buffer
4749 * the Perl_mem_log_...() will use (either via sprintf or snprintf).
4751 #define PERL_MEM_LOG_SPRINTF_BUF_SIZE 128
4753 /* -DPERL_MEM_LOG_FD=N: the file descriptor the Perl_mem_log_...()
4754 * writes to. In the default logger, this is settable at runtime.
4756 #ifndef PERL_MEM_LOG_FD
4757 # define PERL_MEM_LOG_FD 2 /* If STDERR is too boring for you. */
4760 #ifndef PERL_MEM_LOG_NOIMPL
4762 # ifdef DEBUG_LEAKING_SCALARS
4763 # define SV_LOG_SERIAL_FMT " [%lu]"
4764 # define _SV_LOG_SERIAL_ARG(sv) , (unsigned long) (sv)->sv_debug_serial
4766 # define SV_LOG_SERIAL_FMT
4767 # define _SV_LOG_SERIAL_ARG(sv)
4771 S_mem_log_common(enum mem_log_type mlt, const UV n,
4772 const UV typesize, const char *type_name, const SV *sv,
4773 Malloc_t oldalloc, Malloc_t newalloc,
4774 const char *filename, const int linenumber,
4775 const char *funcname)
4779 PERL_ARGS_ASSERT_MEM_LOG_COMMON;
4781 pmlenv = PerlEnv_getenv("PERL_MEM_LOG");
4784 if (mlt < MLT_NEW_SV ? strchr(pmlenv,'m') : strchr(pmlenv,'s'))
4786 /* We can't use SVs or PerlIO for obvious reasons,
4787 * so we'll use stdio and low-level IO instead. */
4788 char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
4790 # ifdef HAS_GETTIMEOFDAY
4791 # define MEM_LOG_TIME_FMT "%10d.%06d: "
4792 # define MEM_LOG_TIME_ARG (int)tv.tv_sec, (int)tv.tv_usec
4794 gettimeofday(&tv, 0);
4796 # define MEM_LOG_TIME_FMT "%10d: "
4797 # define MEM_LOG_TIME_ARG (int)when
4801 /* If there are other OS specific ways of hires time than
4802 * gettimeofday() (see ext/Time-HiRes), the easiest way is
4803 * probably that they would be used to fill in the struct
4808 int fd = grok_atou(pmlenv, &endptr); /* Ignore endptr. */
4810 fd = PERL_MEM_LOG_FD;
4812 if (strchr(pmlenv, 't')) {
4813 len = my_snprintf(buf, sizeof(buf),
4814 MEM_LOG_TIME_FMT, MEM_LOG_TIME_ARG);
4815 PERL_UNUSED_RESULT(PerlLIO_write(fd, buf, len));
4819 len = my_snprintf(buf, sizeof(buf),
4820 "alloc: %s:%d:%s: %"IVdf" %"UVuf
4821 " %s = %"IVdf": %"UVxf"\n",
4822 filename, linenumber, funcname, n, typesize,
4823 type_name, n * typesize, PTR2UV(newalloc));
4826 len = my_snprintf(buf, sizeof(buf),
4827 "realloc: %s:%d:%s: %"IVdf" %"UVuf
4828 " %s = %"IVdf": %"UVxf" -> %"UVxf"\n",
4829 filename, linenumber, funcname, n, typesize,
4830 type_name, n * typesize, PTR2UV(oldalloc),
4834 len = my_snprintf(buf, sizeof(buf),
4835 "free: %s:%d:%s: %"UVxf"\n",
4836 filename, linenumber, funcname,
4841 len = my_snprintf(buf, sizeof(buf),
4842 "%s_SV: %s:%d:%s: %"UVxf SV_LOG_SERIAL_FMT "\n",
4843 mlt == MLT_NEW_SV ? "new" : "del",
4844 filename, linenumber, funcname,
4845 PTR2UV(sv) _SV_LOG_SERIAL_ARG(sv));
4850 PERL_UNUSED_RESULT(PerlLIO_write(fd, buf, len));
4854 #endif /* !PERL_MEM_LOG_NOIMPL */
4856 #ifndef PERL_MEM_LOG_NOIMPL
4858 mem_log_common_if(alty, num, tysz, tynm, sv, oal, nal, flnm, ln, fnnm) \
4859 mem_log_common (alty, num, tysz, tynm, sv, oal, nal, flnm, ln, fnnm)
4861 /* this is suboptimal, but bug compatible. User is providing their
4862 own implementation, but is getting these functions anyway, and they
4863 do nothing. But _NOIMPL users should be able to cope or fix */
4865 mem_log_common_if(alty, num, tysz, tynm, u, oal, nal, flnm, ln, fnnm) \
4866 /* mem_log_common_if_PERL_MEM_LOG_NOIMPL */
4870 Perl_mem_log_alloc(const UV n, const UV typesize, const char *type_name,
4872 const char *filename, const int linenumber,
4873 const char *funcname)
4875 mem_log_common_if(MLT_ALLOC, n, typesize, type_name,
4876 NULL, NULL, newalloc,
4877 filename, linenumber, funcname);
4882 Perl_mem_log_realloc(const UV n, const UV typesize, const char *type_name,
4883 Malloc_t oldalloc, Malloc_t newalloc,
4884 const char *filename, const int linenumber,
4885 const char *funcname)
4887 mem_log_common_if(MLT_REALLOC, n, typesize, type_name,
4888 NULL, oldalloc, newalloc,
4889 filename, linenumber, funcname);
4894 Perl_mem_log_free(Malloc_t oldalloc,
4895 const char *filename, const int linenumber,
4896 const char *funcname)
4898 mem_log_common_if(MLT_FREE, 0, 0, "", NULL, oldalloc, NULL,
4899 filename, linenumber, funcname);
4904 Perl_mem_log_new_sv(const SV *sv,
4905 const char *filename, const int linenumber,
4906 const char *funcname)
4908 mem_log_common_if(MLT_NEW_SV, 0, 0, "", sv, NULL, NULL,
4909 filename, linenumber, funcname);
4913 Perl_mem_log_del_sv(const SV *sv,
4914 const char *filename, const int linenumber,
4915 const char *funcname)
4917 mem_log_common_if(MLT_DEL_SV, 0, 0, "", sv, NULL, NULL,
4918 filename, linenumber, funcname);
4921 #endif /* PERL_MEM_LOG */
4924 =for apidoc my_sprintf
4926 The C library C<sprintf>, wrapped if necessary, to ensure that it will return
4927 the length of the string written to the buffer. Only rare pre-ANSI systems
4928 need the wrapper function - usually this is a direct call to C<sprintf>.
4932 #ifndef SPRINTF_RETURNS_STRLEN
4934 Perl_my_sprintf(char *buffer, const char* pat, ...)
4937 PERL_ARGS_ASSERT_MY_SPRINTF;
4938 va_start(args, pat);
4939 vsprintf(buffer, pat, args);
4941 return strlen(buffer);
4946 =for apidoc quadmath_format_single
4948 quadmath_snprintf() is very strict about its format string and will
4949 fail, returning -1, if the format is invalid. It acccepts exactly
4952 quadmath_format_single() checks that the intended single spec looks
4953 sane: begins with C<%>, has only one C<%>, ends with C<[efgaEFGA]>,
4954 and has C<Q> before it. This is not a full "printf syntax check",
4957 Returns the format if it is valid, NULL if not.
4959 quadmath_format_single() can and will actually patch in the missing
4960 C<Q>, if necessary. In this case it will return the modified copy of
4961 the format, B<which the caller will need to free.>
4963 See also L</quadmath_format_needed>.
4969 Perl_quadmath_format_single(const char* format)
4973 PERL_ARGS_ASSERT_QUADMATH_FORMAT_SINGLE;
4975 if (format[0] != '%' || strchr(format + 1, '%'))
4977 len = strlen(format);
4978 /* minimum length three: %Qg */
4979 if (len < 3 || strchr("efgaEFGA", format[len - 1]) == NULL)
4981 if (format[len - 2] != 'Q') {
4983 Newx(fixed, len + 1, char);
4984 memcpy(fixed, format, len - 1);
4985 fixed[len - 1] = 'Q';
4986 fixed[len ] = format[len - 1];
4988 return (const char*)fixed;
4995 =for apidoc quadmath_format_needed
4997 quadmath_format_needed() returns true if the format string seems to
4998 contain at least one non-Q-prefixed %[efgaEFGA] format specifier,
4999 or returns false otherwise.
5001 The format specifier detection is not complete printf-syntax detection,
5002 but it should catch most common cases.
5004 If true is returned, those arguments B<should> in theory be processed
5005 with quadmath_snprintf(), but in case there is more than one such
5006 format specifier (see L</quadmath_format_single>), and if there is
5007 anything else beyond that one (even just a single byte), they
5008 B<cannot> be processed because quadmath_snprintf() is very strict,
5009 accepting only one format spec, and nothing else.
5010 In this case, the code should probably fail.
5016 Perl_quadmath_format_needed(const char* format)
5018 const char *p = format;
5021 PERL_ARGS_ASSERT_QUADMATH_FORMAT_NEEDED;
5023 while ((q = strchr(p, '%'))) {
5025 if (*q == '+') /* plus */
5027 if (*q == '#') /* alt */
5029 if (*q == '*') /* width */
5033 while (isDIGIT(*q)) q++;
5036 if (*q == '.' && (q[1] == '*' || isDIGIT(q[1]))) { /* prec */
5041 while (isDIGIT(*q)) q++;
5043 if (strchr("efgaEFGA", *q)) /* Would have needed 'Q' in front. */
5052 =for apidoc my_snprintf
5054 The C library C<snprintf> functionality, if available and
5055 standards-compliant (uses C<vsnprintf>, actually). However, if the
5056 C<vsnprintf> is not available, will unfortunately use the unsafe
5057 C<vsprintf> which can overrun the buffer (there is an overrun check,
5058 but that may be too late). Consider using C<sv_vcatpvf> instead, or
5059 getting C<vsnprintf>.
5064 Perl_my_snprintf(char *buffer, const Size_t len, const char *format, ...)
5068 PERL_ARGS_ASSERT_MY_SNPRINTF;
5069 #ifndef HAS_VSNPRINTF
5070 PERL_UNUSED_VAR(len);
5072 va_start(ap, format);
5075 const char* qfmt = quadmath_format_single(format);
5076 bool quadmath_valid = FALSE;
5078 /* If the format looked promising, use it as quadmath. */
5079 retval = quadmath_snprintf(buffer, len, qfmt, va_arg(ap, NV));
5081 Perl_croak_nocontext("panic: quadmath_snprintf failed, format \"%s\"", qfmt);
5082 quadmath_valid = TRUE;
5087 assert(qfmt == NULL);
5088 /* quadmath_format_single() will return false for example for
5089 * "foo = %g", or simply "%g". We could handle the %g by
5090 * using quadmath for the NV args. More complex cases of
5091 * course exist: "foo = %g, bar = %g", or "foo=%Qg" (otherwise
5092 * quadmath-valid but has stuff in front).
5094 * Handling the "Q-less" cases right would require walking
5095 * through the va_list and rewriting the format, calling
5096 * quadmath for the NVs, building a new va_list, and then
5097 * letting vsnprintf/vsprintf to take care of the other
5098 * arguments. This may be doable.
5100 * We do not attempt that now. But for paranoia, we here try
5101 * to detect some common (but not all) cases where the
5102 * "Q-less" %[efgaEFGA] formats are present, and die if
5103 * detected. This doesn't fix the problem, but it stops the
5104 * vsnprintf/vsprintf pulling doubles off the va_list when
5105 * __float128 NVs should be pulled off instead.
5107 * If quadmath_format_needed() returns false, we are reasonably
5108 * certain that we can call vnsprintf() or vsprintf() safely. */
5109 if (!quadmath_valid && quadmath_format_needed(format))
5110 Perl_croak_nocontext("panic: quadmath_snprintf failed, format \"%s\"", format);
5115 #ifdef HAS_VSNPRINTF
5116 retval = vsnprintf(buffer, len, format, ap);
5118 retval = vsprintf(buffer, format, ap);
5121 /* vsprintf() shows failure with < 0 */
5123 #ifdef HAS_VSNPRINTF
5124 /* vsnprintf() shows failure with >= len */
5126 (len > 0 && (Size_t)retval >= len)
5129 Perl_croak_nocontext("panic: my_snprintf buffer overflow");
5134 =for apidoc my_vsnprintf
5136 The C library C<vsnprintf> if available and standards-compliant.
5137 However, if if the C<vsnprintf> is not available, will unfortunately
5138 use the unsafe C<vsprintf> which can overrun the buffer (there is an
5139 overrun check, but that may be too late). Consider using
5140 C<sv_vcatpvf> instead, or getting C<vsnprintf>.
5145 Perl_my_vsnprintf(char *buffer, const Size_t len, const char *format, va_list ap)
5148 PERL_UNUSED_ARG(buffer);
5149 PERL_UNUSED_ARG(len);
5150 PERL_UNUSED_ARG(format);
5151 PERL_UNUSED_ARG(ap);
5152 Perl_croak_nocontext("panic: my_vsnprintf not available with quadmath");
5159 PERL_ARGS_ASSERT_MY_VSNPRINTF;
5160 #ifndef HAS_VSNPRINTF
5161 PERL_UNUSED_VAR(len);
5163 Perl_va_copy(ap, apc);
5164 # ifdef HAS_VSNPRINTF
5165 retval = vsnprintf(buffer, len, format, apc);
5167 retval = vsprintf(buffer, format, apc);
5171 # ifdef HAS_VSNPRINTF
5172 retval = vsnprintf(buffer, len, format, ap);
5174 retval = vsprintf(buffer, format, ap);
5176 #endif /* #ifdef NEED_VA_COPY */
5177 /* vsprintf() shows failure with < 0 */
5179 #ifdef HAS_VSNPRINTF
5180 /* vsnprintf() shows failure with >= len */
5182 (len > 0 && (Size_t)retval >= len)
5185 Perl_croak_nocontext("panic: my_vsnprintf buffer overflow");
5191 Perl_my_clearenv(pTHX)
5194 #if ! defined(PERL_MICRO)
5195 # if defined(PERL_IMPLICIT_SYS) || defined(WIN32)
5197 # else /* ! (PERL_IMPLICIT_SYS || WIN32) */
5198 # if defined(USE_ENVIRON_ARRAY)
5199 # if defined(USE_ITHREADS)
5200 /* only the parent thread can clobber the process environment */
5201 if (PL_curinterp == aTHX)
5202 # endif /* USE_ITHREADS */
5204 # if ! defined(PERL_USE_SAFE_PUTENV)
5205 if ( !PL_use_safe_putenv) {
5207 if (environ == PL_origenviron)
5208 environ = (char**)safesysmalloc(sizeof(char*));
5210 for (i = 0; environ[i]; i++)
5211 (void)safesysfree(environ[i]);
5214 # else /* PERL_USE_SAFE_PUTENV */
5215 # if defined(HAS_CLEARENV)
5217 # elif defined(HAS_UNSETENV)
5218 int bsiz = 80; /* Most envvar names will be shorter than this. */
5219 char *buf = (char*)safesysmalloc(bsiz);
5220 while (*environ != NULL) {
5221 char *e = strchr(*environ, '=');
5222 int l = e ? e - *environ : (int)strlen(*environ);
5224 (void)safesysfree(buf);
5225 bsiz = l + 1; /* + 1 for the \0. */
5226 buf = (char*)safesysmalloc(bsiz);
5228 memcpy(buf, *environ, l);
5230 (void)unsetenv(buf);
5232 (void)safesysfree(buf);
5233 # else /* ! HAS_CLEARENV && ! HAS_UNSETENV */
5234 /* Just null environ and accept the leakage. */
5236 # endif /* HAS_CLEARENV || HAS_UNSETENV */
5237 # endif /* ! PERL_USE_SAFE_PUTENV */
5239 # endif /* USE_ENVIRON_ARRAY */
5240 # endif /* PERL_IMPLICIT_SYS || WIN32 */
5241 #endif /* PERL_MICRO */
5244 #ifdef PERL_IMPLICIT_CONTEXT
5246 /* Implements the MY_CXT_INIT macro. The first time a module is loaded,
5247 the global PL_my_cxt_index is incremented, and that value is assigned to
5248 that module's static my_cxt_index (who's address is passed as an arg).
5249 Then, for each interpreter this function is called for, it makes sure a
5250 void* slot is available to hang the static data off, by allocating or
5251 extending the interpreter's PL_my_cxt_list array */
5253 #ifndef PERL_GLOBAL_STRUCT_PRIVATE
5255 Perl_my_cxt_init(pTHX_ int *index, size_t size)
5259 PERL_ARGS_ASSERT_MY_CXT_INIT;
5261 /* this module hasn't been allocated an index yet */
5262 #if defined(USE_ITHREADS)
5263 MUTEX_LOCK(&PL_my_ctx_mutex);
5265 *index = PL_my_cxt_index++;
5266 #if defined(USE_ITHREADS)
5267 MUTEX_UNLOCK(&PL_my_ctx_mutex);
5271 /* make sure the array is big enough */
5272 if (PL_my_cxt_size <= *index) {
5273 if (PL_my_cxt_size) {
5274 while (PL_my_cxt_size <= *index)
5275 PL_my_cxt_size *= 2;
5276 Renew(PL_my_cxt_list, PL_my_cxt_size, void *);
5279 PL_my_cxt_size = 16;
5280 Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
5283 /* newSV() allocates one more than needed */
5284 p = (void*)SvPVX(newSV(size-1));
5285 PL_my_cxt_list[*index] = p;
5286 Zero(p, size, char);
5290 #else /* #ifndef PERL_GLOBAL_STRUCT_PRIVATE */
5293 Perl_my_cxt_index(pTHX_ const char *my_cxt_key)
5298 PERL_ARGS_ASSERT_MY_CXT_INDEX;
5300 for (index = 0; index < PL_my_cxt_index; index++) {
5301 const char *key = PL_my_cxt_keys[index];
5302 /* try direct pointer compare first - there are chances to success,
5303 * and it's much faster.
5305 if ((key == my_cxt_key) || strEQ(key, my_cxt_key))
5312 Perl_my_cxt_init(pTHX_ const char *my_cxt_key, size_t size)
5318 PERL_ARGS_ASSERT_MY_CXT_INIT;
5320 index = Perl_my_cxt_index(aTHX_ my_cxt_key);
5322 /* this module hasn't been allocated an index yet */
5323 #if defined(USE_ITHREADS)
5324 MUTEX_LOCK(&PL_my_ctx_mutex);
5326 index = PL_my_cxt_index++;
5327 #if defined(USE_ITHREADS)
5328 MUTEX_UNLOCK(&PL_my_ctx_mutex);
5332 /* make sure the array is big enough */
5333 if (PL_my_cxt_size <= index) {
5334 int old_size = PL_my_cxt_size;
5336 if (PL_my_cxt_size) {
5337 while (PL_my_cxt_size <= index)
5338 PL_my_cxt_size *= 2;
5339 Renew(PL_my_cxt_list, PL_my_cxt_size, void *);
5340 Renew(PL_my_cxt_keys, PL_my_cxt_size, const char *);
5343 PL_my_cxt_size = 16;
5344 Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
5345 Newx(PL_my_cxt_keys, PL_my_cxt_size, const char *);
5347 for (i = old_size; i < PL_my_cxt_size; i++) {
5348 PL_my_cxt_keys[i] = 0;
5349 PL_my_cxt_list[i] = 0;
5352 PL_my_cxt_keys[index] = my_cxt_key;
5353 /* newSV() allocates one more than needed */
5354 p = (void*)SvPVX(newSV(size-1));
5355 PL_my_cxt_list[index] = p;
5356 Zero(p, size, char);
5359 #endif /* #ifndef PERL_GLOBAL_STRUCT_PRIVATE */
5360 #endif /* PERL_IMPLICIT_CONTEXT */
5363 /* Perl_xs_handshake():
5364 implement the various XS_*_BOOTCHECK macros, which are added to .c
5365 files by ExtUtils::ParseXS, to check that the perl the module was built
5366 with is binary compatible with the running perl.
5369 Perl_xs_handshake(U32 key, void * v_my_perl, const char * file,
5370 [U32 items, U32 ax], [char * api_version], [char * xs_version])
5372 The meaning of the varargs is determined the U32 key arg (which is not
5373 a format string). The fields of key are assembled by using HS_KEY().
5375 Under PERL_IMPLICIT_CONTEX, the v_my_perl arg is of type
5376 "PerlInterpreter *" and represents the callers context; otherwise it is
5377 of type "CV *", and is the boot xsub's CV.
5379 v_my_perl will catch where a threaded future perl526.dll calling IO.dll
5380 for example, and IO.dll was linked with threaded perl524.dll, and both
5381 perl526.dll and perl524.dll are in %PATH and the Win32 DLL loader
5382 successfully can load IO.dll into the process but simultaneously it
5383 loaded an interpreter of a different version into the process, and XS
5384 code will naturally pass SV*s created by perl524.dll for perl526.dll to
5385 use through perl526.dll's my_perl->Istack_base.
5387 v_my_perl cannot be the first arg, since then 'key' will be out of
5388 place in a threaded vs non-threaded mixup; and analyzing the key
5389 number's bitfields won't reveal the problem, since it will be a valid
5390 key (unthreaded perl) on interp side, but croak will report the XS mod's
5391 key as gibberish (it is really a my_perl ptr) (threaded XS mod); or if
5392 it's a threaded perl and an unthreaded XS module, threaded perl will
5393 look at an uninit C stack or an uninit register to get 'key'
5394 (remember that it assumes that the 1st arg is the interp cxt).
5396 'file' is the source filename of the caller.
5400 Perl_xs_handshake(const U32 key, void * v_my_perl, const char * file, ...)
5406 #ifdef PERL_IMPLICIT_CONTEXT
5413 PERL_ARGS_ASSERT_XS_HANDSHAKE;
5414 va_start(args, file);
5416 got = INT2PTR(void*, (UV)(key & HSm_KEY_MATCH));
5417 need = (void *)(HS_KEY(FALSE, FALSE, "", "") & HSm_KEY_MATCH);
5418 if (UNLIKELY(got != need))
5420 /* try to catch where a 2nd threaded perl interp DLL is loaded into a process
5421 by a XS DLL compiled against the wrong interl DLL b/c of bad @INC, and the
5422 2nd threaded perl interp DLL never initialized its TLS/PERL_SYS_INIT3 so
5423 dTHX call from 2nd interp DLL can't return the my_perl that pp_entersub
5424 passed to the XS DLL */
5425 #ifdef PERL_IMPLICIT_CONTEXT
5426 xs_interp = (tTHX)v_my_perl;
5430 /* try to catch where an unthreaded perl interp DLL (for ex. perl522.dll) is
5431 loaded into a process by a XS DLL built by an unthreaded perl522.dll perl,
5432 but the DynaLoder/Perl that started the process and loaded the XS DLL is
5433 unthreaded perl524.dll, since unthreadeds don't pass my_perl (a unique *)
5434 through pp_entersub, use a unique value (which is a pointer to PL_stack_sp's
5435 location in the unthreaded perl binary) stored in CV * to figure out if this
5436 Perl_xs_handshake was called by the same pp_entersub */
5437 cv = (CV*)v_my_perl;
5438 xs_spp = (SV***)CvHSCXT(cv);
5440 need = &PL_stack_sp;
5442 if(UNLIKELY(got != need)) {
5443 bad_handshake:/* recycle branch and string from above */
5444 if(got != (void *)HSf_NOCHK)
5445 noperl_die("%s: loadable library and perl binaries are mismatched"
5446 " (got handshake key %p, needed %p)\n",
5450 if(key & HSf_SETXSUBFN) { /* this might be called from a module bootstrap */
5451 SAVEPPTR(PL_xsubfilename);/* which was require'd from a XSUB BEGIN */
5452 PL_xsubfilename = file; /* so the old name must be restored for
5453 additional XSUBs to register themselves */
5454 (void)gv_fetchfile(file);
5457 if(key & HSf_POPMARK) {
5459 { SV **mark = PL_stack_base + ax++;
5461 items = (I32)(SP - MARK);
5465 items = va_arg(args, U32);
5466 ax = va_arg(args, U32);
5470 assert(HS_GETAPIVERLEN(key) <= UCHAR_MAX);
5471 if((apiverlen = HS_GETAPIVERLEN(key))) {
5472 char * api_p = va_arg(args, char*);
5473 if(apiverlen != sizeof("v" PERL_API_VERSION_STRING)-1
5474 || memNE(api_p, "v" PERL_API_VERSION_STRING,
5475 sizeof("v" PERL_API_VERSION_STRING)-1))
5476 Perl_croak_nocontext("Perl API version %s of %"SVf" does not match %s",
5477 api_p, SVfARG(PL_stack_base[ax + 0]),
5478 "v" PERL_API_VERSION_STRING);
5483 assert(HS_GETXSVERLEN(key) <= UCHAR_MAX && HS_GETXSVERLEN(key) <= HS_APIVERLEN_MAX);
5484 if((xsverlen = HS_GETXSVERLEN(key)))
5485 S_xs_version_bootcheck(aTHX_
5486 items, ax, va_arg(args, char*), xsverlen);
5494 S_xs_version_bootcheck(pTHX_ U32 items, U32 ax, const char *xs_p,
5498 const char *vn = NULL;
5499 SV *const module = PL_stack_base[ax];
5501 PERL_ARGS_ASSERT_XS_VERSION_BOOTCHECK;
5503 if (items >= 2) /* version supplied as bootstrap arg */
5504 sv = PL_stack_base[ax + 1];
5506 /* XXX GV_ADDWARN */
5508 sv = get_sv(Perl_form(aTHX_ "%"SVf"::%s", SVfARG(module), vn), 0);
5509 if (!sv || !SvOK(sv)) {
5511 sv = get_sv(Perl_form(aTHX_ "%"SVf"::%s", SVfARG(module), vn), 0);
5515 SV *xssv = Perl_newSVpvn_flags(aTHX_ xs_p, xs_len, SVs_TEMP);
5516 SV *pmsv = sv_isobject(sv) && sv_derived_from(sv, "version")
5517 ? sv : sv_2mortal(new_version(sv));
5518 xssv = upg_version(xssv, 0);
5519 if ( vcmp(pmsv,xssv) ) {
5520 SV *string = vstringify(xssv);
5521 SV *xpt = Perl_newSVpvf(aTHX_ "%"SVf" object version %"SVf
5522 " does not match ", SVfARG(module), SVfARG(string));
5524 SvREFCNT_dec(string);
5525 string = vstringify(pmsv);
5528 Perl_sv_catpvf(aTHX_ xpt, "$%"SVf"::%s %"SVf, SVfARG(module), vn,
5531 Perl_sv_catpvf(aTHX_ xpt, "bootstrap parameter %"SVf, SVfARG(string));
5533 SvREFCNT_dec(string);
5535 Perl_sv_2mortal(aTHX_ xpt);
5536 Perl_croak_sv(aTHX_ xpt);
5542 =for apidoc my_strlcat
5544 The C library C<strlcat> if available, or a Perl implementation of it.
5545 This operates on C C<NUL>-terminated strings.
5547 C<my_strlcat()> appends string C<src> to the end of C<dst>. It will append at
5548 most S<C<size - strlen(dst) - 1>> characters. It will then C<NUL>-terminate,
5549 unless C<size> is 0 or the original C<dst> string was longer than C<size> (in
5550 practice this should not happen as it means that either C<size> is incorrect or
5551 that C<dst> is not a proper C<NUL>-terminated string).
5553 Note that C<size> is the full size of the destination buffer and
5554 the result is guaranteed to be C<NUL>-terminated if there is room. Note that
5555 room for the C<NUL> should be included in C<size>.
5559 Description stolen from http://www.openbsd.org/cgi-bin/man.cgi?query=strlcat
5563 Perl_my_strlcat(char *dst, const char *src, Size_t size)
5565 Size_t used, length, copy;
5568 length = strlen(src);
5569 if (size > 0 && used < size - 1) {
5570 copy = (length >= size - used) ? size - used - 1 : length;
5571 memcpy(dst + used, src, copy);
5572 dst[used + copy] = '\0';
5574 return used + length;
5580 =for apidoc my_strlcpy
5582 The C library C<strlcpy> if available, or a Perl implementation of it.
5583 This operates on C C<NUL>-terminated strings.
5585 C<my_strlcpy()> copies up to S<C<size - 1>> characters from the string C<src>
5586 to C<dst>, C<NUL>-terminating the result if C<size> is not 0.
5590 Description stolen from http://www.openbsd.org/cgi-bin/man.cgi?query=strlcpy
5594 Perl_my_strlcpy(char *dst, const char *src, Size_t size)
5596 Size_t length, copy;
5598 length = strlen(src);
5600 copy = (length >= size) ? size - 1 : length;
5601 memcpy(dst, src, copy);
5608 #if defined(_MSC_VER) && (_MSC_VER >= 1300) && (_MSC_VER < 1400) && (WINVER < 0x0500)
5609 /* VC7 or 7.1, building with pre-VC7 runtime libraries. */
5610 long _ftol( double ); /* Defined by VC6 C libs. */
5611 long _ftol2( double dblSource ) { return _ftol( dblSource ); }
5614 PERL_STATIC_INLINE bool
5615 S_gv_has_usable_name(pTHX_ GV *gv)
5619 && HvENAME(GvSTASH(gv))
5620 && (gvp = (GV **)hv_fetchhek(
5621 GvSTASH(gv), GvNAME_HEK(gv), 0
5627 Perl_get_db_sub(pTHX_ SV **svp, CV *cv)
5629 SV * const dbsv = GvSVn(PL_DBsub);
5630 const bool save_taint = TAINT_get;
5632 /* When we are called from pp_goto (svp is null),
5633 * we do not care about using dbsv to call CV;
5634 * it's for informational purposes only.
5637 PERL_ARGS_ASSERT_GET_DB_SUB;
5641 if (!PERLDB_SUB_NN) {
5644 if (!svp && !CvLEXICAL(cv)) {
5645 gv_efullname3(dbsv, gv, NULL);
5647 else if ( (CvFLAGS(cv) & (CVf_ANON | CVf_CLONED)) || CvLEXICAL(cv)
5648 || strEQ(GvNAME(gv), "END")
5649 || ( /* Could be imported, and old sub redefined. */
5650 (GvCV(gv) != cv || !S_gv_has_usable_name(aTHX_ gv))
5652 !( (SvTYPE(*svp) == SVt_PVGV)
5653 && (GvCV((const GV *)*svp) == cv)
5654 /* Use GV from the stack as a fallback. */
5655 && S_gv_has_usable_name(aTHX_ gv = (GV *)*svp)
5659 /* GV is potentially non-unique, or contain different CV. */
5660 SV * const tmp = newRV(MUTABLE_SV(cv));
5661 sv_setsv(dbsv, tmp);
5665 sv_sethek(dbsv, HvENAME_HEK(GvSTASH(gv)));
5666 sv_catpvs(dbsv, "::");
5667 sv_cathek(dbsv, GvNAME_HEK(gv));
5671 const int type = SvTYPE(dbsv);
5672 if (type < SVt_PVIV && type != SVt_IV)
5673 sv_upgrade(dbsv, SVt_PVIV);
5674 (void)SvIOK_on(dbsv);
5675 SvIV_set(dbsv, PTR2IV(cv)); /* Do it the quickest way */
5678 TAINT_IF(save_taint);
5679 #ifdef NO_TAINT_SUPPORT
5680 PERL_UNUSED_VAR(save_taint);
5685 Perl_my_dirfd(DIR * dir) {
5687 /* Most dirfd implementations have problems when passed NULL. */
5692 #elif defined(HAS_DIR_DD_FD)
5695 Perl_croak_nocontext(PL_no_func, "dirfd");
5696 NOT_REACHED; /* NOT REACHED */
5702 Perl_get_re_arg(pTHX_ SV *sv) {
5708 sv = MUTABLE_SV(SvRV(sv));
5709 if (SvTYPE(sv) == SVt_REGEXP)
5710 return (REGEXP*) sv;
5717 * This code is derived from drand48() implementation from FreeBSD,
5718 * found in lib/libc/gen/_rand48.c.
5720 * The U64 implementation is original, based on the POSIX
5721 * specification for drand48().
5725 * Copyright (c) 1993 Martin Birgmeier
5726 * All rights reserved.
5728 * You may redistribute unmodified or modified versions of this source
5729 * code provided that the above copyright notice and this and the
5730 * following conditions are retained.
5732 * This software is provided ``as is'', and comes with no warranties
5733 * of any kind. I shall in no event be liable for anything that happens
5734 * to anyone/anything when using this software.
5737 #define FREEBSD_DRAND48_SEED_0 (0x330e)
5739 #ifdef PERL_DRAND48_QUAD
5741 #define DRAND48_MULT U64_CONST(0x5deece66d)
5742 #define DRAND48_ADD 0xb
5743 #define DRAND48_MASK U64_CONST(0xffffffffffff)
5747 #define FREEBSD_DRAND48_SEED_1 (0xabcd)
5748 #define FREEBSD_DRAND48_SEED_2 (0x1234)
5749 #define FREEBSD_DRAND48_MULT_0 (0xe66d)
5750 #define FREEBSD_DRAND48_MULT_1 (0xdeec)
5751 #define FREEBSD_DRAND48_MULT_2 (0x0005)
5752 #define FREEBSD_DRAND48_ADD (0x000b)
5754 const unsigned short _rand48_mult[3] = {
5755 FREEBSD_DRAND48_MULT_0,
5756 FREEBSD_DRAND48_MULT_1,
5757 FREEBSD_DRAND48_MULT_2
5759 const unsigned short _rand48_add = FREEBSD_DRAND48_ADD;
5764 Perl_drand48_init_r(perl_drand48_t *random_state, U32 seed)
5766 PERL_ARGS_ASSERT_DRAND48_INIT_R;
5768 #ifdef PERL_DRAND48_QUAD
5769 *random_state = FREEBSD_DRAND48_SEED_0 + ((U64TYPE)seed << 16);
5771 random_state->seed[0] = FREEBSD_DRAND48_SEED_0;
5772 random_state->seed[1] = (U16) seed;
5773 random_state->seed[2] = (U16) (seed >> 16);
5778 Perl_drand48_r(perl_drand48_t *random_state)
5780 PERL_ARGS_ASSERT_DRAND48_R;
5782 #ifdef PERL_DRAND48_QUAD
5783 *random_state = (*random_state * DRAND48_MULT + DRAND48_ADD)
5786 return ldexp((double)*random_state, -48);
5792 accu = (U32) _rand48_mult[0] * (U32) random_state->seed[0]
5793 + (U32) _rand48_add;
5794 temp[0] = (U16) accu; /* lower 16 bits */
5795 accu >>= sizeof(U16) * 8;
5796 accu += (U32) _rand48_mult[0] * (U32) random_state->seed[1]
5797 + (U32) _rand48_mult[1] * (U32) random_state->seed[0];
5798 temp[1] = (U16) accu; /* middle 16 bits */
5799 accu >>= sizeof(U16) * 8;
5800 accu += _rand48_mult[0] * random_state->seed[2]
5801 + _rand48_mult[1] * random_state->seed[1]
5802 + _rand48_mult[2] * random_state->seed[0];
5803 random_state->seed[0] = temp[0];
5804 random_state->seed[1] = temp[1];
5805 random_state->seed[2] = (U16) accu;
5807 return ldexp((double) random_state->seed[0], -48) +
5808 ldexp((double) random_state->seed[1], -32) +
5809 ldexp((double) random_state->seed[2], -16);
5814 #ifdef USE_C_BACKTRACE
5816 /* Possibly move all this USE_C_BACKTRACE code into a new file. */
5821 /* abfd is the BFD handle. */
5823 /* bfd_syms is the BFD symbol table. */
5825 /* bfd_text is handle to the the ".text" section of the object file. */
5827 /* Since opening the executable and scanning its symbols is quite
5828 * heavy operation, we remember the filename we used the last time,
5829 * and do the opening and scanning only if the filename changes.
5830 * This removes most (but not all) open+scan cycles. */
5831 const char* fname_prev;
5834 /* Given a dl_info, update the BFD context if necessary. */
5835 static void bfd_update(bfd_context* ctx, Dl_info* dl_info)
5837 /* BFD open and scan only if the filename changed. */
5838 if (ctx->fname_prev == NULL ||
5839 strNE(dl_info->dli_fname, ctx->fname_prev)) {
5841 bfd_close(ctx->abfd);
5843 ctx->abfd = bfd_openr(dl_info->dli_fname, 0);
5845 if (bfd_check_format(ctx->abfd, bfd_object)) {
5846 IV symbol_size = bfd_get_symtab_upper_bound(ctx->abfd);
5847 if (symbol_size > 0) {
5848 Safefree(ctx->bfd_syms);
5849 Newx(ctx->bfd_syms, symbol_size, asymbol*);
5851 bfd_get_section_by_name(ctx->abfd, ".text");
5859 ctx->fname_prev = dl_info->dli_fname;
5863 /* Given a raw frame, try to symbolize it and store
5864 * symbol information (source file, line number) away. */
5865 static void bfd_symbolize(bfd_context* ctx,
5868 STRLEN* symbol_name_size,
5870 STRLEN* source_name_size,
5871 STRLEN* source_line)
5873 *symbol_name = NULL;
5874 *symbol_name_size = 0;
5876 IV offset = PTR2IV(raw_frame) - PTR2IV(ctx->bfd_text->vma);
5878 bfd_canonicalize_symtab(ctx->abfd, ctx->bfd_syms) > 0) {
5881 unsigned int line = 0;
5882 if (bfd_find_nearest_line(ctx->abfd, ctx->bfd_text,
5883 ctx->bfd_syms, offset,
5884 &file, &func, &line) &&
5885 file && func && line > 0) {
5886 /* Size and copy the source file, use only
5887 * the basename of the source file.
5889 * NOTE: the basenames are fine for the
5890 * Perl source files, but may not always
5891 * be the best idea for XS files. */
5892 const char *p, *b = NULL;
5893 /* Look for the last slash. */
5894 for (p = file; *p; p++) {
5898 if (b == NULL || *b == 0) {
5901 *source_name_size = p - b + 1;
5902 Newx(*source_name, *source_name_size + 1, char);
5903 Copy(b, *source_name, *source_name_size + 1, char);
5905 *symbol_name_size = strlen(func);
5906 Newx(*symbol_name, *symbol_name_size + 1, char);
5907 Copy(func, *symbol_name, *symbol_name_size + 1, char);
5909 *source_line = line;
5915 #endif /* #ifdef USE_BFD */
5919 /* OS X has no public API for for 'symbolicating' (Apple official term)
5920 * stack addresses to {function_name, source_file, line_number}.
5921 * Good news: there is command line utility atos(1) which does that.
5922 * Bad news 1: it's a command line utility.
5923 * Bad news 2: one needs to have the Developer Tools installed.
5924 * Bad news 3: in newer releases it needs to be run as 'xcrun atos'.
5926 * To recap: we need to open a pipe for reading for a utility which
5927 * might not exist, or exists in different locations, and then parse
5928 * the output. And since this is all for a low-level API, we cannot
5929 * use high-level stuff. Thanks, Apple. */
5932 /* tool is set to the absolute pathname of the tool to use:
5935 /* format is set to a printf format string used for building
5936 * the external command to run. */
5938 /* unavail is set if e.g. xcrun cannot be found, or something
5939 * else happens that makes getting the backtrace dubious. Note,
5940 * however, that the context isn't persistent, the next call to
5941 * get_c_backtrace() will start from scratch. */
5943 /* fname is the current object file name. */
5945 /* object_base_addr is the base address of the shared object. */
5946 void* object_base_addr;
5949 /* Given |dl_info|, updates the context. If the context has been
5950 * marked unavailable, return immediately. If not but the tool has
5951 * not been set, set it to either "xcrun atos" or "atos" (also set the
5952 * format to use for creating commands for piping), or if neither is
5953 * unavailable (one needs the Developer Tools installed), mark the context
5954 * an unavailable. Finally, update the filename (object name),
5955 * and its base address. */
5957 static void atos_update(atos_context* ctx,
5962 if (ctx->tool == NULL) {
5963 const char* tools[] = {
5967 const char* formats[] = {
5968 "/usr/bin/xcrun atos -o '%s' -l %08x %08x 2>&1",
5969 "/usr/bin/atos -d -o '%s' -l %08x %08x 2>&1"
5973 for (i = 0; i < C_ARRAY_LENGTH(tools); i++) {
5974 if (stat(tools[i], &st) == 0 && S_ISREG(st.st_mode)) {
5975 ctx->tool = tools[i];
5976 ctx->format = formats[i];
5980 if (ctx->tool == NULL) {
5981 ctx->unavail = TRUE;
5985 if (ctx->fname == NULL ||
5986 strNE(dl_info->dli_fname, ctx->fname)) {
5987 ctx->fname = dl_info->dli_fname;
5988 ctx->object_base_addr = dl_info->dli_fbase;
5992 /* Given an output buffer end |p| and its |start|, matches
5993 * for the atos output, extracting the source code location
5994 * and returning non-NULL if possible, returning NULL otherwise. */
5995 static const char* atos_parse(const char* p,
5997 STRLEN* source_name_size,
5998 STRLEN* source_line) {
5999 /* atos() output is something like:
6000 * perl_parse (in miniperl) (perl.c:2314)\n\n".
6001 * We cannot use Perl regular expressions, because we need to
6002 * stay low-level. Therefore here we have a rolled-out version
6003 * of a state machine which matches _backwards_from_the_end_ and
6004 * if there's a success, returns the starts of the filename,
6005 * also setting the filename size and the source line number.
6006 * The matched regular expression is roughly "\(.*:\d+\)\s*$" */
6007 const char* source_number_start;
6008 const char* source_name_end;
6009 const char* source_line_end;
6010 const char* close_paren;
6011 /* Skip trailing whitespace. */
6012 while (p > start && isspace(*p)) p--;
6013 /* Now we should be at the close paren. */
6014 if (p == start || *p != ')')
6018 /* Now we should be in the line number. */
6019 if (p == start || !isdigit(*p))
6021 /* Skip over the digits. */
6022 while (p > start && isdigit(*p))
6024 /* Now we should be at the colon. */
6025 if (p == start || *p != ':')
6027 source_number_start = p + 1;
6028 source_name_end = p; /* Just beyond the end. */
6030 /* Look for the open paren. */
6031 while (p > start && *p != '(')
6036 *source_name_size = source_name_end - p;
6037 *source_line = grok_atou(source_number_start, &source_line_end);
6038 if (source_line_end != close_paren)
6043 /* Given a raw frame, read a pipe from the symbolicator (that's the
6044 * technical term) atos, reads the result, and parses the source code
6045 * location. We must stay low-level, so we use snprintf(), pipe(),
6046 * and fread(), and then also parse the output ourselves. */
6047 static void atos_symbolize(atos_context* ctx,
6050 STRLEN* source_name_size,
6051 STRLEN* source_line)
6059 /* Simple security measure: if there's any funny business with
6060 * the object name (used as "-o '%s'" ), leave since at least
6061 * partially the user controls it. */
6062 for (p = ctx->fname; *p; p++) {
6063 if (*p == '\'' || iscntrl(*p)) {
6064 ctx->unavail = TRUE;
6068 cnt = snprintf(cmd, sizeof(cmd), ctx->format,
6069 ctx->fname, ctx->object_base_addr, raw_frame);
6070 if (cnt < sizeof(cmd)) {
6071 /* Undo nostdio.h #defines that disable stdio.
6072 * This is somewhat naughty, but is used elsewhere
6073 * in the core, and affects only OS X. */
6078 FILE* fp = popen(cmd, "r");
6079 /* At the moment we open a new pipe for each stack frame.
6080 * This is naturally somewhat slow, but hopefully generating
6081 * stack traces is never going to in a performance critical path.
6083 * We could play tricks with atos by batching the stack
6084 * addresses to be resolved: atos can either take multiple
6085 * addresses from the command line, or read addresses from
6086 * a file (though the mess of creating temporary files would
6087 * probably negate much of any possible speedup).
6089 * Normally there are only two objects present in the backtrace:
6090 * perl itself, and the libdyld.dylib. (Note that the object
6091 * filenames contain the full pathname, so perl may not always
6092 * be in the same place.) Whenever the object in the
6093 * backtrace changes, the base address also changes.
6095 * The problem with batching the addresses, though, would be
6096 * matching the results with the addresses: the parsing of
6097 * the results is already painful enough with a single address. */
6100 UV cnt = fread(out, 1, sizeof(out), fp);
6101 if (cnt < sizeof(out)) {
6102 const char* p = atos_parse(out + cnt, out,
6107 *source_name_size + 1, char);
6108 Copy(p, *source_name,
6109 *source_name_size + 1, char);
6117 #endif /* #ifdef PERL_DARWIN */
6120 =for apidoc get_c_backtrace
6122 Collects the backtrace (aka "stacktrace") into a single linear
6123 malloced buffer, which the caller B<must> Perl_free_c_backtrace().
6125 Scans the frames back by depth + skip, then drops the skip innermost,
6126 returning at most depth frames.
6132 Perl_get_c_backtrace(pTHX_ int depth, int skip)
6134 /* Note that here we must stay as low-level as possible: Newx(),
6135 * Copy(), Safefree(); since we may be called from anywhere,
6136 * so we should avoid higher level constructs like SVs or AVs.
6138 * Since we are using safesysmalloc() via Newx(), don't try
6139 * getting backtrace() there, unless you like deep recursion. */
6141 /* Currently only implemented with backtrace() and dladdr(),
6142 * for other platforms NULL is returned. */
6144 #if defined(HAS_BACKTRACE) && defined(HAS_DLADDR)
6145 /* backtrace() is available via <execinfo.h> in glibc and in most
6146 * modern BSDs; dladdr() is available via <dlfcn.h>. */
6148 /* We try fetching this many frames total, but then discard
6149 * the |skip| first ones. For the remaining ones we will try
6150 * retrieving more information with dladdr(). */
6151 int try_depth = skip + depth;
6153 /* The addresses (program counters) returned by backtrace(). */
6156 /* Retrieved with dladdr() from the addresses returned by backtrace(). */
6159 /* Sizes _including_ the terminating \0 of the object name
6160 * and symbol name strings. */
6161 STRLEN* object_name_sizes;
6162 STRLEN* symbol_name_sizes;
6165 /* The symbol names comes either from dli_sname,
6166 * or if using BFD, they can come from BFD. */
6167 char** symbol_names;
6170 /* The source code location information. Dug out with e.g. BFD. */
6171 char** source_names;
6172 STRLEN* source_name_sizes;
6173 STRLEN* source_lines;
6175 Perl_c_backtrace* bt = NULL; /* This is what will be returned. */
6176 int got_depth; /* How many frames were returned from backtrace(). */
6177 UV frame_count = 0; /* How many frames we return. */
6178 UV total_bytes = 0; /* The size of the whole returned backtrace. */
6181 bfd_context bfd_ctx;
6184 atos_context atos_ctx;
6187 /* Here are probably possibilities for optimizing. We could for
6188 * example have a struct that contains most of these and then
6189 * allocate |try_depth| of them, saving a bunch of malloc calls.
6190 * Note, however, that |frames| could not be part of that struct
6191 * because backtrace() will want an array of just them. Also be
6192 * careful about the name strings. */
6193 Newx(raw_frames, try_depth, void*);
6194 Newx(dl_infos, try_depth, Dl_info);
6195 Newx(object_name_sizes, try_depth, STRLEN);
6196 Newx(symbol_name_sizes, try_depth, STRLEN);
6197 Newx(source_names, try_depth, char*);
6198 Newx(source_name_sizes, try_depth, STRLEN);
6199 Newx(source_lines, try_depth, STRLEN);
6201 Newx(symbol_names, try_depth, char*);
6204 /* Get the raw frames. */
6205 got_depth = (int)backtrace(raw_frames, try_depth);
6207 /* We use dladdr() instead of backtrace_symbols() because we want
6208 * the full details instead of opaque strings. This is useful for
6209 * two reasons: () the details are needed for further symbolic
6210 * digging, for example in OS X (2) by having the details we fully
6211 * control the output, which in turn is useful when more platforms
6212 * are added: we can keep out output "portable". */
6214 /* We want a single linear allocation, which can then be freed
6215 * with a single swoop. We will do the usual trick of first
6216 * walking over the structure and seeing how much we need to
6217 * allocate, then allocating, and then walking over the structure
6218 * the second time and populating it. */
6220 /* First we must compute the total size of the buffer. */
6221 total_bytes = sizeof(Perl_c_backtrace_header);
6222 if (got_depth > skip) {
6225 bfd_init(); /* Is this safe to call multiple times? */
6226 Zero(&bfd_ctx, 1, bfd_context);
6229 Zero(&atos_ctx, 1, atos_context);
6231 for (i = skip; i < try_depth; i++) {
6232 Dl_info* dl_info = &dl_infos[i];
6234 total_bytes += sizeof(Perl_c_backtrace_frame);
6236 source_names[i] = NULL;
6237 source_name_sizes[i] = 0;
6238 source_lines[i] = 0;
6240 /* Yes, zero from dladdr() is failure. */
6241 if (dladdr(raw_frames[i], dl_info)) {
6242 object_name_sizes[i] =
6243 dl_info->dli_fname ? strlen(dl_info->dli_fname) : 0;
6244 symbol_name_sizes[i] =
6245 dl_info->dli_sname ? strlen(dl_info->dli_sname) : 0;
6247 bfd_update(&bfd_ctx, dl_info);
6248 bfd_symbolize(&bfd_ctx, raw_frames[i],
6250 &symbol_name_sizes[i],
6252 &source_name_sizes[i],
6256 atos_update(&atos_ctx, dl_info);
6257 atos_symbolize(&atos_ctx,
6260 &source_name_sizes[i],
6264 /* Plus ones for the terminating \0. */
6265 total_bytes += object_name_sizes[i] + 1;
6266 total_bytes += symbol_name_sizes[i] + 1;
6267 total_bytes += source_name_sizes[i] + 1;
6275 Safefree(bfd_ctx.bfd_syms);
6279 /* Now we can allocate and populate the result buffer. */
6280 Newxc(bt, total_bytes, char, Perl_c_backtrace);
6281 Zero(bt, total_bytes, char);
6282 bt->header.frame_count = frame_count;
6283 bt->header.total_bytes = total_bytes;
6284 if (frame_count > 0) {
6285 Perl_c_backtrace_frame* frame = bt->frame_info;
6286 char* name_base = (char *)(frame + frame_count);
6287 char* name_curr = name_base; /* Outputting the name strings here. */
6289 for (i = skip; i < skip + frame_count; i++) {
6290 Dl_info* dl_info = &dl_infos[i];
6292 frame->addr = raw_frames[i];
6293 frame->object_base_addr = dl_info->dli_fbase;
6294 frame->symbol_addr = dl_info->dli_saddr;
6296 /* Copies a string, including the \0, and advances the name_curr.
6297 * Also copies the start and the size to the frame. */
6298 #define PERL_C_BACKTRACE_STRCPY(frame, doffset, src, dsize, size) \
6300 Copy(src, name_curr, size, char); \
6301 frame->doffset = name_curr - (char*)bt; \
6302 frame->dsize = size; \
6303 name_curr += size; \
6306 PERL_C_BACKTRACE_STRCPY(frame, object_name_offset,
6308 object_name_size, object_name_sizes[i]);
6311 PERL_C_BACKTRACE_STRCPY(frame, symbol_name_offset,
6313 symbol_name_size, symbol_name_sizes[i]);
6314 Safefree(symbol_names[i]);
6316 PERL_C_BACKTRACE_STRCPY(frame, symbol_name_offset,
6318 symbol_name_size, symbol_name_sizes[i]);
6321 PERL_C_BACKTRACE_STRCPY(frame, source_name_offset,
6323 source_name_size, source_name_sizes[i]);
6324 Safefree(source_names[i]);
6326 #undef PERL_C_BACKTRACE_STRCPY
6328 frame->source_line_number = source_lines[i];
6332 assert(total_bytes ==
6333 (UV)(sizeof(Perl_c_backtrace_header) +
6334 frame_count * sizeof(Perl_c_backtrace_frame) +
6335 name_curr - name_base));
6338 Safefree(symbol_names);
6340 bfd_close(bfd_ctx.abfd);
6343 Safefree(source_lines);
6344 Safefree(source_name_sizes);
6345 Safefree(source_names);
6346 Safefree(symbol_name_sizes);
6347 Safefree(object_name_sizes);
6348 /* Assuming the strings returned by dladdr() are pointers
6349 * to read-only static memory (the object file), so that
6350 * they do not need freeing (and cannot be). */
6352 Safefree(raw_frames);
6355 PERL_UNUSED_ARGV(depth);
6356 PERL_UNUSED_ARGV(skip);
6362 =for apidoc free_c_backtrace
6364 Deallocates a backtrace received from get_c_bracktrace.
6370 =for apidoc get_c_backtrace_dump
6372 Returns a SV a dump of |depth| frames of the call stack, skipping
6373 the |skip| innermost ones. depth of 20 is usually enough.
6375 The appended output looks like:
6378 1 10e004812:0082 Perl_croak util.c:1716 /usr/bin/perl
6379 2 10df8d6d2:1d72 perl_parse perl.c:3975 /usr/bin/perl
6382 The fields are tab-separated. The first column is the depth (zero
6383 being the innermost non-skipped frame). In the hex:offset, the hex is
6384 where the program counter was in S_parse_body, and the :offset (might
6385 be missing) tells how much inside the S_parse_body the program counter was.
6387 The util.c:1716 is the source code file and line number.
6389 The /usr/bin/perl is obvious (hopefully).
6391 Unknowns are C<"-">. Unknowns can happen unfortunately quite easily:
6392 if the platform doesn't support retrieving the information;
6393 if the binary is missing the debug information;
6394 if the optimizer has transformed the code by for example inlining.
6400 Perl_get_c_backtrace_dump(pTHX_ int depth, int skip)
6402 Perl_c_backtrace* bt;
6404 bt = get_c_backtrace(depth, skip + 1 /* Hide ourselves. */);
6406 Perl_c_backtrace_frame* frame;
6407 SV* dsv = newSVpvs("");
6409 for (i = 0, frame = bt->frame_info;
6410 i < bt->header.frame_count; i++, frame++) {
6411 Perl_sv_catpvf(aTHX_ dsv, "%d", (int)i);
6412 Perl_sv_catpvf(aTHX_ dsv, "\t%p", frame->addr ? frame->addr : "-");
6413 /* Symbol (function) names might disappear without debug info.
6415 * The source code location might disappear in case of the
6416 * optimizer inlining or otherwise rearranging the code. */
6417 if (frame->symbol_addr) {
6418 Perl_sv_catpvf(aTHX_ dsv, ":%04x",
6420 ((char*)frame->addr - (char*)frame->symbol_addr));
6422 Perl_sv_catpvf(aTHX_ dsv, "\t%s",
6423 frame->symbol_name_size &&
6424 frame->symbol_name_offset ?
6425 (char*)bt + frame->symbol_name_offset : "-");
6426 if (frame->source_name_size &&
6427 frame->source_name_offset &&
6428 frame->source_line_number) {
6429 Perl_sv_catpvf(aTHX_ dsv, "\t%s:%"UVuf,
6430 (char*)bt + frame->source_name_offset,
6431 (UV)frame->source_line_number);
6433 Perl_sv_catpvf(aTHX_ dsv, "\t-");
6435 Perl_sv_catpvf(aTHX_ dsv, "\t%s",
6436 frame->object_name_size &&
6437 frame->object_name_offset ?
6438 (char*)bt + frame->object_name_offset : "-");
6439 /* The frame->object_base_addr is not output,
6440 * but it is used for symbolizing/symbolicating. */
6441 sv_catpvs(dsv, "\n");
6444 Perl_free_c_backtrace(aTHX_ bt);
6453 =for apidoc dump_c_backtrace
6455 Dumps the C backtrace to the given fp.
6457 Returns true if a backtrace could be retrieved, false if not.
6463 Perl_dump_c_backtrace(pTHX_ PerlIO* fp, int depth, int skip)
6467 PERL_ARGS_ASSERT_DUMP_C_BACKTRACE;
6469 sv = Perl_get_c_backtrace_dump(aTHX_ depth, skip);
6472 PerlIO_printf(fp, "%s", SvPV_nolen(sv));
6478 #endif /* #ifdef USE_C_BACKTRACE */
6482 * c-indentation-style: bsd
6484 * indent-tabs-mode: nil
6487 * ex: set ts=8 sts=4 sw=4 et: