3 * Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
4 * 2002, 2003, 2004, 2005, 2006, 2007, 2008 by Larry Wall and others
6 * You may distribute under the terms of either the GNU General Public
7 * License or the Artistic License, as specified in the README file.
12 * 'Very useful, no doubt, that was to Saruman; yet it seems that he was
13 * not content.' --Gandalf to Pippin
15 * [p.598 of _The Lord of the Rings_, III/xi: "The PalantÃr"]
18 /* This file contains assorted utility routines.
19 * Which is a polite way of saying any stuff that people couldn't think of
20 * a better place for. Amongst other things, it includes the warning and
21 * dieing stuff, plus wrappers for malloc code.
25 #define PERL_IN_UTIL_C
29 #if defined(USE_PERLIO)
30 #include "perliol.h" /* For PerlIOUnix_refcnt */
36 # define SIG_ERR ((Sighandler_t) -1)
44 /* Missing protos on LynxOS */
50 # include <sys/select.h>
54 #ifdef USE_C_BACKTRACE
58 # undef USE_BFD /* BFD is useless in OS X. */
68 # include <execinfo.h>
72 #ifdef PERL_DEBUG_READONLY_COW
73 # include <sys/mman.h>
78 /* NOTE: Do not call the next three routines directly. Use the macros
79 * in handy.h, so that we can easily redefine everything to do tracking of
80 * allocated hunks back to the original New to track down any memory leaks.
81 * XXX This advice seems to be widely ignored :-( --AD August 1996.
84 #if defined (DEBUGGING) || defined(PERL_IMPLICIT_SYS) || defined (PERL_TRACK_MEMPOOL)
85 # define ALWAYS_NEED_THX
88 #if defined(PERL_TRACK_MEMPOOL) && defined(PERL_DEBUG_READONLY_COW)
90 S_maybe_protect_rw(pTHX_ struct perl_memory_debug_header *header)
93 && mprotect(header, header->size, PROT_READ|PROT_WRITE))
94 Perl_warn(aTHX_ "mprotect for COW string %p %lu failed with %d",
95 header, header->size, errno);
99 S_maybe_protect_ro(pTHX_ struct perl_memory_debug_header *header)
102 && mprotect(header, header->size, PROT_READ))
103 Perl_warn(aTHX_ "mprotect RW for COW string %p %lu failed with %d",
104 header, header->size, errno);
106 # define maybe_protect_rw(foo) S_maybe_protect_rw(aTHX_ foo)
107 # define maybe_protect_ro(foo) S_maybe_protect_ro(aTHX_ foo)
109 # define maybe_protect_rw(foo) NOOP
110 # define maybe_protect_ro(foo) NOOP
113 #if defined(PERL_TRACK_MEMPOOL) || defined(PERL_DEBUG_READONLY_COW)
114 /* Use memory_debug_header */
116 # if (defined(PERL_POISON) && defined(PERL_TRACK_MEMPOOL)) \
117 || defined(PERL_DEBUG_READONLY_COW)
118 # define MDH_HAS_SIZE
122 /* paranoid version of system's malloc() */
125 Perl_safesysmalloc(MEM_SIZE size)
127 #ifdef ALWAYS_NEED_THX
131 size += PERL_MEMORY_DEBUG_HEADER_SIZE;
133 if ((SSize_t)size < 0)
134 Perl_croak_nocontext("panic: malloc, size=%"UVuf, (UV) size);
136 if (!size) size = 1; /* malloc(0) is NASTY on our system */
137 #ifdef PERL_DEBUG_READONLY_COW
138 if ((ptr = mmap(0, size, PROT_READ|PROT_WRITE,
139 MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED) {
140 perror("mmap failed");
144 ptr = (Malloc_t)PerlMem_malloc(size?size:1);
146 PERL_ALLOC_CHECK(ptr);
149 struct perl_memory_debug_header *const header
150 = (struct perl_memory_debug_header *)ptr;
154 PoisonNew(((char *)ptr), size, char);
157 #ifdef PERL_TRACK_MEMPOOL
158 header->interpreter = aTHX;
159 /* Link us into the list. */
160 header->prev = &PL_memory_debug_header;
161 header->next = PL_memory_debug_header.next;
162 PL_memory_debug_header.next = header;
163 maybe_protect_rw(header->next);
164 header->next->prev = header;
165 maybe_protect_ro(header->next);
166 # ifdef PERL_DEBUG_READONLY_COW
167 header->readonly = 0;
173 ptr = (Malloc_t)((char*)ptr+PERL_MEMORY_DEBUG_HEADER_SIZE);
174 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) malloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
178 #ifndef ALWAYS_NEED_THX
190 /* paranoid version of system's realloc() */
193 Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
195 #ifdef ALWAYS_NEED_THX
199 #ifdef PERL_DEBUG_READONLY_COW
200 const MEM_SIZE oldsize = where
201 ? ((struct perl_memory_debug_header *)((char *)where - PERL_MEMORY_DEBUG_HEADER_SIZE))->size
204 #if !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) && !defined(PERL_MICRO)
205 Malloc_t PerlMem_realloc();
206 #endif /* !defined(STANDARD_C) && !defined(HAS_REALLOC_PROTOTYPE) */
214 return safesysmalloc(size);
216 where = (Malloc_t)((char*)where-PERL_MEMORY_DEBUG_HEADER_SIZE);
217 size += PERL_MEMORY_DEBUG_HEADER_SIZE;
219 struct perl_memory_debug_header *const header
220 = (struct perl_memory_debug_header *)where;
222 # ifdef PERL_TRACK_MEMPOOL
223 if (header->interpreter != aTHX) {
224 Perl_croak_nocontext("panic: realloc from wrong pool, %p!=%p",
225 header->interpreter, aTHX);
227 assert(header->next->prev == header);
228 assert(header->prev->next == header);
230 if (header->size > size) {
231 const MEM_SIZE freed_up = header->size - size;
232 char *start_of_freed = ((char *)where) + size;
233 PoisonFree(start_of_freed, freed_up, char);
243 if ((SSize_t)size < 0)
244 Perl_croak_nocontext("panic: realloc, size=%"UVuf, (UV)size);
246 #ifdef PERL_DEBUG_READONLY_COW
247 if ((ptr = mmap(0, size, PROT_READ|PROT_WRITE,
248 MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED) {
249 perror("mmap failed");
252 Copy(where,ptr,oldsize < size ? oldsize : size,char);
253 if (munmap(where, oldsize)) {
254 perror("munmap failed");
258 ptr = (Malloc_t)PerlMem_realloc(where,size);
260 PERL_ALLOC_CHECK(ptr);
262 /* MUST do this fixup first, before doing ANYTHING else, as anything else
263 might allocate memory/free/move memory, and until we do the fixup, it
264 may well be chasing (and writing to) free memory. */
266 #ifdef PERL_TRACK_MEMPOOL
267 struct perl_memory_debug_header *const header
268 = (struct perl_memory_debug_header *)ptr;
271 if (header->size < size) {
272 const MEM_SIZE fresh = size - header->size;
273 char *start_of_fresh = ((char *)ptr) + size;
274 PoisonNew(start_of_fresh, fresh, char);
278 maybe_protect_rw(header->next);
279 header->next->prev = header;
280 maybe_protect_ro(header->next);
281 maybe_protect_rw(header->prev);
282 header->prev->next = header;
283 maybe_protect_ro(header->prev);
285 ptr = (Malloc_t)((char*)ptr+PERL_MEMORY_DEBUG_HEADER_SIZE);
288 /* In particular, must do that fixup above before logging anything via
289 *printf(), as it can reallocate memory, which can cause SEGVs. */
291 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) rfree\n",PTR2UV(where),(long)PL_an++));
292 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) realloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
299 #ifndef ALWAYS_NEED_THX
311 /* safe version of system's free() */
314 Perl_safesysfree(Malloc_t where)
316 #ifdef ALWAYS_NEED_THX
319 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%"UVxf": (%05ld) free\n",PTR2UV(where),(long)PL_an++));
322 Malloc_t where_intrn = (Malloc_t)((char*)where-PERL_MEMORY_DEBUG_HEADER_SIZE);
324 struct perl_memory_debug_header *const header
325 = (struct perl_memory_debug_header *)where_intrn;
328 const MEM_SIZE size = header->size;
330 # ifdef PERL_TRACK_MEMPOOL
331 if (header->interpreter != aTHX) {
332 Perl_croak_nocontext("panic: free from wrong pool, %p!=%p",
333 header->interpreter, aTHX);
336 Perl_croak_nocontext("panic: duplicate free");
339 Perl_croak_nocontext("panic: bad free, header->next==NULL");
340 if (header->next->prev != header || header->prev->next != header) {
341 Perl_croak_nocontext("panic: bad free, ->next->prev=%p, "
342 "header=%p, ->prev->next=%p",
343 header->next->prev, header,
346 /* Unlink us from the chain. */
347 maybe_protect_rw(header->next);
348 header->next->prev = header->prev;
349 maybe_protect_ro(header->next);
350 maybe_protect_rw(header->prev);
351 header->prev->next = header->next;
352 maybe_protect_ro(header->prev);
353 maybe_protect_rw(header);
355 PoisonNew(where_intrn, size, char);
357 /* Trigger the duplicate free warning. */
360 # ifdef PERL_DEBUG_READONLY_COW
361 if (munmap(where_intrn, size)) {
362 perror("munmap failed");
368 Malloc_t where_intrn = where;
370 #ifndef PERL_DEBUG_READONLY_COW
371 PerlMem_free(where_intrn);
376 /* safe version of system's calloc() */
379 Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
381 #ifdef ALWAYS_NEED_THX
385 #if defined(USE_MDH) || defined(DEBUGGING)
386 MEM_SIZE total_size = 0;
389 /* Even though calloc() for zero bytes is strange, be robust. */
390 if (size && (count <= MEM_SIZE_MAX / size)) {
391 #if defined(USE_MDH) || defined(DEBUGGING)
392 total_size = size * count;
398 if (PERL_MEMORY_DEBUG_HEADER_SIZE <= MEM_SIZE_MAX - (MEM_SIZE)total_size)
399 total_size += PERL_MEMORY_DEBUG_HEADER_SIZE;
404 if ((SSize_t)size < 0 || (SSize_t)count < 0)
405 Perl_croak_nocontext("panic: calloc, size=%"UVuf", count=%"UVuf,
406 (UV)size, (UV)count);
408 #ifdef PERL_DEBUG_READONLY_COW
409 if ((ptr = mmap(0, total_size ? total_size : 1, PROT_READ|PROT_WRITE,
410 MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED) {
411 perror("mmap failed");
414 #elif defined(PERL_TRACK_MEMPOOL)
415 /* Have to use malloc() because we've added some space for our tracking
417 /* malloc(0) is non-portable. */
418 ptr = (Malloc_t)PerlMem_malloc(total_size ? total_size : 1);
420 /* Use calloc() because it might save a memset() if the memory is fresh
421 and clean from the OS. */
423 ptr = (Malloc_t)PerlMem_calloc(count, size);
424 else /* calloc(0) is non-portable. */
425 ptr = (Malloc_t)PerlMem_calloc(count ? count : 1, size ? size : 1);
427 PERL_ALLOC_CHECK(ptr);
428 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));
432 struct perl_memory_debug_header *const header
433 = (struct perl_memory_debug_header *)ptr;
435 # ifndef PERL_DEBUG_READONLY_COW
436 memset((void*)ptr, 0, total_size);
438 # ifdef PERL_TRACK_MEMPOOL
439 header->interpreter = aTHX;
440 /* Link us into the list. */
441 header->prev = &PL_memory_debug_header;
442 header->next = PL_memory_debug_header.next;
443 PL_memory_debug_header.next = header;
444 maybe_protect_rw(header->next);
445 header->next->prev = header;
446 maybe_protect_ro(header->next);
447 # ifdef PERL_DEBUG_READONLY_COW
448 header->readonly = 0;
452 header->size = total_size;
454 ptr = (Malloc_t)((char*)ptr+PERL_MEMORY_DEBUG_HEADER_SIZE);
460 #ifndef ALWAYS_NEED_THX
469 /* These must be defined when not using Perl's malloc for binary
474 Malloc_t Perl_malloc (MEM_SIZE nbytes)
476 #ifdef PERL_IMPLICIT_SYS
479 return (Malloc_t)PerlMem_malloc(nbytes);
482 Malloc_t Perl_calloc (MEM_SIZE elements, MEM_SIZE size)
484 #ifdef PERL_IMPLICIT_SYS
487 return (Malloc_t)PerlMem_calloc(elements, size);
490 Malloc_t Perl_realloc (Malloc_t where, MEM_SIZE nbytes)
492 #ifdef PERL_IMPLICIT_SYS
495 return (Malloc_t)PerlMem_realloc(where, nbytes);
498 Free_t Perl_mfree (Malloc_t where)
500 #ifdef PERL_IMPLICIT_SYS
508 /* copy a string up to some (non-backslashed) delimiter, if any */
511 Perl_delimcpy(char *to, const char *toend, const char *from, const char *fromend, int delim, I32 *retlen)
515 PERL_ARGS_ASSERT_DELIMCPY;
517 for (tolen = 0; from < fromend; from++, tolen++) {
519 if (from[1] != delim) {
526 else if (*from == delim)
537 /* return ptr to little string in big string, NULL if not found */
538 /* This routine was donated by Corey Satten. */
541 Perl_instr(const char *big, const char *little)
544 PERL_ARGS_ASSERT_INSTR;
546 /* libc prior to 4.6.27 (late 1994) did not work properly on a NULL
550 return strstr((char*)big, (char*)little);
553 /* same as instr but allow embedded nulls. The end pointers point to 1 beyond
554 * the final character desired to be checked */
557 Perl_ninstr(const char *big, const char *bigend, const char *little, const char *lend)
559 PERL_ARGS_ASSERT_NINSTR;
563 const char first = *little;
565 bigend -= lend - little++;
567 while (big <= bigend) {
568 if (*big++ == first) {
569 for (x=big,s=little; s < lend; x++,s++) {
573 return (char*)(big-1);
580 /* reverse of the above--find last substring */
583 Perl_rninstr(const char *big, const char *bigend, const char *little, const char *lend)
586 const I32 first = *little;
587 const char * const littleend = lend;
589 PERL_ARGS_ASSERT_RNINSTR;
591 if (little >= littleend)
592 return (char*)bigend;
594 big = bigend - (littleend - little++);
595 while (big >= bigbeg) {
599 for (x=big+2,s=little; s < littleend; /**/ ) {
608 return (char*)(big+1);
613 /* As a space optimization, we do not compile tables for strings of length
614 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
615 special-cased in fbm_instr().
617 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
620 =head1 Miscellaneous Functions
622 =for apidoc fbm_compile
624 Analyses the string in order to make fast searches on it using fbm_instr()
625 -- the Boyer-Moore algorithm.
631 Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
638 PERL_DEB( STRLEN rarest = 0 );
640 PERL_ARGS_ASSERT_FBM_COMPILE;
642 if (isGV_with_GP(sv) || SvROK(sv))
648 if (flags & FBMcf_TAIL) {
649 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL;
650 sv_catpvs(sv, "\n"); /* Taken into account in fbm_instr() */
651 if (mg && mg->mg_len >= 0)
654 if (!SvPOK(sv) || SvNIOKp(sv))
655 s = (U8*)SvPV_force_mutable(sv, len);
656 else s = (U8 *)SvPV_mutable(sv, len);
657 if (len == 0) /* TAIL might be on a zero-length string. */
659 SvUPGRADE(sv, SVt_PVMG);
664 /* "deep magic", the comment used to add. The use of MAGIC itself isn't
665 really. MAGIC was originally added in 79072805bf63abe5 (perl 5.0 alpha 2)
666 to call SvVALID_off() if the scalar was assigned to.
668 The comment itself (and "deeper magic" below) date back to
669 378cc40b38293ffc (perl 2.0). "deep magic" was an annotation on
671 where the magic (presumably) was that the scalar had a BM table hidden
674 As MAGIC is always present on BMs [in Perl 5 :-)], we can use it to store
675 the table instead of the previous (somewhat hacky) approach of co-opting
676 the string buffer and storing it after the string. */
678 assert(!mg_find(sv, PERL_MAGIC_bm));
679 mg = sv_magicext(sv, NULL, PERL_MAGIC_bm, &PL_vtbl_bm, NULL, 0);
683 /* Shorter strings are special-cased in Perl_fbm_instr(), and don't use
685 const U8 mlen = (len>255) ? 255 : (U8)len;
686 const unsigned char *const sb = s + len - mlen; /* first char (maybe) */
689 Newx(table, 256, U8);
690 memset((void*)table, mlen, 256);
691 mg->mg_ptr = (char *)table;
694 s += len - 1; /* last char */
697 if (table[*s] == mlen)
703 s = (const unsigned char*)(SvPVX_const(sv)); /* deeper magic */
704 for (i = 0; i < len; i++) {
705 if (PL_freq[s[i]] < frequency) {
706 PERL_DEB( rarest = i );
707 frequency = PL_freq[s[i]];
710 BmUSEFUL(sv) = 100; /* Initial value */
711 if (flags & FBMcf_TAIL)
713 DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %"UVuf"\n",
714 s[rarest], (UV)rarest));
717 /* If SvTAIL(littlestr), it has a fake '\n' at end. */
718 /* If SvTAIL is actually due to \Z or \z, this gives false positives
722 =for apidoc fbm_instr
724 Returns the location of the SV in the string delimited by C<big> and
725 C<bigend>. It returns C<NULL> if the string can't be found. The C<sv>
726 does not have to be fbm_compiled, but the search will not be as fast
733 Perl_fbm_instr(pTHX_ unsigned char *big, unsigned char *bigend, SV *littlestr, U32 flags)
737 const unsigned char *little = (const unsigned char *)SvPV_const(littlestr,l);
738 STRLEN littlelen = l;
739 const I32 multiline = flags & FBMrf_MULTILINE;
741 PERL_ARGS_ASSERT_FBM_INSTR;
743 if ((STRLEN)(bigend - big) < littlelen) {
744 if ( SvTAIL(littlestr)
745 && ((STRLEN)(bigend - big) == littlelen - 1)
747 || (*big == *little &&
748 memEQ((char *)big, (char *)little, littlelen - 1))))
753 switch (littlelen) { /* Special cases for 0, 1 and 2 */
755 return (char*)big; /* Cannot be SvTAIL! */
757 if (SvTAIL(littlestr) && !multiline) { /* Anchor only! */
758 /* Know that bigend != big. */
759 if (bigend[-1] == '\n')
760 return (char *)(bigend - 1);
761 return (char *) bigend;
769 if (SvTAIL(littlestr))
770 return (char *) bigend;
773 if (SvTAIL(littlestr) && !multiline) {
774 if (bigend[-1] == '\n' && bigend[-2] == *little)
775 return (char*)bigend - 2;
776 if (bigend[-1] == *little)
777 return (char*)bigend - 1;
781 /* This should be better than FBM if c1 == c2, and almost
782 as good otherwise: maybe better since we do less indirection.
783 And we save a lot of memory by caching no table. */
784 const unsigned char c1 = little[0];
785 const unsigned char c2 = little[1];
790 while (s <= bigend) {
800 goto check_1char_anchor;
811 goto check_1char_anchor;
814 while (s <= bigend) {
819 goto check_1char_anchor;
828 check_1char_anchor: /* One char and anchor! */
829 if (SvTAIL(littlestr) && (*bigend == *little))
830 return (char *)bigend; /* bigend is already decremented. */
833 break; /* Only lengths 0 1 and 2 have special-case code. */
836 if (SvTAIL(littlestr) && !multiline) { /* tail anchored? */
837 s = bigend - littlelen;
838 if (s >= big && bigend[-1] == '\n' && *s == *little
839 /* Automatically of length > 2 */
840 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
842 return (char*)s; /* how sweet it is */
845 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
847 return (char*)s + 1; /* how sweet it is */
851 if (!SvVALID(littlestr)) {
852 char * const b = ninstr((char*)big,(char*)bigend,
853 (char*)little, (char*)little + littlelen);
855 if (!b && SvTAIL(littlestr)) { /* Automatically multiline! */
856 /* Chop \n from littlestr: */
857 s = bigend - littlelen + 1;
859 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
869 if (littlelen > (STRLEN)(bigend - big))
873 const MAGIC *const mg = mg_find(littlestr, PERL_MAGIC_bm);
874 const unsigned char *oldlittle;
878 --littlelen; /* Last char found by table lookup */
881 little += littlelen; /* last char */
884 const unsigned char * const table = (const unsigned char *) mg->mg_ptr;
888 if ((tmp = table[*s])) {
889 if ((s += tmp) < bigend)
893 else { /* less expensive than calling strncmp() */
894 unsigned char * const olds = s;
899 if (*--s == *--little)
901 s = olds + 1; /* here we pay the price for failure */
903 if (s < bigend) /* fake up continue to outer loop */
913 && memEQ((char *)(bigend - littlelen),
914 (char *)(oldlittle - littlelen), littlelen) )
915 return (char*)bigend - littlelen;
923 Returns true if the leading len bytes of the strings s1 and s2 are the same
924 case-insensitively; false otherwise. Uppercase and lowercase ASCII range bytes
925 match themselves and their opposite case counterparts. Non-cased and non-ASCII
926 range bytes match only themselves.
933 Perl_foldEQ(const char *s1, const char *s2, I32 len)
935 const U8 *a = (const U8 *)s1;
936 const U8 *b = (const U8 *)s2;
938 PERL_ARGS_ASSERT_FOLDEQ;
943 if (*a != *b && *a != PL_fold[*b])
950 Perl_foldEQ_latin1(const char *s1, const char *s2, I32 len)
952 /* Compare non-utf8 using Unicode (Latin1) semantics. Does not work on
953 * MICRO_SIGN, LATIN_SMALL_LETTER_SHARP_S, nor
954 * LATIN_SMALL_LETTER_Y_WITH_DIAERESIS, and does not check for these. Nor
955 * does it check that the strings each have at least 'len' characters */
957 const U8 *a = (const U8 *)s1;
958 const U8 *b = (const U8 *)s2;
960 PERL_ARGS_ASSERT_FOLDEQ_LATIN1;
965 if (*a != *b && *a != PL_fold_latin1[*b]) {
974 =for apidoc foldEQ_locale
976 Returns true if the leading len bytes of the strings s1 and s2 are the same
977 case-insensitively in the current locale; false otherwise.
983 Perl_foldEQ_locale(const char *s1, const char *s2, I32 len)
986 const U8 *a = (const U8 *)s1;
987 const U8 *b = (const U8 *)s2;
989 PERL_ARGS_ASSERT_FOLDEQ_LOCALE;
994 if (*a != *b && *a != PL_fold_locale[*b])
1001 /* copy a string to a safe spot */
1004 =head1 Memory Management
1008 Perl's version of C<strdup()>. Returns a pointer to a newly allocated
1009 string which is a duplicate of C<pv>. The size of the string is
1010 determined by C<strlen()>, which means it may not contain embedded C<NUL>
1011 characters and must have a trailing C<NUL>. The memory allocated for the new
1012 string can be freed with the C<Safefree()> function.
1014 On some platforms, Windows for example, all allocated memory owned by a thread
1015 is deallocated when that thread ends. So if you need that not to happen, you
1016 need to use the shared memory functions, such as C<L</savesharedpv>>.
1022 Perl_savepv(pTHX_ const char *pv)
1024 PERL_UNUSED_CONTEXT;
1029 const STRLEN pvlen = strlen(pv)+1;
1030 Newx(newaddr, pvlen, char);
1031 return (char*)memcpy(newaddr, pv, pvlen);
1035 /* same thing but with a known length */
1040 Perl's version of what C<strndup()> would be if it existed. Returns a
1041 pointer to a newly allocated string which is a duplicate of the first
1042 C<len> bytes from C<pv>, plus a trailing
1043 C<NUL> byte. The memory allocated for
1044 the new string can be freed with the C<Safefree()> function.
1046 On some platforms, Windows for example, all allocated memory owned by a thread
1047 is deallocated when that thread ends. So if you need that not to happen, you
1048 need to use the shared memory functions, such as C<L</savesharedpvn>>.
1054 Perl_savepvn(pTHX_ const char *pv, I32 len)
1057 PERL_UNUSED_CONTEXT;
1061 Newx(newaddr,len+1,char);
1062 /* Give a meaning to NULL pointer mainly for the use in sv_magic() */
1064 /* might not be null terminated */
1065 newaddr[len] = '\0';
1066 return (char *) CopyD(pv,newaddr,len,char);
1069 return (char *) ZeroD(newaddr,len+1,char);
1074 =for apidoc savesharedpv
1076 A version of C<savepv()> which allocates the duplicate string in memory
1077 which is shared between threads.
1082 Perl_savesharedpv(pTHX_ const char *pv)
1087 PERL_UNUSED_CONTEXT;
1092 pvlen = strlen(pv)+1;
1093 newaddr = (char*)PerlMemShared_malloc(pvlen);
1097 return (char*)memcpy(newaddr, pv, pvlen);
1101 =for apidoc savesharedpvn
1103 A version of C<savepvn()> which allocates the duplicate string in memory
1104 which is shared between threads. (With the specific difference that a NULL
1105 pointer is not acceptable)
1110 Perl_savesharedpvn(pTHX_ const char *const pv, const STRLEN len)
1112 char *const newaddr = (char*)PerlMemShared_malloc(len + 1);
1114 PERL_UNUSED_CONTEXT;
1115 /* PERL_ARGS_ASSERT_SAVESHAREDPVN; */
1120 newaddr[len] = '\0';
1121 return (char*)memcpy(newaddr, pv, len);
1125 =for apidoc savesvpv
1127 A version of C<savepv()>/C<savepvn()> which gets the string to duplicate from
1128 the passed in SV using C<SvPV()>
1130 On some platforms, Windows for example, all allocated memory owned by a thread
1131 is deallocated when that thread ends. So if you need that not to happen, you
1132 need to use the shared memory functions, such as C<L</savesharedsvpv>>.
1138 Perl_savesvpv(pTHX_ SV *sv)
1141 const char * const pv = SvPV_const(sv, len);
1144 PERL_ARGS_ASSERT_SAVESVPV;
1147 Newx(newaddr,len,char);
1148 return (char *) CopyD(pv,newaddr,len,char);
1152 =for apidoc savesharedsvpv
1154 A version of C<savesharedpv()> which allocates the duplicate string in
1155 memory which is shared between threads.
1161 Perl_savesharedsvpv(pTHX_ SV *sv)
1164 const char * const pv = SvPV_const(sv, len);
1166 PERL_ARGS_ASSERT_SAVESHAREDSVPV;
1168 return savesharedpvn(pv, len);
1171 /* the SV for Perl_form() and mess() is not kept in an arena */
1179 if (PL_phase != PERL_PHASE_DESTRUCT)
1180 return newSVpvs_flags("", SVs_TEMP);
1185 /* Create as PVMG now, to avoid any upgrading later */
1187 Newxz(any, 1, XPVMG);
1188 SvFLAGS(sv) = SVt_PVMG;
1189 SvANY(sv) = (void*)any;
1191 SvREFCNT(sv) = 1 << 30; /* practically infinite */
1196 #if defined(PERL_IMPLICIT_CONTEXT)
1198 Perl_form_nocontext(const char* pat, ...)
1203 PERL_ARGS_ASSERT_FORM_NOCONTEXT;
1204 va_start(args, pat);
1205 retval = vform(pat, &args);
1209 #endif /* PERL_IMPLICIT_CONTEXT */
1212 =head1 Miscellaneous Functions
1215 Takes a sprintf-style format pattern and conventional
1216 (non-SV) arguments and returns the formatted string.
1218 (char *) Perl_form(pTHX_ const char* pat, ...)
1220 can be used any place a string (char *) is required:
1222 char * s = Perl_form("%d.%d",major,minor);
1224 Uses a single private buffer so if you want to format several strings you
1225 must explicitly copy the earlier strings away (and free the copies when you
1232 Perl_form(pTHX_ const char* pat, ...)
1236 PERL_ARGS_ASSERT_FORM;
1237 va_start(args, pat);
1238 retval = vform(pat, &args);
1244 Perl_vform(pTHX_ const char *pat, va_list *args)
1246 SV * const sv = mess_alloc();
1247 PERL_ARGS_ASSERT_VFORM;
1248 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1253 =for apidoc Am|SV *|mess|const char *pat|...
1255 Take a sprintf-style format pattern and argument list. These are used to
1256 generate a string message. If the message does not end with a newline,
1257 then it will be extended with some indication of the current location
1258 in the code, as described for L</mess_sv>.
1260 Normally, the resulting message is returned in a new mortal SV.
1261 During global destruction a single SV may be shared between uses of
1267 #if defined(PERL_IMPLICIT_CONTEXT)
1269 Perl_mess_nocontext(const char *pat, ...)
1274 PERL_ARGS_ASSERT_MESS_NOCONTEXT;
1275 va_start(args, pat);
1276 retval = vmess(pat, &args);
1280 #endif /* PERL_IMPLICIT_CONTEXT */
1283 Perl_mess(pTHX_ const char *pat, ...)
1287 PERL_ARGS_ASSERT_MESS;
1288 va_start(args, pat);
1289 retval = vmess(pat, &args);
1295 Perl_closest_cop(pTHX_ const COP *cop, const OP *o, const OP *curop,
1298 /* Look for curop starting from o. cop is the last COP we've seen. */
1299 /* opnext means that curop is actually the ->op_next of the op we are
1302 PERL_ARGS_ASSERT_CLOSEST_COP;
1304 if (!o || !curop || (
1305 opnext ? o->op_next == curop && o->op_type != OP_SCOPE : o == curop
1309 if (o->op_flags & OPf_KIDS) {
1311 for (kid = cUNOPo->op_first; kid; kid = OP_SIBLING(kid)) {
1314 /* If the OP_NEXTSTATE has been optimised away we can still use it
1315 * the get the file and line number. */
1317 if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
1318 cop = (const COP *)kid;
1320 /* Keep searching, and return when we've found something. */
1322 new_cop = closest_cop(cop, kid, curop, opnext);
1328 /* Nothing found. */
1334 =for apidoc Am|SV *|mess_sv|SV *basemsg|bool consume
1336 Expands a message, intended for the user, to include an indication of
1337 the current location in the code, if the message does not already appear
1340 C<basemsg> is the initial message or object. If it is a reference, it
1341 will be used as-is and will be the result of this function. Otherwise it
1342 is used as a string, and if it already ends with a newline, it is taken
1343 to be complete, and the result of this function will be the same string.
1344 If the message does not end with a newline, then a segment such as C<at
1345 foo.pl line 37> will be appended, and possibly other clauses indicating
1346 the current state of execution. The resulting message will end with a
1349 Normally, the resulting message is returned in a new mortal SV.
1350 During global destruction a single SV may be shared between uses of this
1351 function. If C<consume> is true, then the function is permitted (but not
1352 required) to modify and return C<basemsg> instead of allocating a new SV.
1358 Perl_mess_sv(pTHX_ SV *basemsg, bool consume)
1362 #if defined(USE_C_BACKTRACE) && defined(USE_C_BACKTRACE_ON_ERROR)
1366 /* The PERL_C_BACKTRACE_ON_WARN must be an integer of one or more. */
1367 if ((ws = PerlEnv_getenv("PERL_C_BACKTRACE_ON_ERROR")) &&
1368 (wi = grok_atou(ws, NULL)) > 0) {
1369 Perl_dump_c_backtrace(aTHX_ Perl_debug_log, wi, 1);
1374 PERL_ARGS_ASSERT_MESS_SV;
1376 if (SvROK(basemsg)) {
1382 sv_setsv(sv, basemsg);
1387 if (SvPOK(basemsg) && consume) {
1392 sv_copypv(sv, basemsg);
1395 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1397 * Try and find the file and line for PL_op. This will usually be
1398 * PL_curcop, but it might be a cop that has been optimised away. We
1399 * can try to find such a cop by searching through the optree starting
1400 * from the sibling of PL_curcop.
1404 closest_cop(PL_curcop, OP_SIBLING(PL_curcop), PL_op, FALSE);
1409 Perl_sv_catpvf(aTHX_ sv, " at %s line %"IVdf,
1410 OutCopFILE(cop), (IV)CopLINE(cop));
1411 /* Seems that GvIO() can be untrustworthy during global destruction. */
1412 if (GvIO(PL_last_in_gv) && (SvTYPE(GvIOp(PL_last_in_gv)) == SVt_PVIO)
1413 && IoLINES(GvIOp(PL_last_in_gv)))
1416 const bool line_mode = (RsSIMPLE(PL_rs) &&
1417 *SvPV_const(PL_rs,l) == '\n' && l == 1);
1418 Perl_sv_catpvf(aTHX_ sv, ", <%"SVf"> %s %"IVdf,
1419 SVfARG(PL_last_in_gv == PL_argvgv
1421 : sv_2mortal(newSVhek(GvNAME_HEK(PL_last_in_gv)))),
1422 line_mode ? "line" : "chunk",
1423 (IV)IoLINES(GvIOp(PL_last_in_gv)));
1425 if (PL_phase == PERL_PHASE_DESTRUCT)
1426 sv_catpvs(sv, " during global destruction");
1427 sv_catpvs(sv, ".\n");
1433 =for apidoc Am|SV *|vmess|const char *pat|va_list *args
1435 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1436 argument list. These are used to generate a string message. If the
1437 message does not end with a newline, then it will be extended with
1438 some indication of the current location in the code, as described for
1441 Normally, the resulting message is returned in a new mortal SV.
1442 During global destruction a single SV may be shared between uses of
1449 Perl_vmess(pTHX_ const char *pat, va_list *args)
1451 SV * const sv = mess_alloc();
1453 PERL_ARGS_ASSERT_VMESS;
1455 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1456 return mess_sv(sv, 1);
1460 Perl_write_to_stderr(pTHX_ SV* msv)
1465 PERL_ARGS_ASSERT_WRITE_TO_STDERR;
1467 if (PL_stderrgv && SvREFCNT(PL_stderrgv)
1468 && (io = GvIO(PL_stderrgv))
1469 && (mg = SvTIED_mg((const SV *)io, PERL_MAGIC_tiedscalar)))
1470 Perl_magic_methcall(aTHX_ MUTABLE_SV(io), mg, SV_CONST(PRINT),
1471 G_SCALAR | G_DISCARD | G_WRITING_TO_STDERR, 1, msv);
1473 PerlIO * const serr = Perl_error_log;
1475 do_print(msv, serr);
1476 (void)PerlIO_flush(serr);
1481 =head1 Warning and Dieing
1484 /* Common code used in dieing and warning */
1487 S_with_queued_errors(pTHX_ SV *ex)
1489 PERL_ARGS_ASSERT_WITH_QUEUED_ERRORS;
1490 if (PL_errors && SvCUR(PL_errors) && !SvROK(ex)) {
1491 sv_catsv(PL_errors, ex);
1492 ex = sv_mortalcopy(PL_errors);
1493 SvCUR_set(PL_errors, 0);
1499 S_invoke_exception_hook(pTHX_ SV *ex, bool warn)
1504 SV **const hook = warn ? &PL_warnhook : &PL_diehook;
1505 /* sv_2cv might call Perl_croak() or Perl_warner() */
1506 SV * const oldhook = *hook;
1514 cv = sv_2cv(oldhook, &stash, &gv, 0);
1516 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1525 exarg = newSVsv(ex);
1526 SvREADONLY_on(exarg);
1529 PUSHSTACKi(warn ? PERLSI_WARNHOOK : PERLSI_DIEHOOK);
1533 call_sv(MUTABLE_SV(cv), G_DISCARD);
1542 =for apidoc Am|OP *|die_sv|SV *baseex
1544 Behaves the same as L</croak_sv>, except for the return type.
1545 It should be used only where the C<OP *> return type is required.
1546 The function never actually returns.
1552 # pragma warning( push )
1553 # pragma warning( disable : 4646 ) /* warning C4646: function declared with
1554 __declspec(noreturn) has non-void return type */
1555 # pragma warning( disable : 4645 ) /* warning C4645: function declared with
1556 __declspec(noreturn) has a return statement */
1559 Perl_die_sv(pTHX_ SV *baseex)
1561 PERL_ARGS_ASSERT_DIE_SV;
1563 assert(0); /* NOTREACHED */
1564 NORETURN_FUNCTION_END;
1567 # pragma warning( pop )
1571 =for apidoc Am|OP *|die|const char *pat|...
1573 Behaves the same as L</croak>, except for the return type.
1574 It should be used only where the C<OP *> return type is required.
1575 The function never actually returns.
1580 #if defined(PERL_IMPLICIT_CONTEXT)
1582 # pragma warning( push )
1583 # pragma warning( disable : 4646 ) /* warning C4646: function declared with
1584 __declspec(noreturn) has non-void return type */
1585 # pragma warning( disable : 4645 ) /* warning C4645: function declared with
1586 __declspec(noreturn) has a return statement */
1589 Perl_die_nocontext(const char* pat, ...)
1593 va_start(args, pat);
1595 assert(0); /* NOTREACHED */
1597 NORETURN_FUNCTION_END;
1600 # pragma warning( pop )
1602 #endif /* PERL_IMPLICIT_CONTEXT */
1605 # pragma warning( push )
1606 # pragma warning( disable : 4646 ) /* warning C4646: function declared with
1607 __declspec(noreturn) has non-void return type */
1608 # pragma warning( disable : 4645 ) /* warning C4645: function declared with
1609 __declspec(noreturn) has a return statement */
1612 Perl_die(pTHX_ const char* pat, ...)
1615 va_start(args, pat);
1617 assert(0); /* NOTREACHED */
1619 NORETURN_FUNCTION_END;
1622 # pragma warning( pop )
1626 =for apidoc Am|void|croak_sv|SV *baseex
1628 This is an XS interface to Perl's C<die> function.
1630 C<baseex> is the error message or object. If it is a reference, it
1631 will be used as-is. Otherwise it is used as a string, and if it does
1632 not end with a newline then it will be extended with some indication of
1633 the current location in the code, as described for L</mess_sv>.
1635 The error message or object will be used as an exception, by default
1636 returning control to the nearest enclosing C<eval>, but subject to
1637 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak_sv>
1638 function never returns normally.
1640 To die with a simple string message, the L</croak> function may be
1647 Perl_croak_sv(pTHX_ SV *baseex)
1649 SV *ex = with_queued_errors(mess_sv(baseex, 0));
1650 PERL_ARGS_ASSERT_CROAK_SV;
1651 invoke_exception_hook(ex, FALSE);
1656 =for apidoc Am|void|vcroak|const char *pat|va_list *args
1658 This is an XS interface to Perl's C<die> function.
1660 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1661 argument list. These are used to generate a string message. If the
1662 message does not end with a newline, then it will be extended with
1663 some indication of the current location in the code, as described for
1666 The error message will be used as an exception, by default
1667 returning control to the nearest enclosing C<eval>, but subject to
1668 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1669 function never returns normally.
1671 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1672 (C<$@>) will be used as an error message or object instead of building an
1673 error message from arguments. If you want to throw a non-string object,
1674 or build an error message in an SV yourself, it is preferable to use
1675 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1681 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1683 SV *ex = with_queued_errors(pat ? vmess(pat, args) : mess_sv(ERRSV, 0));
1684 invoke_exception_hook(ex, FALSE);
1689 =for apidoc Am|void|croak|const char *pat|...
1691 This is an XS interface to Perl's C<die> function.
1693 Take a sprintf-style format pattern and argument list. These are used to
1694 generate a string message. If the message does not end with a newline,
1695 then it will be extended with some indication of the current location
1696 in the code, as described for L</mess_sv>.
1698 The error message will be used as an exception, by default
1699 returning control to the nearest enclosing C<eval>, but subject to
1700 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1701 function never returns normally.
1703 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1704 (C<$@>) will be used as an error message or object instead of building an
1705 error message from arguments. If you want to throw a non-string object,
1706 or build an error message in an SV yourself, it is preferable to use
1707 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1712 #if defined(PERL_IMPLICIT_CONTEXT)
1714 Perl_croak_nocontext(const char *pat, ...)
1718 va_start(args, pat);
1720 assert(0); /* NOTREACHED */
1723 #endif /* PERL_IMPLICIT_CONTEXT */
1726 Perl_croak(pTHX_ const char *pat, ...)
1729 va_start(args, pat);
1731 assert(0); /* NOTREACHED */
1736 =for apidoc Am|void|croak_no_modify
1738 Exactly equivalent to C<Perl_croak(aTHX_ "%s", PL_no_modify)>, but generates
1739 terser object code than using C<Perl_croak>. Less code used on exception code
1740 paths reduces CPU cache pressure.
1746 Perl_croak_no_modify(void)
1748 Perl_croak_nocontext( "%s", PL_no_modify);
1751 /* does not return, used in util.c perlio.c and win32.c
1752 This is typically called when malloc returns NULL.
1755 Perl_croak_no_mem(void)
1759 int fd = PerlIO_fileno(Perl_error_log);
1761 SETERRNO(EBADF,RMS_IFI);
1763 /* Can't use PerlIO to write as it allocates memory */
1764 PERL_UNUSED_RESULT(PerlLIO_write(fd, PL_no_mem, sizeof(PL_no_mem)-1));
1769 /* does not return, used only in POPSTACK */
1771 Perl_croak_popstack(void)
1774 PerlIO_printf(Perl_error_log, "panic: POPSTACK\n");
1779 =for apidoc Am|void|warn_sv|SV *baseex
1781 This is an XS interface to Perl's C<warn> function.
1783 C<baseex> is the error message or object. If it is a reference, it
1784 will be used as-is. Otherwise it is used as a string, and if it does
1785 not end with a newline then it will be extended with some indication of
1786 the current location in the code, as described for L</mess_sv>.
1788 The error message or object will by default be written to standard error,
1789 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1791 To warn with a simple string message, the L</warn> function may be
1798 Perl_warn_sv(pTHX_ SV *baseex)
1800 SV *ex = mess_sv(baseex, 0);
1801 PERL_ARGS_ASSERT_WARN_SV;
1802 if (!invoke_exception_hook(ex, TRUE))
1803 write_to_stderr(ex);
1807 =for apidoc Am|void|vwarn|const char *pat|va_list *args
1809 This is an XS interface to Perl's C<warn> function.
1811 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1812 argument list. These are used to generate a string message. If the
1813 message does not end with a newline, then it will be extended with
1814 some indication of the current location in the code, as described for
1817 The error message or object will by default be written to standard error,
1818 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1820 Unlike with L</vcroak>, C<pat> is not permitted to be null.
1826 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1828 SV *ex = vmess(pat, args);
1829 PERL_ARGS_ASSERT_VWARN;
1830 if (!invoke_exception_hook(ex, TRUE))
1831 write_to_stderr(ex);
1835 =for apidoc Am|void|warn|const char *pat|...
1837 This is an XS interface to Perl's C<warn> function.
1839 Take a sprintf-style format pattern and argument list. These are used to
1840 generate a string message. If the message does not end with a newline,
1841 then it will be extended with some indication of the current location
1842 in the code, as described for L</mess_sv>.
1844 The error message or object will by default be written to standard error,
1845 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1847 Unlike with L</croak>, C<pat> is not permitted to be null.
1852 #if defined(PERL_IMPLICIT_CONTEXT)
1854 Perl_warn_nocontext(const char *pat, ...)
1858 PERL_ARGS_ASSERT_WARN_NOCONTEXT;
1859 va_start(args, pat);
1863 #endif /* PERL_IMPLICIT_CONTEXT */
1866 Perl_warn(pTHX_ const char *pat, ...)
1869 PERL_ARGS_ASSERT_WARN;
1870 va_start(args, pat);
1875 #if defined(PERL_IMPLICIT_CONTEXT)
1877 Perl_warner_nocontext(U32 err, const char *pat, ...)
1881 PERL_ARGS_ASSERT_WARNER_NOCONTEXT;
1882 va_start(args, pat);
1883 vwarner(err, pat, &args);
1886 #endif /* PERL_IMPLICIT_CONTEXT */
1889 Perl_ck_warner_d(pTHX_ U32 err, const char* pat, ...)
1891 PERL_ARGS_ASSERT_CK_WARNER_D;
1893 if (Perl_ckwarn_d(aTHX_ err)) {
1895 va_start(args, pat);
1896 vwarner(err, pat, &args);
1902 Perl_ck_warner(pTHX_ U32 err, const char* pat, ...)
1904 PERL_ARGS_ASSERT_CK_WARNER;
1906 if (Perl_ckwarn(aTHX_ err)) {
1908 va_start(args, pat);
1909 vwarner(err, pat, &args);
1915 Perl_warner(pTHX_ U32 err, const char* pat,...)
1918 PERL_ARGS_ASSERT_WARNER;
1919 va_start(args, pat);
1920 vwarner(err, pat, &args);
1925 Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
1928 PERL_ARGS_ASSERT_VWARNER;
1929 if (PL_warnhook == PERL_WARNHOOK_FATAL || ckDEAD(err)) {
1930 SV * const msv = vmess(pat, args);
1932 if (PL_parser && PL_parser->error_count) {
1936 invoke_exception_hook(msv, FALSE);
1941 Perl_vwarn(aTHX_ pat, args);
1945 /* implements the ckWARN? macros */
1948 Perl_ckwarn(pTHX_ U32 w)
1950 /* If lexical warnings have not been set, use $^W. */
1952 return PL_dowarn & G_WARN_ON;
1954 return ckwarn_common(w);
1957 /* implements the ckWARN?_d macro */
1960 Perl_ckwarn_d(pTHX_ U32 w)
1962 /* If lexical warnings have not been set then default classes warn. */
1966 return ckwarn_common(w);
1970 S_ckwarn_common(pTHX_ U32 w)
1972 if (PL_curcop->cop_warnings == pWARN_ALL)
1975 if (PL_curcop->cop_warnings == pWARN_NONE)
1978 /* Check the assumption that at least the first slot is non-zero. */
1979 assert(unpackWARN1(w));
1981 /* Check the assumption that it is valid to stop as soon as a zero slot is
1983 if (!unpackWARN2(w)) {
1984 assert(!unpackWARN3(w));
1985 assert(!unpackWARN4(w));
1986 } else if (!unpackWARN3(w)) {
1987 assert(!unpackWARN4(w));
1990 /* Right, dealt with all the special cases, which are implemented as non-
1991 pointers, so there is a pointer to a real warnings mask. */
1993 if (isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w)))
1995 } while (w >>= WARNshift);
2000 /* Set buffer=NULL to get a new one. */
2002 Perl_new_warnings_bitfield(pTHX_ STRLEN *buffer, const char *const bits,
2004 const MEM_SIZE len_wanted =
2005 sizeof(STRLEN) + (size > WARNsize ? size : WARNsize);
2006 PERL_UNUSED_CONTEXT;
2007 PERL_ARGS_ASSERT_NEW_WARNINGS_BITFIELD;
2010 (specialWARN(buffer) ?
2011 PerlMemShared_malloc(len_wanted) :
2012 PerlMemShared_realloc(buffer, len_wanted));
2014 Copy(bits, (buffer + 1), size, char);
2015 if (size < WARNsize)
2016 Zero((char *)(buffer + 1) + size, WARNsize - size, char);
2020 /* since we've already done strlen() for both nam and val
2021 * we can use that info to make things faster than
2022 * sprintf(s, "%s=%s", nam, val)
2024 #define my_setenv_format(s, nam, nlen, val, vlen) \
2025 Copy(nam, s, nlen, char); \
2027 Copy(val, s+(nlen+1), vlen, char); \
2028 *(s+(nlen+1+vlen)) = '\0'
2030 #ifdef USE_ENVIRON_ARRAY
2031 /* VMS' my_setenv() is in vms.c */
2032 #if !defined(WIN32) && !defined(NETWARE)
2034 Perl_my_setenv(pTHX_ const char *nam, const char *val)
2038 /* only parent thread can modify process environment */
2039 if (PL_curinterp == aTHX)
2042 #ifndef PERL_USE_SAFE_PUTENV
2043 if (!PL_use_safe_putenv) {
2044 /* most putenv()s leak, so we manipulate environ directly */
2046 const I32 len = strlen(nam);
2049 /* where does it go? */
2050 for (i = 0; environ[i]; i++) {
2051 if (strnEQ(environ[i],nam,len) && environ[i][len] == '=')
2055 if (environ == PL_origenviron) { /* need we copy environment? */
2061 while (environ[max])
2063 tmpenv = (char**)safesysmalloc((max+2) * sizeof(char*));
2064 for (j=0; j<max; j++) { /* copy environment */
2065 const int len = strlen(environ[j]);
2066 tmpenv[j] = (char*)safesysmalloc((len+1)*sizeof(char));
2067 Copy(environ[j], tmpenv[j], len+1, char);
2070 environ = tmpenv; /* tell exec where it is now */
2073 safesysfree(environ[i]);
2074 while (environ[i]) {
2075 environ[i] = environ[i+1];
2080 if (!environ[i]) { /* does not exist yet */
2081 environ = (char**)safesysrealloc(environ, (i+2) * sizeof(char*));
2082 environ[i+1] = NULL; /* make sure it's null terminated */
2085 safesysfree(environ[i]);
2089 environ[i] = (char*)safesysmalloc((nlen+vlen+2) * sizeof(char));
2090 /* all that work just for this */
2091 my_setenv_format(environ[i], nam, nlen, val, vlen);
2094 /* This next branch should only be called #if defined(HAS_SETENV), but
2095 Configure doesn't test for that yet. For Solaris, setenv() and unsetenv()
2096 were introduced in Solaris 9, so testing for HAS UNSETENV is sufficient.
2098 # if defined(__CYGWIN__)|| defined(__SYMBIAN32__) || defined(__riscos__) || (defined(__sun) && defined(HAS_UNSETENV))
2099 # if defined(HAS_UNSETENV)
2101 (void)unsetenv(nam);
2103 (void)setenv(nam, val, 1);
2105 # else /* ! HAS_UNSETENV */
2106 (void)setenv(nam, val, 1);
2107 # endif /* HAS_UNSETENV */
2109 # if defined(HAS_UNSETENV)
2111 if (environ) /* old glibc can crash with null environ */
2112 (void)unsetenv(nam);
2114 const int nlen = strlen(nam);
2115 const int vlen = strlen(val);
2116 char * const new_env =
2117 (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
2118 my_setenv_format(new_env, nam, nlen, val, vlen);
2119 (void)putenv(new_env);
2121 # else /* ! HAS_UNSETENV */
2123 const int nlen = strlen(nam);
2129 new_env = (char*)safesysmalloc((nlen + vlen + 2) * sizeof(char));
2130 /* all that work just for this */
2131 my_setenv_format(new_env, nam, nlen, val, vlen);
2132 (void)putenv(new_env);
2133 # endif /* HAS_UNSETENV */
2134 # endif /* __CYGWIN__ */
2135 #ifndef PERL_USE_SAFE_PUTENV
2141 #else /* WIN32 || NETWARE */
2144 Perl_my_setenv(pTHX_ const char *nam, const char *val)
2148 const int nlen = strlen(nam);
2155 Newx(envstr, nlen+vlen+2, char);
2156 my_setenv_format(envstr, nam, nlen, val, vlen);
2157 (void)PerlEnv_putenv(envstr);
2161 #endif /* WIN32 || NETWARE */
2165 #ifdef UNLINK_ALL_VERSIONS
2167 Perl_unlnk(pTHX_ const char *f) /* unlink all versions of a file */
2171 PERL_ARGS_ASSERT_UNLNK;
2173 while (PerlLIO_unlink(f) >= 0)
2175 return retries ? 0 : -1;
2179 /* this is a drop-in replacement for bcopy() */
2180 #if (!defined(HAS_MEMCPY) && !defined(HAS_BCOPY)) || (!defined(HAS_MEMMOVE) && !defined(HAS_SAFE_MEMCPY) && !defined(HAS_SAFE_BCOPY))
2182 Perl_my_bcopy(const char *from, char *to, I32 len)
2184 char * const retval = to;
2186 PERL_ARGS_ASSERT_MY_BCOPY;
2190 if (from - to >= 0) {
2198 *(--to) = *(--from);
2204 /* this is a drop-in replacement for memset() */
2207 Perl_my_memset(char *loc, I32 ch, I32 len)
2209 char * const retval = loc;
2211 PERL_ARGS_ASSERT_MY_MEMSET;
2221 /* this is a drop-in replacement for bzero() */
2222 #if !defined(HAS_BZERO) && !defined(HAS_MEMSET)
2224 Perl_my_bzero(char *loc, I32 len)
2226 char * const retval = loc;
2228 PERL_ARGS_ASSERT_MY_BZERO;
2238 /* this is a drop-in replacement for memcmp() */
2239 #if !defined(HAS_MEMCMP) || !defined(HAS_SANE_MEMCMP)
2241 Perl_my_memcmp(const char *s1, const char *s2, I32 len)
2243 const U8 *a = (const U8 *)s1;
2244 const U8 *b = (const U8 *)s2;
2247 PERL_ARGS_ASSERT_MY_MEMCMP;
2252 if ((tmp = *a++ - *b++))
2257 #endif /* !HAS_MEMCMP || !HAS_SANE_MEMCMP */
2260 /* This vsprintf replacement should generally never get used, since
2261 vsprintf was available in both System V and BSD 2.11. (There may
2262 be some cross-compilation or embedded set-ups where it is needed,
2265 If you encounter a problem in this function, it's probably a symptom
2266 that Configure failed to detect your system's vprintf() function.
2267 See the section on "item vsprintf" in the INSTALL file.
2269 This version may compile on systems with BSD-ish <stdio.h>,
2270 but probably won't on others.
2273 #ifdef USE_CHAR_VSPRINTF
2278 vsprintf(char *dest, const char *pat, void *args)
2282 #if defined(STDIO_PTR_LVALUE) && defined(STDIO_CNT_LVALUE)
2283 FILE_ptr(&fakebuf) = (STDCHAR *) dest;
2284 FILE_cnt(&fakebuf) = 32767;
2286 /* These probably won't compile -- If you really need
2287 this, you'll have to figure out some other method. */
2288 fakebuf._ptr = dest;
2289 fakebuf._cnt = 32767;
2294 fakebuf._flag = _IOWRT|_IOSTRG;
2295 _doprnt(pat, args, &fakebuf); /* what a kludge */
2296 #if defined(STDIO_PTR_LVALUE)
2297 *(FILE_ptr(&fakebuf)++) = '\0';
2299 /* PerlIO has probably #defined away fputc, but we want it here. */
2301 # undef fputc /* XXX Should really restore it later */
2303 (void)fputc('\0', &fakebuf);
2305 #ifdef USE_CHAR_VSPRINTF
2308 return 0; /* perl doesn't use return value */
2312 #endif /* HAS_VPRINTF */
2315 Perl_my_popen_list(pTHX_ const char *mode, int n, SV **args)
2317 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(OS2) && !defined(VMS) && !defined(NETWARE) && !defined(__LIBCATAMOUNT__)
2325 PERL_ARGS_ASSERT_MY_POPEN_LIST;
2327 PERL_FLUSHALL_FOR_CHILD;
2328 This = (*mode == 'w');
2332 taint_proper("Insecure %s%s", "EXEC");
2334 if (PerlProc_pipe(p) < 0)
2336 /* Try for another pipe pair for error return */
2337 if (PerlProc_pipe(pp) >= 0)
2339 while ((pid = PerlProc_fork()) < 0) {
2340 if (errno != EAGAIN) {
2341 PerlLIO_close(p[This]);
2342 PerlLIO_close(p[that]);
2344 PerlLIO_close(pp[0]);
2345 PerlLIO_close(pp[1]);
2349 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2358 /* Close parent's end of error status pipe (if any) */
2360 PerlLIO_close(pp[0]);
2361 #if defined(HAS_FCNTL) && defined(F_SETFD)
2362 /* Close error pipe automatically if exec works */
2363 if (fcntl(pp[1], F_SETFD, FD_CLOEXEC) < 0)
2367 /* Now dup our end of _the_ pipe to right position */
2368 if (p[THIS] != (*mode == 'r')) {
2369 PerlLIO_dup2(p[THIS], *mode == 'r');
2370 PerlLIO_close(p[THIS]);
2371 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2372 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2375 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2376 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2377 /* No automatic close - do it by hand */
2384 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
2390 do_aexec5(NULL, args-1, args-1+n, pp[1], did_pipes);
2396 do_execfree(); /* free any memory malloced by child on fork */
2398 PerlLIO_close(pp[1]);
2399 /* Keep the lower of the two fd numbers */
2400 if (p[that] < p[This]) {
2401 PerlLIO_dup2(p[This], p[that]);
2402 PerlLIO_close(p[This]);
2406 PerlLIO_close(p[that]); /* close child's end of pipe */
2408 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2409 SvUPGRADE(sv,SVt_IV);
2411 PL_forkprocess = pid;
2412 /* If we managed to get status pipe check for exec fail */
2413 if (did_pipes && pid > 0) {
2418 while (n < sizeof(int)) {
2419 n1 = PerlLIO_read(pp[0],
2420 (void*)(((char*)&errkid)+n),
2426 PerlLIO_close(pp[0]);
2428 if (n) { /* Error */
2430 PerlLIO_close(p[This]);
2431 if (n != sizeof(int))
2432 Perl_croak(aTHX_ "panic: kid popen errno read, n=%u", n);
2434 pid2 = wait4pid(pid, &status, 0);
2435 } while (pid2 == -1 && errno == EINTR);
2436 errno = errkid; /* Propagate errno from kid */
2441 PerlLIO_close(pp[0]);
2442 return PerlIO_fdopen(p[This], mode);
2444 # if defined(OS2) /* Same, without fork()ing and all extra overhead... */
2445 return my_syspopen4(aTHX_ NULL, mode, n, args);
2446 # elif defined(WIN32)
2447 return win32_popenlist(mode, n, args);
2449 Perl_croak(aTHX_ "List form of piped open not implemented");
2450 return (PerlIO *) NULL;
2455 /* VMS' my_popen() is in VMS.c, same with OS/2. */
2456 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__LIBCATAMOUNT__)
2458 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2464 const I32 doexec = !(*cmd == '-' && cmd[1] == '\0');
2468 PERL_ARGS_ASSERT_MY_POPEN;
2470 PERL_FLUSHALL_FOR_CHILD;
2473 return my_syspopen(aTHX_ cmd,mode);
2476 This = (*mode == 'w');
2478 if (doexec && TAINTING_get) {
2480 taint_proper("Insecure %s%s", "EXEC");
2482 if (PerlProc_pipe(p) < 0)
2484 if (doexec && PerlProc_pipe(pp) >= 0)
2486 while ((pid = PerlProc_fork()) < 0) {
2487 if (errno != EAGAIN) {
2488 PerlLIO_close(p[This]);
2489 PerlLIO_close(p[that]);
2491 PerlLIO_close(pp[0]);
2492 PerlLIO_close(pp[1]);
2495 Perl_croak(aTHX_ "Can't fork: %s", Strerror(errno));
2498 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2508 PerlLIO_close(pp[0]);
2509 #if defined(HAS_FCNTL) && defined(F_SETFD)
2510 if (fcntl(pp[1], F_SETFD, FD_CLOEXEC) < 0)
2514 if (p[THIS] != (*mode == 'r')) {
2515 PerlLIO_dup2(p[THIS], *mode == 'r');
2516 PerlLIO_close(p[THIS]);
2517 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2518 PerlLIO_close(p[THAT]);
2521 PerlLIO_close(p[THAT]);
2524 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2531 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2536 /* may or may not use the shell */
2537 do_exec3(cmd, pp[1], did_pipes);
2540 #endif /* defined OS2 */
2542 #ifdef PERLIO_USING_CRLF
2543 /* Since we circumvent IO layers when we manipulate low-level
2544 filedescriptors directly, need to manually switch to the
2545 default, binary, low-level mode; see PerlIOBuf_open(). */
2546 PerlLIO_setmode((*mode == 'r'), O_BINARY);
2549 #ifdef PERL_USES_PL_PIDSTATUS
2550 hv_clear(PL_pidstatus); /* we have no children */
2556 do_execfree(); /* free any memory malloced by child on vfork */
2558 PerlLIO_close(pp[1]);
2559 if (p[that] < p[This]) {
2560 PerlLIO_dup2(p[This], p[that]);
2561 PerlLIO_close(p[This]);
2565 PerlLIO_close(p[that]);
2567 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2568 SvUPGRADE(sv,SVt_IV);
2570 PL_forkprocess = pid;
2571 if (did_pipes && pid > 0) {
2576 while (n < sizeof(int)) {
2577 n1 = PerlLIO_read(pp[0],
2578 (void*)(((char*)&errkid)+n),
2584 PerlLIO_close(pp[0]);
2586 if (n) { /* Error */
2588 PerlLIO_close(p[This]);
2589 if (n != sizeof(int))
2590 Perl_croak(aTHX_ "panic: kid popen errno read, n=%u", n);
2592 pid2 = wait4pid(pid, &status, 0);
2593 } while (pid2 == -1 && errno == EINTR);
2594 errno = errkid; /* Propagate errno from kid */
2599 PerlLIO_close(pp[0]);
2600 return PerlIO_fdopen(p[This], mode);
2604 FILE *djgpp_popen();
2606 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2608 PERL_FLUSHALL_FOR_CHILD;
2609 /* Call system's popen() to get a FILE *, then import it.
2610 used 0 for 2nd parameter to PerlIO_importFILE;
2613 return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2616 #if defined(__LIBCATAMOUNT__)
2618 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2625 #endif /* !DOSISH */
2627 /* this is called in parent before the fork() */
2629 Perl_atfork_lock(void)
2631 #if defined(USE_ITHREADS)
2633 /* locks must be held in locking order (if any) */
2635 MUTEX_LOCK(&PL_perlio_mutex);
2638 MUTEX_LOCK(&PL_malloc_mutex);
2644 /* this is called in both parent and child after the fork() */
2646 Perl_atfork_unlock(void)
2648 #if defined(USE_ITHREADS)
2650 /* locks must be released in same order as in atfork_lock() */
2652 MUTEX_UNLOCK(&PL_perlio_mutex);
2655 MUTEX_UNLOCK(&PL_malloc_mutex);
2664 #if defined(HAS_FORK)
2666 #if defined(USE_ITHREADS) && !defined(HAS_PTHREAD_ATFORK)
2671 /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2672 * handlers elsewhere in the code */
2677 /* this "canna happen" since nothing should be calling here if !HAS_FORK */
2678 Perl_croak_nocontext("fork() not available");
2680 #endif /* HAS_FORK */
2685 dup2(int oldfd, int newfd)
2687 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2690 PerlLIO_close(newfd);
2691 return fcntl(oldfd, F_DUPFD, newfd);
2693 #define DUP2_MAX_FDS 256
2694 int fdtmp[DUP2_MAX_FDS];
2700 PerlLIO_close(newfd);
2701 /* good enough for low fd's... */
2702 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2703 if (fdx >= DUP2_MAX_FDS) {
2711 PerlLIO_close(fdtmp[--fdx]);
2718 #ifdef HAS_SIGACTION
2721 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2723 struct sigaction act, oact;
2727 /* only "parent" interpreter can diddle signals */
2728 if (PL_curinterp != aTHX)
2729 return (Sighandler_t) SIG_ERR;
2732 act.sa_handler = (void(*)(int))handler;
2733 sigemptyset(&act.sa_mask);
2736 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2737 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2739 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2740 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2741 act.sa_flags |= SA_NOCLDWAIT;
2743 if (sigaction(signo, &act, &oact) == -1)
2744 return (Sighandler_t) SIG_ERR;
2746 return (Sighandler_t) oact.sa_handler;
2750 Perl_rsignal_state(pTHX_ int signo)
2752 struct sigaction oact;
2753 PERL_UNUSED_CONTEXT;
2755 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2756 return (Sighandler_t) SIG_ERR;
2758 return (Sighandler_t) oact.sa_handler;
2762 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2767 struct sigaction act;
2769 PERL_ARGS_ASSERT_RSIGNAL_SAVE;
2772 /* only "parent" interpreter can diddle signals */
2773 if (PL_curinterp != aTHX)
2777 act.sa_handler = (void(*)(int))handler;
2778 sigemptyset(&act.sa_mask);
2781 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2782 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2784 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2785 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2786 act.sa_flags |= SA_NOCLDWAIT;
2788 return sigaction(signo, &act, save);
2792 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2797 PERL_UNUSED_CONTEXT;
2799 /* only "parent" interpreter can diddle signals */
2800 if (PL_curinterp != aTHX)
2804 return sigaction(signo, save, (struct sigaction *)NULL);
2807 #else /* !HAS_SIGACTION */
2810 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2812 #if defined(USE_ITHREADS) && !defined(WIN32)
2813 /* only "parent" interpreter can diddle signals */
2814 if (PL_curinterp != aTHX)
2815 return (Sighandler_t) SIG_ERR;
2818 return PerlProc_signal(signo, handler);
2829 Perl_rsignal_state(pTHX_ int signo)
2832 Sighandler_t oldsig;
2834 #if defined(USE_ITHREADS) && !defined(WIN32)
2835 /* only "parent" interpreter can diddle signals */
2836 if (PL_curinterp != aTHX)
2837 return (Sighandler_t) SIG_ERR;
2841 oldsig = PerlProc_signal(signo, sig_trap);
2842 PerlProc_signal(signo, oldsig);
2844 PerlProc_kill(PerlProc_getpid(), signo);
2849 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2851 #if defined(USE_ITHREADS) && !defined(WIN32)
2852 /* only "parent" interpreter can diddle signals */
2853 if (PL_curinterp != aTHX)
2856 *save = PerlProc_signal(signo, handler);
2857 return (*save == (Sighandler_t) SIG_ERR) ? -1 : 0;
2861 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2863 #if defined(USE_ITHREADS) && !defined(WIN32)
2864 /* only "parent" interpreter can diddle signals */
2865 if (PL_curinterp != aTHX)
2868 return (PerlProc_signal(signo, *save) == (Sighandler_t) SIG_ERR) ? -1 : 0;
2871 #endif /* !HAS_SIGACTION */
2872 #endif /* !PERL_MICRO */
2874 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
2875 #if (!defined(DOSISH) || defined(HAS_FORK) || defined(AMIGAOS)) && !defined(VMS) && !defined(__LIBCATAMOUNT__)
2877 Perl_my_pclose(pTHX_ PerlIO *ptr)
2885 const int fd = PerlIO_fileno(ptr);
2888 svp = av_fetch(PL_fdpid,fd,TRUE);
2889 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
2893 #if defined(USE_PERLIO)
2894 /* Find out whether the refcount is low enough for us to wait for the
2895 child proc without blocking. */
2896 should_wait = PerlIOUnix_refcnt(fd) == 1 && pid > 0;
2898 should_wait = pid > 0;
2902 if (pid == -1) { /* Opened by popen. */
2903 return my_syspclose(ptr);
2906 close_failed = (PerlIO_close(ptr) == EOF);
2908 if (should_wait) do {
2909 pid2 = wait4pid(pid, &status, 0);
2910 } while (pid2 == -1 && errno == EINTR);
2917 ? pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status)
2922 #if defined(__LIBCATAMOUNT__)
2924 Perl_my_pclose(pTHX_ PerlIO *ptr)
2929 #endif /* !DOSISH */
2931 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(__LIBCATAMOUNT__)
2933 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
2936 PERL_ARGS_ASSERT_WAIT4PID;
2937 #ifdef PERL_USES_PL_PIDSTATUS
2939 /* PERL_USES_PL_PIDSTATUS is only defined when neither
2940 waitpid() nor wait4() is available, or on OS/2, which
2941 doesn't appear to support waiting for a progress group
2942 member, so we can only treat a 0 pid as an unknown child.
2949 /* The keys in PL_pidstatus are now the raw 4 (or 8) bytes of the
2950 pid, rather than a string form. */
2951 SV * const * const svp = hv_fetch(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),FALSE);
2952 if (svp && *svp != &PL_sv_undef) {
2953 *statusp = SvIVX(*svp);
2954 (void)hv_delete(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),
2962 hv_iterinit(PL_pidstatus);
2963 if ((entry = hv_iternext(PL_pidstatus))) {
2964 SV * const sv = hv_iterval(PL_pidstatus,entry);
2966 const char * const spid = hv_iterkey(entry,&len);
2968 assert (len == sizeof(Pid_t));
2969 memcpy((char *)&pid, spid, len);
2970 *statusp = SvIVX(sv);
2971 /* The hash iterator is currently on this entry, so simply
2972 calling hv_delete would trigger the lazy delete, which on
2973 aggregate does more work, beacuse next call to hv_iterinit()
2974 would spot the flag, and have to call the delete routine,
2975 while in the meantime any new entries can't re-use that
2977 hv_iterinit(PL_pidstatus);
2978 (void)hv_delete(PL_pidstatus,spid,len,G_DISCARD);
2985 # ifdef HAS_WAITPID_RUNTIME
2986 if (!HAS_WAITPID_RUNTIME)
2989 result = PerlProc_waitpid(pid,statusp,flags);
2992 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
2993 result = wait4(pid,statusp,flags,NULL);
2996 #ifdef PERL_USES_PL_PIDSTATUS
2997 #if defined(HAS_WAITPID) && defined(HAS_WAITPID_RUNTIME)
3002 Perl_croak(aTHX_ "Can't do waitpid with flags");
3004 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
3005 pidgone(result,*statusp);
3011 #if defined(HAS_WAITPID) || defined(HAS_WAIT4)
3014 if (result < 0 && errno == EINTR) {
3016 errno = EINTR; /* reset in case a signal handler changed $! */
3020 #endif /* !DOSISH || OS2 || WIN32 || NETWARE */
3022 #ifdef PERL_USES_PL_PIDSTATUS
3024 S_pidgone(pTHX_ Pid_t pid, int status)
3028 sv = *hv_fetch(PL_pidstatus,(const char*)&pid,sizeof(Pid_t),TRUE);
3029 SvUPGRADE(sv,SVt_IV);
3030 SvIV_set(sv, status);
3038 int /* Cannot prototype with I32
3040 my_syspclose(PerlIO *ptr)
3043 Perl_my_pclose(pTHX_ PerlIO *ptr)
3046 /* Needs work for PerlIO ! */
3047 FILE * const f = PerlIO_findFILE(ptr);
3048 const I32 result = pclose(f);
3049 PerlIO_releaseFILE(ptr,f);
3057 Perl_my_pclose(pTHX_ PerlIO *ptr)
3059 /* Needs work for PerlIO ! */
3060 FILE * const f = PerlIO_findFILE(ptr);
3061 I32 result = djgpp_pclose(f);
3062 result = (result << 8) & 0xff00;
3063 PerlIO_releaseFILE(ptr,f);
3068 #define PERL_REPEATCPY_LINEAR 4
3070 Perl_repeatcpy(char *to, const char *from, I32 len, IV count)
3072 PERL_ARGS_ASSERT_REPEATCPY;
3077 croak_memory_wrap();
3080 memset(to, *from, count);
3083 IV items, linear, half;
3085 linear = count < PERL_REPEATCPY_LINEAR ? count : PERL_REPEATCPY_LINEAR;
3086 for (items = 0; items < linear; ++items) {
3087 const char *q = from;
3089 for (todo = len; todo > 0; todo--)
3094 while (items <= half) {
3095 IV size = items * len;
3096 memcpy(p, to, size);
3102 memcpy(p, to, (count - items) * len);
3108 Perl_same_dirent(pTHX_ const char *a, const char *b)
3110 char *fa = strrchr(a,'/');
3111 char *fb = strrchr(b,'/');
3114 SV * const tmpsv = sv_newmortal();
3116 PERL_ARGS_ASSERT_SAME_DIRENT;
3129 sv_setpvs(tmpsv, ".");
3131 sv_setpvn(tmpsv, a, fa - a);
3132 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf1) < 0)
3135 sv_setpvs(tmpsv, ".");
3137 sv_setpvn(tmpsv, b, fb - b);
3138 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf2) < 0)
3140 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
3141 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
3143 #endif /* !HAS_RENAME */
3146 Perl_find_script(pTHX_ const char *scriptname, bool dosearch,
3147 const char *const *const search_ext, I32 flags)
3149 const char *xfound = NULL;
3150 char *xfailed = NULL;
3151 char tmpbuf[MAXPATHLEN];
3156 #if defined(DOSISH) && !defined(OS2)
3157 # define SEARCH_EXTS ".bat", ".cmd", NULL
3158 # define MAX_EXT_LEN 4
3161 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
3162 # define MAX_EXT_LEN 4
3165 # define SEARCH_EXTS ".pl", ".com", NULL
3166 # define MAX_EXT_LEN 4
3168 /* additional extensions to try in each dir if scriptname not found */
3170 static const char *const exts[] = { SEARCH_EXTS };
3171 const char *const *const ext = search_ext ? search_ext : exts;
3172 int extidx = 0, i = 0;
3173 const char *curext = NULL;
3175 PERL_UNUSED_ARG(search_ext);
3176 # define MAX_EXT_LEN 0
3179 PERL_ARGS_ASSERT_FIND_SCRIPT;
3182 * If dosearch is true and if scriptname does not contain path
3183 * delimiters, search the PATH for scriptname.
3185 * If SEARCH_EXTS is also defined, will look for each
3186 * scriptname{SEARCH_EXTS} whenever scriptname is not found
3187 * while searching the PATH.
3189 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
3190 * proceeds as follows:
3191 * If DOSISH or VMSISH:
3192 * + look for ./scriptname{,.foo,.bar}
3193 * + search the PATH for scriptname{,.foo,.bar}
3196 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
3197 * this will not look in '.' if it's not in the PATH)
3202 # ifdef ALWAYS_DEFTYPES
3203 len = strlen(scriptname);
3204 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
3205 int idx = 0, deftypes = 1;
3208 const int hasdir = !dosearch || (strpbrk(scriptname,":[</") != NULL);
3211 int idx = 0, deftypes = 1;
3214 const int hasdir = (strpbrk(scriptname,":[</") != NULL);
3216 /* The first time through, just add SEARCH_EXTS to whatever we
3217 * already have, so we can check for default file types. */
3219 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
3225 if ((strlen(tmpbuf) + strlen(scriptname)
3226 + MAX_EXT_LEN) >= sizeof tmpbuf)
3227 continue; /* don't search dir with too-long name */
3228 my_strlcat(tmpbuf, scriptname, sizeof(tmpbuf));
3232 if (strEQ(scriptname, "-"))
3234 if (dosearch) { /* Look in '.' first. */
3235 const char *cur = scriptname;
3237 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
3239 if (strEQ(ext[i++],curext)) {
3240 extidx = -1; /* already has an ext */
3245 DEBUG_p(PerlIO_printf(Perl_debug_log,
3246 "Looking for %s\n",cur));
3247 if (PerlLIO_stat(cur,&PL_statbuf) >= 0
3248 && !S_ISDIR(PL_statbuf.st_mode)) {
3256 if (cur == scriptname) {
3257 len = strlen(scriptname);
3258 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
3260 my_strlcpy(tmpbuf, scriptname, sizeof(tmpbuf));
3263 } while (extidx >= 0 && ext[extidx] /* try an extension? */
3264 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len));
3269 if (dosearch && !strchr(scriptname, '/')
3271 && !strchr(scriptname, '\\')
3273 && (s = PerlEnv_getenv("PATH")))
3277 bufend = s + strlen(s);
3278 while (s < bufend) {
3281 && *s != ';'; len++, s++) {
3282 if (len < sizeof tmpbuf)
3285 if (len < sizeof tmpbuf)
3288 s = delimcpy(tmpbuf, tmpbuf + sizeof tmpbuf, s, bufend,
3294 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
3295 continue; /* don't search dir with too-long name */
3298 && tmpbuf[len - 1] != '/'
3299 && tmpbuf[len - 1] != '\\'
3302 tmpbuf[len++] = '/';
3303 if (len == 2 && tmpbuf[0] == '.')
3305 (void)my_strlcpy(tmpbuf + len, scriptname, sizeof(tmpbuf) - len);
3309 len = strlen(tmpbuf);
3310 if (extidx > 0) /* reset after previous loop */
3314 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
3315 retval = PerlLIO_stat(tmpbuf,&PL_statbuf);
3316 if (S_ISDIR(PL_statbuf.st_mode)) {
3320 } while ( retval < 0 /* not there */
3321 && extidx>=0 && ext[extidx] /* try an extension? */
3322 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len)
3327 if (S_ISREG(PL_statbuf.st_mode)
3328 && cando(S_IRUSR,TRUE,&PL_statbuf)
3329 #if !defined(DOSISH)
3330 && cando(S_IXUSR,TRUE,&PL_statbuf)
3334 xfound = tmpbuf; /* bingo! */
3338 xfailed = savepv(tmpbuf);
3341 if (!xfound && !seen_dot && !xfailed &&
3342 (PerlLIO_stat(scriptname,&PL_statbuf) < 0
3343 || S_ISDIR(PL_statbuf.st_mode)))
3345 seen_dot = 1; /* Disable message. */
3347 if (flags & 1) { /* do or die? */
3348 /* diag_listed_as: Can't execute %s */
3349 Perl_croak(aTHX_ "Can't %s %s%s%s",
3350 (xfailed ? "execute" : "find"),
3351 (xfailed ? xfailed : scriptname),
3352 (xfailed ? "" : " on PATH"),
3353 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
3358 scriptname = xfound;
3360 return (scriptname ? savepv(scriptname) : NULL);
3363 #ifndef PERL_GET_CONTEXT_DEFINED
3366 Perl_get_context(void)
3368 #if defined(USE_ITHREADS)
3370 # ifdef OLD_PTHREADS_API
3372 int error = pthread_getspecific(PL_thr_key, &t)
3374 Perl_croak_nocontext("panic: pthread_getspecific, error=%d", error);
3377 # ifdef I_MACH_CTHREADS
3378 return (void*)cthread_data(cthread_self());
3380 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
3389 Perl_set_context(void *t)
3391 #if defined(USE_ITHREADS)
3394 PERL_ARGS_ASSERT_SET_CONTEXT;
3395 #if defined(USE_ITHREADS)
3396 # ifdef I_MACH_CTHREADS
3397 cthread_set_data(cthread_self(), t);
3400 const int error = pthread_setspecific(PL_thr_key, t);
3402 Perl_croak_nocontext("panic: pthread_setspecific, error=%d", error);
3410 #endif /* !PERL_GET_CONTEXT_DEFINED */
3412 #if defined(PERL_GLOBAL_STRUCT) && !defined(PERL_GLOBAL_STRUCT_PRIVATE)
3416 PERL_UNUSED_CONTEXT;
3422 Perl_get_op_names(pTHX)
3424 PERL_UNUSED_CONTEXT;
3425 return (char **)PL_op_name;
3429 Perl_get_op_descs(pTHX)
3431 PERL_UNUSED_CONTEXT;
3432 return (char **)PL_op_desc;
3436 Perl_get_no_modify(pTHX)
3438 PERL_UNUSED_CONTEXT;
3439 return PL_no_modify;
3443 Perl_get_opargs(pTHX)
3445 PERL_UNUSED_CONTEXT;
3446 return (U32 *)PL_opargs;
3450 Perl_get_ppaddr(pTHX)
3453 PERL_UNUSED_CONTEXT;
3454 return (PPADDR_t*)PL_ppaddr;
3457 #ifndef HAS_GETENV_LEN
3459 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3461 char * const env_trans = PerlEnv_getenv(env_elem);
3462 PERL_UNUSED_CONTEXT;
3463 PERL_ARGS_ASSERT_GETENV_LEN;
3465 *len = strlen(env_trans);
3472 Perl_get_vtbl(pTHX_ int vtbl_id)
3474 PERL_UNUSED_CONTEXT;
3476 return (vtbl_id < 0 || vtbl_id >= magic_vtable_max)
3477 ? NULL : (MGVTBL*)PL_magic_vtables + vtbl_id;
3481 Perl_my_fflush_all(pTHX)
3483 #if defined(USE_PERLIO) || defined(FFLUSH_NULL)
3484 return PerlIO_flush(NULL);
3486 # if defined(HAS__FWALK)
3487 extern int fflush(FILE *);
3488 /* undocumented, unprototyped, but very useful BSDism */
3489 extern void _fwalk(int (*)(FILE *));
3493 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3495 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3496 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3498 # if defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3499 open_max = sysconf(_SC_OPEN_MAX);
3502 open_max = FOPEN_MAX;
3505 open_max = OPEN_MAX;
3516 for (i = 0; i < open_max; i++)
3517 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3518 STDIO_STREAM_ARRAY[i]._file < open_max &&
3519 STDIO_STREAM_ARRAY[i]._flag)
3520 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3524 SETERRNO(EBADF,RMS_IFI);
3531 Perl_report_wrongway_fh(pTHX_ const GV *gv, const char have)
3533 if (ckWARN(WARN_IO)) {
3535 = gv && (isGV_with_GP(gv))
3538 const char * const direction = have == '>' ? "out" : "in";
3540 if (name && HEK_LEN(name))
3541 Perl_warner(aTHX_ packWARN(WARN_IO),
3542 "Filehandle %"HEKf" opened only for %sput",
3543 HEKfARG(name), direction);
3545 Perl_warner(aTHX_ packWARN(WARN_IO),
3546 "Filehandle opened only for %sput", direction);
3551 Perl_report_evil_fh(pTHX_ const GV *gv)
3553 const IO *io = gv ? GvIO(gv) : NULL;
3554 const PERL_BITFIELD16 op = PL_op->op_type;
3558 if (io && IoTYPE(io) == IoTYPE_CLOSED) {
3560 warn_type = WARN_CLOSED;
3564 warn_type = WARN_UNOPENED;
3567 if (ckWARN(warn_type)) {
3569 = gv && isGV_with_GP(gv) && GvENAMELEN(gv) ?
3570 sv_2mortal(newSVhek(GvENAME_HEK(gv))) : NULL;
3571 const char * const pars =
3572 (const char *)(OP_IS_FILETEST(op) ? "" : "()");
3573 const char * const func =
3575 (op == OP_READLINE || op == OP_RCATLINE
3576 ? "readline" : /* "<HANDLE>" not nice */
3577 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
3579 const char * const type =
3581 (OP_IS_SOCKET(op) || (io && IoTYPE(io) == IoTYPE_SOCKET)
3582 ? "socket" : "filehandle");
3583 const bool have_name = name && SvCUR(name);
3584 Perl_warner(aTHX_ packWARN(warn_type),
3585 "%s%s on %s %s%s%"SVf, func, pars, vile, type,
3586 have_name ? " " : "",
3587 SVfARG(have_name ? name : &PL_sv_no));
3588 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3590 aTHX_ packWARN(warn_type),
3591 "\t(Are you trying to call %s%s on dirhandle%s%"SVf"?)\n",
3592 func, pars, have_name ? " " : "",
3593 SVfARG(have_name ? name : &PL_sv_no)
3598 /* To workaround core dumps from the uninitialised tm_zone we get the
3599 * system to give us a reasonable struct to copy. This fix means that
3600 * strftime uses the tm_zone and tm_gmtoff values returned by
3601 * localtime(time()). That should give the desired result most of the
3602 * time. But probably not always!
3604 * This does not address tzname aspects of NETaa14816.
3609 # ifndef STRUCT_TM_HASZONE
3610 # define STRUCT_TM_HASZONE
3614 #ifdef STRUCT_TM_HASZONE /* Backward compat */
3615 # ifndef HAS_TM_TM_ZONE
3616 # define HAS_TM_TM_ZONE
3621 Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
3623 #ifdef HAS_TM_TM_ZONE
3625 const struct tm* my_tm;
3626 PERL_UNUSED_CONTEXT;
3627 PERL_ARGS_ASSERT_INIT_TM;
3629 my_tm = localtime(&now);
3631 Copy(my_tm, ptm, 1, struct tm);
3633 PERL_UNUSED_CONTEXT;
3634 PERL_ARGS_ASSERT_INIT_TM;
3635 PERL_UNUSED_ARG(ptm);
3640 * mini_mktime - normalise struct tm values without the localtime()
3641 * semantics (and overhead) of mktime().
3644 Perl_mini_mktime(struct tm *ptm)
3648 int month, mday, year, jday;
3649 int odd_cent, odd_year;
3651 PERL_ARGS_ASSERT_MINI_MKTIME;
3653 #define DAYS_PER_YEAR 365
3654 #define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
3655 #define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
3656 #define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
3657 #define SECS_PER_HOUR (60*60)
3658 #define SECS_PER_DAY (24*SECS_PER_HOUR)
3659 /* parentheses deliberately absent on these two, otherwise they don't work */
3660 #define MONTH_TO_DAYS 153/5
3661 #define DAYS_TO_MONTH 5/153
3662 /* offset to bias by March (month 4) 1st between month/mday & year finding */
3663 #define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
3664 /* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
3665 #define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
3668 * Year/day algorithm notes:
3670 * With a suitable offset for numeric value of the month, one can find
3671 * an offset into the year by considering months to have 30.6 (153/5) days,
3672 * using integer arithmetic (i.e., with truncation). To avoid too much
3673 * messing about with leap days, we consider January and February to be
3674 * the 13th and 14th month of the previous year. After that transformation,
3675 * we need the month index we use to be high by 1 from 'normal human' usage,
3676 * so the month index values we use run from 4 through 15.
3678 * Given that, and the rules for the Gregorian calendar (leap years are those
3679 * divisible by 4 unless also divisible by 100, when they must be divisible
3680 * by 400 instead), we can simply calculate the number of days since some
3681 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
3682 * the days we derive from our month index, and adding in the day of the
3683 * month. The value used here is not adjusted for the actual origin which
3684 * it normally would use (1 January A.D. 1), since we're not exposing it.
3685 * We're only building the value so we can turn around and get the
3686 * normalised values for the year, month, day-of-month, and day-of-year.
3688 * For going backward, we need to bias the value we're using so that we find
3689 * the right year value. (Basically, we don't want the contribution of
3690 * March 1st to the number to apply while deriving the year). Having done
3691 * that, we 'count up' the contribution to the year number by accounting for
3692 * full quadracenturies (400-year periods) with their extra leap days, plus
3693 * the contribution from full centuries (to avoid counting in the lost leap
3694 * days), plus the contribution from full quad-years (to count in the normal
3695 * leap days), plus the leftover contribution from any non-leap years.
3696 * At this point, if we were working with an actual leap day, we'll have 0
3697 * days left over. This is also true for March 1st, however. So, we have
3698 * to special-case that result, and (earlier) keep track of the 'odd'
3699 * century and year contributions. If we got 4 extra centuries in a qcent,
3700 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
3701 * Otherwise, we add back in the earlier bias we removed (the 123 from
3702 * figuring in March 1st), find the month index (integer division by 30.6),
3703 * and the remainder is the day-of-month. We then have to convert back to
3704 * 'real' months (including fixing January and February from being 14/15 in
3705 * the previous year to being in the proper year). After that, to get
3706 * tm_yday, we work with the normalised year and get a new yearday value for
3707 * January 1st, which we subtract from the yearday value we had earlier,
3708 * representing the date we've re-built. This is done from January 1
3709 * because tm_yday is 0-origin.
3711 * Since POSIX time routines are only guaranteed to work for times since the
3712 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
3713 * applies Gregorian calendar rules even to dates before the 16th century
3714 * doesn't bother me. Besides, you'd need cultural context for a given
3715 * date to know whether it was Julian or Gregorian calendar, and that's
3716 * outside the scope for this routine. Since we convert back based on the
3717 * same rules we used to build the yearday, you'll only get strange results
3718 * for input which needed normalising, or for the 'odd' century years which
3719 * were leap years in the Julian calendar but not in the Gregorian one.
3720 * I can live with that.
3722 * This algorithm also fails to handle years before A.D. 1 gracefully, but
3723 * that's still outside the scope for POSIX time manipulation, so I don't
3727 year = 1900 + ptm->tm_year;
3728 month = ptm->tm_mon;
3729 mday = ptm->tm_mday;
3735 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
3736 yearday += month*MONTH_TO_DAYS + mday + jday;
3738 * Note that we don't know when leap-seconds were or will be,
3739 * so we have to trust the user if we get something which looks
3740 * like a sensible leap-second. Wild values for seconds will
3741 * be rationalised, however.
3743 if ((unsigned) ptm->tm_sec <= 60) {
3750 secs += 60 * ptm->tm_min;
3751 secs += SECS_PER_HOUR * ptm->tm_hour;
3753 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
3754 /* got negative remainder, but need positive time */
3755 /* back off an extra day to compensate */
3756 yearday += (secs/SECS_PER_DAY)-1;
3757 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
3760 yearday += (secs/SECS_PER_DAY);
3761 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
3764 else if (secs >= SECS_PER_DAY) {
3765 yearday += (secs/SECS_PER_DAY);
3766 secs %= SECS_PER_DAY;
3768 ptm->tm_hour = secs/SECS_PER_HOUR;
3769 secs %= SECS_PER_HOUR;
3770 ptm->tm_min = secs/60;
3772 ptm->tm_sec += secs;
3773 /* done with time of day effects */
3775 * The algorithm for yearday has (so far) left it high by 428.
3776 * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
3777 * bias it by 123 while trying to figure out what year it
3778 * really represents. Even with this tweak, the reverse
3779 * translation fails for years before A.D. 0001.
3780 * It would still fail for Feb 29, but we catch that one below.
3782 jday = yearday; /* save for later fixup vis-a-vis Jan 1 */
3783 yearday -= YEAR_ADJUST;
3784 year = (yearday / DAYS_PER_QCENT) * 400;
3785 yearday %= DAYS_PER_QCENT;
3786 odd_cent = yearday / DAYS_PER_CENT;
3787 year += odd_cent * 100;
3788 yearday %= DAYS_PER_CENT;
3789 year += (yearday / DAYS_PER_QYEAR) * 4;
3790 yearday %= DAYS_PER_QYEAR;
3791 odd_year = yearday / DAYS_PER_YEAR;
3793 yearday %= DAYS_PER_YEAR;
3794 if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
3799 yearday += YEAR_ADJUST; /* recover March 1st crock */
3800 month = yearday*DAYS_TO_MONTH;
3801 yearday -= month*MONTH_TO_DAYS;
3802 /* recover other leap-year adjustment */
3811 ptm->tm_year = year - 1900;
3813 ptm->tm_mday = yearday;
3814 ptm->tm_mon = month;
3818 ptm->tm_mon = month - 1;
3820 /* re-build yearday based on Jan 1 to get tm_yday */
3822 yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
3823 yearday += 14*MONTH_TO_DAYS + 1;
3824 ptm->tm_yday = jday - yearday;
3825 ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
3829 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)
3833 /* Note that yday and wday effectively are ignored by this function, as mini_mktime() overwrites them */
3840 PERL_ARGS_ASSERT_MY_STRFTIME;
3842 init_tm(&mytm); /* XXX workaround - see init_tm() above */
3845 mytm.tm_hour = hour;
3846 mytm.tm_mday = mday;
3848 mytm.tm_year = year;
3849 mytm.tm_wday = wday;
3850 mytm.tm_yday = yday;
3851 mytm.tm_isdst = isdst;
3853 /* use libc to get the values for tm_gmtoff and tm_zone [perl #18238] */
3854 #if defined(HAS_MKTIME) && (defined(HAS_TM_TM_GMTOFF) || defined(HAS_TM_TM_ZONE))
3859 #ifdef HAS_TM_TM_GMTOFF
3860 mytm.tm_gmtoff = mytm2.tm_gmtoff;
3862 #ifdef HAS_TM_TM_ZONE
3863 mytm.tm_zone = mytm2.tm_zone;
3868 Newx(buf, buflen, char);
3870 GCC_DIAG_IGNORE(-Wformat-nonliteral); /* fmt checked by caller */
3871 len = strftime(buf, buflen, fmt, &mytm);
3875 ** The following is needed to handle to the situation where
3876 ** tmpbuf overflows. Basically we want to allocate a buffer
3877 ** and try repeatedly. The reason why it is so complicated
3878 ** is that getting a return value of 0 from strftime can indicate
3879 ** one of the following:
3880 ** 1. buffer overflowed,
3881 ** 2. illegal conversion specifier, or
3882 ** 3. the format string specifies nothing to be returned(not
3883 ** an error). This could be because format is an empty string
3884 ** or it specifies %p that yields an empty string in some locale.
3885 ** If there is a better way to make it portable, go ahead by
3888 if ((len > 0 && len < buflen) || (len == 0 && *fmt == '\0'))
3891 /* Possibly buf overflowed - try again with a bigger buf */
3892 const int fmtlen = strlen(fmt);
3893 int bufsize = fmtlen + buflen;
3895 Renew(buf, bufsize, char);
3898 GCC_DIAG_IGNORE(-Wformat-nonliteral); /* fmt checked by caller */
3899 buflen = strftime(buf, bufsize, fmt, &mytm);
3902 if (buflen > 0 && buflen < bufsize)
3904 /* heuristic to prevent out-of-memory errors */
3905 if (bufsize > 100*fmtlen) {
3911 Renew(buf, bufsize, char);
3916 Perl_croak(aTHX_ "panic: no strftime");
3922 #define SV_CWD_RETURN_UNDEF \
3923 sv_setsv(sv, &PL_sv_undef); \
3926 #define SV_CWD_ISDOT(dp) \
3927 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
3928 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
3931 =head1 Miscellaneous Functions
3933 =for apidoc getcwd_sv
3935 Fill the sv with current working directory
3940 /* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
3941 * rewritten again by dougm, optimized for use with xs TARG, and to prefer
3942 * getcwd(3) if available
3943 * Comments from the orignal:
3944 * This is a faster version of getcwd. It's also more dangerous
3945 * because you might chdir out of a directory that you can't chdir
3949 Perl_getcwd_sv(pTHX_ SV *sv)
3954 PERL_ARGS_ASSERT_GETCWD_SV;
3958 char buf[MAXPATHLEN];
3960 /* Some getcwd()s automatically allocate a buffer of the given
3961 * size from the heap if they are given a NULL buffer pointer.
3962 * The problem is that this behaviour is not portable. */
3963 if (getcwd(buf, sizeof(buf) - 1)) {
3968 sv_setsv(sv, &PL_sv_undef);
3976 int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
3980 SvUPGRADE(sv, SVt_PV);
3982 if (PerlLIO_lstat(".", &statbuf) < 0) {
3983 SV_CWD_RETURN_UNDEF;
3986 orig_cdev = statbuf.st_dev;
3987 orig_cino = statbuf.st_ino;
3997 if (PerlDir_chdir("..") < 0) {
3998 SV_CWD_RETURN_UNDEF;
4000 if (PerlLIO_stat(".", &statbuf) < 0) {
4001 SV_CWD_RETURN_UNDEF;
4004 cdev = statbuf.st_dev;
4005 cino = statbuf.st_ino;
4007 if (odev == cdev && oino == cino) {
4010 if (!(dir = PerlDir_open("."))) {
4011 SV_CWD_RETURN_UNDEF;
4014 while ((dp = PerlDir_read(dir)) != NULL) {
4016 namelen = dp->d_namlen;
4018 namelen = strlen(dp->d_name);
4021 if (SV_CWD_ISDOT(dp)) {
4025 if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
4026 SV_CWD_RETURN_UNDEF;
4029 tdev = statbuf.st_dev;
4030 tino = statbuf.st_ino;
4031 if (tino == oino && tdev == odev) {
4037 SV_CWD_RETURN_UNDEF;
4040 if (pathlen + namelen + 1 >= MAXPATHLEN) {
4041 SV_CWD_RETURN_UNDEF;
4044 SvGROW(sv, pathlen + namelen + 1);
4048 Move(SvPVX_const(sv), SvPVX(sv) + namelen + 1, pathlen, char);
4051 /* prepend current directory to the front */
4053 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
4054 pathlen += (namelen + 1);
4056 #ifdef VOID_CLOSEDIR
4059 if (PerlDir_close(dir) < 0) {
4060 SV_CWD_RETURN_UNDEF;
4066 SvCUR_set(sv, pathlen);
4070 if (PerlDir_chdir(SvPVX_const(sv)) < 0) {
4071 SV_CWD_RETURN_UNDEF;
4074 if (PerlLIO_stat(".", &statbuf) < 0) {
4075 SV_CWD_RETURN_UNDEF;
4078 cdev = statbuf.st_dev;
4079 cino = statbuf.st_ino;
4081 if (cdev != orig_cdev || cino != orig_cino) {
4082 Perl_croak(aTHX_ "Unstable directory path, "
4083 "current directory changed unexpectedly");
4096 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET) && defined(SOCK_DGRAM) && defined(HAS_SELECT)
4097 # define EMULATE_SOCKETPAIR_UDP
4100 #ifdef EMULATE_SOCKETPAIR_UDP
4102 S_socketpair_udp (int fd[2]) {
4104 /* Fake a datagram socketpair using UDP to localhost. */
4105 int sockets[2] = {-1, -1};
4106 struct sockaddr_in addresses[2];
4108 Sock_size_t size = sizeof(struct sockaddr_in);
4109 unsigned short port;
4112 memset(&addresses, 0, sizeof(addresses));
4115 sockets[i] = PerlSock_socket(AF_INET, SOCK_DGRAM, PF_INET);
4116 if (sockets[i] == -1)
4117 goto tidy_up_and_fail;
4119 addresses[i].sin_family = AF_INET;
4120 addresses[i].sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4121 addresses[i].sin_port = 0; /* kernel choses port. */
4122 if (PerlSock_bind(sockets[i], (struct sockaddr *) &addresses[i],
4123 sizeof(struct sockaddr_in)) == -1)
4124 goto tidy_up_and_fail;
4127 /* Now have 2 UDP sockets. Find out which port each is connected to, and
4128 for each connect the other socket to it. */
4131 if (PerlSock_getsockname(sockets[i], (struct sockaddr *) &addresses[i],
4133 goto tidy_up_and_fail;
4134 if (size != sizeof(struct sockaddr_in))
4135 goto abort_tidy_up_and_fail;
4136 /* !1 is 0, !0 is 1 */
4137 if (PerlSock_connect(sockets[!i], (struct sockaddr *) &addresses[i],
4138 sizeof(struct sockaddr_in)) == -1)
4139 goto tidy_up_and_fail;
4142 /* Now we have 2 sockets connected to each other. I don't trust some other
4143 process not to have already sent a packet to us (by random) so send
4144 a packet from each to the other. */
4147 /* I'm going to send my own port number. As a short.
4148 (Who knows if someone somewhere has sin_port as a bitfield and needs
4149 this routine. (I'm assuming crays have socketpair)) */
4150 port = addresses[i].sin_port;
4151 got = PerlLIO_write(sockets[i], &port, sizeof(port));
4152 if (got != sizeof(port)) {
4154 goto tidy_up_and_fail;
4155 goto abort_tidy_up_and_fail;
4159 /* Packets sent. I don't trust them to have arrived though.
4160 (As I understand it Solaris TCP stack is multithreaded. Non-blocking
4161 connect to localhost will use a second kernel thread. In 2.6 the
4162 first thread running the connect() returns before the second completes,
4163 so EINPROGRESS> In 2.7 the improved stack is faster and connect()
4164 returns 0. Poor programs have tripped up. One poor program's authors'
4165 had a 50-1 reverse stock split. Not sure how connected these were.)
4166 So I don't trust someone not to have an unpredictable UDP stack.
4170 struct timeval waitfor = {0, 100000}; /* You have 0.1 seconds */
4171 int max = sockets[1] > sockets[0] ? sockets[1] : sockets[0];
4175 FD_SET((unsigned int)sockets[0], &rset);
4176 FD_SET((unsigned int)sockets[1], &rset);
4178 got = PerlSock_select(max + 1, &rset, NULL, NULL, &waitfor);
4179 if (got != 2 || !FD_ISSET(sockets[0], &rset)
4180 || !FD_ISSET(sockets[1], &rset)) {
4181 /* I hope this is portable and appropriate. */
4183 goto tidy_up_and_fail;
4184 goto abort_tidy_up_and_fail;
4188 /* And the paranoia department even now doesn't trust it to have arrive
4189 (hence MSG_DONTWAIT). Or that what arrives was sent by us. */
4191 struct sockaddr_in readfrom;
4192 unsigned short buffer[2];
4197 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4198 sizeof(buffer), MSG_DONTWAIT,
4199 (struct sockaddr *) &readfrom, &size);
4201 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4203 (struct sockaddr *) &readfrom, &size);
4207 goto tidy_up_and_fail;
4208 if (got != sizeof(port)
4209 || size != sizeof(struct sockaddr_in)
4210 /* Check other socket sent us its port. */
4211 || buffer[0] != (unsigned short) addresses[!i].sin_port
4212 /* Check kernel says we got the datagram from that socket */
4213 || readfrom.sin_family != addresses[!i].sin_family
4214 || readfrom.sin_addr.s_addr != addresses[!i].sin_addr.s_addr
4215 || readfrom.sin_port != addresses[!i].sin_port)
4216 goto abort_tidy_up_and_fail;
4219 /* My caller (my_socketpair) has validated that this is non-NULL */
4222 /* I hereby declare this connection open. May God bless all who cross
4226 abort_tidy_up_and_fail:
4227 errno = ECONNABORTED;
4231 if (sockets[0] != -1)
4232 PerlLIO_close(sockets[0]);
4233 if (sockets[1] != -1)
4234 PerlLIO_close(sockets[1]);
4239 #endif /* EMULATE_SOCKETPAIR_UDP */
4241 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET)
4243 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4244 /* Stevens says that family must be AF_LOCAL, protocol 0.
4245 I'm going to enforce that, then ignore it, and use TCP (or UDP). */
4250 struct sockaddr_in listen_addr;
4251 struct sockaddr_in connect_addr;
4256 || family != AF_UNIX
4259 errno = EAFNOSUPPORT;
4267 #ifdef EMULATE_SOCKETPAIR_UDP
4268 if (type == SOCK_DGRAM)
4269 return S_socketpair_udp(fd);
4272 aTHXa(PERL_GET_THX);
4273 listener = PerlSock_socket(AF_INET, type, 0);
4276 memset(&listen_addr, 0, sizeof(listen_addr));
4277 listen_addr.sin_family = AF_INET;
4278 listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4279 listen_addr.sin_port = 0; /* kernel choses port. */
4280 if (PerlSock_bind(listener, (struct sockaddr *) &listen_addr,
4281 sizeof(listen_addr)) == -1)
4282 goto tidy_up_and_fail;
4283 if (PerlSock_listen(listener, 1) == -1)
4284 goto tidy_up_and_fail;
4286 connector = PerlSock_socket(AF_INET, type, 0);
4287 if (connector == -1)
4288 goto tidy_up_and_fail;
4289 /* We want to find out the port number to connect to. */
4290 size = sizeof(connect_addr);
4291 if (PerlSock_getsockname(listener, (struct sockaddr *) &connect_addr,
4293 goto tidy_up_and_fail;
4294 if (size != sizeof(connect_addr))
4295 goto abort_tidy_up_and_fail;
4296 if (PerlSock_connect(connector, (struct sockaddr *) &connect_addr,
4297 sizeof(connect_addr)) == -1)
4298 goto tidy_up_and_fail;
4300 size = sizeof(listen_addr);
4301 acceptor = PerlSock_accept(listener, (struct sockaddr *) &listen_addr,
4304 goto tidy_up_and_fail;
4305 if (size != sizeof(listen_addr))
4306 goto abort_tidy_up_and_fail;
4307 PerlLIO_close(listener);
4308 /* Now check we are talking to ourself by matching port and host on the
4310 if (PerlSock_getsockname(connector, (struct sockaddr *) &connect_addr,
4312 goto tidy_up_and_fail;
4313 if (size != sizeof(connect_addr)
4314 || listen_addr.sin_family != connect_addr.sin_family
4315 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
4316 || listen_addr.sin_port != connect_addr.sin_port) {
4317 goto abort_tidy_up_and_fail;
4323 abort_tidy_up_and_fail:
4325 errno = ECONNABORTED; /* This would be the standard thing to do. */
4327 # ifdef ECONNREFUSED
4328 errno = ECONNREFUSED; /* E.g. Symbian does not have ECONNABORTED. */
4330 errno = ETIMEDOUT; /* Desperation time. */
4337 PerlLIO_close(listener);
4338 if (connector != -1)
4339 PerlLIO_close(connector);
4341 PerlLIO_close(acceptor);
4347 /* In any case have a stub so that there's code corresponding
4348 * to the my_socketpair in embed.fnc. */
4350 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4351 #ifdef HAS_SOCKETPAIR
4352 return socketpair(family, type, protocol, fd);
4361 =for apidoc sv_nosharing
4363 Dummy routine which "shares" an SV when there is no sharing module present.
4364 Or "locks" it. Or "unlocks" it. In other
4365 words, ignores its single SV argument.
4366 Exists to avoid test for a NULL function pointer and because it could
4367 potentially warn under some level of strict-ness.
4373 Perl_sv_nosharing(pTHX_ SV *sv)
4375 PERL_UNUSED_CONTEXT;
4376 PERL_UNUSED_ARG(sv);
4381 =for apidoc sv_destroyable
4383 Dummy routine which reports that object can be destroyed when there is no
4384 sharing module present. It ignores its single SV argument, and returns
4385 'true'. Exists to avoid test for a NULL function pointer and because it
4386 could potentially warn under some level of strict-ness.
4392 Perl_sv_destroyable(pTHX_ SV *sv)
4394 PERL_UNUSED_CONTEXT;
4395 PERL_UNUSED_ARG(sv);
4400 Perl_parse_unicode_opts(pTHX_ const char **popt)
4402 const char *p = *popt;
4405 PERL_ARGS_ASSERT_PARSE_UNICODE_OPTS;
4410 opt = (U32) grok_atou(p, &endptr);
4412 if (*p && *p != '\n' && *p != '\r') {
4413 if(isSPACE(*p)) goto the_end_of_the_opts_parser;
4415 Perl_croak(aTHX_ "Unknown Unicode option letter '%c'", *p);
4421 case PERL_UNICODE_STDIN:
4422 opt |= PERL_UNICODE_STDIN_FLAG; break;
4423 case PERL_UNICODE_STDOUT:
4424 opt |= PERL_UNICODE_STDOUT_FLAG; break;
4425 case PERL_UNICODE_STDERR:
4426 opt |= PERL_UNICODE_STDERR_FLAG; break;
4427 case PERL_UNICODE_STD:
4428 opt |= PERL_UNICODE_STD_FLAG; break;
4429 case PERL_UNICODE_IN:
4430 opt |= PERL_UNICODE_IN_FLAG; break;
4431 case PERL_UNICODE_OUT:
4432 opt |= PERL_UNICODE_OUT_FLAG; break;
4433 case PERL_UNICODE_INOUT:
4434 opt |= PERL_UNICODE_INOUT_FLAG; break;
4435 case PERL_UNICODE_LOCALE:
4436 opt |= PERL_UNICODE_LOCALE_FLAG; break;
4437 case PERL_UNICODE_ARGV:
4438 opt |= PERL_UNICODE_ARGV_FLAG; break;
4439 case PERL_UNICODE_UTF8CACHEASSERT:
4440 opt |= PERL_UNICODE_UTF8CACHEASSERT_FLAG; break;
4442 if (*p != '\n' && *p != '\r') {
4443 if(isSPACE(*p)) goto the_end_of_the_opts_parser;
4446 "Unknown Unicode option letter '%c'", *p);
4453 opt = PERL_UNICODE_DEFAULT_FLAGS;
4455 the_end_of_the_opts_parser:
4457 if (opt & ~PERL_UNICODE_ALL_FLAGS)
4458 Perl_croak(aTHX_ "Unknown Unicode option value %"UVuf,
4459 (UV) (opt & ~PERL_UNICODE_ALL_FLAGS));
4467 # include <starlet.h>
4474 * This is really just a quick hack which grabs various garbage
4475 * values. It really should be a real hash algorithm which
4476 * spreads the effect of every input bit onto every output bit,
4477 * if someone who knows about such things would bother to write it.
4478 * Might be a good idea to add that function to CORE as well.
4479 * No numbers below come from careful analysis or anything here,
4480 * except they are primes and SEED_C1 > 1E6 to get a full-width
4481 * value from (tv_sec * SEED_C1 + tv_usec). The multipliers should
4482 * probably be bigger too.
4485 # define SEED_C1 1000003
4486 #define SEED_C4 73819
4488 # define SEED_C1 25747
4489 #define SEED_C4 20639
4493 #define SEED_C5 26107
4495 #ifndef PERL_NO_DEV_RANDOM
4500 /* when[] = (low 32 bits, high 32 bits) of time since epoch
4501 * in 100-ns units, typically incremented ever 10 ms. */
4502 unsigned int when[2];
4504 # ifdef HAS_GETTIMEOFDAY
4505 struct timeval when;
4511 /* This test is an escape hatch, this symbol isn't set by Configure. */
4512 #ifndef PERL_NO_DEV_RANDOM
4513 #ifndef PERL_RANDOM_DEVICE
4514 /* /dev/random isn't used by default because reads from it will block
4515 * if there isn't enough entropy available. You can compile with
4516 * PERL_RANDOM_DEVICE to it if you'd prefer Perl to block until there
4517 * is enough real entropy to fill the seed. */
4518 # define PERL_RANDOM_DEVICE "/dev/urandom"
4520 fd = PerlLIO_open(PERL_RANDOM_DEVICE, 0);
4522 if (PerlLIO_read(fd, (void*)&u, sizeof u) != sizeof u)
4531 _ckvmssts(sys$gettim(when));
4532 u = (U32)SEED_C1 * when[0] + (U32)SEED_C2 * when[1];
4534 # ifdef HAS_GETTIMEOFDAY
4535 PerlProc_gettimeofday(&when,NULL);
4536 u = (U32)SEED_C1 * when.tv_sec + (U32)SEED_C2 * when.tv_usec;
4539 u = (U32)SEED_C1 * when;
4542 u += SEED_C3 * (U32)PerlProc_getpid();
4543 u += SEED_C4 * (U32)PTR2UV(PL_stack_sp);
4544 #ifndef PLAN9 /* XXX Plan9 assembler chokes on this; fix needed */
4545 u += SEED_C5 * (U32)PTR2UV(&when);
4551 Perl_get_hash_seed(pTHX_ unsigned char * const seed_buffer)
4556 PERL_ARGS_ASSERT_GET_HASH_SEED;
4558 env_pv= PerlEnv_getenv("PERL_HASH_SEED");
4561 #ifndef USE_HASH_SEED_EXPLICIT
4563 /* ignore leading spaces */
4564 while (isSPACE(*env_pv))
4566 #ifdef USE_PERL_PERTURB_KEYS
4567 /* if they set it to "0" we disable key traversal randomization completely */
4568 if (strEQ(env_pv,"0")) {
4569 PL_hash_rand_bits_enabled= 0;
4571 /* otherwise switch to deterministic mode */
4572 PL_hash_rand_bits_enabled= 2;
4575 /* ignore a leading 0x... if it is there */
4576 if (env_pv[0] == '0' && env_pv[1] == 'x')
4579 for( i = 0; isXDIGIT(*env_pv) && i < PERL_HASH_SEED_BYTES; i++ ) {
4580 seed_buffer[i] = READ_XDIGIT(env_pv) << 4;
4581 if ( isXDIGIT(*env_pv)) {
4582 seed_buffer[i] |= READ_XDIGIT(env_pv);
4585 while (isSPACE(*env_pv))
4588 if (*env_pv && !isXDIGIT(*env_pv)) {
4589 Perl_warn(aTHX_ "perl: warning: Non hex character in '$ENV{PERL_HASH_SEED}', seed only partially set\n");
4591 /* should we check for unparsed crap? */
4592 /* should we warn about unused hex? */
4593 /* should we warn about insufficient hex? */
4598 (void)seedDrand01((Rand_seed_t)seed());
4600 for( i = 0; i < PERL_HASH_SEED_BYTES; i++ ) {
4601 seed_buffer[i] = (unsigned char)(Drand01() * (U8_MAX+1));
4604 #ifdef USE_PERL_PERTURB_KEYS
4605 { /* initialize PL_hash_rand_bits from the hash seed.
4606 * This value is highly volatile, it is updated every
4607 * hash insert, and is used as part of hash bucket chain
4608 * randomization and hash iterator randomization. */
4609 PL_hash_rand_bits= 0xbe49d17f; /* I just picked a number */
4610 for( i = 0; i < sizeof(UV) ; i++ ) {
4611 PL_hash_rand_bits += seed_buffer[i % PERL_HASH_SEED_BYTES];
4612 PL_hash_rand_bits = ROTL_UV(PL_hash_rand_bits,8);
4615 env_pv= PerlEnv_getenv("PERL_PERTURB_KEYS");
4617 if (strEQ(env_pv,"0") || strEQ(env_pv,"NO")) {
4618 PL_hash_rand_bits_enabled= 0;
4619 } else if (strEQ(env_pv,"1") || strEQ(env_pv,"RANDOM")) {
4620 PL_hash_rand_bits_enabled= 1;
4621 } else if (strEQ(env_pv,"2") || strEQ(env_pv,"DETERMINISTIC")) {
4622 PL_hash_rand_bits_enabled= 2;
4624 Perl_warn(aTHX_ "perl: warning: strange setting in '$ENV{PERL_PERTURB_KEYS}': '%s'\n", env_pv);
4630 #ifdef PERL_GLOBAL_STRUCT
4632 #define PERL_GLOBAL_STRUCT_INIT
4633 #include "opcode.h" /* the ppaddr and check */
4636 Perl_init_global_struct(pTHX)
4638 struct perl_vars *plvarsp = NULL;
4639 # ifdef PERL_GLOBAL_STRUCT
4640 const IV nppaddr = C_ARRAY_LENGTH(Gppaddr);
4641 const IV ncheck = C_ARRAY_LENGTH(Gcheck);
4642 PERL_UNUSED_CONTEXT;
4643 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
4644 /* PerlMem_malloc() because can't use even safesysmalloc() this early. */
4645 plvarsp = (struct perl_vars*)PerlMem_malloc(sizeof(struct perl_vars));
4649 plvarsp = PL_VarsPtr;
4650 # endif /* PERL_GLOBAL_STRUCT_PRIVATE */
4655 # define PERLVAR(prefix,var,type) /**/
4656 # define PERLVARA(prefix,var,n,type) /**/
4657 # define PERLVARI(prefix,var,type,init) plvarsp->prefix##var = init;
4658 # define PERLVARIC(prefix,var,type,init) plvarsp->prefix##var = init;
4659 # include "perlvars.h"
4664 # ifdef PERL_GLOBAL_STRUCT
4667 PerlMem_malloc(nppaddr * sizeof(Perl_ppaddr_t));
4668 if (!plvarsp->Gppaddr)
4672 PerlMem_malloc(ncheck * sizeof(Perl_check_t));
4673 if (!plvarsp->Gcheck)
4675 Copy(Gppaddr, plvarsp->Gppaddr, nppaddr, Perl_ppaddr_t);
4676 Copy(Gcheck, plvarsp->Gcheck, ncheck, Perl_check_t);
4678 # ifdef PERL_SET_VARS
4679 PERL_SET_VARS(plvarsp);
4681 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
4682 plvarsp->Gsv_placeholder.sv_flags = 0;
4683 memset(plvarsp->Ghash_seed, 0, sizeof(plvarsp->Ghash_seed));
4685 # undef PERL_GLOBAL_STRUCT_INIT
4690 #endif /* PERL_GLOBAL_STRUCT */
4692 #ifdef PERL_GLOBAL_STRUCT
4695 Perl_free_global_struct(pTHX_ struct perl_vars *plvarsp)
4697 int veto = plvarsp->Gveto_cleanup;
4699 PERL_ARGS_ASSERT_FREE_GLOBAL_STRUCT;
4700 PERL_UNUSED_CONTEXT;
4701 # ifdef PERL_GLOBAL_STRUCT
4702 # ifdef PERL_UNSET_VARS
4703 PERL_UNSET_VARS(plvarsp);
4707 free(plvarsp->Gppaddr);
4708 free(plvarsp->Gcheck);
4709 # ifdef PERL_GLOBAL_STRUCT_PRIVATE
4715 #endif /* PERL_GLOBAL_STRUCT */
4719 /* -DPERL_MEM_LOG: the Perl_mem_log_..() is compiled, including the
4720 * the default implementation, unless -DPERL_MEM_LOG_NOIMPL is also
4721 * given, and you supply your own implementation.
4723 * The default implementation reads a single env var, PERL_MEM_LOG,
4724 * expecting one or more of the following:
4726 * \d+ - fd fd to write to : must be 1st (grok_atou)
4727 * 'm' - memlog was PERL_MEM_LOG=1
4728 * 's' - svlog was PERL_SV_LOG=1
4729 * 't' - timestamp was PERL_MEM_LOG_TIMESTAMP=1
4731 * This makes the logger controllable enough that it can reasonably be
4732 * added to the system perl.
4735 /* -DPERL_MEM_LOG_SPRINTF_BUF_SIZE=X: size of a (stack-allocated) buffer
4736 * the Perl_mem_log_...() will use (either via sprintf or snprintf).
4738 #define PERL_MEM_LOG_SPRINTF_BUF_SIZE 128
4740 /* -DPERL_MEM_LOG_FD=N: the file descriptor the Perl_mem_log_...()
4741 * writes to. In the default logger, this is settable at runtime.
4743 #ifndef PERL_MEM_LOG_FD
4744 # define PERL_MEM_LOG_FD 2 /* If STDERR is too boring for you. */
4747 #ifndef PERL_MEM_LOG_NOIMPL
4749 # ifdef DEBUG_LEAKING_SCALARS
4750 # define SV_LOG_SERIAL_FMT " [%lu]"
4751 # define _SV_LOG_SERIAL_ARG(sv) , (unsigned long) (sv)->sv_debug_serial
4753 # define SV_LOG_SERIAL_FMT
4754 # define _SV_LOG_SERIAL_ARG(sv)
4758 S_mem_log_common(enum mem_log_type mlt, const UV n,
4759 const UV typesize, const char *type_name, const SV *sv,
4760 Malloc_t oldalloc, Malloc_t newalloc,
4761 const char *filename, const int linenumber,
4762 const char *funcname)
4766 PERL_ARGS_ASSERT_MEM_LOG_COMMON;
4768 pmlenv = PerlEnv_getenv("PERL_MEM_LOG");
4771 if (mlt < MLT_NEW_SV ? strchr(pmlenv,'m') : strchr(pmlenv,'s'))
4773 /* We can't use SVs or PerlIO for obvious reasons,
4774 * so we'll use stdio and low-level IO instead. */
4775 char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
4777 # ifdef HAS_GETTIMEOFDAY
4778 # define MEM_LOG_TIME_FMT "%10d.%06d: "
4779 # define MEM_LOG_TIME_ARG (int)tv.tv_sec, (int)tv.tv_usec
4781 gettimeofday(&tv, 0);
4783 # define MEM_LOG_TIME_FMT "%10d: "
4784 # define MEM_LOG_TIME_ARG (int)when
4788 /* If there are other OS specific ways of hires time than
4789 * gettimeofday() (see ext/Time-HiRes), the easiest way is
4790 * probably that they would be used to fill in the struct
4795 int fd = grok_atou(pmlenv, &endptr); /* Ignore endptr. */
4797 fd = PERL_MEM_LOG_FD;
4799 if (strchr(pmlenv, 't')) {
4800 len = my_snprintf(buf, sizeof(buf),
4801 MEM_LOG_TIME_FMT, MEM_LOG_TIME_ARG);
4802 PERL_UNUSED_RESULT(PerlLIO_write(fd, buf, len));
4806 len = my_snprintf(buf, sizeof(buf),
4807 "alloc: %s:%d:%s: %"IVdf" %"UVuf
4808 " %s = %"IVdf": %"UVxf"\n",
4809 filename, linenumber, funcname, n, typesize,
4810 type_name, n * typesize, PTR2UV(newalloc));
4813 len = my_snprintf(buf, sizeof(buf),
4814 "realloc: %s:%d:%s: %"IVdf" %"UVuf
4815 " %s = %"IVdf": %"UVxf" -> %"UVxf"\n",
4816 filename, linenumber, funcname, n, typesize,
4817 type_name, n * typesize, PTR2UV(oldalloc),
4821 len = my_snprintf(buf, sizeof(buf),
4822 "free: %s:%d:%s: %"UVxf"\n",
4823 filename, linenumber, funcname,
4828 len = my_snprintf(buf, sizeof(buf),
4829 "%s_SV: %s:%d:%s: %"UVxf SV_LOG_SERIAL_FMT "\n",
4830 mlt == MLT_NEW_SV ? "new" : "del",
4831 filename, linenumber, funcname,
4832 PTR2UV(sv) _SV_LOG_SERIAL_ARG(sv));
4837 PERL_UNUSED_RESULT(PerlLIO_write(fd, buf, len));
4841 #endif /* !PERL_MEM_LOG_NOIMPL */
4843 #ifndef PERL_MEM_LOG_NOIMPL
4845 mem_log_common_if(alty, num, tysz, tynm, sv, oal, nal, flnm, ln, fnnm) \
4846 mem_log_common (alty, num, tysz, tynm, sv, oal, nal, flnm, ln, fnnm)
4848 /* this is suboptimal, but bug compatible. User is providing their
4849 own implementation, but is getting these functions anyway, and they
4850 do nothing. But _NOIMPL users should be able to cope or fix */
4852 mem_log_common_if(alty, num, tysz, tynm, u, oal, nal, flnm, ln, fnnm) \
4853 /* mem_log_common_if_PERL_MEM_LOG_NOIMPL */
4857 Perl_mem_log_alloc(const UV n, const UV typesize, const char *type_name,
4859 const char *filename, const int linenumber,
4860 const char *funcname)
4862 mem_log_common_if(MLT_ALLOC, n, typesize, type_name,
4863 NULL, NULL, newalloc,
4864 filename, linenumber, funcname);
4869 Perl_mem_log_realloc(const UV n, const UV typesize, const char *type_name,
4870 Malloc_t oldalloc, Malloc_t newalloc,
4871 const char *filename, const int linenumber,
4872 const char *funcname)
4874 mem_log_common_if(MLT_REALLOC, n, typesize, type_name,
4875 NULL, oldalloc, newalloc,
4876 filename, linenumber, funcname);
4881 Perl_mem_log_free(Malloc_t oldalloc,
4882 const char *filename, const int linenumber,
4883 const char *funcname)
4885 mem_log_common_if(MLT_FREE, 0, 0, "", NULL, oldalloc, NULL,
4886 filename, linenumber, funcname);
4891 Perl_mem_log_new_sv(const SV *sv,
4892 const char *filename, const int linenumber,
4893 const char *funcname)
4895 mem_log_common_if(MLT_NEW_SV, 0, 0, "", sv, NULL, NULL,
4896 filename, linenumber, funcname);
4900 Perl_mem_log_del_sv(const SV *sv,
4901 const char *filename, const int linenumber,
4902 const char *funcname)
4904 mem_log_common_if(MLT_DEL_SV, 0, 0, "", sv, NULL, NULL,
4905 filename, linenumber, funcname);
4908 #endif /* PERL_MEM_LOG */
4911 =for apidoc my_sprintf
4913 The C library C<sprintf>, wrapped if necessary, to ensure that it will return
4914 the length of the string written to the buffer. Only rare pre-ANSI systems
4915 need the wrapper function - usually this is a direct call to C<sprintf>.
4919 #ifndef SPRINTF_RETURNS_STRLEN
4921 Perl_my_sprintf(char *buffer, const char* pat, ...)
4924 PERL_ARGS_ASSERT_MY_SPRINTF;
4925 va_start(args, pat);
4926 vsprintf(buffer, pat, args);
4928 return strlen(buffer);
4933 =for apidoc quadmath_format_single
4935 quadmath_snprintf() is very strict about its format string and will
4936 fail, returning -1, if the format is invalid. It acccepts exactly
4939 quadmath_format_single() checks that the intended single spec looks
4940 sane: begins with C<%>, has only one C<%>, ends with C<[efgaEFGA]>,
4941 and has C<Q> before it. This is not a full "printf syntax check",
4944 Returns the format if it is valid, NULL if not.
4946 quadmath_format_single() can and will actually patch in the missing
4947 C<Q>, if necessary. In this case it will return the modified copy of
4948 the format, B<which the caller will need to free.>
4950 See also L</quadmath_format_needed>.
4956 Perl_quadmath_format_single(const char* format)
4960 PERL_ARGS_ASSERT_QUADMATH_FORMAT_SINGLE;
4962 if (format[0] != '%' || strchr(format + 1, '%'))
4964 len = strlen(format);
4965 /* minimum length three: %Qg */
4966 if (len < 3 || strchr("efgaEFGA", format[len - 1]) == NULL)
4968 if (format[len - 2] != 'Q') {
4970 Newx(fixed, len + 1, char);
4971 memcpy(fixed, format, len - 1);
4972 fixed[len - 1] = 'Q';
4973 fixed[len ] = format[len - 1];
4975 return (const char*)fixed;
4982 =for apidoc quadmath_format_needed
4984 quadmath_format_needed() returns true if the format string seems to
4985 contain at least one non-Q-prefixed %[efgaEFGA] format specifier,
4986 or returns false otherwise.
4988 The format specifier detection is not complete printf-syntax detection,
4989 but it should catch most common cases.
4991 If true is returned, those arguments B<should> in theory be processed
4992 with quadmath_snprintf(), but in case there is more than one such
4993 format specifier (see L</quadmath_format_single>), and if there is
4994 anything else beyond that one (even just a single byte), they
4995 B<cannot> be processed because quadmath_snprintf() is very strict,
4996 accepting only one format spec, and nothing else.
4997 In this case, the code should probably fail.
5003 Perl_quadmath_format_needed(const char* format)
5005 const char *p = format;
5008 PERL_ARGS_ASSERT_QUADMATH_FORMAT_NEEDED;
5010 while ((q = strchr(p, '%'))) {
5012 if (*q == '+') /* plus */
5014 if (*q == '#') /* alt */
5016 if (*q == '*') /* width */
5020 while (isDIGIT(*q)) q++;
5023 if (*q == '.' && (q[1] == '*' || isDIGIT(q[1]))) { /* prec */
5028 while (isDIGIT(*q)) q++;
5030 if (strchr("efgaEFGA", *q)) /* Would have needed 'Q' in front. */
5039 =for apidoc my_snprintf
5041 The C library C<snprintf> functionality, if available and
5042 standards-compliant (uses C<vsnprintf>, actually). However, if the
5043 C<vsnprintf> is not available, will unfortunately use the unsafe
5044 C<vsprintf> which can overrun the buffer (there is an overrun check,
5045 but that may be too late). Consider using C<sv_vcatpvf> instead, or
5046 getting C<vsnprintf>.
5051 Perl_my_snprintf(char *buffer, const Size_t len, const char *format, ...)
5055 PERL_ARGS_ASSERT_MY_SNPRINTF;
5056 #ifndef HAS_VSNPRINTF
5057 PERL_UNUSED_VAR(len);
5059 va_start(ap, format);
5062 const char* qfmt = quadmath_format_single(format);
5063 bool quadmath_valid = FALSE;
5065 /* If the format looked promising, use it as quadmath. */
5066 retval = quadmath_snprintf(buffer, len, qfmt, va_arg(ap, NV));
5068 Perl_croak_nocontext("panic: quadmath_snprintf failed, format \"%s\"", qfmt);
5069 quadmath_valid = TRUE;
5074 assert(qfmt == NULL);
5075 /* quadmath_format_single() will return false for example for
5076 * "foo = %g", or simply "%g". We could handle the %g by
5077 * using quadmath for the NV args. More complex cases of
5078 * course exist: "foo = %g, bar = %g", or "foo=%Qg" (otherwise
5079 * quadmath-valid but has stuff in front).
5081 * Handling the "Q-less" cases right would require walking
5082 * through the va_list and rewriting the format, calling
5083 * quadmath for the NVs, building a new va_list, and then
5084 * letting vsnprintf/vsprintf to take care of the other
5085 * arguments. This may be doable.
5087 * We do not attempt that now. But for paranoia, we here try
5088 * to detect some common (but not all) cases where the
5089 * "Q-less" %[efgaEFGA] formats are present, and die if
5090 * detected. This doesn't fix the problem, but it stops the
5091 * vsnprintf/vsprintf pulling doubles off the va_list when
5092 * __float128 NVs should be pulled off instead.
5094 * If quadmath_format_needed() returns false, we are reasonably
5095 * certain that we can call vnsprintf() or vsprintf() safely. */
5096 if (!quadmath_valid && quadmath_format_needed(format))
5097 Perl_croak_nocontext("panic: quadmath_snprintf failed, format \"%s\"", format);
5102 #ifdef HAS_VSNPRINTF
5103 retval = vsnprintf(buffer, len, format, ap);
5105 retval = vsprintf(buffer, format, ap);
5108 /* vsprintf() shows failure with < 0 */
5110 #ifdef HAS_VSNPRINTF
5111 /* vsnprintf() shows failure with >= len */
5113 (len > 0 && (Size_t)retval >= len)
5116 Perl_croak_nocontext("panic: my_snprintf buffer overflow");
5121 =for apidoc my_vsnprintf
5123 The C library C<vsnprintf> if available and standards-compliant.
5124 However, if if the C<vsnprintf> is not available, will unfortunately
5125 use the unsafe C<vsprintf> which can overrun the buffer (there is an
5126 overrun check, but that may be too late). Consider using
5127 C<sv_vcatpvf> instead, or getting C<vsnprintf>.
5132 Perl_my_vsnprintf(char *buffer, const Size_t len, const char *format, va_list ap)
5135 PERL_UNUSED_ARG(buffer);
5136 PERL_UNUSED_ARG(len);
5137 PERL_UNUSED_ARG(format);
5138 PERL_UNUSED_ARG(ap);
5139 Perl_croak_nocontext("panic: my_vsnprintf not available with quadmath");
5146 PERL_ARGS_ASSERT_MY_VSNPRINTF;
5147 #ifndef HAS_VSNPRINTF
5148 PERL_UNUSED_VAR(len);
5150 Perl_va_copy(ap, apc);
5151 # ifdef HAS_VSNPRINTF
5152 retval = vsnprintf(buffer, len, format, apc);
5154 retval = vsprintf(buffer, format, apc);
5158 # ifdef HAS_VSNPRINTF
5159 retval = vsnprintf(buffer, len, format, ap);
5161 retval = vsprintf(buffer, format, ap);
5163 #endif /* #ifdef NEED_VA_COPY */
5164 /* vsprintf() shows failure with < 0 */
5166 #ifdef HAS_VSNPRINTF
5167 /* vsnprintf() shows failure with >= len */
5169 (len > 0 && (Size_t)retval >= len)
5172 Perl_croak_nocontext("panic: my_vsnprintf buffer overflow");
5178 Perl_my_clearenv(pTHX)
5181 #if ! defined(PERL_MICRO)
5182 # if defined(PERL_IMPLICIT_SYS) || defined(WIN32)
5184 # else /* ! (PERL_IMPLICIT_SYS || WIN32) */
5185 # if defined(USE_ENVIRON_ARRAY)
5186 # if defined(USE_ITHREADS)
5187 /* only the parent thread can clobber the process environment */
5188 if (PL_curinterp == aTHX)
5189 # endif /* USE_ITHREADS */
5191 # if ! defined(PERL_USE_SAFE_PUTENV)
5192 if ( !PL_use_safe_putenv) {
5194 if (environ == PL_origenviron)
5195 environ = (char**)safesysmalloc(sizeof(char*));
5197 for (i = 0; environ[i]; i++)
5198 (void)safesysfree(environ[i]);
5201 # else /* PERL_USE_SAFE_PUTENV */
5202 # if defined(HAS_CLEARENV)
5204 # elif defined(HAS_UNSETENV)
5205 int bsiz = 80; /* Most envvar names will be shorter than this. */
5206 char *buf = (char*)safesysmalloc(bsiz);
5207 while (*environ != NULL) {
5208 char *e = strchr(*environ, '=');
5209 int l = e ? e - *environ : (int)strlen(*environ);
5211 (void)safesysfree(buf);
5212 bsiz = l + 1; /* + 1 for the \0. */
5213 buf = (char*)safesysmalloc(bsiz);
5215 memcpy(buf, *environ, l);
5217 (void)unsetenv(buf);
5219 (void)safesysfree(buf);
5220 # else /* ! HAS_CLEARENV && ! HAS_UNSETENV */
5221 /* Just null environ and accept the leakage. */
5223 # endif /* HAS_CLEARENV || HAS_UNSETENV */
5224 # endif /* ! PERL_USE_SAFE_PUTENV */
5226 # endif /* USE_ENVIRON_ARRAY */
5227 # endif /* PERL_IMPLICIT_SYS || WIN32 */
5228 #endif /* PERL_MICRO */
5231 #ifdef PERL_IMPLICIT_CONTEXT
5233 /* Implements the MY_CXT_INIT macro. The first time a module is loaded,
5234 the global PL_my_cxt_index is incremented, and that value is assigned to
5235 that module's static my_cxt_index (who's address is passed as an arg).
5236 Then, for each interpreter this function is called for, it makes sure a
5237 void* slot is available to hang the static data off, by allocating or
5238 extending the interpreter's PL_my_cxt_list array */
5240 #ifndef PERL_GLOBAL_STRUCT_PRIVATE
5242 Perl_my_cxt_init(pTHX_ int *index, size_t size)
5246 PERL_ARGS_ASSERT_MY_CXT_INIT;
5248 /* this module hasn't been allocated an index yet */
5249 #if defined(USE_ITHREADS)
5250 MUTEX_LOCK(&PL_my_ctx_mutex);
5252 *index = PL_my_cxt_index++;
5253 #if defined(USE_ITHREADS)
5254 MUTEX_UNLOCK(&PL_my_ctx_mutex);
5258 /* make sure the array is big enough */
5259 if (PL_my_cxt_size <= *index) {
5260 if (PL_my_cxt_size) {
5261 while (PL_my_cxt_size <= *index)
5262 PL_my_cxt_size *= 2;
5263 Renew(PL_my_cxt_list, PL_my_cxt_size, void *);
5266 PL_my_cxt_size = 16;
5267 Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
5270 /* newSV() allocates one more than needed */
5271 p = (void*)SvPVX(newSV(size-1));
5272 PL_my_cxt_list[*index] = p;
5273 Zero(p, size, char);
5277 #else /* #ifndef PERL_GLOBAL_STRUCT_PRIVATE */
5280 Perl_my_cxt_index(pTHX_ const char *my_cxt_key)
5285 PERL_ARGS_ASSERT_MY_CXT_INDEX;
5287 for (index = 0; index < PL_my_cxt_index; index++) {
5288 const char *key = PL_my_cxt_keys[index];
5289 /* try direct pointer compare first - there are chances to success,
5290 * and it's much faster.
5292 if ((key == my_cxt_key) || strEQ(key, my_cxt_key))
5299 Perl_my_cxt_init(pTHX_ const char *my_cxt_key, size_t size)
5305 PERL_ARGS_ASSERT_MY_CXT_INIT;
5307 index = Perl_my_cxt_index(aTHX_ my_cxt_key);
5309 /* this module hasn't been allocated an index yet */
5310 #if defined(USE_ITHREADS)
5311 MUTEX_LOCK(&PL_my_ctx_mutex);
5313 index = PL_my_cxt_index++;
5314 #if defined(USE_ITHREADS)
5315 MUTEX_UNLOCK(&PL_my_ctx_mutex);
5319 /* make sure the array is big enough */
5320 if (PL_my_cxt_size <= index) {
5321 int old_size = PL_my_cxt_size;
5323 if (PL_my_cxt_size) {
5324 while (PL_my_cxt_size <= index)
5325 PL_my_cxt_size *= 2;
5326 Renew(PL_my_cxt_list, PL_my_cxt_size, void *);
5327 Renew(PL_my_cxt_keys, PL_my_cxt_size, const char *);
5330 PL_my_cxt_size = 16;
5331 Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
5332 Newx(PL_my_cxt_keys, PL_my_cxt_size, const char *);
5334 for (i = old_size; i < PL_my_cxt_size; i++) {
5335 PL_my_cxt_keys[i] = 0;
5336 PL_my_cxt_list[i] = 0;
5339 PL_my_cxt_keys[index] = my_cxt_key;
5340 /* newSV() allocates one more than needed */
5341 p = (void*)SvPVX(newSV(size-1));
5342 PL_my_cxt_list[index] = p;
5343 Zero(p, size, char);
5346 #endif /* #ifndef PERL_GLOBAL_STRUCT_PRIVATE */
5347 #endif /* PERL_IMPLICIT_CONTEXT */
5350 /* The meaning of the varargs is determined U32 key arg. This is not a format
5351 string. The U32 key is assembled with HS_KEY.
5353 v_my_perl arg is "PerlInterpreter * my_perl" if PERL_IMPLICIT_CONTEXT and
5354 otherwise "CV * cv" (boot xsub's CV *). v_my_perl will catch where a threaded
5355 future perl526.dll calling IO.dll for example, and IO.dll was linked with
5356 threaded perl524.dll, and both perl526.dll and perl524.dll are in %PATH and
5357 the Win32 DLL loader sucessfully can load IO.dll into the process but
5358 simultaniously it loaded a interp of a different version into the process,
5359 and XS code will naturally pass SV*s created by perl524.dll for perl526.dll
5360 to use through perl526.dll's my_perl->Istack_base.
5362 v_my_perl (v=void) can not be the first arg since then key will be out of
5363 place in a threaded vs non-threaded mixup and analyzing the key number's
5364 bitfields won't reveal the problem since it will be a valid key
5365 (unthreaded perl) on interp side, but croak reports the XS mod's key as
5366 gibberish (it is really my_perl ptr) (threaded XS mod), or if threaded perl
5367 and unthreaded XS module, threaded perl will look at uninit C stack or uninit
5368 register to get var key (remember it assumes 1st arg is interp cxt).
5370 Perl_xs_handshake(U32 key, void * v_my_perl, const char * file,
5371 [U32 items, U32 ax], [char * api_version], [char * xs_version]) */
5373 Perl_xs_handshake(const U32 key, void * v_my_perl, const char * file, ...)
5379 #ifdef PERL_IMPLICIT_CONTEXT
5386 PERL_ARGS_ASSERT_XS_HANDSHAKE;
5387 va_start(args, file);
5389 got = INT2PTR(void*, (UV)(key & HSm_KEY_MATCH));
5390 need = (void *)(HS_KEY(FALSE, FALSE, "", "") & HSm_KEY_MATCH);
5391 if (UNLIKELY(got != need))
5393 /* try to catch where a 2nd threaded perl interp DLL is loaded into a process
5394 by a XS DLL compiled against the wrong interl DLL b/c of bad @INC, and the
5395 2nd threaded perl interp DLL never initialized its TLS/PERL_SYS_INIT3 so
5396 dTHX call from 2nd interp DLL can't return the my_perl that pp_entersub
5397 passed to the XS DLL */
5398 #ifdef PERL_IMPLICIT_CONTEXT
5399 xs_interp = (tTHX)v_my_perl;
5403 /* try to catch where an unthreaded perl interp DLL (for ex. perl522.dll) is
5404 loaded into a process by a XS DLL built by an unthreaded perl522.dll perl,
5405 but the DynaLoder/Perl that started the process and loaded the XS DLL is
5406 unthreaded perl524.dll, since unthreadeds don't pass my_perl (a unique *)
5407 through pp_entersub, use a unique value (which is a pointer to PL_stack_sp's
5408 location in the unthreaded perl binary) stored in CV * to figure out if this
5409 Perl_xs_handshake was called by the same pp_entersub */
5410 cv = (CV*)v_my_perl;
5411 xs_spp = (SV***)CvHSCXT(cv);
5413 need = &PL_stack_sp;
5415 if(UNLIKELY(got != need)) {
5416 bad_handshake:/* recycle branch and string from above */
5417 if(got != (void *)HSf_NOCHK)
5418 noperl_die("%s: Invalid handshake key got %p"
5419 " needed %p, binaries are mismatched",
5423 if(key & HSf_SETXSUBFN) { /* this might be called from a module bootstrap */
5424 SAVEPPTR(PL_xsubfilename);/* which was require'd from a XSUB BEGIN */
5425 PL_xsubfilename = file; /* so the old name must be restored for
5426 additional XSUBs to register themselves */
5427 (void)gv_fetchfile(file);
5430 if(key & HSf_POPMARK) {
5432 { SV **mark = PL_stack_base + ax++;
5434 items = (I32)(SP - MARK);
5438 items = va_arg(args, U32);
5439 ax = va_arg(args, U32);
5443 assert(HS_GETAPIVERLEN(key) <= UCHAR_MAX);
5444 if((apiverlen = HS_GETAPIVERLEN(key))) {
5445 char * api_p = va_arg(args, char*);
5446 if(apiverlen != sizeof("v" PERL_API_VERSION_STRING)-1
5447 || memNE(api_p, "v" PERL_API_VERSION_STRING,
5448 sizeof("v" PERL_API_VERSION_STRING)-1))
5449 Perl_croak_nocontext("Perl API version %s of %"SVf" does not match %s",
5450 api_p, SVfARG(PL_stack_base[ax + 0]),
5451 "v" PERL_API_VERSION_STRING);
5456 assert(HS_GETXSVERLEN(key) <= UCHAR_MAX && HS_GETXSVERLEN(key) <= HS_APIVERLEN_MAX);
5457 if((xsverlen = HS_GETXSVERLEN(key)))
5458 Perl_xs_version_bootcheck(aTHX_
5459 items, ax, va_arg(args, char*), xsverlen);
5466 Perl_xs_version_bootcheck(pTHX_ U32 items, U32 ax, const char *xs_p,
5470 const char *vn = NULL;
5471 SV *const module = PL_stack_base[ax];
5473 PERL_ARGS_ASSERT_XS_VERSION_BOOTCHECK;
5475 if (items >= 2) /* version supplied as bootstrap arg */
5476 sv = PL_stack_base[ax + 1];
5478 /* XXX GV_ADDWARN */
5480 sv = get_sv(Perl_form(aTHX_ "%"SVf"::%s", SVfARG(module), vn), 0);
5481 if (!sv || !SvOK(sv)) {
5483 sv = get_sv(Perl_form(aTHX_ "%"SVf"::%s", SVfARG(module), vn), 0);
5487 SV *xssv = Perl_newSVpvn_flags(aTHX_ xs_p, xs_len, SVs_TEMP);
5488 SV *pmsv = sv_isobject(sv) && sv_derived_from(sv, "version")
5489 ? sv : sv_2mortal(new_version(sv));
5490 xssv = upg_version(xssv, 0);
5491 if ( vcmp(pmsv,xssv) ) {
5492 SV *string = vstringify(xssv);
5493 SV *xpt = Perl_newSVpvf(aTHX_ "%"SVf" object version %"SVf
5494 " does not match ", SVfARG(module), SVfARG(string));
5496 SvREFCNT_dec(string);
5497 string = vstringify(pmsv);
5500 Perl_sv_catpvf(aTHX_ xpt, "$%"SVf"::%s %"SVf, SVfARG(module), vn,
5503 Perl_sv_catpvf(aTHX_ xpt, "bootstrap parameter %"SVf, SVfARG(string));
5505 SvREFCNT_dec(string);
5507 Perl_sv_2mortal(aTHX_ xpt);
5508 Perl_croak_sv(aTHX_ xpt);
5514 =for apidoc my_strlcat
5516 The C library C<strlcat> if available, or a Perl implementation of it.
5517 This operates on C C<NUL>-terminated strings.
5519 C<my_strlcat()> appends string C<src> to the end of C<dst>. It will append at
5520 most S<C<size - strlen(dst) - 1>> characters. It will then C<NUL>-terminate,
5521 unless C<size> is 0 or the original C<dst> string was longer than C<size> (in
5522 practice this should not happen as it means that either C<size> is incorrect or
5523 that C<dst> is not a proper C<NUL>-terminated string).
5525 Note that C<size> is the full size of the destination buffer and
5526 the result is guaranteed to be C<NUL>-terminated if there is room. Note that
5527 room for the C<NUL> should be included in C<size>.
5531 Description stolen from http://www.openbsd.org/cgi-bin/man.cgi?query=strlcat
5535 Perl_my_strlcat(char *dst, const char *src, Size_t size)
5537 Size_t used, length, copy;
5540 length = strlen(src);
5541 if (size > 0 && used < size - 1) {
5542 copy = (length >= size - used) ? size - used - 1 : length;
5543 memcpy(dst + used, src, copy);
5544 dst[used + copy] = '\0';
5546 return used + length;
5552 =for apidoc my_strlcpy
5554 The C library C<strlcpy> if available, or a Perl implementation of it.
5555 This operates on C C<NUL>-terminated strings.
5557 C<my_strlcpy()> copies up to S<C<size - 1>> characters from the string C<src>
5558 to C<dst>, C<NUL>-terminating the result if C<size> is not 0.
5562 Description stolen from http://www.openbsd.org/cgi-bin/man.cgi?query=strlcpy
5566 Perl_my_strlcpy(char *dst, const char *src, Size_t size)
5568 Size_t length, copy;
5570 length = strlen(src);
5572 copy = (length >= size) ? size - 1 : length;
5573 memcpy(dst, src, copy);
5580 #if defined(_MSC_VER) && (_MSC_VER >= 1300) && (_MSC_VER < 1400) && (WINVER < 0x0500)
5581 /* VC7 or 7.1, building with pre-VC7 runtime libraries. */
5582 long _ftol( double ); /* Defined by VC6 C libs. */
5583 long _ftol2( double dblSource ) { return _ftol( dblSource ); }
5586 PERL_STATIC_INLINE bool
5587 S_gv_has_usable_name(pTHX_ GV *gv)
5591 && HvENAME(GvSTASH(gv))
5592 && (gvp = (GV **)hv_fetchhek(
5593 GvSTASH(gv), GvNAME_HEK(gv), 0
5599 Perl_get_db_sub(pTHX_ SV **svp, CV *cv)
5601 SV * const dbsv = GvSVn(PL_DBsub);
5602 const bool save_taint = TAINT_get;
5604 /* When we are called from pp_goto (svp is null),
5605 * we do not care about using dbsv to call CV;
5606 * it's for informational purposes only.
5609 PERL_ARGS_ASSERT_GET_DB_SUB;
5613 if (!PERLDB_SUB_NN) {
5616 if (!svp && !CvLEXICAL(cv)) {
5617 gv_efullname3(dbsv, gv, NULL);
5619 else if ( (CvFLAGS(cv) & (CVf_ANON | CVf_CLONED)) || CvLEXICAL(cv)
5620 || strEQ(GvNAME(gv), "END")
5621 || ( /* Could be imported, and old sub redefined. */
5622 (GvCV(gv) != cv || !S_gv_has_usable_name(aTHX_ gv))
5624 !( (SvTYPE(*svp) == SVt_PVGV)
5625 && (GvCV((const GV *)*svp) == cv)
5626 /* Use GV from the stack as a fallback. */
5627 && S_gv_has_usable_name(aTHX_ gv = (GV *)*svp)
5631 /* GV is potentially non-unique, or contain different CV. */
5632 SV * const tmp = newRV(MUTABLE_SV(cv));
5633 sv_setsv(dbsv, tmp);
5637 sv_sethek(dbsv, HvENAME_HEK(GvSTASH(gv)));
5638 sv_catpvs(dbsv, "::");
5639 sv_cathek(dbsv, GvNAME_HEK(gv));
5643 const int type = SvTYPE(dbsv);
5644 if (type < SVt_PVIV && type != SVt_IV)
5645 sv_upgrade(dbsv, SVt_PVIV);
5646 (void)SvIOK_on(dbsv);
5647 SvIV_set(dbsv, PTR2IV(cv)); /* Do it the quickest way */
5650 TAINT_IF(save_taint);
5651 #ifdef NO_TAINT_SUPPORT
5652 PERL_UNUSED_VAR(save_taint);
5657 Perl_my_dirfd(DIR * dir) {
5659 /* Most dirfd implementations have problems when passed NULL. */
5664 #elif defined(HAS_DIR_DD_FD)
5667 Perl_croak_nocontext(PL_no_func, "dirfd");
5668 assert(0); /* NOT REACHED */
5674 Perl_get_re_arg(pTHX_ SV *sv) {
5680 sv = MUTABLE_SV(SvRV(sv));
5681 if (SvTYPE(sv) == SVt_REGEXP)
5682 return (REGEXP*) sv;
5689 * This code is derived from drand48() implementation from FreeBSD,
5690 * found in lib/libc/gen/_rand48.c.
5692 * The U64 implementation is original, based on the POSIX
5693 * specification for drand48().
5697 * Copyright (c) 1993 Martin Birgmeier
5698 * All rights reserved.
5700 * You may redistribute unmodified or modified versions of this source
5701 * code provided that the above copyright notice and this and the
5702 * following conditions are retained.
5704 * This software is provided ``as is'', and comes with no warranties
5705 * of any kind. I shall in no event be liable for anything that happens
5706 * to anyone/anything when using this software.
5709 #define FREEBSD_DRAND48_SEED_0 (0x330e)
5711 #ifdef PERL_DRAND48_QUAD
5713 #define DRAND48_MULT U64_CONST(0x5deece66d)
5714 #define DRAND48_ADD 0xb
5715 #define DRAND48_MASK U64_CONST(0xffffffffffff)
5719 #define FREEBSD_DRAND48_SEED_1 (0xabcd)
5720 #define FREEBSD_DRAND48_SEED_2 (0x1234)
5721 #define FREEBSD_DRAND48_MULT_0 (0xe66d)
5722 #define FREEBSD_DRAND48_MULT_1 (0xdeec)
5723 #define FREEBSD_DRAND48_MULT_2 (0x0005)
5724 #define FREEBSD_DRAND48_ADD (0x000b)
5726 const unsigned short _rand48_mult[3] = {
5727 FREEBSD_DRAND48_MULT_0,
5728 FREEBSD_DRAND48_MULT_1,
5729 FREEBSD_DRAND48_MULT_2
5731 const unsigned short _rand48_add = FREEBSD_DRAND48_ADD;
5736 Perl_drand48_init_r(perl_drand48_t *random_state, U32 seed)
5738 PERL_ARGS_ASSERT_DRAND48_INIT_R;
5740 #ifdef PERL_DRAND48_QUAD
5741 *random_state = FREEBSD_DRAND48_SEED_0 + ((U64TYPE)seed << 16);
5743 random_state->seed[0] = FREEBSD_DRAND48_SEED_0;
5744 random_state->seed[1] = (U16) seed;
5745 random_state->seed[2] = (U16) (seed >> 16);
5750 Perl_drand48_r(perl_drand48_t *random_state)
5752 PERL_ARGS_ASSERT_DRAND48_R;
5754 #ifdef PERL_DRAND48_QUAD
5755 *random_state = (*random_state * DRAND48_MULT + DRAND48_ADD)
5758 return ldexp((double)*random_state, -48);
5764 accu = (U32) _rand48_mult[0] * (U32) random_state->seed[0]
5765 + (U32) _rand48_add;
5766 temp[0] = (U16) accu; /* lower 16 bits */
5767 accu >>= sizeof(U16) * 8;
5768 accu += (U32) _rand48_mult[0] * (U32) random_state->seed[1]
5769 + (U32) _rand48_mult[1] * (U32) random_state->seed[0];
5770 temp[1] = (U16) accu; /* middle 16 bits */
5771 accu >>= sizeof(U16) * 8;
5772 accu += _rand48_mult[0] * random_state->seed[2]
5773 + _rand48_mult[1] * random_state->seed[1]
5774 + _rand48_mult[2] * random_state->seed[0];
5775 random_state->seed[0] = temp[0];
5776 random_state->seed[1] = temp[1];
5777 random_state->seed[2] = (U16) accu;
5779 return ldexp((double) random_state->seed[0], -48) +
5780 ldexp((double) random_state->seed[1], -32) +
5781 ldexp((double) random_state->seed[2], -16);
5786 #ifdef USE_C_BACKTRACE
5788 /* Possibly move all this USE_C_BACKTRACE code into a new file. */
5793 /* abfd is the BFD handle. */
5795 /* bfd_syms is the BFD symbol table. */
5797 /* bfd_text is handle to the the ".text" section of the object file. */
5799 /* Since opening the executable and scanning its symbols is quite
5800 * heavy operation, we remember the filename we used the last time,
5801 * and do the opening and scanning only if the filename changes.
5802 * This removes most (but not all) open+scan cycles. */
5803 const char* fname_prev;
5806 /* Given a dl_info, update the BFD context if necessary. */
5807 static void bfd_update(bfd_context* ctx, Dl_info* dl_info)
5809 /* BFD open and scan only if the filename changed. */
5810 if (ctx->fname_prev == NULL ||
5811 strNE(dl_info->dli_fname, ctx->fname_prev)) {
5812 ctx->abfd = bfd_openr(dl_info->dli_fname, 0);
5814 if (bfd_check_format(ctx->abfd, bfd_object)) {
5815 IV symbol_size = bfd_get_symtab_upper_bound(ctx->abfd);
5816 if (symbol_size > 0) {
5817 Safefree(ctx->bfd_syms);
5818 Newx(ctx->bfd_syms, symbol_size, asymbol*);
5820 bfd_get_section_by_name(ctx->abfd, ".text");
5828 ctx->fname_prev = dl_info->dli_fname;
5832 /* Given a raw frame, try to symbolize it and store
5833 * symbol information (source file, line number) away. */
5834 static void bfd_symbolize(bfd_context* ctx,
5837 STRLEN* symbol_name_size,
5839 STRLEN* source_name_size,
5840 STRLEN* source_line)
5842 *symbol_name = NULL;
5843 *symbol_name_size = 0;
5845 IV offset = PTR2IV(raw_frame) - PTR2IV(ctx->bfd_text->vma);
5847 bfd_canonicalize_symtab(ctx->abfd, ctx->bfd_syms) > 0) {
5850 unsigned int line = 0;
5851 if (bfd_find_nearest_line(ctx->abfd, ctx->bfd_text,
5852 ctx->bfd_syms, offset,
5853 &file, &func, &line) &&
5854 file && func && line > 0) {
5855 /* Size and copy the source file, use only
5856 * the basename of the source file.
5858 * NOTE: the basenames are fine for the
5859 * Perl source files, but may not always
5860 * be the best idea for XS files. */
5861 const char *p, *b = NULL;
5862 /* Look for the last slash. */
5863 for (p = file; *p; p++) {
5867 if (b == NULL || *b == 0) {
5870 *source_name_size = p - b + 1;
5871 Newx(*source_name, *source_name_size + 1, char);
5872 Copy(b, *source_name, *source_name_size + 1, char);
5874 *symbol_name_size = strlen(func);
5875 Newx(*symbol_name, *symbol_name_size + 1, char);
5876 Copy(func, *symbol_name, *symbol_name_size + 1, char);
5878 *source_line = line;
5884 #endif /* #ifdef USE_BFD */
5888 /* OS X has no public API for for 'symbolicating' (Apple official term)
5889 * stack addresses to {function_name, source_file, line_number}.
5890 * Good news: there is command line utility atos(1) which does that.
5891 * Bad news 1: it's a command line utility.
5892 * Bad news 2: one needs to have the Developer Tools installed.
5893 * Bad news 3: in newer releases it needs to be run as 'xcrun atos'.
5895 * To recap: we need to open a pipe for reading for a utility which
5896 * might not exist, or exists in different locations, and then parse
5897 * the output. And since this is all for a low-level API, we cannot
5898 * use high-level stuff. Thanks, Apple. */
5901 /* tool is set to the absolute pathname of the tool to use:
5904 /* format is set to a printf format string used for building
5905 * the external command to run. */
5907 /* unavail is set if e.g. xcrun cannot be found, or something
5908 * else happens that makes getting the backtrace dubious. Note,
5909 * however, that the context isn't persistent, the next call to
5910 * get_c_backtrace() will start from scratch. */
5912 /* fname is the current object file name. */
5914 /* object_base_addr is the base address of the shared object. */
5915 void* object_base_addr;
5918 /* Given |dl_info|, updates the context. If the context has been
5919 * marked unavailable, return immediately. If not but the tool has
5920 * not been set, set it to either "xcrun atos" or "atos" (also set the
5921 * format to use for creating commands for piping), or if neither is
5922 * unavailable (one needs the Developer Tools installed), mark the context
5923 * an unavailable. Finally, update the filename (object name),
5924 * and its base address. */
5926 static void atos_update(atos_context* ctx,
5931 if (ctx->tool == NULL) {
5932 const char* tools[] = {
5936 const char* formats[] = {
5937 "/usr/bin/xcrun atos -o '%s' -l %08x %08x 2>&1",
5938 "/usr/bin/atos -d -o '%s' -l %08x %08x 2>&1"
5942 for (i = 0; i < C_ARRAY_LENGTH(tools); i++) {
5943 if (stat(tools[i], &st) == 0 && S_ISREG(st.st_mode)) {
5944 ctx->tool = tools[i];
5945 ctx->format = formats[i];
5949 if (ctx->tool == NULL) {
5950 ctx->unavail = TRUE;
5954 if (ctx->fname == NULL ||
5955 strNE(dl_info->dli_fname, ctx->fname)) {
5956 ctx->fname = dl_info->dli_fname;
5957 ctx->object_base_addr = dl_info->dli_fbase;
5961 /* Given an output buffer end |p| and its |start|, matches
5962 * for the atos output, extracting the source code location
5963 * and returning non-NULL if possible, returning NULL otherwise. */
5964 static const char* atos_parse(const char* p,
5966 STRLEN* source_name_size,
5967 STRLEN* source_line) {
5968 /* atos() output is something like:
5969 * perl_parse (in miniperl) (perl.c:2314)\n\n".
5970 * We cannot use Perl regular expressions, because we need to
5971 * stay low-level. Therefore here we have a rolled-out version
5972 * of a state machine which matches _backwards_from_the_end_ and
5973 * if there's a success, returns the starts of the filename,
5974 * also setting the filename size and the source line number.
5975 * The matched regular expression is roughly "\(.*:\d+\)\s*$" */
5976 const char* source_number_start;
5977 const char* source_name_end;
5978 const char* source_line_end;
5979 const char* close_paren;
5980 /* Skip trailing whitespace. */
5981 while (p > start && isspace(*p)) p--;
5982 /* Now we should be at the close paren. */
5983 if (p == start || *p != ')')
5987 /* Now we should be in the line number. */
5988 if (p == start || !isdigit(*p))
5990 /* Skip over the digits. */
5991 while (p > start && isdigit(*p))
5993 /* Now we should be at the colon. */
5994 if (p == start || *p != ':')
5996 source_number_start = p + 1;
5997 source_name_end = p; /* Just beyond the end. */
5999 /* Look for the open paren. */
6000 while (p > start && *p != '(')
6005 *source_name_size = source_name_end - p;
6006 *source_line = grok_atou(source_number_start, &source_line_end);
6007 if (source_line_end != close_paren)
6012 /* Given a raw frame, read a pipe from the symbolicator (that's the
6013 * technical term) atos, reads the result, and parses the source code
6014 * location. We must stay low-level, so we use snprintf(), pipe(),
6015 * and fread(), and then also parse the output ourselves. */
6016 static void atos_symbolize(atos_context* ctx,
6019 STRLEN* source_name_size,
6020 STRLEN* source_line)
6028 /* Simple security measure: if there's any funny business with
6029 * the object name (used as "-o '%s'" ), leave since at least
6030 * partially the user controls it. */
6031 for (p = ctx->fname; *p; p++) {
6032 if (*p == '\'' || iscntrl(*p)) {
6033 ctx->unavail = TRUE;
6037 cnt = snprintf(cmd, sizeof(cmd), ctx->format,
6038 ctx->fname, ctx->object_base_addr, raw_frame);
6039 if (cnt < sizeof(cmd)) {
6040 /* Undo nostdio.h #defines that disable stdio.
6041 * This is somewhat naughty, but is used elsewhere
6042 * in the core, and affects only OS X. */
6047 FILE* fp = popen(cmd, "r");
6048 /* At the moment we open a new pipe for each stack frame.
6049 * This is naturally somewhat slow, but hopefully generating
6050 * stack traces is never going to in a performance critical path.
6052 * We could play tricks with atos by batching the stack
6053 * addresses to be resolved: atos can either take multiple
6054 * addresses from the command line, or read addresses from
6055 * a file (though the mess of creating temporary files would
6056 * probably negate much of any possible speedup).
6058 * Normally there are only two objects present in the backtrace:
6059 * perl itself, and the libdyld.dylib. (Note that the object
6060 * filenames contain the full pathname, so perl may not always
6061 * be in the same place.) Whenever the object in the
6062 * backtrace changes, the base address also changes.
6064 * The problem with batching the addresses, though, would be
6065 * matching the results with the addresses: the parsing of
6066 * the results is already painful enough with a single address. */
6069 UV cnt = fread(out, 1, sizeof(out), fp);
6070 if (cnt < sizeof(out)) {
6071 const char* p = atos_parse(out + cnt, out,
6076 *source_name_size + 1, char);
6077 Copy(p, *source_name,
6078 *source_name_size + 1, char);
6086 #endif /* #ifdef PERL_DARWIN */
6089 =for apidoc get_c_backtrace
6091 Collects the backtrace (aka "stacktrace") into a single linear
6092 malloced buffer, which the caller B<must> Perl_free_c_backtrace().
6094 Scans the frames back by depth + skip, then drops the skip innermost,
6095 returning at most depth frames.
6101 Perl_get_c_backtrace(pTHX_ int depth, int skip)
6103 /* Note that here we must stay as low-level as possible: Newx(),
6104 * Copy(), Safefree(); since we may be called from anywhere,
6105 * so we should avoid higher level constructs like SVs or AVs.
6107 * Since we are using safesysmalloc() via Newx(), don't try
6108 * getting backtrace() there, unless you like deep recursion. */
6110 /* Currently only implemented with backtrace() and dladdr(),
6111 * for other platforms NULL is returned. */
6113 #if defined(HAS_BACKTRACE) && defined(HAS_DLADDR)
6114 /* backtrace() is available via <execinfo.h> in glibc and in most
6115 * modern BSDs; dladdr() is available via <dlfcn.h>. */
6117 /* We try fetching this many frames total, but then discard
6118 * the |skip| first ones. For the remaining ones we will try
6119 * retrieving more information with dladdr(). */
6120 int try_depth = skip + depth;
6122 /* The addresses (program counters) returned by backtrace(). */
6125 /* Retrieved with dladdr() from the addresses returned by backtrace(). */
6128 /* Sizes _including_ the terminating \0 of the object name
6129 * and symbol name strings. */
6130 STRLEN* object_name_sizes;
6131 STRLEN* symbol_name_sizes;
6134 /* The symbol names comes either from dli_sname,
6135 * or if using BFD, they can come from BFD. */
6136 char** symbol_names;
6139 /* The source code location information. Dug out with e.g. BFD. */
6140 char** source_names;
6141 STRLEN* source_name_sizes;
6142 STRLEN* source_lines;
6144 Perl_c_backtrace* bt = NULL; /* This is what will be returned. */
6145 int got_depth; /* How many frames were returned from backtrace(). */
6146 UV frame_count = 0; /* How many frames we return. */
6147 UV total_bytes = 0; /* The size of the whole returned backtrace. */
6150 bfd_context bfd_ctx;
6153 atos_context atos_ctx;
6156 /* Here are probably possibilities for optimizing. We could for
6157 * example have a struct that contains most of these and then
6158 * allocate |try_depth| of them, saving a bunch of malloc calls.
6159 * Note, however, that |frames| could not be part of that struct
6160 * because backtrace() will want an array of just them. Also be
6161 * careful about the name strings. */
6162 Newx(raw_frames, try_depth, void*);
6163 Newx(dl_infos, try_depth, Dl_info);
6164 Newx(object_name_sizes, try_depth, STRLEN);
6165 Newx(symbol_name_sizes, try_depth, STRLEN);
6166 Newx(source_names, try_depth, char*);
6167 Newx(source_name_sizes, try_depth, STRLEN);
6168 Newx(source_lines, try_depth, STRLEN);
6170 Newx(symbol_names, try_depth, char*);
6173 /* Get the raw frames. */
6174 got_depth = (int)backtrace(raw_frames, try_depth);
6176 /* We use dladdr() instead of backtrace_symbols() because we want
6177 * the full details instead of opaque strings. This is useful for
6178 * two reasons: () the details are needed for further symbolic
6179 * digging, for example in OS X (2) by having the details we fully
6180 * control the output, which in turn is useful when more platforms
6181 * are added: we can keep out output "portable". */
6183 /* We want a single linear allocation, which can then be freed
6184 * with a single swoop. We will do the usual trick of first
6185 * walking over the structure and seeing how much we need to
6186 * allocate, then allocating, and then walking over the structure
6187 * the second time and populating it. */
6189 /* First we must compute the total size of the buffer. */
6190 total_bytes = sizeof(Perl_c_backtrace_header);
6191 if (got_depth > skip) {
6194 bfd_init(); /* Is this safe to call multiple times? */
6195 Zero(&bfd_ctx, 1, bfd_context);
6198 Zero(&atos_ctx, 1, atos_context);
6200 for (i = skip; i < try_depth; i++) {
6201 Dl_info* dl_info = &dl_infos[i];
6203 total_bytes += sizeof(Perl_c_backtrace_frame);
6205 source_names[i] = NULL;
6206 source_name_sizes[i] = 0;
6207 source_lines[i] = 0;
6209 /* Yes, zero from dladdr() is failure. */
6210 if (dladdr(raw_frames[i], dl_info)) {
6211 object_name_sizes[i] =
6212 dl_info->dli_fname ? strlen(dl_info->dli_fname) : 0;
6213 symbol_name_sizes[i] =
6214 dl_info->dli_sname ? strlen(dl_info->dli_sname) : 0;
6216 bfd_update(&bfd_ctx, dl_info);
6217 bfd_symbolize(&bfd_ctx, raw_frames[i],
6219 &symbol_name_sizes[i],
6221 &source_name_sizes[i],
6225 atos_update(&atos_ctx, dl_info);
6226 atos_symbolize(&atos_ctx,
6229 &source_name_sizes[i],
6233 /* Plus ones for the terminating \0. */
6234 total_bytes += object_name_sizes[i] + 1;
6235 total_bytes += symbol_name_sizes[i] + 1;
6236 total_bytes += source_name_sizes[i] + 1;
6244 Safefree(bfd_ctx.bfd_syms);
6248 /* Now we can allocate and populate the result buffer. */
6249 Newxc(bt, total_bytes, char, Perl_c_backtrace);
6250 Zero(bt, total_bytes, char);
6251 bt->header.frame_count = frame_count;
6252 bt->header.total_bytes = total_bytes;
6253 if (frame_count > 0) {
6254 Perl_c_backtrace_frame* frame = bt->frame_info;
6255 char* name_base = (char *)(frame + frame_count);
6256 char* name_curr = name_base; /* Outputting the name strings here. */
6258 for (i = skip; i < skip + frame_count; i++) {
6259 Dl_info* dl_info = &dl_infos[i];
6261 frame->addr = raw_frames[i];
6262 frame->object_base_addr = dl_info->dli_fbase;
6263 frame->symbol_addr = dl_info->dli_saddr;
6265 /* Copies a string, including the \0, and advances the name_curr.
6266 * Also copies the start and the size to the frame. */
6267 #define PERL_C_BACKTRACE_STRCPY(frame, doffset, src, dsize, size) \
6269 Copy(src, name_curr, size, char); \
6270 frame->doffset = name_curr - (char*)bt; \
6271 frame->dsize = size; \
6272 name_curr += size; \
6275 PERL_C_BACKTRACE_STRCPY(frame, object_name_offset,
6277 object_name_size, object_name_sizes[i]);
6280 PERL_C_BACKTRACE_STRCPY(frame, symbol_name_offset,
6282 symbol_name_size, symbol_name_sizes[i]);
6283 Safefree(symbol_names[i]);
6285 PERL_C_BACKTRACE_STRCPY(frame, symbol_name_offset,
6287 symbol_name_size, symbol_name_sizes[i]);
6290 PERL_C_BACKTRACE_STRCPY(frame, source_name_offset,
6292 source_name_size, source_name_sizes[i]);
6293 Safefree(source_names[i]);
6295 #undef PERL_C_BACKTRACE_STRCPY
6297 frame->source_line_number = source_lines[i];
6301 assert(total_bytes ==
6302 (UV)(sizeof(Perl_c_backtrace_header) +
6303 frame_count * sizeof(Perl_c_backtrace_frame) +
6304 name_curr - name_base));
6307 Safefree(symbol_names);
6309 Safefree(source_lines);
6310 Safefree(source_name_sizes);
6311 Safefree(source_names);
6312 Safefree(symbol_name_sizes);
6313 Safefree(object_name_sizes);
6314 /* Assuming the strings returned by dladdr() are pointers
6315 * to read-only static memory (the object file), so that
6316 * they do not need freeing (and cannot be). */
6318 Safefree(raw_frames);
6321 PERL_UNUSED_ARGV(depth);
6322 PERL_UNUSED_ARGV(skip);
6328 =for apidoc free_c_backtrace
6330 Deallocates a backtrace received from get_c_bracktrace.
6336 =for apidoc get_c_backtrace_dump
6338 Returns a SV a dump of |depth| frames of the call stack, skipping
6339 the |skip| innermost ones. depth of 20 is usually enough.
6341 The appended output looks like:
6344 1 10e004812:0082 Perl_croak util.c:1716 /usr/bin/perl
6345 2 10df8d6d2:1d72 perl_parse perl.c:3975 /usr/bin/perl
6348 The fields are tab-separated. The first column is the depth (zero
6349 being the innermost non-skipped frame). In the hex:offset, the hex is
6350 where the program counter was in S_parse_body, and the :offset (might
6351 be missing) tells how much inside the S_parse_body the program counter was.
6353 The util.c:1716 is the source code file and line number.
6355 The /usr/bin/perl is obvious (hopefully).
6357 Unknowns are C<"-">. Unknowns can happen unfortunately quite easily:
6358 if the platform doesn't support retrieving the information;
6359 if the binary is missing the debug information;
6360 if the optimizer has transformed the code by for example inlining.
6366 Perl_get_c_backtrace_dump(pTHX_ int depth, int skip)
6368 Perl_c_backtrace* bt;
6370 bt = get_c_backtrace(depth, skip + 1 /* Hide ourselves. */);
6372 Perl_c_backtrace_frame* frame;
6373 SV* dsv = newSVpvs("");
6375 for (i = 0, frame = bt->frame_info;
6376 i < bt->header.frame_count; i++, frame++) {
6377 Perl_sv_catpvf(aTHX_ dsv, "%d", (int)i);
6378 Perl_sv_catpvf(aTHX_ dsv, "\t%p", frame->addr ? frame->addr : "-");
6379 /* Symbol (function) names might disappear without debug info.
6381 * The source code location might disappear in case of the
6382 * optimizer inlining or otherwise rearranging the code. */
6383 if (frame->symbol_addr) {
6384 Perl_sv_catpvf(aTHX_ dsv, ":%04x",
6386 ((char*)frame->addr - (char*)frame->symbol_addr));
6388 Perl_sv_catpvf(aTHX_ dsv, "\t%s",
6389 frame->symbol_name_size &&
6390 frame->symbol_name_offset ?
6391 (char*)bt + frame->symbol_name_offset : "-");
6392 if (frame->source_name_size &&
6393 frame->source_name_offset &&
6394 frame->source_line_number) {
6395 Perl_sv_catpvf(aTHX_ dsv, "\t%s:%"UVuf,
6396 (char*)bt + frame->source_name_offset,
6397 (UV)frame->source_line_number);
6399 Perl_sv_catpvf(aTHX_ dsv, "\t-");
6401 Perl_sv_catpvf(aTHX_ dsv, "\t%s",
6402 frame->object_name_size &&
6403 frame->object_name_offset ?
6404 (char*)bt + frame->object_name_offset : "-");
6405 /* The frame->object_base_addr is not output,
6406 * but it is used for symbolizing/symbolicating. */
6407 sv_catpvs(dsv, "\n");
6410 Perl_free_c_backtrace(aTHX_ bt);
6419 =for apidoc dump_c_backtrace
6421 Dumps the C backtrace to the given fp.
6423 Returns true if a backtrace could be retrieved, false if not.
6429 Perl_dump_c_backtrace(pTHX_ PerlIO* fp, int depth, int skip)
6433 PERL_ARGS_ASSERT_DUMP_C_BACKTRACE;
6435 sv = Perl_get_c_backtrace_dump(aTHX_ depth, skip);
6438 PerlIO_printf(fp, "%s", SvPV_nolen(sv));
6444 #endif /* #ifdef USE_C_BACKTRACE */
6448 * c-indentation-style: bsd
6450 * indent-tabs-mode: nil
6453 * ex: set ts=8 sts=4 sw=4 et: