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 */
49 # include "amigaos4/amigaio.h"
54 # include <sys/select.h>
58 #ifdef USE_C_BACKTRACE
62 # undef USE_BFD /* BFD is useless in OS X. */
72 # include <execinfo.h>
76 #ifdef PERL_DEBUG_READONLY_COW
77 # include <sys/mman.h>
82 /* NOTE: Do not call the next three routines directly. Use the macros
83 * in handy.h, so that we can easily redefine everything to do tracking of
84 * allocated hunks back to the original New to track down any memory leaks.
85 * XXX This advice seems to be widely ignored :-( --AD August 1996.
88 #if defined (DEBUGGING) || defined(PERL_IMPLICIT_SYS) || defined (PERL_TRACK_MEMPOOL)
89 # define ALWAYS_NEED_THX
92 #if defined(PERL_TRACK_MEMPOOL) && defined(PERL_DEBUG_READONLY_COW)
94 S_maybe_protect_rw(pTHX_ struct perl_memory_debug_header *header)
97 && mprotect(header, header->size, PROT_READ|PROT_WRITE))
98 Perl_warn(aTHX_ "mprotect for COW string %p %lu failed with %d",
99 header, header->size, errno);
103 S_maybe_protect_ro(pTHX_ struct perl_memory_debug_header *header)
106 && mprotect(header, header->size, PROT_READ))
107 Perl_warn(aTHX_ "mprotect RW for COW string %p %lu failed with %d",
108 header, header->size, errno);
110 # define maybe_protect_rw(foo) S_maybe_protect_rw(aTHX_ foo)
111 # define maybe_protect_ro(foo) S_maybe_protect_ro(aTHX_ foo)
113 # define maybe_protect_rw(foo) NOOP
114 # define maybe_protect_ro(foo) NOOP
117 #if defined(PERL_TRACK_MEMPOOL) || defined(PERL_DEBUG_READONLY_COW)
118 /* Use memory_debug_header */
120 # if (defined(PERL_POISON) && defined(PERL_TRACK_MEMPOOL)) \
121 || defined(PERL_DEBUG_READONLY_COW)
122 # define MDH_HAS_SIZE
126 /* paranoid version of system's malloc() */
129 Perl_safesysmalloc(MEM_SIZE size)
131 #ifdef ALWAYS_NEED_THX
138 if (size + PERL_MEMORY_DEBUG_HEADER_SIZE < size)
140 size += PERL_MEMORY_DEBUG_HEADER_SIZE;
143 if ((SSize_t)size < 0)
144 Perl_croak_nocontext("panic: malloc, size=%" UVuf, (UV) size);
146 if (!size) size = 1; /* malloc(0) is NASTY on our system */
148 #ifdef PERL_DEBUG_READONLY_COW
149 if ((ptr = mmap(0, size, PROT_READ|PROT_WRITE,
150 MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED) {
151 perror("mmap failed");
155 ptr = (Malloc_t)PerlMem_malloc(size);
157 PERL_ALLOC_CHECK(ptr);
160 struct perl_memory_debug_header *const header
161 = (struct perl_memory_debug_header *)ptr;
165 PoisonNew(((char *)ptr), size, char);
168 #ifdef PERL_TRACK_MEMPOOL
169 header->interpreter = aTHX;
170 /* Link us into the list. */
171 header->prev = &PL_memory_debug_header;
172 header->next = PL_memory_debug_header.next;
173 PL_memory_debug_header.next = header;
174 maybe_protect_rw(header->next);
175 header->next->prev = header;
176 maybe_protect_ro(header->next);
177 # ifdef PERL_DEBUG_READONLY_COW
178 header->readonly = 0;
184 ptr = (Malloc_t)((char*)ptr+PERL_MEMORY_DEBUG_HEADER_SIZE);
185 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%" UVxf ": (%05ld) malloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
187 /* malloc() can modify errno() even on success, but since someone
188 writing perl code doesn't have any control over when perl calls
189 malloc() we need to hide that.
198 #ifndef ALWAYS_NEED_THX
210 /* paranoid version of system's realloc() */
213 Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
215 #ifdef ALWAYS_NEED_THX
219 #ifdef PERL_DEBUG_READONLY_COW
220 const MEM_SIZE oldsize = where
221 ? ((struct perl_memory_debug_header *)((char *)where - PERL_MEMORY_DEBUG_HEADER_SIZE))->size
230 ptr = safesysmalloc(size);
235 where = (Malloc_t)((char*)where-PERL_MEMORY_DEBUG_HEADER_SIZE);
236 if (size + PERL_MEMORY_DEBUG_HEADER_SIZE < size)
238 size += PERL_MEMORY_DEBUG_HEADER_SIZE;
240 struct perl_memory_debug_header *const header
241 = (struct perl_memory_debug_header *)where;
243 # ifdef PERL_TRACK_MEMPOOL
244 if (header->interpreter != aTHX) {
245 Perl_croak_nocontext("panic: realloc from wrong pool, %p!=%p",
246 header->interpreter, aTHX);
248 assert(header->next->prev == header);
249 assert(header->prev->next == header);
251 if (header->size > size) {
252 const MEM_SIZE freed_up = header->size - size;
253 char *start_of_freed = ((char *)where) + size;
254 PoisonFree(start_of_freed, freed_up, char);
264 if ((SSize_t)size < 0)
265 Perl_croak_nocontext("panic: realloc, size=%" UVuf, (UV)size);
267 #ifdef PERL_DEBUG_READONLY_COW
268 if ((ptr = mmap(0, size, PROT_READ|PROT_WRITE,
269 MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED) {
270 perror("mmap failed");
273 Copy(where,ptr,oldsize < size ? oldsize : size,char);
274 if (munmap(where, oldsize)) {
275 perror("munmap failed");
279 ptr = (Malloc_t)PerlMem_realloc(where,size);
281 PERL_ALLOC_CHECK(ptr);
283 /* MUST do this fixup first, before doing ANYTHING else, as anything else
284 might allocate memory/free/move memory, and until we do the fixup, it
285 may well be chasing (and writing to) free memory. */
287 #ifdef PERL_TRACK_MEMPOOL
288 struct perl_memory_debug_header *const header
289 = (struct perl_memory_debug_header *)ptr;
292 if (header->size < size) {
293 const MEM_SIZE fresh = size - header->size;
294 char *start_of_fresh = ((char *)ptr) + size;
295 PoisonNew(start_of_fresh, fresh, char);
299 maybe_protect_rw(header->next);
300 header->next->prev = header;
301 maybe_protect_ro(header->next);
302 maybe_protect_rw(header->prev);
303 header->prev->next = header;
304 maybe_protect_ro(header->prev);
306 ptr = (Malloc_t)((char*)ptr+PERL_MEMORY_DEBUG_HEADER_SIZE);
308 /* realloc() can modify errno() even on success, but since someone
309 writing perl code doesn't have any control over when perl calls
310 realloc() we need to hide that.
315 /* In particular, must do that fixup above before logging anything via
316 *printf(), as it can reallocate memory, which can cause SEGVs. */
318 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%" UVxf ": (%05ld) rfree\n",PTR2UV(where),(long)PL_an++));
319 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%" UVxf ": (%05ld) realloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
326 #ifndef ALWAYS_NEED_THX
339 /* safe version of system's free() */
342 Perl_safesysfree(Malloc_t where)
344 #ifdef ALWAYS_NEED_THX
347 DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%" UVxf ": (%05ld) free\n",PTR2UV(where),(long)PL_an++));
350 Malloc_t where_intrn = (Malloc_t)((char*)where-PERL_MEMORY_DEBUG_HEADER_SIZE);
352 struct perl_memory_debug_header *const header
353 = (struct perl_memory_debug_header *)where_intrn;
356 const MEM_SIZE size = header->size;
358 # ifdef PERL_TRACK_MEMPOOL
359 if (header->interpreter != aTHX) {
360 Perl_croak_nocontext("panic: free from wrong pool, %p!=%p",
361 header->interpreter, aTHX);
364 Perl_croak_nocontext("panic: duplicate free");
367 Perl_croak_nocontext("panic: bad free, header->next==NULL");
368 if (header->next->prev != header || header->prev->next != header) {
369 Perl_croak_nocontext("panic: bad free, ->next->prev=%p, "
370 "header=%p, ->prev->next=%p",
371 header->next->prev, header,
374 /* Unlink us from the chain. */
375 maybe_protect_rw(header->next);
376 header->next->prev = header->prev;
377 maybe_protect_ro(header->next);
378 maybe_protect_rw(header->prev);
379 header->prev->next = header->next;
380 maybe_protect_ro(header->prev);
381 maybe_protect_rw(header);
383 PoisonNew(where_intrn, size, char);
385 /* Trigger the duplicate free warning. */
388 # ifdef PERL_DEBUG_READONLY_COW
389 if (munmap(where_intrn, size)) {
390 perror("munmap failed");
396 Malloc_t where_intrn = where;
398 #ifndef PERL_DEBUG_READONLY_COW
399 PerlMem_free(where_intrn);
404 /* safe version of system's calloc() */
407 Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
409 #ifdef ALWAYS_NEED_THX
413 #if defined(USE_MDH) || defined(DEBUGGING)
414 MEM_SIZE total_size = 0;
417 /* Even though calloc() for zero bytes is strange, be robust. */
418 if (size && (count <= MEM_SIZE_MAX / size)) {
419 #if defined(USE_MDH) || defined(DEBUGGING)
420 total_size = size * count;
426 if (PERL_MEMORY_DEBUG_HEADER_SIZE <= MEM_SIZE_MAX - (MEM_SIZE)total_size)
427 total_size += PERL_MEMORY_DEBUG_HEADER_SIZE;
432 if ((SSize_t)size < 0 || (SSize_t)count < 0)
433 Perl_croak_nocontext("panic: calloc, size=%" UVuf ", count=%" UVuf,
434 (UV)size, (UV)count);
436 #ifdef PERL_DEBUG_READONLY_COW
437 if ((ptr = mmap(0, total_size ? total_size : 1, PROT_READ|PROT_WRITE,
438 MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED) {
439 perror("mmap failed");
442 #elif defined(PERL_TRACK_MEMPOOL)
443 /* Have to use malloc() because we've added some space for our tracking
445 /* malloc(0) is non-portable. */
446 ptr = (Malloc_t)PerlMem_malloc(total_size ? total_size : 1);
448 /* Use calloc() because it might save a memset() if the memory is fresh
449 and clean from the OS. */
451 ptr = (Malloc_t)PerlMem_calloc(count, size);
452 else /* calloc(0) is non-portable. */
453 ptr = (Malloc_t)PerlMem_calloc(count ? count : 1, size ? size : 1);
455 PERL_ALLOC_CHECK(ptr);
456 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%" UVxf ": (%05ld) calloc %zu x %zu = %zu bytes\n",PTR2UV(ptr),(long)PL_an++, count, size, total_size));
460 struct perl_memory_debug_header *const header
461 = (struct perl_memory_debug_header *)ptr;
463 # ifndef PERL_DEBUG_READONLY_COW
464 memset((void*)ptr, 0, total_size);
466 # ifdef PERL_TRACK_MEMPOOL
467 header->interpreter = aTHX;
468 /* Link us into the list. */
469 header->prev = &PL_memory_debug_header;
470 header->next = PL_memory_debug_header.next;
471 PL_memory_debug_header.next = header;
472 maybe_protect_rw(header->next);
473 header->next->prev = header;
474 maybe_protect_ro(header->next);
475 # ifdef PERL_DEBUG_READONLY_COW
476 header->readonly = 0;
480 header->size = total_size;
482 ptr = (Malloc_t)((char*)ptr+PERL_MEMORY_DEBUG_HEADER_SIZE);
488 #ifndef ALWAYS_NEED_THX
497 /* These must be defined when not using Perl's malloc for binary
502 Malloc_t Perl_malloc (MEM_SIZE nbytes)
504 #ifdef PERL_IMPLICIT_SYS
507 return (Malloc_t)PerlMem_malloc(nbytes);
510 Malloc_t Perl_calloc (MEM_SIZE elements, MEM_SIZE size)
512 #ifdef PERL_IMPLICIT_SYS
515 return (Malloc_t)PerlMem_calloc(elements, size);
518 Malloc_t Perl_realloc (Malloc_t where, MEM_SIZE nbytes)
520 #ifdef PERL_IMPLICIT_SYS
523 return (Malloc_t)PerlMem_realloc(where, nbytes);
526 Free_t Perl_mfree (Malloc_t where)
528 #ifdef PERL_IMPLICIT_SYS
536 /* copy a string up to some (non-backslashed) delimiter, if any.
537 * With allow_escape, converts \<delimiter> to <delimiter>, while leaves
538 * \<non-delimiter> as-is.
539 * Returns the position in the src string of the closing delimiter, if
540 * any, or returns fromend otherwise.
541 * This is the internal implementation for Perl_delimcpy and
542 * Perl_delimcpy_no_escape.
546 S_delimcpy_intern(char *to, const char *toend, const char *from,
547 const char *fromend, int delim, I32 *retlen,
548 const bool allow_escape)
552 PERL_ARGS_ASSERT_DELIMCPY;
554 for (tolen = 0; from < fromend; from++, tolen++) {
555 if (allow_escape && *from == '\\' && from + 1 < fromend) {
556 if (from[1] != delim) {
563 else if (*from == delim)
576 =for apidoc delimcpy_no_escape
578 Copy a source buffer to a destination buffer, stopping at (but not including)
579 the first occurrence of the delimiter byte C<delim>, in the source. The source
580 is the bytes between C<from> and C<fromend> inclusive. The dest is C<to>
583 Nothing is copied beyond what fits between C<to> through C<toend>. If C<delim>
584 doesn't occur in the source buffer, as much of the source as will fit is copied
587 The actual number of bytes copied is written to C<*retlen>.
589 If there is room in the destination available after the copy, an extra
590 terminating safety NUL byte is written (not included in the returned length).
595 Perl_delimcpy_no_escape(char *to, const char *toend, const char *from,
596 const char *fromend, int delim, I32 *retlen)
598 const char * delim_pos;
599 Ptrdiff_t to_len = toend - to;
601 /* Only use the minimum of the available source/dest */
602 Ptrdiff_t copy_len = MIN(fromend - from, to_len);
604 PERL_ARGS_ASSERT_DELIMCPY_NO_ESCAPE;
606 assert(copy_len >= 0);
608 /* Look for the first delimiter in the portion of the source we are allowed
609 * to look at (determined by the input bounds). */
610 delim_pos = (const char *) memchr(from, delim, copy_len);
612 copy_len = delim_pos - from;
613 } /* else didn't find it: copy all of the source permitted */
615 Copy(from, to, copy_len, char);
621 /* If there is extra space available, add a trailing NUL */
622 if (copy_len < to_len) {
626 return (char *) from + copy_len;
630 Perl_delimcpy(char *to, const char *toend, const char *from, const char *fromend, int delim, I32 *retlen)
632 PERL_ARGS_ASSERT_DELIMCPY;
634 return S_delimcpy_intern(to, toend, from, fromend, delim, retlen, 1);
638 =head1 Miscellaneous Functions
642 Find the first (leftmost) occurrence of a sequence of bytes within another
643 sequence. This is the Perl version of C<strstr()>, extended to handle
644 arbitrary sequences, potentially containing embedded C<NUL> characters (C<NUL>
645 is what the initial C<n> in the function name stands for; some systems have an
646 equivalent, C<memmem()>, but with a somewhat different API).
648 Another way of thinking about this function is finding a needle in a haystack.
649 C<big> points to the first byte in the haystack. C<big_end> points to one byte
650 beyond the final byte in the haystack. C<little> points to the first byte in
651 the needle. C<little_end> points to one byte beyond the final byte in the
652 needle. All the parameters must be non-C<NULL>.
654 The function returns C<NULL> if there is no occurrence of C<little> within
655 C<big>. If C<little> is the empty string, C<big> is returned.
657 Because this function operates at the byte level, and because of the inherent
658 characteristics of UTF-8 (or UTF-EBCDIC), it will work properly if both the
659 needle and the haystack are strings with the same UTF-8ness, but not if the
667 Perl_ninstr(const char *big, const char *bigend, const char *little, const char *lend)
669 PERL_ARGS_ASSERT_NINSTR;
672 return ninstr(big, bigend, little, lend);
675 if (little >= lend) {
679 const U8 first = *little;
682 /* No match can start closer to the end of the haystack than the length
684 bigend -= lend - little;
685 little++; /* Look for 'first', then the remainder is in here */
686 lsize = lend - little;
688 while (big <= bigend) {
689 big = (char *) memchr((U8 *) big, first, bigend - big + 1);
690 if (big == NULL || big > bigend) {
694 if (memEQ(big + 1, little, lsize)) {
708 =head1 Miscellaneous Functions
712 Like C<L</ninstr>>, but instead finds the final (rightmost) occurrence of a
713 sequence of bytes within another sequence, returning C<NULL> if there is no
721 Perl_rninstr(const char *big, const char *bigend, const char *little, const char *lend)
723 const Ptrdiff_t little_len = lend - little;
724 const Ptrdiff_t big_len = bigend - big;
726 PERL_ARGS_ASSERT_RNINSTR;
728 /* A non-existent needle trivially matches the rightmost possible position
730 if (UNLIKELY(little_len <= 0)) {
731 return (char*)bigend;
734 /* If the needle is larger than the haystack, the needle can't possibly fit
735 * inside the haystack. */
736 if (UNLIKELY(little_len > big_len)) {
740 /* Special case length 1 needles. It's trivial if we have memrchr();
741 * and otherwise we just do a per-byte search backwards.
743 * XXX When we don't have memrchr, we could use something like
744 * S_find_next_masked( or S_find_span_end() to do per-word searches */
745 if (little_len == 1) {
746 const char final = *little;
750 return (char *) memrchr(big, final, big_len);
752 const char * cur = bigend - 1;
758 } while (--cur >= big);
764 else { /* Below, the needle is longer than a single byte */
766 /* We search backwards in the haystack for the final character of the
767 * needle. Each time one is found, we see if the characters just
768 * before it in the haystack match the rest of the needle. */
769 const char final = *(lend - 1);
771 /* What matches consists of 'little_len'-1 characters, then the final
773 const Size_t prefix_len = little_len - 1;
775 /* If the final character in the needle is any closer than this to the
776 * left edge, there wouldn't be enough room for all of it to fit in the
778 const char * const left_fence = big + prefix_len;
780 /* Start at the right edge */
781 char * cur = (char *) bigend;
783 /* memrchr() makes the search easy (and fast); otherwise, look
784 * backwards byte-by-byte. */
789 cur = (char *) memrchr(left_fence, final, cur - left_fence);
796 if (cur < left_fence) {
800 while (*cur != final);
803 /* Here, we know that *cur is 'final'; see if the preceding bytes
804 * of the needle also match the corresponding haystack bytes */
805 if memEQ(cur - prefix_len, little, prefix_len) {
806 return cur - prefix_len;
808 } while (cur > left_fence);
814 /* As a space optimization, we do not compile tables for strings of length
815 0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
816 special-cased in fbm_instr().
818 If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
821 =head1 Miscellaneous Functions
823 =for apidoc fbm_compile
825 Analyzes the string in order to make fast searches on it using C<fbm_instr()>
826 -- the Boyer-Moore algorithm.
832 Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
839 PERL_ARGS_ASSERT_FBM_COMPILE;
841 if (isGV_with_GP(sv) || SvROK(sv))
847 if (flags & FBMcf_TAIL) {
848 MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL;
849 sv_catpvs(sv, "\n"); /* Taken into account in fbm_instr() */
850 if (mg && mg->mg_len >= 0)
853 if (!SvPOK(sv) || SvNIOKp(sv))
854 s = (U8*)SvPV_force_mutable(sv, len);
855 else s = (U8 *)SvPV_mutable(sv, len);
856 if (len == 0) /* TAIL might be on a zero-length string. */
858 SvUPGRADE(sv, SVt_PVMG);
862 /* add PERL_MAGIC_bm magic holding the FBM lookup table */
864 assert(!mg_find(sv, PERL_MAGIC_bm));
865 mg = sv_magicext(sv, NULL, PERL_MAGIC_bm, &PL_vtbl_bm, NULL, 0);
869 /* Shorter strings are special-cased in Perl_fbm_instr(), and don't use
871 const U8 mlen = (len>255) ? 255 : (U8)len;
872 const unsigned char *const sb = s + len - mlen; /* first char (maybe) */
875 Newx(table, 256, U8);
876 memset((void*)table, mlen, 256);
877 mg->mg_ptr = (char *)table;
880 s += len - 1; /* last char */
883 if (table[*s] == mlen)
889 BmUSEFUL(sv) = 100; /* Initial value */
890 ((XPVNV*)SvANY(sv))->xnv_u.xnv_bm_tail = cBOOL(flags & FBMcf_TAIL);
895 =for apidoc fbm_instr
897 Returns the location of the SV in the string delimited by C<big> and
898 C<bigend> (C<bigend>) is the char following the last char).
899 It returns C<NULL> if the string can't be found. The C<sv>
900 does not have to be C<fbm_compiled>, but the search will not be as fast
905 If SvTAIL(littlestr) is true, a fake "\n" was appended to the string
906 during FBM compilation due to FBMcf_TAIL in flags. It indicates that
907 the littlestr must be anchored to the end of bigstr (or to any \n if
910 E.g. The regex compiler would compile /abc/ to a littlestr of "abc",
911 while /abc$/ compiles to "abc\n" with SvTAIL() true.
913 A littlestr of "abc", !SvTAIL matches as /abc/;
914 a littlestr of "ab\n", SvTAIL matches as:
915 without FBMrf_MULTILINE: /ab\n?\z/
916 with FBMrf_MULTILINE: /ab\n/ || /ab\z/;
918 (According to Ilya from 1999; I don't know if this is still true, DAPM 2015):
919 "If SvTAIL is actually due to \Z or \z, this gives false positives
925 Perl_fbm_instr(pTHX_ unsigned char *big, unsigned char *bigend, SV *littlestr, U32 flags)
929 const unsigned char *little = (const unsigned char *)SvPV_const(littlestr,l);
930 STRLEN littlelen = l;
931 const I32 multiline = flags & FBMrf_MULTILINE;
932 bool valid = SvVALID(littlestr);
933 bool tail = valid ? cBOOL(SvTAIL(littlestr)) : FALSE;
935 PERL_ARGS_ASSERT_FBM_INSTR;
937 assert(bigend >= big);
939 if ((STRLEN)(bigend - big) < littlelen) {
941 && ((STRLEN)(bigend - big) == littlelen - 1)
943 || (*big == *little &&
944 memEQ((char *)big, (char *)little, littlelen - 1))))
949 switch (littlelen) { /* Special cases for 0, 1 and 2 */
951 return (char*)big; /* Cannot be SvTAIL! */
954 if (tail && !multiline) /* Anchor only! */
955 /* [-1] is safe because we know that bigend != big. */
956 return (char *) (bigend - (bigend[-1] == '\n'));
958 s = (unsigned char *)memchr((void*)big, *little, bigend-big);
962 return (char *) bigend;
966 if (tail && !multiline) {
967 /* a littlestr with SvTAIL must be of the form "X\n" (where X
968 * is a single char). It is anchored, and can only match
969 * "....X\n" or "....X" */
970 if (bigend[-2] == *little && bigend[-1] == '\n')
971 return (char*)bigend - 2;
972 if (bigend[-1] == *little)
973 return (char*)bigend - 1;
978 /* memchr() is likely to be very fast, possibly using whatever
979 * hardware support is available, such as checking a whole
980 * cache line in one instruction.
981 * So for a 2 char pattern, calling memchr() is likely to be
982 * faster than running FBM, or rolling our own. The previous
983 * version of this code was roll-your-own which typically
984 * only needed to read every 2nd char, which was good back in
985 * the day, but no longer.
987 unsigned char c1 = little[0];
988 unsigned char c2 = little[1];
990 /* *** for all this case, bigend points to the last char,
991 * not the trailing \0: this makes the conditions slightly
997 /* do a quick test for c1 before calling memchr();
998 * this avoids the expensive fn call overhead when
999 * there are lots of c1's */
1000 if (LIKELY(*s != c1)) {
1002 s = (unsigned char *)memchr((void*)s, c1, bigend - s);
1009 /* failed; try searching for c2 this time; that way
1010 * we don't go pathologically slow when the string
1011 * consists mostly of c1's or vice versa.
1016 s = (unsigned char *)memchr((void*)s, c2, bigend - s + 1);
1020 return (char*)s - 1;
1024 /* c1, c2 the same */
1025 while (s < bigend) {
1034 s = (unsigned char *)memchr((void*)s, c1, bigend - s);
1035 if (!s || s >= bigend)
1042 /* failed to find 2 chars; try anchored match at end without
1044 if (tail && bigend[0] == little[0])
1045 return (char *)bigend;
1050 break; /* Only lengths 0 1 and 2 have special-case code. */
1053 if (tail && !multiline) { /* tail anchored? */
1054 s = bigend - littlelen;
1055 if (s >= big && bigend[-1] == '\n' && *s == *little
1056 /* Automatically of length > 2 */
1057 && memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
1059 return (char*)s; /* how sweet it is */
1062 && memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
1064 return (char*)s + 1; /* how sweet it is */
1070 /* not compiled; use Perl_ninstr() instead */
1071 char * const b = ninstr((char*)big,(char*)bigend,
1072 (char*)little, (char*)little + littlelen);
1074 assert(!tail); /* valid => FBM; tail only set on SvVALID SVs */
1078 /* Do actual FBM. */
1079 if (littlelen > (STRLEN)(bigend - big))
1083 const MAGIC *const mg = mg_find(littlestr, PERL_MAGIC_bm);
1084 const unsigned char *oldlittle;
1088 --littlelen; /* Last char found by table lookup */
1090 s = big + littlelen;
1091 little += littlelen; /* last char */
1094 const unsigned char * const table = (const unsigned char *) mg->mg_ptr;
1095 const unsigned char lastc = *little;
1099 if ((tmp = table[*s])) {
1100 /* *s != lastc; earliest position it could match now is
1101 * tmp slots further on */
1102 if ((s += tmp) >= bigend)
1104 if (LIKELY(*s != lastc)) {
1106 s = (unsigned char *)memchr((void*)s, lastc, bigend - s);
1116 /* hand-rolled strncmp(): less expensive than calling the
1117 * real function (maybe???) */
1119 unsigned char * const olds = s;
1124 if (*--s == *--little)
1126 s = olds + 1; /* here we pay the price for failure */
1128 if (s < bigend) /* fake up continue to outer loop */
1138 && memEQ((char *)(bigend - littlelen),
1139 (char *)(oldlittle - littlelen), littlelen) )
1140 return (char*)bigend - littlelen;
1146 Perl_cntrl_to_mnemonic(const U8 c)
1148 /* Returns the mnemonic string that represents character 'c', if one
1149 * exists; NULL otherwise. The only ones that exist for the purposes of
1150 * this routine are a few control characters */
1153 case '\a': return "\\a";
1154 case '\b': return "\\b";
1155 case ESC_NATIVE: return "\\e";
1156 case '\f': return "\\f";
1157 case '\n': return "\\n";
1158 case '\r': return "\\r";
1159 case '\t': return "\\t";
1165 /* copy a string to a safe spot */
1168 =head1 Memory Management
1172 Perl's version of C<strdup()>. Returns a pointer to a newly allocated
1173 string which is a duplicate of C<pv>. The size of the string is
1174 determined by C<strlen()>, which means it may not contain embedded C<NUL>
1175 characters and must have a trailing C<NUL>. To prevent memory leaks, the
1176 memory allocated for the new string needs to be freed when no longer needed.
1177 This can be done with the L</C<Safefree>> function, or
1178 L<C<SAVEFREEPV>|perlguts/SAVEFREEPV(p)>.
1180 On some platforms, Windows for example, all allocated memory owned by a thread
1181 is deallocated when that thread ends. So if you need that not to happen, you
1182 need to use the shared memory functions, such as C<L</savesharedpv>>.
1188 Perl_savepv(pTHX_ const char *pv)
1190 PERL_UNUSED_CONTEXT;
1195 const STRLEN pvlen = strlen(pv)+1;
1196 Newx(newaddr, pvlen, char);
1197 return (char*)memcpy(newaddr, pv, pvlen);
1201 /* same thing but with a known length */
1206 Perl's version of what C<strndup()> would be if it existed. Returns a
1207 pointer to a newly allocated string which is a duplicate of the first
1208 C<len> bytes from C<pv>, plus a trailing
1209 C<NUL> byte. The memory allocated for
1210 the new string can be freed with the C<Safefree()> function.
1212 On some platforms, Windows for example, all allocated memory owned by a thread
1213 is deallocated when that thread ends. So if you need that not to happen, you
1214 need to use the shared memory functions, such as C<L</savesharedpvn>>.
1220 Perl_savepvn(pTHX_ const char *pv, Size_t len)
1223 PERL_UNUSED_CONTEXT;
1225 Newx(newaddr,len+1,char);
1226 /* Give a meaning to NULL pointer mainly for the use in sv_magic() */
1228 /* might not be null terminated */
1229 newaddr[len] = '\0';
1230 return (char *) CopyD(pv,newaddr,len,char);
1233 return (char *) ZeroD(newaddr,len+1,char);
1238 =for apidoc savesharedpv
1240 A version of C<savepv()> which allocates the duplicate string in memory
1241 which is shared between threads.
1246 Perl_savesharedpv(pTHX_ const char *pv)
1251 PERL_UNUSED_CONTEXT;
1256 pvlen = strlen(pv)+1;
1257 newaddr = (char*)PerlMemShared_malloc(pvlen);
1261 return (char*)memcpy(newaddr, pv, pvlen);
1265 =for apidoc savesharedpvn
1267 A version of C<savepvn()> which allocates the duplicate string in memory
1268 which is shared between threads. (With the specific difference that a C<NULL>
1269 pointer is not acceptable)
1274 Perl_savesharedpvn(pTHX_ const char *const pv, const STRLEN len)
1276 char *const newaddr = (char*)PerlMemShared_malloc(len + 1);
1278 PERL_UNUSED_CONTEXT;
1279 /* PERL_ARGS_ASSERT_SAVESHAREDPVN; */
1284 newaddr[len] = '\0';
1285 return (char*)memcpy(newaddr, pv, len);
1289 =for apidoc savesvpv
1291 A version of C<savepv()>/C<savepvn()> which gets the string to duplicate from
1292 the passed in SV using C<SvPV()>
1294 On some platforms, Windows for example, all allocated memory owned by a thread
1295 is deallocated when that thread ends. So if you need that not to happen, you
1296 need to use the shared memory functions, such as C<L</savesharedsvpv>>.
1302 Perl_savesvpv(pTHX_ SV *sv)
1305 const char * const pv = SvPV_const(sv, len);
1308 PERL_ARGS_ASSERT_SAVESVPV;
1311 Newx(newaddr,len,char);
1312 return (char *) CopyD(pv,newaddr,len,char);
1316 =for apidoc savesharedsvpv
1318 A version of C<savesharedpv()> which allocates the duplicate string in
1319 memory which is shared between threads.
1325 Perl_savesharedsvpv(pTHX_ SV *sv)
1328 const char * const pv = SvPV_const(sv, len);
1330 PERL_ARGS_ASSERT_SAVESHAREDSVPV;
1332 return savesharedpvn(pv, len);
1335 /* the SV for Perl_form() and mess() is not kept in an arena */
1343 if (PL_phase != PERL_PHASE_DESTRUCT)
1344 return newSVpvs_flags("", SVs_TEMP);
1349 /* Create as PVMG now, to avoid any upgrading later */
1351 Newxz(any, 1, XPVMG);
1352 SvFLAGS(sv) = SVt_PVMG;
1353 SvANY(sv) = (void*)any;
1355 SvREFCNT(sv) = 1 << 30; /* practically infinite */
1360 #if defined(PERL_IMPLICIT_CONTEXT)
1362 Perl_form_nocontext(const char* pat, ...)
1367 PERL_ARGS_ASSERT_FORM_NOCONTEXT;
1368 va_start(args, pat);
1369 retval = vform(pat, &args);
1373 #endif /* PERL_IMPLICIT_CONTEXT */
1376 =head1 Miscellaneous Functions
1379 Takes a sprintf-style format pattern and conventional
1380 (non-SV) arguments and returns the formatted string.
1382 (char *) Perl_form(pTHX_ const char* pat, ...)
1384 can be used any place a string (char *) is required:
1386 char * s = Perl_form("%d.%d",major,minor);
1388 Uses a single private buffer so if you want to format several strings you
1389 must explicitly copy the earlier strings away (and free the copies when you
1396 Perl_form(pTHX_ const char* pat, ...)
1400 PERL_ARGS_ASSERT_FORM;
1401 va_start(args, pat);
1402 retval = vform(pat, &args);
1408 Perl_vform(pTHX_ const char *pat, va_list *args)
1410 SV * const sv = mess_alloc();
1411 PERL_ARGS_ASSERT_VFORM;
1412 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1419 Take a sprintf-style format pattern and argument list. These are used to
1420 generate a string message. If the message does not end with a newline,
1421 then it will be extended with some indication of the current location
1422 in the code, as described for L</mess_sv>.
1424 Normally, the resulting message is returned in a new mortal SV.
1425 During global destruction a single SV may be shared between uses of
1431 #if defined(PERL_IMPLICIT_CONTEXT)
1433 Perl_mess_nocontext(const char *pat, ...)
1438 PERL_ARGS_ASSERT_MESS_NOCONTEXT;
1439 va_start(args, pat);
1440 retval = vmess(pat, &args);
1444 #endif /* PERL_IMPLICIT_CONTEXT */
1447 Perl_mess(pTHX_ const char *pat, ...)
1451 PERL_ARGS_ASSERT_MESS;
1452 va_start(args, pat);
1453 retval = vmess(pat, &args);
1459 Perl_closest_cop(pTHX_ const COP *cop, const OP *o, const OP *curop,
1462 /* Look for curop starting from o. cop is the last COP we've seen. */
1463 /* opnext means that curop is actually the ->op_next of the op we are
1466 PERL_ARGS_ASSERT_CLOSEST_COP;
1468 if (!o || !curop || (
1469 opnext ? o->op_next == curop && o->op_type != OP_SCOPE : o == curop
1473 if (o->op_flags & OPf_KIDS) {
1475 for (kid = cUNOPo->op_first; kid; kid = OpSIBLING(kid)) {
1478 /* If the OP_NEXTSTATE has been optimised away we can still use it
1479 * the get the file and line number. */
1481 if (kid->op_type == OP_NULL && kid->op_targ == OP_NEXTSTATE)
1482 cop = (const COP *)kid;
1484 /* Keep searching, and return when we've found something. */
1486 new_cop = closest_cop(cop, kid, curop, opnext);
1492 /* Nothing found. */
1500 Expands a message, intended for the user, to include an indication of
1501 the current location in the code, if the message does not already appear
1504 C<basemsg> is the initial message or object. If it is a reference, it
1505 will be used as-is and will be the result of this function. Otherwise it
1506 is used as a string, and if it already ends with a newline, it is taken
1507 to be complete, and the result of this function will be the same string.
1508 If the message does not end with a newline, then a segment such as C<at
1509 foo.pl line 37> will be appended, and possibly other clauses indicating
1510 the current state of execution. The resulting message will end with a
1513 Normally, the resulting message is returned in a new mortal SV.
1514 During global destruction a single SV may be shared between uses of this
1515 function. If C<consume> is true, then the function is permitted (but not
1516 required) to modify and return C<basemsg> instead of allocating a new SV.
1522 Perl_mess_sv(pTHX_ SV *basemsg, bool consume)
1526 #if defined(USE_C_BACKTRACE) && defined(USE_C_BACKTRACE_ON_ERROR)
1530 /* The PERL_C_BACKTRACE_ON_WARN must be an integer of one or more. */
1531 if ((ws = PerlEnv_getenv("PERL_C_BACKTRACE_ON_ERROR"))
1532 && grok_atoUV(ws, &wi, NULL)
1533 && wi <= PERL_INT_MAX
1535 Perl_dump_c_backtrace(aTHX_ Perl_debug_log, (int)wi, 1);
1540 PERL_ARGS_ASSERT_MESS_SV;
1542 if (SvROK(basemsg)) {
1548 sv_setsv(sv, basemsg);
1553 if (SvPOK(basemsg) && consume) {
1558 sv_copypv(sv, basemsg);
1561 if (!SvCUR(sv) || *(SvEND(sv) - 1) != '\n') {
1563 * Try and find the file and line for PL_op. This will usually be
1564 * PL_curcop, but it might be a cop that has been optimised away. We
1565 * can try to find such a cop by searching through the optree starting
1566 * from the sibling of PL_curcop.
1571 closest_cop(PL_curcop, OpSIBLING(PL_curcop), PL_op, FALSE);
1576 Perl_sv_catpvf(aTHX_ sv, " at %s line %" IVdf,
1577 OutCopFILE(cop), (IV)CopLINE(cop));
1580 /* Seems that GvIO() can be untrustworthy during global destruction. */
1581 if (GvIO(PL_last_in_gv) && (SvTYPE(GvIOp(PL_last_in_gv)) == SVt_PVIO)
1582 && IoLINES(GvIOp(PL_last_in_gv)))
1585 const bool line_mode = (RsSIMPLE(PL_rs) &&
1586 *SvPV_const(PL_rs,l) == '\n' && l == 1);
1587 Perl_sv_catpvf(aTHX_ sv, ", <%" SVf "> %s %" IVdf,
1588 SVfARG(PL_last_in_gv == PL_argvgv
1590 : sv_2mortal(newSVhek(GvNAME_HEK(PL_last_in_gv)))),
1591 line_mode ? "line" : "chunk",
1592 (IV)IoLINES(GvIOp(PL_last_in_gv)));
1594 if (PL_phase == PERL_PHASE_DESTRUCT)
1595 sv_catpvs(sv, " during global destruction");
1596 sv_catpvs(sv, ".\n");
1604 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1605 argument list, respectively. These are used to generate a string message. If
1607 message does not end with a newline, then it will be extended with
1608 some indication of the current location in the code, as described for
1611 Normally, the resulting message is returned in a new mortal SV.
1612 During global destruction a single SV may be shared between uses of
1619 Perl_vmess(pTHX_ const char *pat, va_list *args)
1621 SV * const sv = mess_alloc();
1623 PERL_ARGS_ASSERT_VMESS;
1625 sv_vsetpvfn(sv, pat, strlen(pat), args, NULL, 0, NULL);
1626 return mess_sv(sv, 1);
1630 Perl_write_to_stderr(pTHX_ SV* msv)
1635 PERL_ARGS_ASSERT_WRITE_TO_STDERR;
1637 if (PL_stderrgv && SvREFCNT(PL_stderrgv)
1638 && (io = GvIO(PL_stderrgv))
1639 && (mg = SvTIED_mg((const SV *)io, PERL_MAGIC_tiedscalar)))
1640 Perl_magic_methcall(aTHX_ MUTABLE_SV(io), mg, SV_CONST(PRINT),
1641 G_SCALAR | G_DISCARD | G_WRITING_TO_STDERR, 1, msv);
1643 PerlIO * const serr = Perl_error_log;
1645 do_print(msv, serr);
1646 (void)PerlIO_flush(serr);
1651 =head1 Warning and Dieing
1654 /* Common code used in dieing and warning */
1657 S_with_queued_errors(pTHX_ SV *ex)
1659 PERL_ARGS_ASSERT_WITH_QUEUED_ERRORS;
1660 if (PL_errors && SvCUR(PL_errors) && !SvROK(ex)) {
1661 sv_catsv(PL_errors, ex);
1662 ex = sv_mortalcopy(PL_errors);
1663 SvCUR_set(PL_errors, 0);
1669 S_invoke_exception_hook(pTHX_ SV *ex, bool warn)
1674 SV **const hook = warn ? &PL_warnhook : &PL_diehook;
1675 /* sv_2cv might call Perl_croak() or Perl_warner() */
1676 SV * const oldhook = *hook;
1678 if (!oldhook || oldhook == PERL_WARNHOOK_FATAL)
1684 cv = sv_2cv(oldhook, &stash, &gv, 0);
1686 if (cv && !CvDEPTH(cv) && (CvROOT(cv) || CvXSUB(cv))) {
1696 exarg = newSVsv(ex);
1697 SvREADONLY_on(exarg);
1700 PUSHSTACKi(warn ? PERLSI_WARNHOOK : PERLSI_DIEHOOK);
1704 call_sv(MUTABLE_SV(cv), G_DISCARD);
1715 Behaves the same as L</croak_sv>, except for the return type.
1716 It should be used only where the C<OP *> return type is required.
1717 The function never actually returns.
1722 /* silence __declspec(noreturn) warnings */
1723 MSVC_DIAG_IGNORE(4646 4645)
1725 Perl_die_sv(pTHX_ SV *baseex)
1727 PERL_ARGS_ASSERT_DIE_SV;
1730 NORETURN_FUNCTION_END;
1737 Behaves the same as L</croak>, except for the return type.
1738 It should be used only where the C<OP *> return type is required.
1739 The function never actually returns.
1744 #if defined(PERL_IMPLICIT_CONTEXT)
1746 /* silence __declspec(noreturn) warnings */
1747 MSVC_DIAG_IGNORE(4646 4645)
1749 Perl_die_nocontext(const char* pat, ...)
1753 va_start(args, pat);
1755 NOT_REACHED; /* NOTREACHED */
1757 NORETURN_FUNCTION_END;
1761 #endif /* PERL_IMPLICIT_CONTEXT */
1763 /* silence __declspec(noreturn) warnings */
1764 MSVC_DIAG_IGNORE(4646 4645)
1766 Perl_die(pTHX_ const char* pat, ...)
1769 va_start(args, pat);
1771 NOT_REACHED; /* NOTREACHED */
1773 NORETURN_FUNCTION_END;
1778 =for apidoc croak_sv
1780 This is an XS interface to Perl's C<die> function.
1782 C<baseex> is the error message or object. If it is a reference, it
1783 will be used as-is. Otherwise it is used as a string, and if it does
1784 not end with a newline then it will be extended with some indication of
1785 the current location in the code, as described for L</mess_sv>.
1787 The error message or object will be used as an exception, by default
1788 returning control to the nearest enclosing C<eval>, but subject to
1789 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak_sv>
1790 function never returns normally.
1792 To die with a simple string message, the L</croak> function may be
1799 Perl_croak_sv(pTHX_ SV *baseex)
1801 SV *ex = with_queued_errors(mess_sv(baseex, 0));
1802 PERL_ARGS_ASSERT_CROAK_SV;
1803 invoke_exception_hook(ex, FALSE);
1810 This is an XS interface to Perl's C<die> function.
1812 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1813 argument list. These are used to generate a string message. If the
1814 message does not end with a newline, then it will be extended with
1815 some indication of the current location in the code, as described for
1818 The error message will be used as an exception, by default
1819 returning control to the nearest enclosing C<eval>, but subject to
1820 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1821 function never returns normally.
1823 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1824 (C<$@>) will be used as an error message or object instead of building an
1825 error message from arguments. If you want to throw a non-string object,
1826 or build an error message in an SV yourself, it is preferable to use
1827 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1833 Perl_vcroak(pTHX_ const char* pat, va_list *args)
1835 SV *ex = with_queued_errors(pat ? vmess(pat, args) : mess_sv(ERRSV, 0));
1836 invoke_exception_hook(ex, FALSE);
1843 This is an XS interface to Perl's C<die> function.
1845 Take a sprintf-style format pattern and argument list. These are used to
1846 generate a string message. If the message does not end with a newline,
1847 then it will be extended with some indication of the current location
1848 in the code, as described for L</mess_sv>.
1850 The error message will be used as an exception, by default
1851 returning control to the nearest enclosing C<eval>, but subject to
1852 modification by a C<$SIG{__DIE__}> handler. In any case, the C<croak>
1853 function never returns normally.
1855 For historical reasons, if C<pat> is null then the contents of C<ERRSV>
1856 (C<$@>) will be used as an error message or object instead of building an
1857 error message from arguments. If you want to throw a non-string object,
1858 or build an error message in an SV yourself, it is preferable to use
1859 the L</croak_sv> function, which does not involve clobbering C<ERRSV>.
1864 #if defined(PERL_IMPLICIT_CONTEXT)
1866 Perl_croak_nocontext(const char *pat, ...)
1870 va_start(args, pat);
1872 NOT_REACHED; /* NOTREACHED */
1875 #endif /* PERL_IMPLICIT_CONTEXT */
1877 /* saves machine code for a common noreturn idiom typically used in Newx*() */
1878 GCC_DIAG_IGNORE_DECL(-Wunused-function);
1880 Perl_croak_memory_wrap(void)
1882 Perl_croak_nocontext("%s",PL_memory_wrap);
1884 GCC_DIAG_RESTORE_DECL;
1887 Perl_croak(pTHX_ const char *pat, ...)
1890 va_start(args, pat);
1892 NOT_REACHED; /* NOTREACHED */
1897 =for apidoc croak_no_modify
1899 Exactly equivalent to C<Perl_croak(aTHX_ "%s", PL_no_modify)>, but generates
1900 terser object code than using C<Perl_croak>. Less code used on exception code
1901 paths reduces CPU cache pressure.
1907 Perl_croak_no_modify(void)
1909 Perl_croak_nocontext( "%s", PL_no_modify);
1912 /* does not return, used in util.c perlio.c and win32.c
1913 This is typically called when malloc returns NULL.
1916 Perl_croak_no_mem(void)
1920 int fd = PerlIO_fileno(Perl_error_log);
1922 SETERRNO(EBADF,RMS_IFI);
1924 /* Can't use PerlIO to write as it allocates memory */
1925 PERL_UNUSED_RESULT(PerlLIO_write(fd, PL_no_mem, sizeof(PL_no_mem)-1));
1930 /* does not return, used only in POPSTACK */
1932 Perl_croak_popstack(void)
1935 PerlIO_printf(Perl_error_log, "panic: POPSTACK\n");
1942 This is an XS interface to Perl's C<warn> function.
1944 C<baseex> is the error message or object. If it is a reference, it
1945 will be used as-is. Otherwise it is used as a string, and if it does
1946 not end with a newline then it will be extended with some indication of
1947 the current location in the code, as described for L</mess_sv>.
1949 The error message or object will by default be written to standard error,
1950 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1952 To warn with a simple string message, the L</warn> function may be
1959 Perl_warn_sv(pTHX_ SV *baseex)
1961 SV *ex = mess_sv(baseex, 0);
1962 PERL_ARGS_ASSERT_WARN_SV;
1963 if (!invoke_exception_hook(ex, TRUE))
1964 write_to_stderr(ex);
1970 This is an XS interface to Perl's C<warn> function.
1972 C<pat> and C<args> are a sprintf-style format pattern and encapsulated
1973 argument list. These are used to generate a string message. If the
1974 message does not end with a newline, then it will be extended with
1975 some indication of the current location in the code, as described for
1978 The error message or object will by default be written to standard error,
1979 but this is subject to modification by a C<$SIG{__WARN__}> handler.
1981 Unlike with L</vcroak>, C<pat> is not permitted to be null.
1987 Perl_vwarn(pTHX_ const char* pat, va_list *args)
1989 SV *ex = vmess(pat, args);
1990 PERL_ARGS_ASSERT_VWARN;
1991 if (!invoke_exception_hook(ex, TRUE))
1992 write_to_stderr(ex);
1998 This is an XS interface to Perl's C<warn> function.
2000 Take a sprintf-style format pattern and argument list. These are used to
2001 generate a string message. If the message does not end with a newline,
2002 then it will be extended with some indication of the current location
2003 in the code, as described for L</mess_sv>.
2005 The error message or object will by default be written to standard error,
2006 but this is subject to modification by a C<$SIG{__WARN__}> handler.
2008 Unlike with L</croak>, C<pat> is not permitted to be null.
2013 #if defined(PERL_IMPLICIT_CONTEXT)
2015 Perl_warn_nocontext(const char *pat, ...)
2019 PERL_ARGS_ASSERT_WARN_NOCONTEXT;
2020 va_start(args, pat);
2024 #endif /* PERL_IMPLICIT_CONTEXT */
2027 Perl_warn(pTHX_ const char *pat, ...)
2030 PERL_ARGS_ASSERT_WARN;
2031 va_start(args, pat);
2036 #if defined(PERL_IMPLICIT_CONTEXT)
2038 Perl_warner_nocontext(U32 err, const char *pat, ...)
2042 PERL_ARGS_ASSERT_WARNER_NOCONTEXT;
2043 va_start(args, pat);
2044 vwarner(err, pat, &args);
2047 #endif /* PERL_IMPLICIT_CONTEXT */
2050 Perl_ck_warner_d(pTHX_ U32 err, const char* pat, ...)
2052 PERL_ARGS_ASSERT_CK_WARNER_D;
2054 if (Perl_ckwarn_d(aTHX_ err)) {
2056 va_start(args, pat);
2057 vwarner(err, pat, &args);
2063 Perl_ck_warner(pTHX_ U32 err, const char* pat, ...)
2065 PERL_ARGS_ASSERT_CK_WARNER;
2067 if (Perl_ckwarn(aTHX_ err)) {
2069 va_start(args, pat);
2070 vwarner(err, pat, &args);
2076 Perl_warner(pTHX_ U32 err, const char* pat,...)
2079 PERL_ARGS_ASSERT_WARNER;
2080 va_start(args, pat);
2081 vwarner(err, pat, &args);
2086 Perl_vwarner(pTHX_ U32 err, const char* pat, va_list* args)
2088 PERL_ARGS_ASSERT_VWARNER;
2090 (PL_warnhook == PERL_WARNHOOK_FATAL || ckDEAD(err)) &&
2091 !(PL_in_eval & EVAL_KEEPERR)
2093 SV * const msv = vmess(pat, args);
2095 if (PL_parser && PL_parser->error_count) {
2099 invoke_exception_hook(msv, FALSE);
2104 Perl_vwarn(aTHX_ pat, args);
2108 /* implements the ckWARN? macros */
2111 Perl_ckwarn(pTHX_ U32 w)
2113 /* If lexical warnings have not been set, use $^W. */
2115 return PL_dowarn & G_WARN_ON;
2117 return ckwarn_common(w);
2120 /* implements the ckWARN?_d macro */
2123 Perl_ckwarn_d(pTHX_ U32 w)
2125 /* If lexical warnings have not been set then default classes warn. */
2129 return ckwarn_common(w);
2133 S_ckwarn_common(pTHX_ U32 w)
2135 if (PL_curcop->cop_warnings == pWARN_ALL)
2138 if (PL_curcop->cop_warnings == pWARN_NONE)
2141 /* Check the assumption that at least the first slot is non-zero. */
2142 assert(unpackWARN1(w));
2144 /* Check the assumption that it is valid to stop as soon as a zero slot is
2146 if (!unpackWARN2(w)) {
2147 assert(!unpackWARN3(w));
2148 assert(!unpackWARN4(w));
2149 } else if (!unpackWARN3(w)) {
2150 assert(!unpackWARN4(w));
2153 /* Right, dealt with all the special cases, which are implemented as non-
2154 pointers, so there is a pointer to a real warnings mask. */
2156 if (isWARN_on(PL_curcop->cop_warnings, unpackWARN1(w)))
2158 } while (w >>= WARNshift);
2163 /* Set buffer=NULL to get a new one. */
2165 Perl_new_warnings_bitfield(pTHX_ STRLEN *buffer, const char *const bits,
2167 const MEM_SIZE len_wanted =
2168 sizeof(STRLEN) + (size > WARNsize ? size : WARNsize);
2169 PERL_UNUSED_CONTEXT;
2170 PERL_ARGS_ASSERT_NEW_WARNINGS_BITFIELD;
2173 (specialWARN(buffer) ?
2174 PerlMemShared_malloc(len_wanted) :
2175 PerlMemShared_realloc(buffer, len_wanted));
2177 Copy(bits, (buffer + 1), size, char);
2178 if (size < WARNsize)
2179 Zero((char *)(buffer + 1) + size, WARNsize - size, char);
2183 /* since we've already done strlen() for both nam and val
2184 * we can use that info to make things faster than
2185 * sprintf(s, "%s=%s", nam, val)
2187 #define my_setenv_format(s, nam, nlen, val, vlen) \
2188 Copy(nam, s, nlen, char); \
2190 Copy(val, s+(nlen+1), vlen, char); \
2191 *(s+(nlen+1+vlen)) = '\0'
2195 #ifdef USE_ENVIRON_ARRAY
2196 /* NB: VMS' my_setenv() is in vms.c */
2198 /* Configure doesn't test for HAS_SETENV yet, so decide based on platform.
2199 * For Solaris, setenv() and unsetenv() were introduced in Solaris 9, so
2200 * testing for HAS UNSETENV is sufficient.
2202 # if defined(__CYGWIN__)|| defined(__riscos__) || (defined(__sun) && defined(HAS_UNSETENV)) || defined(PERL_DARWIN)
2203 # define MY_HAS_SETENV
2206 /* small wrapper for use by Perl_my_setenv that mallocs, or reallocs if
2207 * 'current' is non-null, with up to three sizes that are added together.
2208 * It handles integer overflow.
2210 # ifndef MY_HAS_SETENV
2212 S_env_alloc(void *current, Size_t l1, Size_t l2, Size_t l3, Size_t size)
2215 Size_t sl, l = l1 + l2;
2227 ? safesysrealloc(current, sl)
2228 : safesysmalloc(sl);
2233 croak_memory_wrap();
2238 # if !defined(WIN32) && !defined(NETWARE)
2241 =for apidoc my_setenv
2243 A wrapper for the C library L<setenv(3)>. Don't use the latter, as the perl
2244 version has desirable safeguards
2250 Perl_my_setenv(pTHX_ const char *nam, const char *val)
2252 # ifdef __amigaos4__
2253 amigaos4_obtain_environ(__FUNCTION__);
2256 # ifdef USE_ITHREADS
2257 /* only parent thread can modify process environment, so no need to use a
2259 if (PL_curinterp == aTHX)
2263 # ifndef PERL_USE_SAFE_PUTENV
2264 if (!PL_use_safe_putenv) {
2265 /* most putenv()s leak, so we manipulate environ directly */
2267 Size_t vlen, nlen = strlen(nam);
2269 /* where does it go? */
2270 for (i = 0; environ[i]; i++) {
2271 if (strnEQ(environ[i], nam, nlen) && environ[i][nlen] == '=')
2275 if (environ == PL_origenviron) { /* need we copy environment? */
2280 while (environ[max])
2283 /* XXX shouldn't that be max+1 rather than max+2 ??? - DAPM */
2284 tmpenv = (char**)S_env_alloc(NULL, max, 2, 0, sizeof(char*));
2286 for (j=0; j<max; j++) { /* copy environment */
2287 const Size_t len = strlen(environ[j]);
2288 tmpenv[j] = S_env_alloc(NULL, len, 1, 0, 1);
2289 Copy(environ[j], tmpenv[j], len+1, char);
2293 environ = tmpenv; /* tell exec where it is now */
2297 safesysfree(environ[i]);
2298 while (environ[i]) {
2299 environ[i] = environ[i+1];
2302 # ifdef __amigaos4__
2309 if (!environ[i]) { /* does not exist yet */
2310 environ = (char**)S_env_alloc(environ, i, 2, 0, sizeof(char*));
2311 environ[i+1] = NULL; /* make sure it's null terminated */
2314 safesysfree(environ[i]);
2318 environ[i] = S_env_alloc(NULL, nlen, vlen, 2, 1);
2319 /* all that work just for this */
2320 my_setenv_format(environ[i], nam, nlen, val, vlen);
2324 # endif /* !PERL_USE_SAFE_PUTENV */
2326 # ifdef MY_HAS_SETENV
2327 # if defined(HAS_UNSETENV)
2329 (void)unsetenv(nam);
2331 (void)setenv(nam, val, 1);
2333 # else /* ! HAS_UNSETENV */
2334 (void)setenv(nam, val, 1);
2335 # endif /* HAS_UNSETENV */
2337 # elif defined(HAS_UNSETENV)
2340 if (environ) /* old glibc can crash with null environ */
2341 (void)unsetenv(nam);
2343 const Size_t nlen = strlen(nam);
2344 const Size_t vlen = strlen(val);
2345 char * const new_env = S_env_alloc(NULL, nlen, vlen, 2, 1);
2346 my_setenv_format(new_env, nam, nlen, val, vlen);
2347 (void)putenv(new_env);
2350 # else /* ! HAS_UNSETENV */
2353 const Size_t nlen = strlen(nam);
2359 new_env = S_env_alloc(NULL, nlen, vlen, 2, 1);
2360 /* all that work just for this */
2361 my_setenv_format(new_env, nam, nlen, val, vlen);
2362 (void)putenv(new_env);
2364 # endif /* MY_HAS_SETENV */
2366 # ifndef PERL_USE_SAFE_PUTENV
2371 # ifdef __amigaos4__
2373 amigaos4_release_environ(__FUNCTION__);
2377 # else /* WIN32 || NETWARE */
2380 Perl_my_setenv(pTHX_ const char *nam, const char *val)
2383 const Size_t nlen = strlen(nam);
2390 envstr = S_env_alloc(NULL, nlen, vlen, 2, 1);
2391 my_setenv_format(envstr, nam, nlen, val, vlen);
2392 (void)PerlEnv_putenv(envstr);
2393 safesysfree(envstr);
2396 # endif /* WIN32 || NETWARE */
2398 #endif /* USE_ENVIRON_ARRAY */
2403 #ifdef UNLINK_ALL_VERSIONS
2405 Perl_unlnk(pTHX_ const char *f) /* unlink all versions of a file */
2409 PERL_ARGS_ASSERT_UNLNK;
2411 while (PerlLIO_unlink(f) >= 0)
2413 return retries ? 0 : -1;
2418 Perl_my_popen_list(pTHX_ const char *mode, int n, SV **args)
2420 #if (!defined(DOSISH) || defined(HAS_FORK)) && !defined(OS2) && !defined(VMS) && !defined(NETWARE) && !defined(__LIBCATAMOUNT__) && !defined(__amigaos4__)
2428 PERL_ARGS_ASSERT_MY_POPEN_LIST;
2430 PERL_FLUSHALL_FOR_CHILD;
2431 This = (*mode == 'w');
2435 taint_proper("Insecure %s%s", "EXEC");
2437 if (PerlProc_pipe_cloexec(p) < 0)
2439 /* Try for another pipe pair for error return */
2440 if (PerlProc_pipe_cloexec(pp) >= 0)
2442 while ((pid = PerlProc_fork()) < 0) {
2443 if (errno != EAGAIN) {
2444 PerlLIO_close(p[This]);
2445 PerlLIO_close(p[that]);
2447 PerlLIO_close(pp[0]);
2448 PerlLIO_close(pp[1]);
2452 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2461 /* Close parent's end of error status pipe (if any) */
2463 PerlLIO_close(pp[0]);
2464 /* Now dup our end of _the_ pipe to right position */
2465 if (p[THIS] != (*mode == 'r')) {
2466 PerlLIO_dup2(p[THIS], *mode == 'r');
2467 PerlLIO_close(p[THIS]);
2468 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2469 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2472 setfd_cloexec_or_inhexec_by_sysfdness(p[THIS]);
2473 PerlLIO_close(p[THAT]); /* close parent's end of _the_ pipe */
2475 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2476 /* No automatic close - do it by hand */
2483 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++) {
2489 do_aexec5(NULL, args-1, args-1+n, pp[1], did_pipes);
2496 PerlLIO_close(pp[1]);
2497 /* Keep the lower of the two fd numbers */
2498 if (p[that] < p[This]) {
2499 PerlLIO_dup2_cloexec(p[This], p[that]);
2500 PerlLIO_close(p[This]);
2504 PerlLIO_close(p[that]); /* close child's end of pipe */
2506 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2507 SvUPGRADE(sv,SVt_IV);
2509 PL_forkprocess = pid;
2510 /* If we managed to get status pipe check for exec fail */
2511 if (did_pipes && pid > 0) {
2513 unsigned read_total = 0;
2515 while (read_total < sizeof(int)) {
2516 const SSize_t n1 = PerlLIO_read(pp[0],
2517 (void*)(((char*)&errkid)+read_total),
2518 (sizeof(int)) - read_total);
2523 PerlLIO_close(pp[0]);
2525 if (read_total) { /* Error */
2527 PerlLIO_close(p[This]);
2528 if (read_total != sizeof(int))
2529 Perl_croak(aTHX_ "panic: kid popen errno read, n=%u", read_total);
2531 pid2 = wait4pid(pid, &status, 0);
2532 } while (pid2 == -1 && errno == EINTR);
2533 errno = errkid; /* Propagate errno from kid */
2538 PerlLIO_close(pp[0]);
2539 return PerlIO_fdopen(p[This], mode);
2541 # if defined(OS2) /* Same, without fork()ing and all extra overhead... */
2542 return my_syspopen4(aTHX_ NULL, mode, n, args);
2543 # elif defined(WIN32)
2544 return win32_popenlist(mode, n, args);
2546 Perl_croak(aTHX_ "List form of piped open not implemented");
2547 return (PerlIO *) NULL;
2552 /* VMS' my_popen() is in VMS.c, same with OS/2 and AmigaOS 4. */
2553 #if (!defined(DOSISH) || defined(HAS_FORK)) && !defined(VMS) && !defined(__LIBCATAMOUNT__) && !defined(__amigaos4__)
2555 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2561 const I32 doexec = !(*cmd == '-' && cmd[1] == '\0');
2565 PERL_ARGS_ASSERT_MY_POPEN;
2567 PERL_FLUSHALL_FOR_CHILD;
2570 return my_syspopen(aTHX_ cmd,mode);
2573 This = (*mode == 'w');
2575 if (doexec && TAINTING_get) {
2577 taint_proper("Insecure %s%s", "EXEC");
2579 if (PerlProc_pipe_cloexec(p) < 0)
2581 if (doexec && PerlProc_pipe_cloexec(pp) >= 0)
2583 while ((pid = PerlProc_fork()) < 0) {
2584 if (errno != EAGAIN) {
2585 PerlLIO_close(p[This]);
2586 PerlLIO_close(p[that]);
2588 PerlLIO_close(pp[0]);
2589 PerlLIO_close(pp[1]);
2592 Perl_croak(aTHX_ "Can't fork: %s", Strerror(errno));
2595 Perl_ck_warner(aTHX_ packWARN(WARN_PIPE), "Can't fork, trying again in 5 seconds");
2605 PerlLIO_close(pp[0]);
2606 if (p[THIS] != (*mode == 'r')) {
2607 PerlLIO_dup2(p[THIS], *mode == 'r');
2608 PerlLIO_close(p[THIS]);
2609 if (p[THAT] != (*mode == 'r')) /* if dup2() didn't close it */
2610 PerlLIO_close(p[THAT]);
2613 setfd_cloexec_or_inhexec_by_sysfdness(p[THIS]);
2614 PerlLIO_close(p[THAT]);
2618 #if !defined(HAS_FCNTL) || !defined(F_SETFD)
2625 for (fd = PL_maxsysfd + 1; fd < NOFILE; fd++)
2630 /* may or may not use the shell */
2631 do_exec3(cmd, pp[1], did_pipes);
2634 #endif /* defined OS2 */
2636 #ifdef PERLIO_USING_CRLF
2637 /* Since we circumvent IO layers when we manipulate low-level
2638 filedescriptors directly, need to manually switch to the
2639 default, binary, low-level mode; see PerlIOBuf_open(). */
2640 PerlLIO_setmode((*mode == 'r'), O_BINARY);
2643 #ifdef PERL_USES_PL_PIDSTATUS
2644 hv_clear(PL_pidstatus); /* we have no children */
2651 PerlLIO_close(pp[1]);
2652 if (p[that] < p[This]) {
2653 PerlLIO_dup2_cloexec(p[This], p[that]);
2654 PerlLIO_close(p[This]);
2658 PerlLIO_close(p[that]);
2660 sv = *av_fetch(PL_fdpid,p[This],TRUE);
2661 SvUPGRADE(sv,SVt_IV);
2663 PL_forkprocess = pid;
2664 if (did_pipes && pid > 0) {
2668 while (n < sizeof(int)) {
2669 const SSize_t n1 = PerlLIO_read(pp[0],
2670 (void*)(((char*)&errkid)+n),
2676 PerlLIO_close(pp[0]);
2678 if (n) { /* Error */
2680 PerlLIO_close(p[This]);
2681 if (n != sizeof(int))
2682 Perl_croak(aTHX_ "panic: kid popen errno read, n=%u", n);
2684 pid2 = wait4pid(pid, &status, 0);
2685 } while (pid2 == -1 && errno == EINTR);
2686 errno = errkid; /* Propagate errno from kid */
2691 PerlLIO_close(pp[0]);
2692 return PerlIO_fdopen(p[This], mode);
2694 #elif defined(DJGPP)
2695 FILE *djgpp_popen();
2697 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2699 PERL_FLUSHALL_FOR_CHILD;
2700 /* Call system's popen() to get a FILE *, then import it.
2701 used 0 for 2nd parameter to PerlIO_importFILE;
2704 return PerlIO_importFILE(djgpp_popen(cmd, mode), 0);
2706 #elif defined(__LIBCATAMOUNT__)
2708 Perl_my_popen(pTHX_ const char *cmd, const char *mode)
2713 #endif /* !DOSISH */
2715 /* this is called in parent before the fork() */
2717 Perl_atfork_lock(void)
2718 #if defined(USE_ITHREADS)
2720 PERL_TSA_ACQUIRE(PL_perlio_mutex)
2723 PERL_TSA_ACQUIRE(PL_malloc_mutex)
2725 PERL_TSA_ACQUIRE(PL_op_mutex)
2728 #if defined(USE_ITHREADS)
2729 /* locks must be held in locking order (if any) */
2731 MUTEX_LOCK(&PL_perlio_mutex);
2734 MUTEX_LOCK(&PL_malloc_mutex);
2740 /* this is called in both parent and child after the fork() */
2742 Perl_atfork_unlock(void)
2743 #if defined(USE_ITHREADS)
2745 PERL_TSA_RELEASE(PL_perlio_mutex)
2748 PERL_TSA_RELEASE(PL_malloc_mutex)
2750 PERL_TSA_RELEASE(PL_op_mutex)
2753 #if defined(USE_ITHREADS)
2754 /* locks must be released in same order as in atfork_lock() */
2756 MUTEX_UNLOCK(&PL_perlio_mutex);
2759 MUTEX_UNLOCK(&PL_malloc_mutex);
2768 #if defined(HAS_FORK)
2770 #if defined(USE_ITHREADS) && !defined(HAS_PTHREAD_ATFORK)
2775 /* atfork_lock() and atfork_unlock() are installed as pthread_atfork()
2776 * handlers elsewhere in the code */
2780 #elif defined(__amigaos4__)
2781 return amigaos_fork();
2783 /* this "canna happen" since nothing should be calling here if !HAS_FORK */
2784 Perl_croak_nocontext("fork() not available");
2786 #endif /* HAS_FORK */
2791 dup2(int oldfd, int newfd)
2793 #if defined(HAS_FCNTL) && defined(F_DUPFD)
2796 PerlLIO_close(newfd);
2797 return fcntl(oldfd, F_DUPFD, newfd);
2799 #define DUP2_MAX_FDS 256
2800 int fdtmp[DUP2_MAX_FDS];
2806 PerlLIO_close(newfd);
2807 /* good enough for low fd's... */
2808 while ((fd = PerlLIO_dup(oldfd)) != newfd && fd >= 0) {
2809 if (fdx >= DUP2_MAX_FDS) {
2817 PerlLIO_close(fdtmp[--fdx]);
2824 #ifdef HAS_SIGACTION
2829 A wrapper for the C library L<signal(2)>. Don't use the latter, as the Perl
2830 version knows things that interact with the rest of the perl interpreter.
2836 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2838 struct sigaction act, oact;
2841 /* only "parent" interpreter can diddle signals */
2842 if (PL_curinterp != aTHX)
2843 return (Sighandler_t) SIG_ERR;
2846 act.sa_handler = handler;
2847 sigemptyset(&act.sa_mask);
2850 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2851 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2853 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2854 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2855 act.sa_flags |= SA_NOCLDWAIT;
2857 if (sigaction(signo, &act, &oact) == -1)
2858 return (Sighandler_t) SIG_ERR;
2860 return (Sighandler_t) oact.sa_handler;
2864 Perl_rsignal_state(pTHX_ int signo)
2866 struct sigaction oact;
2867 PERL_UNUSED_CONTEXT;
2869 if (sigaction(signo, (struct sigaction *)NULL, &oact) == -1)
2870 return (Sighandler_t) SIG_ERR;
2872 return (Sighandler_t) oact.sa_handler;
2876 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2880 struct sigaction act;
2882 PERL_ARGS_ASSERT_RSIGNAL_SAVE;
2885 /* only "parent" interpreter can diddle signals */
2886 if (PL_curinterp != aTHX)
2890 act.sa_handler = handler;
2891 sigemptyset(&act.sa_mask);
2894 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
2895 act.sa_flags |= SA_RESTART; /* SVR4, 4.3+BSD */
2897 #if defined(SA_NOCLDWAIT) && !defined(BSDish) /* See [perl #18849] */
2898 if (signo == SIGCHLD && handler == (Sighandler_t) SIG_IGN)
2899 act.sa_flags |= SA_NOCLDWAIT;
2901 return sigaction(signo, &act, save);
2905 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2909 PERL_UNUSED_CONTEXT;
2911 /* only "parent" interpreter can diddle signals */
2912 if (PL_curinterp != aTHX)
2916 return sigaction(signo, save, (struct sigaction *)NULL);
2919 #else /* !HAS_SIGACTION */
2922 Perl_rsignal(pTHX_ int signo, Sighandler_t handler)
2924 #if defined(USE_ITHREADS) && !defined(WIN32)
2925 /* only "parent" interpreter can diddle signals */
2926 if (PL_curinterp != aTHX)
2927 return (Sighandler_t) SIG_ERR;
2930 return PerlProc_signal(signo, handler);
2940 Perl_rsignal_state(pTHX_ int signo)
2942 Sighandler_t oldsig;
2944 #if defined(USE_ITHREADS) && !defined(WIN32)
2945 /* only "parent" interpreter can diddle signals */
2946 if (PL_curinterp != aTHX)
2947 return (Sighandler_t) SIG_ERR;
2951 oldsig = PerlProc_signal(signo, sig_trap);
2952 PerlProc_signal(signo, oldsig);
2954 PerlProc_kill(PerlProc_getpid(), signo);
2959 Perl_rsignal_save(pTHX_ int signo, Sighandler_t handler, Sigsave_t *save)
2961 #if defined(USE_ITHREADS) && !defined(WIN32)
2962 /* only "parent" interpreter can diddle signals */
2963 if (PL_curinterp != aTHX)
2966 *save = PerlProc_signal(signo, handler);
2967 return (*save == (Sighandler_t) SIG_ERR) ? -1 : 0;
2971 Perl_rsignal_restore(pTHX_ int signo, Sigsave_t *save)
2973 #if defined(USE_ITHREADS) && !defined(WIN32)
2974 /* only "parent" interpreter can diddle signals */
2975 if (PL_curinterp != aTHX)
2978 return (PerlProc_signal(signo, *save) == (Sighandler_t) SIG_ERR) ? -1 : 0;
2981 #endif /* !HAS_SIGACTION */
2982 #endif /* !PERL_MICRO */
2984 /* VMS' my_pclose() is in VMS.c; same with OS/2 */
2985 #if (!defined(DOSISH) || defined(HAS_FORK)) && !defined(VMS) && !defined(__LIBCATAMOUNT__) && !defined(__amigaos4__)
2987 Perl_my_pclose(pTHX_ PerlIO *ptr)
2995 const int fd = PerlIO_fileno(ptr);
2998 svp = av_fetch(PL_fdpid,fd,TRUE);
2999 pid = (SvTYPE(*svp) == SVt_IV) ? SvIVX(*svp) : -1;
3003 #if defined(USE_PERLIO)
3004 /* Find out whether the refcount is low enough for us to wait for the
3005 child proc without blocking. */
3006 should_wait = PerlIOUnix_refcnt(fd) == 1 && pid > 0;
3008 should_wait = pid > 0;
3012 if (pid == -1) { /* Opened by popen. */
3013 return my_syspclose(ptr);
3016 close_failed = (PerlIO_close(ptr) == EOF);
3018 if (should_wait) do {
3019 pid2 = wait4pid(pid, &status, 0);
3020 } while (pid2 == -1 && errno == EINTR);
3027 ? pid2 < 0 ? pid2 : status == 0 ? 0 : (errno = 0, status)
3031 #elif defined(__LIBCATAMOUNT__)
3033 Perl_my_pclose(pTHX_ PerlIO *ptr)
3037 #endif /* !DOSISH */
3039 #if (!defined(DOSISH) || defined(OS2) || defined(WIN32) || defined(NETWARE)) && !defined(__LIBCATAMOUNT__)
3041 Perl_wait4pid(pTHX_ Pid_t pid, int *statusp, int flags)
3044 PERL_ARGS_ASSERT_WAIT4PID;
3045 #ifdef PERL_USES_PL_PIDSTATUS
3047 /* PERL_USES_PL_PIDSTATUS is only defined when neither
3048 waitpid() nor wait4() is available, or on OS/2, which
3049 doesn't appear to support waiting for a progress group
3050 member, so we can only treat a 0 pid as an unknown child.
3057 /* The keys in PL_pidstatus are now the raw 4 (or 8) bytes of the
3058 pid, rather than a string form. */
3059 SV * const * const svp = hv_fetch(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),FALSE);
3060 if (svp && *svp != &PL_sv_undef) {
3061 *statusp = SvIVX(*svp);
3062 (void)hv_delete(PL_pidstatus,(const char*) &pid,sizeof(Pid_t),
3070 hv_iterinit(PL_pidstatus);
3071 if ((entry = hv_iternext(PL_pidstatus))) {
3072 SV * const sv = hv_iterval(PL_pidstatus,entry);
3074 const char * const spid = hv_iterkey(entry,&len);
3076 assert (len == sizeof(Pid_t));
3077 memcpy((char *)&pid, spid, len);
3078 *statusp = SvIVX(sv);
3079 /* The hash iterator is currently on this entry, so simply
3080 calling hv_delete would trigger the lazy delete, which on
3081 aggregate does more work, because next call to hv_iterinit()
3082 would spot the flag, and have to call the delete routine,
3083 while in the meantime any new entries can't re-use that
3085 hv_iterinit(PL_pidstatus);
3086 (void)hv_delete(PL_pidstatus,spid,len,G_DISCARD);
3093 # ifdef HAS_WAITPID_RUNTIME
3094 if (!HAS_WAITPID_RUNTIME)
3097 result = PerlProc_waitpid(pid,statusp,flags);
3100 #if !defined(HAS_WAITPID) && defined(HAS_WAIT4)
3101 result = wait4(pid,statusp,flags,NULL);
3104 #ifdef PERL_USES_PL_PIDSTATUS
3105 #if defined(HAS_WAITPID) && defined(HAS_WAITPID_RUNTIME)
3110 Perl_croak(aTHX_ "Can't do waitpid with flags");
3112 while ((result = PerlProc_wait(statusp)) != pid && pid > 0 && result >= 0)
3113 pidgone(result,*statusp);
3119 #if defined(HAS_WAITPID) || defined(HAS_WAIT4)
3122 if (result < 0 && errno == EINTR) {
3124 errno = EINTR; /* reset in case a signal handler changed $! */
3128 #endif /* !DOSISH || OS2 || WIN32 || NETWARE */
3130 #ifdef PERL_USES_PL_PIDSTATUS
3132 S_pidgone(pTHX_ Pid_t pid, int status)
3136 sv = *hv_fetch(PL_pidstatus,(const char*)&pid,sizeof(Pid_t),TRUE);
3137 SvUPGRADE(sv,SVt_IV);
3138 SvIV_set(sv, status);
3146 int /* Cannot prototype with I32
3148 my_syspclose(PerlIO *ptr)
3151 Perl_my_pclose(pTHX_ PerlIO *ptr)
3154 /* Needs work for PerlIO ! */
3155 FILE * const f = PerlIO_findFILE(ptr);
3156 const I32 result = pclose(f);
3157 PerlIO_releaseFILE(ptr,f);
3165 Perl_my_pclose(pTHX_ PerlIO *ptr)
3167 /* Needs work for PerlIO ! */
3168 FILE * const f = PerlIO_findFILE(ptr);
3169 I32 result = djgpp_pclose(f);
3170 result = (result << 8) & 0xff00;
3171 PerlIO_releaseFILE(ptr,f);
3176 #define PERL_REPEATCPY_LINEAR 4
3178 Perl_repeatcpy(char *to, const char *from, I32 len, IV count)
3180 PERL_ARGS_ASSERT_REPEATCPY;
3185 croak_memory_wrap();
3188 memset(to, *from, count);
3191 IV items, linear, half;
3193 linear = count < PERL_REPEATCPY_LINEAR ? count : PERL_REPEATCPY_LINEAR;
3194 for (items = 0; items < linear; ++items) {
3195 const char *q = from;
3197 for (todo = len; todo > 0; todo--)
3202 while (items <= half) {
3203 IV size = items * len;
3204 memcpy(p, to, size);
3210 memcpy(p, to, (count - items) * len);
3216 Perl_same_dirent(pTHX_ const char *a, const char *b)
3218 char *fa = strrchr(a,'/');
3219 char *fb = strrchr(b,'/');
3222 SV * const tmpsv = sv_newmortal();
3224 PERL_ARGS_ASSERT_SAME_DIRENT;
3237 sv_setpvs(tmpsv, ".");
3239 sv_setpvn(tmpsv, a, fa - a);
3240 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf1) < 0)
3243 sv_setpvs(tmpsv, ".");
3245 sv_setpvn(tmpsv, b, fb - b);
3246 if (PerlLIO_stat(SvPVX_const(tmpsv), &tmpstatbuf2) < 0)
3248 return tmpstatbuf1.st_dev == tmpstatbuf2.st_dev &&
3249 tmpstatbuf1.st_ino == tmpstatbuf2.st_ino;
3251 #endif /* !HAS_RENAME */
3254 Perl_find_script(pTHX_ const char *scriptname, bool dosearch,
3255 const char *const *const search_ext, I32 flags)
3257 const char *xfound = NULL;
3258 char *xfailed = NULL;
3259 char tmpbuf[MAXPATHLEN];
3264 #if defined(DOSISH) && !defined(OS2)
3265 # define SEARCH_EXTS ".bat", ".cmd", NULL
3266 # define MAX_EXT_LEN 4
3269 # define SEARCH_EXTS ".cmd", ".btm", ".bat", ".pl", NULL
3270 # define MAX_EXT_LEN 4
3273 # define SEARCH_EXTS ".pl", ".com", NULL
3274 # define MAX_EXT_LEN 4
3276 /* additional extensions to try in each dir if scriptname not found */
3278 static const char *const exts[] = { SEARCH_EXTS };
3279 const char *const *const ext = search_ext ? search_ext : exts;
3280 int extidx = 0, i = 0;
3281 const char *curext = NULL;
3283 PERL_UNUSED_ARG(search_ext);
3284 # define MAX_EXT_LEN 0
3287 PERL_ARGS_ASSERT_FIND_SCRIPT;
3290 * If dosearch is true and if scriptname does not contain path
3291 * delimiters, search the PATH for scriptname.
3293 * If SEARCH_EXTS is also defined, will look for each
3294 * scriptname{SEARCH_EXTS} whenever scriptname is not found
3295 * while searching the PATH.
3297 * Assuming SEARCH_EXTS is C<".foo",".bar",NULL>, PATH search
3298 * proceeds as follows:
3299 * If DOSISH or VMSISH:
3300 * + look for ./scriptname{,.foo,.bar}
3301 * + search the PATH for scriptname{,.foo,.bar}
3304 * + look *only* in the PATH for scriptname{,.foo,.bar} (note
3305 * this will not look in '.' if it's not in the PATH)
3310 # ifdef ALWAYS_DEFTYPES
3311 len = strlen(scriptname);
3312 if (!(len == 1 && *scriptname == '-') && scriptname[len-1] != ':') {
3313 int idx = 0, deftypes = 1;
3316 const int hasdir = !dosearch || (strpbrk(scriptname,":[</") != NULL);
3319 int idx = 0, deftypes = 1;
3322 const int hasdir = (strpbrk(scriptname,":[</") != NULL);
3324 /* The first time through, just add SEARCH_EXTS to whatever we
3325 * already have, so we can check for default file types. */
3327 (!hasdir && my_trnlnm("DCL$PATH",tmpbuf,idx++)) )
3334 if ((strlen(tmpbuf) + strlen(scriptname)
3335 + MAX_EXT_LEN) >= sizeof tmpbuf)
3336 continue; /* don't search dir with too-long name */
3337 my_strlcat(tmpbuf, scriptname, sizeof(tmpbuf));
3341 if (strEQ(scriptname, "-"))
3343 if (dosearch) { /* Look in '.' first. */
3344 const char *cur = scriptname;
3346 if ((curext = strrchr(scriptname,'.'))) /* possible current ext */
3348 if (strEQ(ext[i++],curext)) {
3349 extidx = -1; /* already has an ext */
3354 DEBUG_p(PerlIO_printf(Perl_debug_log,
3355 "Looking for %s\n",cur));
3358 if (PerlLIO_stat(cur,&statbuf) >= 0
3359 && !S_ISDIR(statbuf.st_mode)) {
3368 if (cur == scriptname) {
3369 len = strlen(scriptname);
3370 if (len+MAX_EXT_LEN+1 >= sizeof(tmpbuf))
3372 my_strlcpy(tmpbuf, scriptname, sizeof(tmpbuf));
3375 } while (extidx >= 0 && ext[extidx] /* try an extension? */
3376 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len));
3381 if (dosearch && !strchr(scriptname, '/')
3383 && !strchr(scriptname, '\\')
3385 && (s = PerlEnv_getenv("PATH")))
3389 bufend = s + strlen(s);
3390 while (s < bufend) {
3394 && *s != ';'; len++, s++) {
3395 if (len < sizeof tmpbuf)
3398 if (len < sizeof tmpbuf)
3401 s = delimcpy_no_escape(tmpbuf, tmpbuf + sizeof tmpbuf, s, bufend,
3406 if (len + 1 + strlen(scriptname) + MAX_EXT_LEN >= sizeof tmpbuf)
3407 continue; /* don't search dir with too-long name */
3410 && tmpbuf[len - 1] != '/'
3411 && tmpbuf[len - 1] != '\\'
3414 tmpbuf[len++] = '/';
3415 if (len == 2 && tmpbuf[0] == '.')
3417 (void)my_strlcpy(tmpbuf + len, scriptname, sizeof(tmpbuf) - len);
3421 len = strlen(tmpbuf);
3422 if (extidx > 0) /* reset after previous loop */
3426 DEBUG_p(PerlIO_printf(Perl_debug_log, "Looking for %s\n",tmpbuf));
3427 retval = PerlLIO_stat(tmpbuf,&statbuf);
3428 if (S_ISDIR(statbuf.st_mode)) {
3432 } while ( retval < 0 /* not there */
3433 && extidx>=0 && ext[extidx] /* try an extension? */
3434 && my_strlcpy(tmpbuf+len, ext[extidx++], sizeof(tmpbuf) - len)
3439 if (S_ISREG(statbuf.st_mode)
3440 && cando(S_IRUSR,TRUE,&statbuf)
3441 #if !defined(DOSISH)
3442 && cando(S_IXUSR,TRUE,&statbuf)
3446 xfound = tmpbuf; /* bingo! */
3450 xfailed = savepv(tmpbuf);
3455 if (!xfound && !seen_dot && !xfailed &&
3456 (PerlLIO_stat(scriptname,&statbuf) < 0
3457 || S_ISDIR(statbuf.st_mode)))
3459 seen_dot = 1; /* Disable message. */
3464 if (flags & 1) { /* do or die? */
3465 /* diag_listed_as: Can't execute %s */
3466 Perl_croak(aTHX_ "Can't %s %s%s%s",
3467 (xfailed ? "execute" : "find"),
3468 (xfailed ? xfailed : scriptname),
3469 (xfailed ? "" : " on PATH"),
3470 (xfailed || seen_dot) ? "" : ", '.' not in PATH");
3475 scriptname = xfound;
3477 return (scriptname ? savepv(scriptname) : NULL);
3480 #ifndef PERL_GET_CONTEXT_DEFINED
3483 Perl_get_context(void)
3485 #if defined(USE_ITHREADS)
3486 # ifdef OLD_PTHREADS_API
3488 int error = pthread_getspecific(PL_thr_key, &t);
3490 Perl_croak_nocontext("panic: pthread_getspecific, error=%d", error);
3492 # elif defined(I_MACH_CTHREADS)
3493 return (void*)cthread_data(cthread_self());
3495 return (void*)PTHREAD_GETSPECIFIC(PL_thr_key);
3503 Perl_set_context(void *t)
3505 #if defined(USE_ITHREADS)
3507 PERL_ARGS_ASSERT_SET_CONTEXT;
3508 #if defined(USE_ITHREADS)
3509 # ifdef I_MACH_CTHREADS
3510 cthread_set_data(cthread_self(), t);
3513 const int error = pthread_setspecific(PL_thr_key, t);
3515 Perl_croak_nocontext("panic: pthread_setspecific, error=%d", error);
3523 #endif /* !PERL_GET_CONTEXT_DEFINED */
3526 Perl_get_op_names(pTHX)
3528 PERL_UNUSED_CONTEXT;
3529 return (char **)PL_op_name;
3533 Perl_get_op_descs(pTHX)
3535 PERL_UNUSED_CONTEXT;
3536 return (char **)PL_op_desc;
3540 Perl_get_no_modify(pTHX)
3542 PERL_UNUSED_CONTEXT;
3543 return PL_no_modify;
3547 Perl_get_opargs(pTHX)
3549 PERL_UNUSED_CONTEXT;
3550 return (U32 *)PL_opargs;
3554 Perl_get_ppaddr(pTHX)
3556 PERL_UNUSED_CONTEXT;
3557 return (PPADDR_t*)PL_ppaddr;
3560 #ifndef HAS_GETENV_LEN
3562 Perl_getenv_len(pTHX_ const char *env_elem, unsigned long *len)
3564 char * const env_trans = PerlEnv_getenv(env_elem);
3565 PERL_UNUSED_CONTEXT;
3566 PERL_ARGS_ASSERT_GETENV_LEN;
3568 *len = strlen(env_trans);
3575 Perl_get_vtbl(pTHX_ int vtbl_id)
3577 PERL_UNUSED_CONTEXT;
3579 return (vtbl_id < 0 || vtbl_id >= magic_vtable_max)
3580 ? NULL : (MGVTBL*)PL_magic_vtables + vtbl_id;
3584 Perl_my_fflush_all(pTHX)
3586 #if defined(USE_PERLIO) || defined(FFLUSH_NULL)
3587 return PerlIO_flush(NULL);
3589 # if defined(HAS__FWALK)
3590 extern int fflush(FILE *);
3591 /* undocumented, unprototyped, but very useful BSDism */
3592 extern void _fwalk(int (*)(FILE *));
3596 # if defined(FFLUSH_ALL) && defined(HAS_STDIO_STREAM_ARRAY)
3598 # ifdef PERL_FFLUSH_ALL_FOPEN_MAX
3599 open_max = PERL_FFLUSH_ALL_FOPEN_MAX;
3600 # elif defined(HAS_SYSCONF) && defined(_SC_OPEN_MAX)
3601 open_max = sysconf(_SC_OPEN_MAX);
3602 # elif defined(FOPEN_MAX)
3603 open_max = FOPEN_MAX;
3604 # elif defined(OPEN_MAX)
3605 open_max = OPEN_MAX;
3606 # elif defined(_NFILE)
3611 for (i = 0; i < open_max; i++)
3612 if (STDIO_STREAM_ARRAY[i]._file >= 0 &&
3613 STDIO_STREAM_ARRAY[i]._file < open_max &&
3614 STDIO_STREAM_ARRAY[i]._flag)
3615 PerlIO_flush(&STDIO_STREAM_ARRAY[i]);
3619 SETERRNO(EBADF,RMS_IFI);
3626 Perl_report_wrongway_fh(pTHX_ const GV *gv, const char have)
3628 if (ckWARN(WARN_IO)) {
3630 = gv && (isGV_with_GP(gv))
3633 const char * const direction = have == '>' ? "out" : "in";
3635 if (name && HEK_LEN(name))
3636 Perl_warner(aTHX_ packWARN(WARN_IO),
3637 "Filehandle %" HEKf " opened only for %sput",
3638 HEKfARG(name), direction);
3640 Perl_warner(aTHX_ packWARN(WARN_IO),
3641 "Filehandle opened only for %sput", direction);
3646 Perl_report_evil_fh(pTHX_ const GV *gv)
3648 const IO *io = gv ? GvIO(gv) : NULL;
3649 const PERL_BITFIELD16 op = PL_op->op_type;
3653 if (io && IoTYPE(io) == IoTYPE_CLOSED) {
3655 warn_type = WARN_CLOSED;
3659 warn_type = WARN_UNOPENED;
3662 if (ckWARN(warn_type)) {
3664 = gv && isGV_with_GP(gv) && GvENAMELEN(gv) ?
3665 sv_2mortal(newSVhek(GvENAME_HEK(gv))) : NULL;
3666 const char * const pars =
3667 (const char *)(OP_IS_FILETEST(op) ? "" : "()");
3668 const char * const func =
3670 (op == OP_READLINE || op == OP_RCATLINE
3671 ? "readline" : /* "<HANDLE>" not nice */
3672 op == OP_LEAVEWRITE ? "write" : /* "write exit" not nice */
3674 const char * const type =
3676 (OP_IS_SOCKET(op) || (io && IoTYPE(io) == IoTYPE_SOCKET)
3677 ? "socket" : "filehandle");
3678 const bool have_name = name && SvCUR(name);
3679 Perl_warner(aTHX_ packWARN(warn_type),
3680 "%s%s on %s %s%s%" SVf, func, pars, vile, type,
3681 have_name ? " " : "",
3682 SVfARG(have_name ? name : &PL_sv_no));
3683 if (io && IoDIRP(io) && !(IoFLAGS(io) & IOf_FAKE_DIRP))
3685 aTHX_ packWARN(warn_type),
3686 "\t(Are you trying to call %s%s on dirhandle%s%" SVf "?)\n",
3687 func, pars, have_name ? " " : "",
3688 SVfARG(have_name ? name : &PL_sv_no)
3693 /* To workaround core dumps from the uninitialised tm_zone we get the
3694 * system to give us a reasonable struct to copy. This fix means that
3695 * strftime uses the tm_zone and tm_gmtoff values returned by
3696 * localtime(time()). That should give the desired result most of the
3697 * time. But probably not always!
3699 * This does not address tzname aspects of NETaa14816.
3704 # ifndef STRUCT_TM_HASZONE
3705 # define STRUCT_TM_HASZONE
3709 #ifdef STRUCT_TM_HASZONE /* Backward compat */
3710 # ifndef HAS_TM_TM_ZONE
3711 # define HAS_TM_TM_ZONE
3716 Perl_init_tm(pTHX_ struct tm *ptm) /* see mktime, strftime and asctime */
3718 #ifdef HAS_TM_TM_ZONE
3720 const struct tm* my_tm;
3721 PERL_UNUSED_CONTEXT;
3722 PERL_ARGS_ASSERT_INIT_TM;
3724 ENV_LOCALE_READ_LOCK;
3725 my_tm = localtime(&now);
3727 Copy(my_tm, ptm, 1, struct tm);
3728 ENV_LOCALE_READ_UNLOCK;
3730 PERL_UNUSED_CONTEXT;
3731 PERL_ARGS_ASSERT_INIT_TM;
3732 PERL_UNUSED_ARG(ptm);
3737 * mini_mktime - normalise struct tm values without the localtime()
3738 * semantics (and overhead) of mktime().
3741 Perl_mini_mktime(struct tm *ptm)
3745 int month, mday, year, jday;
3746 int odd_cent, odd_year;
3748 PERL_ARGS_ASSERT_MINI_MKTIME;
3750 #define DAYS_PER_YEAR 365
3751 #define DAYS_PER_QYEAR (4*DAYS_PER_YEAR+1)
3752 #define DAYS_PER_CENT (25*DAYS_PER_QYEAR-1)
3753 #define DAYS_PER_QCENT (4*DAYS_PER_CENT+1)
3754 #define SECS_PER_HOUR (60*60)
3755 #define SECS_PER_DAY (24*SECS_PER_HOUR)
3756 /* parentheses deliberately absent on these two, otherwise they don't work */
3757 #define MONTH_TO_DAYS 153/5
3758 #define DAYS_TO_MONTH 5/153
3759 /* offset to bias by March (month 4) 1st between month/mday & year finding */
3760 #define YEAR_ADJUST (4*MONTH_TO_DAYS+1)
3761 /* as used here, the algorithm leaves Sunday as day 1 unless we adjust it */
3762 #define WEEKDAY_BIAS 6 /* (1+6)%7 makes Sunday 0 again */
3765 * Year/day algorithm notes:
3767 * With a suitable offset for numeric value of the month, one can find
3768 * an offset into the year by considering months to have 30.6 (153/5) days,
3769 * using integer arithmetic (i.e., with truncation). To avoid too much
3770 * messing about with leap days, we consider January and February to be
3771 * the 13th and 14th month of the previous year. After that transformation,
3772 * we need the month index we use to be high by 1 from 'normal human' usage,
3773 * so the month index values we use run from 4 through 15.
3775 * Given that, and the rules for the Gregorian calendar (leap years are those
3776 * divisible by 4 unless also divisible by 100, when they must be divisible
3777 * by 400 instead), we can simply calculate the number of days since some
3778 * arbitrary 'beginning of time' by futzing with the (adjusted) year number,
3779 * the days we derive from our month index, and adding in the day of the
3780 * month. The value used here is not adjusted for the actual origin which
3781 * it normally would use (1 January A.D. 1), since we're not exposing it.
3782 * We're only building the value so we can turn around and get the
3783 * normalised values for the year, month, day-of-month, and day-of-year.
3785 * For going backward, we need to bias the value we're using so that we find
3786 * the right year value. (Basically, we don't want the contribution of
3787 * March 1st to the number to apply while deriving the year). Having done
3788 * that, we 'count up' the contribution to the year number by accounting for
3789 * full quadracenturies (400-year periods) with their extra leap days, plus
3790 * the contribution from full centuries (to avoid counting in the lost leap
3791 * days), plus the contribution from full quad-years (to count in the normal
3792 * leap days), plus the leftover contribution from any non-leap years.
3793 * At this point, if we were working with an actual leap day, we'll have 0
3794 * days left over. This is also true for March 1st, however. So, we have
3795 * to special-case that result, and (earlier) keep track of the 'odd'
3796 * century and year contributions. If we got 4 extra centuries in a qcent,
3797 * or 4 extra years in a qyear, then it's a leap day and we call it 29 Feb.
3798 * Otherwise, we add back in the earlier bias we removed (the 123 from
3799 * figuring in March 1st), find the month index (integer division by 30.6),
3800 * and the remainder is the day-of-month. We then have to convert back to
3801 * 'real' months (including fixing January and February from being 14/15 in
3802 * the previous year to being in the proper year). After that, to get
3803 * tm_yday, we work with the normalised year and get a new yearday value for
3804 * January 1st, which we subtract from the yearday value we had earlier,
3805 * representing the date we've re-built. This is done from January 1
3806 * because tm_yday is 0-origin.
3808 * Since POSIX time routines are only guaranteed to work for times since the
3809 * UNIX epoch (00:00:00 1 Jan 1970 UTC), the fact that this algorithm
3810 * applies Gregorian calendar rules even to dates before the 16th century
3811 * doesn't bother me. Besides, you'd need cultural context for a given
3812 * date to know whether it was Julian or Gregorian calendar, and that's
3813 * outside the scope for this routine. Since we convert back based on the
3814 * same rules we used to build the yearday, you'll only get strange results
3815 * for input which needed normalising, or for the 'odd' century years which
3816 * were leap years in the Julian calendar but not in the Gregorian one.
3817 * I can live with that.
3819 * This algorithm also fails to handle years before A.D. 1 gracefully, but
3820 * that's still outside the scope for POSIX time manipulation, so I don't
3826 year = 1900 + ptm->tm_year;
3827 month = ptm->tm_mon;
3828 mday = ptm->tm_mday;
3834 yearday = DAYS_PER_YEAR * year + year/4 - year/100 + year/400;
3835 yearday += month*MONTH_TO_DAYS + mday + jday;
3837 * Note that we don't know when leap-seconds were or will be,
3838 * so we have to trust the user if we get something which looks
3839 * like a sensible leap-second. Wild values for seconds will
3840 * be rationalised, however.
3842 if ((unsigned) ptm->tm_sec <= 60) {
3849 secs += 60 * ptm->tm_min;
3850 secs += SECS_PER_HOUR * ptm->tm_hour;
3852 if (secs-(secs/SECS_PER_DAY*SECS_PER_DAY) < 0) {
3853 /* got negative remainder, but need positive time */
3854 /* back off an extra day to compensate */
3855 yearday += (secs/SECS_PER_DAY)-1;
3856 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY - 1);
3859 yearday += (secs/SECS_PER_DAY);
3860 secs -= SECS_PER_DAY * (secs/SECS_PER_DAY);
3863 else if (secs >= SECS_PER_DAY) {
3864 yearday += (secs/SECS_PER_DAY);
3865 secs %= SECS_PER_DAY;
3867 ptm->tm_hour = secs/SECS_PER_HOUR;
3868 secs %= SECS_PER_HOUR;
3869 ptm->tm_min = secs/60;
3871 ptm->tm_sec += secs;
3872 /* done with time of day effects */
3874 * The algorithm for yearday has (so far) left it high by 428.
3875 * To avoid mistaking a legitimate Feb 29 as Mar 1, we need to
3876 * bias it by 123 while trying to figure out what year it
3877 * really represents. Even with this tweak, the reverse
3878 * translation fails for years before A.D. 0001.
3879 * It would still fail for Feb 29, but we catch that one below.
3881 jday = yearday; /* save for later fixup vis-a-vis Jan 1 */
3882 yearday -= YEAR_ADJUST;
3883 year = (yearday / DAYS_PER_QCENT) * 400;
3884 yearday %= DAYS_PER_QCENT;
3885 odd_cent = yearday / DAYS_PER_CENT;
3886 year += odd_cent * 100;
3887 yearday %= DAYS_PER_CENT;
3888 year += (yearday / DAYS_PER_QYEAR) * 4;
3889 yearday %= DAYS_PER_QYEAR;
3890 odd_year = yearday / DAYS_PER_YEAR;
3892 yearday %= DAYS_PER_YEAR;
3893 if (!yearday && (odd_cent==4 || odd_year==4)) { /* catch Feb 29 */
3898 yearday += YEAR_ADJUST; /* recover March 1st crock */
3899 month = yearday*DAYS_TO_MONTH;
3900 yearday -= month*MONTH_TO_DAYS;
3901 /* recover other leap-year adjustment */
3910 ptm->tm_year = year - 1900;
3912 ptm->tm_mday = yearday;
3913 ptm->tm_mon = month;
3917 ptm->tm_mon = month - 1;
3919 /* re-build yearday based on Jan 1 to get tm_yday */
3921 yearday = year*DAYS_PER_YEAR + year/4 - year/100 + year/400;
3922 yearday += 14*MONTH_TO_DAYS + 1;
3923 ptm->tm_yday = jday - yearday;
3924 ptm->tm_wday = (jday + WEEKDAY_BIAS) % 7;
3928 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)
3933 =for apidoc my_strftime
3934 strftime(), but with a different API so that the return value is a pointer
3935 to the formatted result (which MUST be arranged to be FREED BY THE
3936 CALLER). This allows this function to increase the buffer size as needed,
3937 so that the caller doesn't have to worry about that.
3939 Note that yday and wday effectively are ignored by this function, as
3940 mini_mktime() overwrites them
3950 PERL_ARGS_ASSERT_MY_STRFTIME;
3952 init_tm(&mytm); /* XXX workaround - see init_tm() above */
3955 mytm.tm_hour = hour;
3956 mytm.tm_mday = mday;
3958 mytm.tm_year = year;
3959 mytm.tm_wday = wday;
3960 mytm.tm_yday = yday;
3961 mytm.tm_isdst = isdst;
3963 /* use libc to get the values for tm_gmtoff and tm_zone [perl #18238] */
3964 #if defined(HAS_MKTIME) && (defined(HAS_TM_TM_GMTOFF) || defined(HAS_TM_TM_ZONE))
3969 #ifdef HAS_TM_TM_GMTOFF
3970 mytm.tm_gmtoff = mytm2.tm_gmtoff;
3972 #ifdef HAS_TM_TM_ZONE
3973 mytm.tm_zone = mytm2.tm_zone;
3978 Newx(buf, buflen, char);
3980 GCC_DIAG_IGNORE_STMT(-Wformat-nonliteral); /* fmt checked by caller */
3981 len = strftime(buf, buflen, fmt, &mytm);
3982 GCC_DIAG_RESTORE_STMT;
3985 ** The following is needed to handle to the situation where
3986 ** tmpbuf overflows. Basically we want to allocate a buffer
3987 ** and try repeatedly. The reason why it is so complicated
3988 ** is that getting a return value of 0 from strftime can indicate
3989 ** one of the following:
3990 ** 1. buffer overflowed,
3991 ** 2. illegal conversion specifier, or
3992 ** 3. the format string specifies nothing to be returned(not
3993 ** an error). This could be because format is an empty string
3994 ** or it specifies %p that yields an empty string in some locale.
3995 ** If there is a better way to make it portable, go ahead by
3998 if (inRANGE(len, 1, buflen - 1) || (len == 0 && *fmt == '\0'))
4001 /* Possibly buf overflowed - try again with a bigger buf */
4002 const int fmtlen = strlen(fmt);
4003 int bufsize = fmtlen + buflen;
4005 Renew(buf, bufsize, char);
4008 GCC_DIAG_IGNORE_STMT(-Wformat-nonliteral); /* fmt checked by caller */
4009 buflen = strftime(buf, bufsize, fmt, &mytm);
4010 GCC_DIAG_RESTORE_STMT;
4012 if (inRANGE(buflen, 1, bufsize - 1))
4014 /* heuristic to prevent out-of-memory errors */
4015 if (bufsize > 100*fmtlen) {
4021 Renew(buf, bufsize, char);
4026 Perl_croak(aTHX_ "panic: no strftime");
4032 #define SV_CWD_RETURN_UNDEF \
4036 #define SV_CWD_ISDOT(dp) \
4037 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
4038 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
4041 =head1 Miscellaneous Functions
4043 =for apidoc getcwd_sv
4045 Fill C<sv> with current working directory
4050 /* Originally written in Perl by John Bazik; rewritten in C by Ben Sugars.
4051 * rewritten again by dougm, optimized for use with xs TARG, and to prefer
4052 * getcwd(3) if available
4053 * Comments from the original:
4054 * This is a faster version of getcwd. It's also more dangerous
4055 * because you might chdir out of a directory that you can't chdir
4059 Perl_getcwd_sv(pTHX_ SV *sv)
4064 PERL_ARGS_ASSERT_GETCWD_SV;
4068 char buf[MAXPATHLEN];
4070 /* Some getcwd()s automatically allocate a buffer of the given
4071 * size from the heap if they are given a NULL buffer pointer.
4072 * The problem is that this behaviour is not portable. */
4073 if (getcwd(buf, sizeof(buf) - 1)) {
4078 SV_CWD_RETURN_UNDEF;
4085 int orig_cdev, orig_cino, cdev, cino, odev, oino, tdev, tino;
4089 SvUPGRADE(sv, SVt_PV);
4091 if (PerlLIO_lstat(".", &statbuf) < 0) {
4092 SV_CWD_RETURN_UNDEF;
4095 orig_cdev = statbuf.st_dev;
4096 orig_cino = statbuf.st_ino;
4106 if (PerlDir_chdir("..") < 0) {
4107 SV_CWD_RETURN_UNDEF;
4109 if (PerlLIO_stat(".", &statbuf) < 0) {
4110 SV_CWD_RETURN_UNDEF;
4113 cdev = statbuf.st_dev;
4114 cino = statbuf.st_ino;
4116 if (odev == cdev && oino == cino) {
4119 if (!(dir = PerlDir_open("."))) {
4120 SV_CWD_RETURN_UNDEF;
4123 while ((dp = PerlDir_read(dir)) != NULL) {
4125 namelen = dp->d_namlen;
4127 namelen = strlen(dp->d_name);
4130 if (SV_CWD_ISDOT(dp)) {
4134 if (PerlLIO_lstat(dp->d_name, &statbuf) < 0) {
4135 SV_CWD_RETURN_UNDEF;
4138 tdev = statbuf.st_dev;
4139 tino = statbuf.st_ino;
4140 if (tino == oino && tdev == odev) {
4146 SV_CWD_RETURN_UNDEF;
4149 if (pathlen + namelen + 1 >= MAXPATHLEN) {
4150 SV_CWD_RETURN_UNDEF;
4153 SvGROW(sv, pathlen + namelen + 1);
4157 Move(SvPVX_const(sv), SvPVX(sv) + namelen + 1, pathlen, char);
4160 /* prepend current directory to the front */
4162 Move(dp->d_name, SvPVX(sv)+1, namelen, char);
4163 pathlen += (namelen + 1);
4165 #ifdef VOID_CLOSEDIR
4168 if (PerlDir_close(dir) < 0) {
4169 SV_CWD_RETURN_UNDEF;
4175 SvCUR_set(sv, pathlen);
4179 if (PerlDir_chdir(SvPVX_const(sv)) < 0) {
4180 SV_CWD_RETURN_UNDEF;
4183 if (PerlLIO_stat(".", &statbuf) < 0) {
4184 SV_CWD_RETURN_UNDEF;
4187 cdev = statbuf.st_dev;
4188 cino = statbuf.st_ino;
4190 if (cdev != orig_cdev || cino != orig_cino) {
4191 Perl_croak(aTHX_ "Unstable directory path, "
4192 "current directory changed unexpectedly");
4205 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET) && defined(SOCK_DGRAM) && defined(HAS_SELECT)
4206 # define EMULATE_SOCKETPAIR_UDP
4209 #ifdef EMULATE_SOCKETPAIR_UDP
4211 S_socketpair_udp (int fd[2]) {
4213 /* Fake a datagram socketpair using UDP to localhost. */
4214 int sockets[2] = {-1, -1};
4215 struct sockaddr_in addresses[2];
4217 Sock_size_t size = sizeof(struct sockaddr_in);
4218 unsigned short port;
4221 memset(&addresses, 0, sizeof(addresses));
4224 sockets[i] = PerlSock_socket(AF_INET, SOCK_DGRAM, PF_INET);
4225 if (sockets[i] == -1)
4226 goto tidy_up_and_fail;
4228 addresses[i].sin_family = AF_INET;
4229 addresses[i].sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4230 addresses[i].sin_port = 0; /* kernel choses port. */
4231 if (PerlSock_bind(sockets[i], (struct sockaddr *) &addresses[i],
4232 sizeof(struct sockaddr_in)) == -1)
4233 goto tidy_up_and_fail;
4236 /* Now have 2 UDP sockets. Find out which port each is connected to, and
4237 for each connect the other socket to it. */
4240 if (PerlSock_getsockname(sockets[i], (struct sockaddr *) &addresses[i],
4242 goto tidy_up_and_fail;
4243 if (size != sizeof(struct sockaddr_in))
4244 goto abort_tidy_up_and_fail;
4245 /* !1 is 0, !0 is 1 */
4246 if (PerlSock_connect(sockets[!i], (struct sockaddr *) &addresses[i],
4247 sizeof(struct sockaddr_in)) == -1)
4248 goto tidy_up_and_fail;
4251 /* Now we have 2 sockets connected to each other. I don't trust some other
4252 process not to have already sent a packet to us (by random) so send
4253 a packet from each to the other. */
4256 /* I'm going to send my own port number. As a short.
4257 (Who knows if someone somewhere has sin_port as a bitfield and needs
4258 this routine. (I'm assuming crays have socketpair)) */
4259 port = addresses[i].sin_port;
4260 got = PerlLIO_write(sockets[i], &port, sizeof(port));
4261 if (got != sizeof(port)) {
4263 goto tidy_up_and_fail;
4264 goto abort_tidy_up_and_fail;
4268 /* Packets sent. I don't trust them to have arrived though.
4269 (As I understand it Solaris TCP stack is multithreaded. Non-blocking
4270 connect to localhost will use a second kernel thread. In 2.6 the
4271 first thread running the connect() returns before the second completes,
4272 so EINPROGRESS> In 2.7 the improved stack is faster and connect()
4273 returns 0. Poor programs have tripped up. One poor program's authors'
4274 had a 50-1 reverse stock split. Not sure how connected these were.)
4275 So I don't trust someone not to have an unpredictable UDP stack.
4279 struct timeval waitfor = {0, 100000}; /* You have 0.1 seconds */
4280 int max = sockets[1] > sockets[0] ? sockets[1] : sockets[0];
4284 FD_SET((unsigned int)sockets[0], &rset);
4285 FD_SET((unsigned int)sockets[1], &rset);
4287 got = PerlSock_select(max + 1, &rset, NULL, NULL, &waitfor);
4288 if (got != 2 || !FD_ISSET(sockets[0], &rset)
4289 || !FD_ISSET(sockets[1], &rset)) {
4290 /* I hope this is portable and appropriate. */
4292 goto tidy_up_and_fail;
4293 goto abort_tidy_up_and_fail;
4297 /* And the paranoia department even now doesn't trust it to have arrive
4298 (hence MSG_DONTWAIT). Or that what arrives was sent by us. */
4300 struct sockaddr_in readfrom;
4301 unsigned short buffer[2];
4306 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4307 sizeof(buffer), MSG_DONTWAIT,
4308 (struct sockaddr *) &readfrom, &size);
4310 got = PerlSock_recvfrom(sockets[i], (char *) &buffer,
4312 (struct sockaddr *) &readfrom, &size);
4316 goto tidy_up_and_fail;
4317 if (got != sizeof(port)
4318 || size != sizeof(struct sockaddr_in)
4319 /* Check other socket sent us its port. */
4320 || buffer[0] != (unsigned short) addresses[!i].sin_port
4321 /* Check kernel says we got the datagram from that socket */
4322 || readfrom.sin_family != addresses[!i].sin_family
4323 || readfrom.sin_addr.s_addr != addresses[!i].sin_addr.s_addr
4324 || readfrom.sin_port != addresses[!i].sin_port)
4325 goto abort_tidy_up_and_fail;
4328 /* My caller (my_socketpair) has validated that this is non-NULL */
4331 /* I hereby declare this connection open. May God bless all who cross
4335 abort_tidy_up_and_fail:
4336 errno = ECONNABORTED;
4340 if (sockets[0] != -1)
4341 PerlLIO_close(sockets[0]);
4342 if (sockets[1] != -1)
4343 PerlLIO_close(sockets[1]);
4348 #endif /* EMULATE_SOCKETPAIR_UDP */
4350 #if !defined(HAS_SOCKETPAIR) && defined(HAS_SOCKET) && defined(AF_INET) && defined(PF_INET)
4352 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4353 /* Stevens says that family must be AF_LOCAL, protocol 0.
4354 I'm going to enforce that, then ignore it, and use TCP (or UDP). */
4359 struct sockaddr_in listen_addr;
4360 struct sockaddr_in connect_addr;
4365 || family != AF_UNIX
4368 errno = EAFNOSUPPORT;
4377 type &= ~SOCK_CLOEXEC;
4380 #ifdef EMULATE_SOCKETPAIR_UDP
4381 if (type == SOCK_DGRAM)
4382 return S_socketpair_udp(fd);
4385 aTHXa(PERL_GET_THX);
4386 listener = PerlSock_socket(AF_INET, type, 0);
4389 memset(&listen_addr, 0, sizeof(listen_addr));
4390 listen_addr.sin_family = AF_INET;
4391 listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4392 listen_addr.sin_port = 0; /* kernel choses port. */
4393 if (PerlSock_bind(listener, (struct sockaddr *) &listen_addr,
4394 sizeof(listen_addr)) == -1)
4395 goto tidy_up_and_fail;
4396 if (PerlSock_listen(listener, 1) == -1)
4397 goto tidy_up_and_fail;
4399 connector = PerlSock_socket(AF_INET, type, 0);
4400 if (connector == -1)
4401 goto tidy_up_and_fail;
4402 /* We want to find out the port number to connect to. */
4403 size = sizeof(connect_addr);
4404 if (PerlSock_getsockname(listener, (struct sockaddr *) &connect_addr,
4406 goto tidy_up_and_fail;
4407 if (size != sizeof(connect_addr))
4408 goto abort_tidy_up_and_fail;
4409 if (PerlSock_connect(connector, (struct sockaddr *) &connect_addr,
4410 sizeof(connect_addr)) == -1)
4411 goto tidy_up_and_fail;
4413 size = sizeof(listen_addr);
4414 acceptor = PerlSock_accept(listener, (struct sockaddr *) &listen_addr,
4417 goto tidy_up_and_fail;
4418 if (size != sizeof(listen_addr))
4419 goto abort_tidy_up_and_fail;
4420 PerlLIO_close(listener);
4421 /* Now check we are talking to ourself by matching port and host on the
4423 if (PerlSock_getsockname(connector, (struct sockaddr *) &connect_addr,
4425 goto tidy_up_and_fail;
4426 if (size != sizeof(connect_addr)
4427 || listen_addr.sin_family != connect_addr.sin_family
4428 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
4429 || listen_addr.sin_port != connect_addr.sin_port) {
4430 goto abort_tidy_up_and_fail;
4436 abort_tidy_up_and_fail:
4438 errno = ECONNABORTED; /* This would be the standard thing to do. */
4439 #elif defined(ECONNREFUSED)
4440 errno = ECONNREFUSED; /* some OSes might not have ECONNABORTED. */
4442 errno = ETIMEDOUT; /* Desperation time. */
4448 PerlLIO_close(listener);
4449 if (connector != -1)
4450 PerlLIO_close(connector);
4452 PerlLIO_close(acceptor);
4458 /* In any case have a stub so that there's code corresponding
4459 * to the my_socketpair in embed.fnc. */
4461 Perl_my_socketpair (int family, int type, int protocol, int fd[2]) {
4462 #ifdef HAS_SOCKETPAIR
4463 return socketpair(family, type, protocol, fd);
4472 =for apidoc sv_nosharing
4474 Dummy routine which "shares" an SV when there is no sharing module present.
4475 Or "locks" it. Or "unlocks" it. In other
4476 words, ignores its single SV argument.
4477 Exists to avoid test for a C<NULL> function pointer and because it could
4478 potentially warn under some level of strict-ness.
4484 Perl_sv_nosharing(pTHX_ SV *sv)
4486 PERL_UNUSED_CONTEXT;
4487 PERL_UNUSED_ARG(sv);
4492 =for apidoc sv_destroyable
4494 Dummy routine which reports that object can be destroyed when there is no
4495 sharing module present. It ignores its single SV argument, and returns
4496 'true'. Exists to avoid test for a C<NULL> function pointer and because it
4497 could potentially warn under some level of strict-ness.
4503 Perl_sv_destroyable(pTHX_ SV *sv)
4505 PERL_UNUSED_CONTEXT;
4506 PERL_UNUSED_ARG(sv);
4511 Perl_parse_unicode_opts(pTHX_ const char **popt)
4513 const char *p = *popt;
4516 PERL_ARGS_ASSERT_PARSE_UNICODE_OPTS;
4520 const char* endptr = p + strlen(p);
4522 if (grok_atoUV(p, &uv, &endptr) && uv <= U32_MAX) {
4525 if (p && *p && *p != '\n' && *p != '\r') {
4527 goto the_end_of_the_opts_parser;
4529 Perl_croak(aTHX_ "Unknown Unicode option letter '%c'", *p);
4533 Perl_croak(aTHX_ "Invalid number '%s' for -C option.\n", p);
4539 case PERL_UNICODE_STDIN:
4540 opt |= PERL_UNICODE_STDIN_FLAG; break;
4541 case PERL_UNICODE_STDOUT:
4542 opt |= PERL_UNICODE_STDOUT_FLAG; break;
4543 case PERL_UNICODE_STDERR:
4544 opt |= PERL_UNICODE_STDERR_FLAG; break;
4545 case PERL_UNICODE_STD:
4546 opt |= PERL_UNICODE_STD_FLAG; break;
4547 case PERL_UNICODE_IN:
4548 opt |= PERL_UNICODE_IN_FLAG; break;
4549 case PERL_UNICODE_OUT:
4550 opt |= PERL_UNICODE_OUT_FLAG; break;
4551 case PERL_UNICODE_INOUT:
4552 opt |= PERL_UNICODE_INOUT_FLAG; break;
4553 case PERL_UNICODE_LOCALE:
4554 opt |= PERL_UNICODE_LOCALE_FLAG; break;
4555 case PERL_UNICODE_ARGV:
4556 opt |= PERL_UNICODE_ARGV_FLAG; break;
4557 case PERL_UNICODE_UTF8CACHEASSERT:
4558 opt |= PERL_UNICODE_UTF8CACHEASSERT_FLAG; break;
4560 if (*p != '\n' && *p != '\r') {
4561 if(isSPACE(*p)) goto the_end_of_the_opts_parser;
4564 "Unknown Unicode option letter '%c'", *p);
4571 opt = PERL_UNICODE_DEFAULT_FLAGS;
4573 the_end_of_the_opts_parser:
4575 if (opt & ~PERL_UNICODE_ALL_FLAGS)
4576 Perl_croak(aTHX_ "Unknown Unicode option value %" UVuf,
4577 (UV) (opt & ~PERL_UNICODE_ALL_FLAGS));
4585 # include <starlet.h>
4592 * This is really just a quick hack which grabs various garbage
4593 * values. It really should be a real hash algorithm which
4594 * spreads the effect of every input bit onto every output bit,
4595 * if someone who knows about such things would bother to write it.
4596 * Might be a good idea to add that function to CORE as well.
4597 * No numbers below come from careful analysis or anything here,
4598 * except they are primes and SEED_C1 > 1E6 to get a full-width
4599 * value from (tv_sec * SEED_C1 + tv_usec). The multipliers should
4600 * probably be bigger too.
4603 # define SEED_C1 1000003
4604 #define SEED_C4 73819
4606 # define SEED_C1 25747
4607 #define SEED_C4 20639
4611 #define SEED_C5 26107
4613 #ifndef PERL_NO_DEV_RANDOM
4617 #ifdef HAS_GETTIMEOFDAY
4618 struct timeval when;
4623 /* This test is an escape hatch, this symbol isn't set by Configure. */
4624 #ifndef PERL_NO_DEV_RANDOM
4625 #ifndef PERL_RANDOM_DEVICE
4626 /* /dev/random isn't used by default because reads from it will block
4627 * if there isn't enough entropy available. You can compile with
4628 * PERL_RANDOM_DEVICE to it if you'd prefer Perl to block until there
4629 * is enough real entropy to fill the seed. */
4630 # ifdef __amigaos4__
4631 # define PERL_RANDOM_DEVICE "RANDOM:SIZE=4"
4633 # define PERL_RANDOM_DEVICE "/dev/urandom"
4636 fd = PerlLIO_open_cloexec(PERL_RANDOM_DEVICE, 0);
4638 if (PerlLIO_read(fd, (void*)&u, sizeof u) != sizeof u)
4646 #ifdef HAS_GETTIMEOFDAY
4647 PerlProc_gettimeofday(&when,NULL);
4648 u = (U32)SEED_C1 * when.tv_sec + (U32)SEED_C2 * when.tv_usec;
4651 u = (U32)SEED_C1 * when;
4653 u += SEED_C3 * (U32)PerlProc_getpid();
4654 u += SEED_C4 * (U32)PTR2UV(PL_stack_sp);
4655 #ifndef PLAN9 /* XXX Plan9 assembler chokes on this; fix needed */
4656 u += SEED_C5 * (U32)PTR2UV(&when);
4662 Perl_get_hash_seed(pTHX_ unsigned char * const seed_buffer)
4664 #ifndef NO_PERL_HASH_ENV
4669 PERL_ARGS_ASSERT_GET_HASH_SEED;
4671 #ifndef NO_PERL_HASH_ENV
4672 env_pv= PerlEnv_getenv("PERL_HASH_SEED");
4676 /* ignore leading spaces */
4677 while (isSPACE(*env_pv))
4679 # ifdef USE_PERL_PERTURB_KEYS
4680 /* if they set it to "0" we disable key traversal randomization completely */
4681 if (strEQ(env_pv,"0")) {
4682 PL_hash_rand_bits_enabled= 0;
4684 /* otherwise switch to deterministic mode */
4685 PL_hash_rand_bits_enabled= 2;
4688 /* ignore a leading 0x... if it is there */
4689 if (env_pv[0] == '0' && env_pv[1] == 'x')
4692 for( i = 0; isXDIGIT(*env_pv) && i < PERL_HASH_SEED_BYTES; i++ ) {
4693 seed_buffer[i] = READ_XDIGIT(env_pv) << 4;
4694 if ( isXDIGIT(*env_pv)) {
4695 seed_buffer[i] |= READ_XDIGIT(env_pv);
4698 while (isSPACE(*env_pv))
4701 if (*env_pv && !isXDIGIT(*env_pv)) {
4702 Perl_warn(aTHX_ "perl: warning: Non hex character in '$ENV{PERL_HASH_SEED}', seed only partially set\n");
4704 /* should we check for unparsed crap? */
4705 /* should we warn about unused hex? */
4706 /* should we warn about insufficient hex? */
4709 #endif /* NO_PERL_HASH_ENV */
4711 for( i = 0; i < PERL_HASH_SEED_BYTES; i++ ) {
4712 seed_buffer[i] = (unsigned char)(Perl_internal_drand48() * (U8_MAX+1));
4715 #ifdef USE_PERL_PERTURB_KEYS
4716 { /* initialize PL_hash_rand_bits from the hash seed.
4717 * This value is highly volatile, it is updated every
4718 * hash insert, and is used as part of hash bucket chain
4719 * randomization and hash iterator randomization. */
4720 PL_hash_rand_bits= 0xbe49d17f; /* I just picked a number */
4721 for( i = 0; i < sizeof(UV) ; i++ ) {
4722 PL_hash_rand_bits += seed_buffer[i % PERL_HASH_SEED_BYTES];
4723 PL_hash_rand_bits = ROTL_UV(PL_hash_rand_bits,8);
4726 # ifndef NO_PERL_HASH_ENV
4727 env_pv= PerlEnv_getenv("PERL_PERTURB_KEYS");
4729 if (strEQ(env_pv,"0") || strEQ(env_pv,"NO")) {
4730 PL_hash_rand_bits_enabled= 0;
4731 } else if (strEQ(env_pv,"1") || strEQ(env_pv,"RANDOM")) {
4732 PL_hash_rand_bits_enabled= 1;
4733 } else if (strEQ(env_pv,"2") || strEQ(env_pv,"DETERMINISTIC")) {
4734 PL_hash_rand_bits_enabled= 2;
4736 Perl_warn(aTHX_ "perl: warning: strange setting in '$ENV{PERL_PERTURB_KEYS}': '%s'\n", env_pv);
4745 /* -DPERL_MEM_LOG: the Perl_mem_log_..() is compiled, including
4746 * the default implementation, unless -DPERL_MEM_LOG_NOIMPL is also
4747 * given, and you supply your own implementation.
4749 * The default implementation reads a single env var, PERL_MEM_LOG,
4750 * expecting one or more of the following:
4752 * \d+ - fd fd to write to : must be 1st (grok_atoUV)
4753 * 'm' - memlog was PERL_MEM_LOG=1
4754 * 's' - svlog was PERL_SV_LOG=1
4755 * 't' - timestamp was PERL_MEM_LOG_TIMESTAMP=1
4757 * This makes the logger controllable enough that it can reasonably be
4758 * added to the system perl.
4761 /* -DPERL_MEM_LOG_SPRINTF_BUF_SIZE=X: size of a (stack-allocated) buffer
4762 * the Perl_mem_log_...() will use (either via sprintf or snprintf).
4764 #define PERL_MEM_LOG_SPRINTF_BUF_SIZE 128
4766 /* -DPERL_MEM_LOG_FD=N: the file descriptor the Perl_mem_log_...()
4767 * writes to. In the default logger, this is settable at runtime.
4769 #ifndef PERL_MEM_LOG_FD
4770 # define PERL_MEM_LOG_FD 2 /* If STDERR is too boring for you. */
4773 #ifndef PERL_MEM_LOG_NOIMPL
4775 # ifdef DEBUG_LEAKING_SCALARS
4776 # define SV_LOG_SERIAL_FMT " [%lu]"
4777 # define _SV_LOG_SERIAL_ARG(sv) , (unsigned long) (sv)->sv_debug_serial
4779 # define SV_LOG_SERIAL_FMT
4780 # define _SV_LOG_SERIAL_ARG(sv)
4784 S_mem_log_common(enum mem_log_type mlt, const UV n,
4785 const UV typesize, const char *type_name, const SV *sv,
4786 Malloc_t oldalloc, Malloc_t newalloc,
4787 const char *filename, const int linenumber,
4788 const char *funcname)
4792 PERL_ARGS_ASSERT_MEM_LOG_COMMON;
4794 pmlenv = PerlEnv_getenv("PERL_MEM_LOG");
4797 if (mlt < MLT_NEW_SV ? strchr(pmlenv,'m') : strchr(pmlenv,'s'))
4799 /* We can't use SVs or PerlIO for obvious reasons,
4800 * so we'll use stdio and low-level IO instead. */
4801 char buf[PERL_MEM_LOG_SPRINTF_BUF_SIZE];
4803 # ifdef HAS_GETTIMEOFDAY
4804 # define MEM_LOG_TIME_FMT "%10d.%06d: "
4805 # define MEM_LOG_TIME_ARG (int)tv.tv_sec, (int)tv.tv_usec
4807 gettimeofday(&tv, 0);
4809 # define MEM_LOG_TIME_FMT "%10d: "
4810 # define MEM_LOG_TIME_ARG (int)when
4814 /* If there are other OS specific ways of hires time than
4815 * gettimeofday() (see dist/Time-HiRes), the easiest way is
4816 * probably that they would be used to fill in the struct
4820 const char* endptr = pmlenv + strlen(pmlenv);
4823 if (grok_atoUV(pmlenv, &uv, &endptr) /* Ignore endptr. */
4824 && uv && uv <= PERL_INT_MAX
4828 fd = PERL_MEM_LOG_FD;
4831 if (strchr(pmlenv, 't')) {
4832 len = my_snprintf(buf, sizeof(buf),
4833 MEM_LOG_TIME_FMT, MEM_LOG_TIME_ARG);
4834 PERL_UNUSED_RESULT(PerlLIO_write(fd, buf, len));
4838 len = my_snprintf(buf, sizeof(buf),
4839 "alloc: %s:%d:%s: %" IVdf " %" UVuf
4840 " %s = %" IVdf ": %" UVxf "\n",
4841 filename, linenumber, funcname, n, typesize,
4842 type_name, n * typesize, PTR2UV(newalloc));
4845 len = my_snprintf(buf, sizeof(buf),
4846 "realloc: %s:%d:%s: %" IVdf " %" UVuf
4847 " %s = %" IVdf ": %" UVxf " -> %" UVxf "\n",
4848 filename, linenumber, funcname, n, typesize,
4849 type_name, n * typesize, PTR2UV(oldalloc),
4853 len = my_snprintf(buf, sizeof(buf),
4854 "free: %s:%d:%s: %" UVxf "\n",
4855 filename, linenumber, funcname,
4860 len = my_snprintf(buf, sizeof(buf),
4861 "%s_SV: %s:%d:%s: %" UVxf SV_LOG_SERIAL_FMT "\n",
4862 mlt == MLT_NEW_SV ? "new" : "del",
4863 filename, linenumber, funcname,
4864 PTR2UV(sv) _SV_LOG_SERIAL_ARG(sv));
4869 PERL_UNUSED_RESULT(PerlLIO_write(fd, buf, len));
4873 #endif /* !PERL_MEM_LOG_NOIMPL */
4875 #ifndef PERL_MEM_LOG_NOIMPL
4877 mem_log_common_if(alty, num, tysz, tynm, sv, oal, nal, flnm, ln, fnnm) \
4878 mem_log_common (alty, num, tysz, tynm, sv, oal, nal, flnm, ln, fnnm)
4880 /* this is suboptimal, but bug compatible. User is providing their
4881 own implementation, but is getting these functions anyway, and they
4882 do nothing. But _NOIMPL users should be able to cope or fix */
4884 mem_log_common_if(alty, num, tysz, tynm, u, oal, nal, flnm, ln, fnnm) \
4885 /* mem_log_common_if_PERL_MEM_LOG_NOIMPL */
4889 Perl_mem_log_alloc(const UV n, const UV typesize, const char *type_name,
4891 const char *filename, const int linenumber,
4892 const char *funcname)
4894 PERL_ARGS_ASSERT_MEM_LOG_ALLOC;
4896 mem_log_common_if(MLT_ALLOC, n, typesize, type_name,
4897 NULL, NULL, newalloc,
4898 filename, linenumber, funcname);
4903 Perl_mem_log_realloc(const UV n, const UV typesize, const char *type_name,
4904 Malloc_t oldalloc, Malloc_t newalloc,
4905 const char *filename, const int linenumber,
4906 const char *funcname)
4908 PERL_ARGS_ASSERT_MEM_LOG_REALLOC;
4910 mem_log_common_if(MLT_REALLOC, n, typesize, type_name,
4911 NULL, oldalloc, newalloc,
4912 filename, linenumber, funcname);
4917 Perl_mem_log_free(Malloc_t oldalloc,
4918 const char *filename, const int linenumber,
4919 const char *funcname)
4921 PERL_ARGS_ASSERT_MEM_LOG_FREE;
4923 mem_log_common_if(MLT_FREE, 0, 0, "", NULL, oldalloc, NULL,
4924 filename, linenumber, funcname);
4929 Perl_mem_log_new_sv(const SV *sv,
4930 const char *filename, const int linenumber,
4931 const char *funcname)
4933 mem_log_common_if(MLT_NEW_SV, 0, 0, "", sv, NULL, NULL,
4934 filename, linenumber, funcname);
4938 Perl_mem_log_del_sv(const SV *sv,
4939 const char *filename, const int linenumber,
4940 const char *funcname)
4942 mem_log_common_if(MLT_DEL_SV, 0, 0, "", sv, NULL, NULL,
4943 filename, linenumber, funcname);
4946 #endif /* PERL_MEM_LOG */
4949 =for apidoc quadmath_format_valid
4951 C<quadmath_snprintf()> is very strict about its C<format> string and will
4952 fail, returning -1, if the format is invalid. It accepts exactly
4955 C<quadmath_format_valid()> checks that the intended single spec looks
4956 sane: begins with C<%>, has only one C<%>, ends with C<[efgaEFGA]>,
4957 and has C<Q> before it. This is not a full "printf syntax check",
4960 Returns true if it is valid, false if not.
4962 See also L</quadmath_format_needed>.
4968 Perl_quadmath_format_valid(const char* format)
4972 PERL_ARGS_ASSERT_QUADMATH_FORMAT_VALID;
4974 if (format[0] != '%' || strchr(format + 1, '%'))
4976 len = strlen(format);
4977 /* minimum length three: %Qg */
4978 if (len < 3 || memCHRs("efgaEFGA", format[len - 1]) == NULL)
4980 if (format[len - 2] != 'Q')
4987 =for apidoc quadmath_format_needed
4989 C<quadmath_format_needed()> returns true if the C<format> string seems to
4990 contain at least one non-Q-prefixed C<%[efgaEFGA]> format specifier,
4991 or returns false otherwise.
4993 The format specifier detection is not complete printf-syntax detection,
4994 but it should catch most common cases.
4996 If true is returned, those arguments B<should> in theory be processed
4997 with C<quadmath_snprintf()>, but in case there is more than one such
4998 format specifier (see L</quadmath_format_valid>), and if there is
4999 anything else beyond that one (even just a single byte), they
5000 B<cannot> be processed because C<quadmath_snprintf()> is very strict,
5001 accepting only one format spec, and nothing else.
5002 In this case, the code should probably fail.
5008 Perl_quadmath_format_needed(const char* format)
5010 const char *p = format;
5013 PERL_ARGS_ASSERT_QUADMATH_FORMAT_NEEDED;
5015 while ((q = strchr(p, '%'))) {
5017 if (*q == '+') /* plus */
5019 if (*q == '#') /* alt */
5021 if (*q == '*') /* width */
5025 while (isDIGIT(*q)) q++;
5028 if (*q == '.' && (q[1] == '*' || isDIGIT(q[1]))) { /* prec */
5033 while (isDIGIT(*q)) q++;
5035 if (memCHRs("efgaEFGA", *q)) /* Would have needed 'Q' in front. */
5044 =for apidoc my_snprintf
5046 The C library C<snprintf> functionality, if available and
5047 standards-compliant (uses C<vsnprintf>, actually). However, if the
5048 C<vsnprintf> is not available, will unfortunately use the unsafe
5049 C<vsprintf> which can overrun the buffer (there is an overrun check,
5050 but that may be too late). Consider using C<sv_vcatpvf> instead, or
5051 getting C<vsnprintf>.
5056 Perl_my_snprintf(char *buffer, const Size_t len, const char *format, ...)
5060 PERL_ARGS_ASSERT_MY_SNPRINTF;
5061 #ifndef HAS_VSNPRINTF
5062 PERL_UNUSED_VAR(len);
5064 va_start(ap, format);
5067 bool quadmath_valid = FALSE;
5068 if (quadmath_format_valid(format)) {
5069 /* If the format looked promising, use it as quadmath. */
5070 retval = quadmath_snprintf(buffer, len, format, va_arg(ap, NV));
5072 Perl_croak_nocontext("panic: quadmath_snprintf failed, format \"%s\"", format);
5074 quadmath_valid = TRUE;
5076 /* quadmath_format_single() will return false for example for
5077 * "foo = %g", or simply "%g". We could handle the %g by
5078 * using quadmath for the NV args. More complex cases of
5079 * course exist: "foo = %g, bar = %g", or "foo=%Qg" (otherwise
5080 * quadmath-valid but has stuff in front).
5082 * Handling the "Q-less" cases right would require walking
5083 * through the va_list and rewriting the format, calling
5084 * quadmath for the NVs, building a new va_list, and then
5085 * letting vsnprintf/vsprintf to take care of the other
5086 * arguments. This may be doable.
5088 * We do not attempt that now. But for paranoia, we here try
5089 * to detect some common (but not all) cases where the
5090 * "Q-less" %[efgaEFGA] formats are present, and die if
5091 * detected. This doesn't fix the problem, but it stops the
5092 * vsnprintf/vsprintf pulling doubles off the va_list when
5093 * __float128 NVs should be pulled off instead.
5095 * If quadmath_format_needed() returns false, we are reasonably
5096 * certain that we can call vnsprintf() or vsprintf() safely. */
5097 if (!quadmath_valid && quadmath_format_needed(format))
5098 Perl_croak_nocontext("panic: quadmath_snprintf failed, format \"%s\"", format);
5103 #ifdef HAS_VSNPRINTF
5104 retval = vsnprintf(buffer, len, format, ap);
5106 retval = vsprintf(buffer, format, ap);
5109 /* vsprintf() shows failure with < 0 */
5111 #ifdef HAS_VSNPRINTF
5112 /* vsnprintf() shows failure with >= len */
5114 (len > 0 && (Size_t)retval >= len)
5117 Perl_croak_nocontext("panic: my_snprintf buffer overflow");
5122 =for apidoc my_vsnprintf
5124 The C library C<vsnprintf> if available and standards-compliant.
5125 However, if the C<vsnprintf> is not available, will unfortunately
5126 use the unsafe C<vsprintf> which can overrun the buffer (there is an
5127 overrun check, but that may be too late). Consider using
5128 C<sv_vcatpvf> instead, or getting C<vsnprintf>.
5133 Perl_my_vsnprintf(char *buffer, const Size_t len, const char *format, va_list ap)
5136 PERL_UNUSED_ARG(buffer);
5137 PERL_UNUSED_ARG(len);
5138 PERL_UNUSED_ARG(format);
5139 /* the cast is to avoid gcc -Wsizeof-array-argument complaining */
5140 PERL_UNUSED_ARG((void*)ap);
5141 Perl_croak_nocontext("panic: my_vsnprintf not available with quadmath");
5148 PERL_ARGS_ASSERT_MY_VSNPRINTF;
5149 Perl_va_copy(ap, apc);
5150 # ifdef HAS_VSNPRINTF
5151 retval = vsnprintf(buffer, len, format, apc);
5153 PERL_UNUSED_ARG(len);
5154 retval = vsprintf(buffer, format, apc);
5158 # ifdef HAS_VSNPRINTF
5159 retval = vsnprintf(buffer, len, format, ap);
5161 PERL_UNUSED_ARG(len);
5162 retval = vsprintf(buffer, format, ap);
5164 #endif /* #ifdef NEED_VA_COPY */
5165 /* vsprintf() shows failure with < 0 */
5167 #ifdef HAS_VSNPRINTF
5168 /* vsnprintf() shows failure with >= len */
5170 (len > 0 && (Size_t)retval >= len)
5173 Perl_croak_nocontext("panic: my_vsnprintf buffer overflow");
5179 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, so no need
5189 if (PL_curinterp == aTHX)
5190 # endif /* USE_ITHREADS */
5192 # if ! defined(PERL_USE_SAFE_PUTENV)
5193 if ( !PL_use_safe_putenv) {
5195 if (environ == PL_origenviron)
5196 environ = (char**)safesysmalloc(sizeof(char*));
5198 for (i = 0; environ[i]; i++)
5199 (void)safesysfree(environ[i]);
5202 # else /* PERL_USE_SAFE_PUTENV */
5203 # if defined(HAS_CLEARENV)
5205 # elif defined(HAS_UNSETENV)
5206 int bsiz = 80; /* Most envvar names will be shorter than this. */
5207 char *buf = (char*)safesysmalloc(bsiz);
5208 while (*environ != NULL) {
5209 char *e = strchr(*environ, '=');
5210 int l = e ? e - *environ : (int)strlen(*environ);
5212 (void)safesysfree(buf);
5213 bsiz = l + 1; /* + 1 for the \0. */
5214 buf = (char*)safesysmalloc(bsiz);
5216 memcpy(buf, *environ, l);
5218 (void)unsetenv(buf);
5220 (void)safesysfree(buf);
5221 # else /* ! HAS_CLEARENV && ! HAS_UNSETENV */
5222 /* Just null environ and accept the leakage. */
5224 # endif /* HAS_CLEARENV || HAS_UNSETENV */
5225 # endif /* ! PERL_USE_SAFE_PUTENV */
5227 # endif /* USE_ENVIRON_ARRAY */
5228 # endif /* PERL_IMPLICIT_SYS || WIN32 */
5229 #endif /* PERL_MICRO */
5232 #ifdef PERL_IMPLICIT_CONTEXT
5235 /* Implements the MY_CXT_INIT macro. The first time a module is loaded,
5236 the global PL_my_cxt_index is incremented, and that value is assigned to
5237 that module's static my_cxt_index (who's address is passed as an arg).
5238 Then, for each interpreter this function is called for, it makes sure a
5239 void* slot is available to hang the static data off, by allocating or
5240 extending the interpreter's PL_my_cxt_list array */
5243 Perl_my_cxt_init(pTHX_ int *indexp, size_t size)
5248 PERL_ARGS_ASSERT_MY_CXT_INIT;
5251 /* do initial check without locking.
5252 * -1: not allocated or another thread currently allocating
5253 * other: already allocated by another thread
5256 MUTEX_LOCK(&PL_my_ctx_mutex);
5257 /*now a stricter check with locking */
5260 /* this module hasn't been allocated an index yet */
5261 *indexp = PL_my_cxt_index++;
5263 MUTEX_UNLOCK(&PL_my_ctx_mutex);
5266 /* make sure the array is big enough */
5267 if (PL_my_cxt_size <= index) {
5268 if (PL_my_cxt_size) {
5269 IV new_size = PL_my_cxt_size;
5270 while (new_size <= index)
5272 Renew(PL_my_cxt_list, new_size, void *);
5273 PL_my_cxt_size = new_size;
5276 PL_my_cxt_size = 16;
5277 Newx(PL_my_cxt_list, PL_my_cxt_size, void *);
5280 /* newSV() allocates one more than needed */
5281 p = (void*)SvPVX(newSV(size-1));
5282 PL_my_cxt_list[index] = p;
5283 Zero(p, size, char);
5287 #endif /* PERL_IMPLICIT_CONTEXT */
5290 /* Perl_xs_handshake():
5291 implement the various XS_*_BOOTCHECK macros, which are added to .c
5292 files by ExtUtils::ParseXS, to check that the perl the module was built
5293 with is binary compatible with the running perl.
5296 Perl_xs_handshake(U32 key, void * v_my_perl, const char * file,
5297 [U32 items, U32 ax], [char * api_version], [char * xs_version])
5299 The meaning of the varargs is determined the U32 key arg (which is not
5300 a format string). The fields of key are assembled by using HS_KEY().
5302 Under PERL_IMPLICIT_CONTEX, the v_my_perl arg is of type
5303 "PerlInterpreter *" and represents the callers context; otherwise it is
5304 of type "CV *", and is the boot xsub's CV.
5306 v_my_perl will catch where a threaded future perl526.dll calling IO.dll
5307 for example, and IO.dll was linked with threaded perl524.dll, and both
5308 perl526.dll and perl524.dll are in %PATH and the Win32 DLL loader
5309 successfully can load IO.dll into the process but simultaneously it
5310 loaded an interpreter of a different version into the process, and XS
5311 code will naturally pass SV*s created by perl524.dll for perl526.dll to
5312 use through perl526.dll's my_perl->Istack_base.
5314 v_my_perl cannot be the first arg, since then 'key' will be out of
5315 place in a threaded vs non-threaded mixup; and analyzing the key
5316 number's bitfields won't reveal the problem, since it will be a valid
5317 key (unthreaded perl) on interp side, but croak will report the XS mod's
5318 key as gibberish (it is really a my_perl ptr) (threaded XS mod); or if
5319 it's a threaded perl and an unthreaded XS module, threaded perl will
5320 look at an uninit C stack or an uninit register to get 'key'
5321 (remember that it assumes that the 1st arg is the interp cxt).
5323 'file' is the source filename of the caller.
5327 Perl_xs_handshake(const U32 key, void * v_my_perl, const char * file, ...)
5333 #ifdef PERL_IMPLICIT_CONTEXT
5340 PERL_ARGS_ASSERT_XS_HANDSHAKE;
5341 va_start(args, file);
5343 got = INT2PTR(void*, (UV)(key & HSm_KEY_MATCH));
5344 need = (void *)(HS_KEY(FALSE, FALSE, "", "") & HSm_KEY_MATCH);
5345 if (UNLIKELY(got != need))
5347 /* try to catch where a 2nd threaded perl interp DLL is loaded into a process
5348 by a XS DLL compiled against the wrong interl DLL b/c of bad @INC, and the
5349 2nd threaded perl interp DLL never initialized its TLS/PERL_SYS_INIT3 so
5350 dTHX call from 2nd interp DLL can't return the my_perl that pp_entersub
5351 passed to the XS DLL */
5352 #ifdef PERL_IMPLICIT_CONTEXT
5353 xs_interp = (tTHX)v_my_perl;
5357 /* try to catch where an unthreaded perl interp DLL (for ex. perl522.dll) is
5358 loaded into a process by a XS DLL built by an unthreaded perl522.dll perl,
5359 but the DynaLoder/Perl that started the process and loaded the XS DLL is
5360 unthreaded perl524.dll, since unthreadeds don't pass my_perl (a unique *)
5361 through pp_entersub, use a unique value (which is a pointer to PL_stack_sp's
5362 location in the unthreaded perl binary) stored in CV * to figure out if this
5363 Perl_xs_handshake was called by the same pp_entersub */
5364 cv = (CV*)v_my_perl;
5365 xs_spp = (SV***)CvHSCXT(cv);
5367 need = &PL_stack_sp;
5369 if(UNLIKELY(got != need)) {
5370 bad_handshake:/* recycle branch and string from above */
5371 if(got != (void *)HSf_NOCHK)
5372 noperl_die("%s: loadable library and perl binaries are mismatched"
5373 " (got handshake key %p, needed %p)\n",
5377 if(key & HSf_SETXSUBFN) { /* this might be called from a module bootstrap */
5378 SAVEPPTR(PL_xsubfilename);/* which was require'd from a XSUB BEGIN */
5379 PL_xsubfilename = file; /* so the old name must be restored for
5380 additional XSUBs to register themselves */
5381 /* XSUBs can't be perl lang/perl5db.pl debugged
5382 if (PERLDB_LINE_OR_SAVESRC)
5383 (void)gv_fetchfile(file); */
5386 if(key & HSf_POPMARK) {
5388 { SV **mark = PL_stack_base + ax++;
5390 items = (I32)(SP - MARK);
5394 items = va_arg(args, U32);
5395 ax = va_arg(args, U32);
5399 assert(HS_GETAPIVERLEN(key) <= UCHAR_MAX);
5400 if((apiverlen = HS_GETAPIVERLEN(key))) {
5401 char * api_p = va_arg(args, char*);
5402 if(apiverlen != sizeof("v" PERL_API_VERSION_STRING)-1
5403 || memNE(api_p, "v" PERL_API_VERSION_STRING,
5404 sizeof("v" PERL_API_VERSION_STRING)-1))
5405 Perl_croak_nocontext("Perl API version %s of %" SVf " does not match %s",
5406 api_p, SVfARG(PL_stack_base[ax + 0]),
5407 "v" PERL_API_VERSION_STRING);
5412 assert(HS_GETXSVERLEN(key) <= UCHAR_MAX && HS_GETXSVERLEN(key) <= HS_APIVERLEN_MAX);
5413 if((xsverlen = HS_GETXSVERLEN(key)))
5414 S_xs_version_bootcheck(aTHX_
5415 items, ax, va_arg(args, char*), xsverlen);
5423 S_xs_version_bootcheck(pTHX_ U32 items, U32 ax, const char *xs_p,
5427 const char *vn = NULL;
5428 SV *const module = PL_stack_base[ax];
5430 PERL_ARGS_ASSERT_XS_VERSION_BOOTCHECK;
5432 if (items >= 2) /* version supplied as bootstrap arg */
5433 sv = PL_stack_base[ax + 1];
5435 /* XXX GV_ADDWARN */
5437 sv = get_sv(Perl_form(aTHX_ "%" SVf "::%s", SVfARG(module), vn), 0);
5438 if (!sv || !SvOK(sv)) {
5440 sv = get_sv(Perl_form(aTHX_ "%" SVf "::%s", SVfARG(module), vn), 0);
5444 SV *xssv = Perl_newSVpvn_flags(aTHX_ xs_p, xs_len, SVs_TEMP);
5445 SV *pmsv = sv_isobject(sv) && sv_derived_from(sv, "version")
5446 ? sv : sv_2mortal(new_version(sv));
5447 xssv = upg_version(xssv, 0);
5448 if ( vcmp(pmsv,xssv) ) {
5449 SV *string = vstringify(xssv);
5450 SV *xpt = Perl_newSVpvf(aTHX_ "%" SVf " object version %" SVf
5451 " does not match ", SVfARG(module), SVfARG(string));
5453 SvREFCNT_dec(string);
5454 string = vstringify(pmsv);
5457 Perl_sv_catpvf(aTHX_ xpt, "$%" SVf "::%s %" SVf, SVfARG(module), vn,
5460 Perl_sv_catpvf(aTHX_ xpt, "bootstrap parameter %" SVf, SVfARG(string));
5462 SvREFCNT_dec(string);
5464 Perl_sv_2mortal(aTHX_ xpt);
5465 Perl_croak_sv(aTHX_ xpt);
5471 =for apidoc my_strlcat
5473 The C library C<strlcat> if available, or a Perl implementation of it.
5474 This operates on C C<NUL>-terminated strings.
5476 C<my_strlcat()> appends string C<src> to the end of C<dst>. It will append at
5477 most S<C<size - strlen(dst) - 1>> characters. It will then C<NUL>-terminate,
5478 unless C<size> is 0 or the original C<dst> string was longer than C<size> (in
5479 practice this should not happen as it means that either C<size> is incorrect or
5480 that C<dst> is not a proper C<NUL>-terminated string).
5482 Note that C<size> is the full size of the destination buffer and
5483 the result is guaranteed to be C<NUL>-terminated if there is room. Note that
5484 room for the C<NUL> should be included in C<size>.
5486 The return value is the total length that C<dst> would have if C<size> is
5487 sufficiently large. Thus it is the initial length of C<dst> plus the length of
5488 C<src>. If C<size> is smaller than the return, the excess was not appended.
5492 Description stolen from http://man.openbsd.org/strlcat.3
5496 Perl_my_strlcat(char *dst, const char *src, Size_t size)
5498 Size_t used, length, copy;
5501 length = strlen(src);
5502 if (size > 0 && used < size - 1) {
5503 copy = (length >= size - used) ? size - used - 1 : length;
5504 memcpy(dst + used, src, copy);
5505 dst[used + copy] = '\0';
5507 return used + length;
5513 =for apidoc my_strlcpy
5515 The C library C<strlcpy> if available, or a Perl implementation of it.
5516 This operates on C C<NUL>-terminated strings.
5518 C<my_strlcpy()> copies up to S<C<size - 1>> characters from the string C<src>
5519 to C<dst>, C<NUL>-terminating the result if C<size> is not 0.
5521 The return value is the total length C<src> would be if the copy completely
5522 succeeded. If it is larger than C<size>, the excess was not copied.
5526 Description stolen from http://man.openbsd.org/strlcpy.3
5530 Perl_my_strlcpy(char *dst, const char *src, Size_t size)
5532 Size_t length, copy;
5534 length = strlen(src);
5536 copy = (length >= size) ? size - 1 : length;
5537 memcpy(dst, src, copy);
5544 #if defined(_MSC_VER) && (_MSC_VER >= 1300) && (_MSC_VER < 1400) && (WINVER < 0x0500)
5545 /* VC7 or 7.1, building with pre-VC7 runtime libraries. */
5546 long _ftol( double ); /* Defined by VC6 C libs. */
5547 long _ftol2( double dblSource ) { return _ftol( dblSource ); }
5550 PERL_STATIC_INLINE bool
5551 S_gv_has_usable_name(pTHX_ GV *gv)
5555 && HvENAME(GvSTASH(gv))
5556 && (gvp = (GV **)hv_fetchhek(
5557 GvSTASH(gv), GvNAME_HEK(gv), 0
5563 Perl_get_db_sub(pTHX_ SV **svp, CV *cv)
5565 SV * const dbsv = GvSVn(PL_DBsub);
5566 const bool save_taint = TAINT_get;
5568 /* When we are called from pp_goto (svp is null),
5569 * we do not care about using dbsv to call CV;
5570 * it's for informational purposes only.
5573 PERL_ARGS_ASSERT_GET_DB_SUB;
5577 if (!PERLDB_SUB_NN) {
5580 if (!svp && !CvLEXICAL(cv)) {
5581 gv_efullname3(dbsv, gv, NULL);
5583 else if ( (CvFLAGS(cv) & (CVf_ANON | CVf_CLONED)) || CvLEXICAL(cv)
5584 || strEQ(GvNAME(gv), "END")
5585 || ( /* Could be imported, and old sub redefined. */
5586 (GvCV(gv) != cv || !S_gv_has_usable_name(aTHX_ gv))
5588 !( (SvTYPE(*svp) == SVt_PVGV)
5589 && (GvCV((const GV *)*svp) == cv)
5590 /* Use GV from the stack as a fallback. */
5591 && S_gv_has_usable_name(aTHX_ gv = (GV *)*svp)
5595 /* GV is potentially non-unique, or contain different CV. */
5596 SV * const tmp = newRV(MUTABLE_SV(cv));
5597 sv_setsv(dbsv, tmp);
5601 sv_sethek(dbsv, HvENAME_HEK(GvSTASH(gv)));
5602 sv_catpvs(dbsv, "::");
5603 sv_cathek(dbsv, GvNAME_HEK(gv));
5607 const int type = SvTYPE(dbsv);
5608 if (type < SVt_PVIV && type != SVt_IV)
5609 sv_upgrade(dbsv, SVt_PVIV);
5610 (void)SvIOK_on(dbsv);
5611 SvIV_set(dbsv, PTR2IV(cv)); /* Do it the quickest way */
5614 TAINT_IF(save_taint);
5615 #ifdef NO_TAINT_SUPPORT
5616 PERL_UNUSED_VAR(save_taint);
5621 Perl_my_dirfd(DIR * dir) {
5623 /* Most dirfd implementations have problems when passed NULL. */
5628 #elif defined(HAS_DIR_DD_FD)
5631 Perl_croak_nocontext(PL_no_func, "dirfd");
5632 NOT_REACHED; /* NOTREACHED */
5637 #if !defined(HAS_MKOSTEMP) || !defined(HAS_MKSTEMP)
5639 #define TEMP_FILE_CH "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvxyz0123456789"
5640 #define TEMP_FILE_CH_COUNT (sizeof(TEMP_FILE_CH)-1)
5643 S_my_mkostemp(char *templte, int flags) {
5645 STRLEN len = strlen(templte);
5649 int delete_on_close = flags & O_VMS_DELETEONCLOSE;
5651 flags &= ~O_VMS_DELETEONCLOSE;
5655 templte[len-1] != 'X' || templte[len-2] != 'X' || templte[len-3] != 'X' ||
5656 templte[len-4] != 'X' || templte[len-5] != 'X' || templte[len-6] != 'X') {
5657 SETERRNO(EINVAL, LIB_INVARG);
5663 for (i = 1; i <= 6; ++i) {
5664 templte[len-i] = TEMP_FILE_CH[(int)(Perl_internal_drand48() * TEMP_FILE_CH_COUNT)];
5667 if (delete_on_close) {
5668 fd = open(templte, O_RDWR | O_CREAT | O_EXCL | flags, 0600, "fop=dlt");
5673 fd = PerlLIO_open3(templte, O_RDWR | O_CREAT | O_EXCL | flags, 0600);
5675 } while (fd == -1 && errno == EEXIST && ++attempts <= 100);
5682 #ifndef HAS_MKOSTEMP
5684 Perl_my_mkostemp(char *templte, int flags)
5686 PERL_ARGS_ASSERT_MY_MKOSTEMP;
5687 return S_my_mkostemp(templte, flags);
5693 Perl_my_mkstemp(char *templte)
5695 PERL_ARGS_ASSERT_MY_MKSTEMP;
5696 return S_my_mkostemp(templte, 0);
5701 Perl_get_re_arg(pTHX_ SV *sv) {
5707 sv = MUTABLE_SV(SvRV(sv));
5708 if (SvTYPE(sv) == SVt_REGEXP)
5709 return (REGEXP*) sv;
5716 * This code is derived from drand48() implementation from FreeBSD,
5717 * found in lib/libc/gen/_rand48.c.
5719 * The U64 implementation is original, based on the POSIX
5720 * specification for drand48().
5724 * Copyright (c) 1993 Martin Birgmeier
5725 * All rights reserved.
5727 * You may redistribute unmodified or modified versions of this source
5728 * code provided that the above copyright notice and this and the
5729 * following conditions are retained.
5731 * This software is provided ``as is'', and comes with no warranties
5732 * of any kind. I shall in no event be liable for anything that happens
5733 * to anyone/anything when using this software.
5736 #define FREEBSD_DRAND48_SEED_0 (0x330e)
5738 #ifdef PERL_DRAND48_QUAD
5740 #define DRAND48_MULT UINT64_C(0x5deece66d)
5741 #define DRAND48_ADD 0xb
5742 #define DRAND48_MASK UINT64_C(0xffffffffffff)
5746 #define FREEBSD_DRAND48_SEED_1 (0xabcd)
5747 #define FREEBSD_DRAND48_SEED_2 (0x1234)
5748 #define FREEBSD_DRAND48_MULT_0 (0xe66d)
5749 #define FREEBSD_DRAND48_MULT_1 (0xdeec)
5750 #define FREEBSD_DRAND48_MULT_2 (0x0005)
5751 #define FREEBSD_DRAND48_ADD (0x000b)
5753 const unsigned short _rand48_mult[3] = {
5754 FREEBSD_DRAND48_MULT_0,
5755 FREEBSD_DRAND48_MULT_1,
5756 FREEBSD_DRAND48_MULT_2
5758 const unsigned short _rand48_add = FREEBSD_DRAND48_ADD;
5763 Perl_drand48_init_r(perl_drand48_t *random_state, U32 seed)
5765 PERL_ARGS_ASSERT_DRAND48_INIT_R;
5767 #ifdef PERL_DRAND48_QUAD
5768 *random_state = FREEBSD_DRAND48_SEED_0 + ((U64)seed << 16);
5770 random_state->seed[0] = FREEBSD_DRAND48_SEED_0;
5771 random_state->seed[1] = (U16) seed;
5772 random_state->seed[2] = (U16) (seed >> 16);
5777 Perl_drand48_r(perl_drand48_t *random_state)
5779 PERL_ARGS_ASSERT_DRAND48_R;
5781 #ifdef PERL_DRAND48_QUAD
5782 *random_state = (*random_state * DRAND48_MULT + DRAND48_ADD)
5785 return ldexp((double)*random_state, -48);
5791 accu = (U32) _rand48_mult[0] * (U32) random_state->seed[0]
5792 + (U32) _rand48_add;
5793 temp[0] = (U16) accu; /* lower 16 bits */
5794 accu >>= sizeof(U16) * 8;
5795 accu += (U32) _rand48_mult[0] * (U32) random_state->seed[1]
5796 + (U32) _rand48_mult[1] * (U32) random_state->seed[0];
5797 temp[1] = (U16) accu; /* middle 16 bits */
5798 accu >>= sizeof(U16) * 8;
5799 accu += _rand48_mult[0] * random_state->seed[2]
5800 + _rand48_mult[1] * random_state->seed[1]
5801 + _rand48_mult[2] * random_state->seed[0];
5802 random_state->seed[0] = temp[0];
5803 random_state->seed[1] = temp[1];
5804 random_state->seed[2] = (U16) accu;
5806 return ldexp((double) random_state->seed[0], -48) +
5807 ldexp((double) random_state->seed[1], -32) +
5808 ldexp((double) random_state->seed[2], -16);
5813 #ifdef USE_C_BACKTRACE
5815 /* Possibly move all this USE_C_BACKTRACE code into a new file. */
5820 /* abfd is the BFD handle. */
5822 /* bfd_syms is the BFD symbol table. */
5824 /* bfd_text is handle to the the ".text" section of the object file. */
5826 /* Since opening the executable and scanning its symbols is quite
5827 * heavy operation, we remember the filename we used the last time,
5828 * and do the opening and scanning only if the filename changes.
5829 * This removes most (but not all) open+scan cycles. */
5830 const char* fname_prev;
5833 /* Given a dl_info, update the BFD context if necessary. */
5834 static void bfd_update(bfd_context* ctx, Dl_info* dl_info)
5836 /* BFD open and scan only if the filename changed. */
5837 if (ctx->fname_prev == NULL ||
5838 strNE(dl_info->dli_fname, ctx->fname_prev)) {
5840 bfd_close(ctx->abfd);
5842 ctx->abfd = bfd_openr(dl_info->dli_fname, 0);
5844 if (bfd_check_format(ctx->abfd, bfd_object)) {
5845 IV symbol_size = bfd_get_symtab_upper_bound(ctx->abfd);
5846 if (symbol_size > 0) {
5847 Safefree(ctx->bfd_syms);
5848 Newx(ctx->bfd_syms, symbol_size, asymbol*);
5850 bfd_get_section_by_name(ctx->abfd, ".text");
5858 ctx->fname_prev = dl_info->dli_fname;
5862 /* Given a raw frame, try to symbolize it and store
5863 * symbol information (source file, line number) away. */
5864 static void bfd_symbolize(bfd_context* ctx,
5867 STRLEN* symbol_name_size,
5869 STRLEN* source_name_size,
5870 STRLEN* source_line)
5872 *symbol_name = NULL;
5873 *symbol_name_size = 0;
5875 IV offset = PTR2IV(raw_frame) - PTR2IV(ctx->bfd_text->vma);
5877 bfd_canonicalize_symtab(ctx->abfd, ctx->bfd_syms) > 0) {
5880 unsigned int line = 0;
5881 if (bfd_find_nearest_line(ctx->abfd, ctx->bfd_text,
5882 ctx->bfd_syms, offset,
5883 &file, &func, &line) &&
5884 file && func && line > 0) {
5885 /* Size and copy the source file, use only
5886 * the basename of the source file.
5888 * NOTE: the basenames are fine for the
5889 * Perl source files, but may not always
5890 * be the best idea for XS files. */
5891 const char *p, *b = NULL;
5892 /* Look for the last slash. */
5893 for (p = file; *p; p++) {
5897 if (b == NULL || *b == 0) {
5900 *source_name_size = p - b + 1;
5901 Newx(*source_name, *source_name_size + 1, char);
5902 Copy(b, *source_name, *source_name_size + 1, char);
5904 *symbol_name_size = strlen(func);
5905 Newx(*symbol_name, *symbol_name_size + 1, char);
5906 Copy(func, *symbol_name, *symbol_name_size + 1, char);
5908 *source_line = line;
5914 #endif /* #ifdef USE_BFD */
5918 /* OS X has no public API for for 'symbolicating' (Apple official term)
5919 * stack addresses to {function_name, source_file, line_number}.
5920 * Good news: there is command line utility atos(1) which does that.
5921 * Bad news 1: it's a command line utility.
5922 * Bad news 2: one needs to have the Developer Tools installed.
5923 * Bad news 3: in newer releases it needs to be run as 'xcrun atos'.
5925 * To recap: we need to open a pipe for reading for a utility which
5926 * might not exist, or exists in different locations, and then parse
5927 * the output. And since this is all for a low-level API, we cannot
5928 * use high-level stuff. Thanks, Apple. */
5931 /* tool is set to the absolute pathname of the tool to use:
5934 /* format is set to a printf format string used for building
5935 * the external command to run. */
5937 /* unavail is set if e.g. xcrun cannot be found, or something
5938 * else happens that makes getting the backtrace dubious. Note,
5939 * however, that the context isn't persistent, the next call to
5940 * get_c_backtrace() will start from scratch. */
5942 /* fname is the current object file name. */
5944 /* object_base_addr is the base address of the shared object. */
5945 void* object_base_addr;
5948 /* Given |dl_info|, updates the context. If the context has been
5949 * marked unavailable, return immediately. If not but the tool has
5950 * not been set, set it to either "xcrun atos" or "atos" (also set the
5951 * format to use for creating commands for piping), or if neither is
5952 * unavailable (one needs the Developer Tools installed), mark the context
5953 * an unavailable. Finally, update the filename (object name),
5954 * and its base address. */
5956 static void atos_update(atos_context* ctx,
5961 if (ctx->tool == NULL) {
5962 const char* tools[] = {
5966 const char* formats[] = {
5967 "/usr/bin/xcrun atos -o '%s' -l %08x %08x 2>&1",
5968 "/usr/bin/atos -d -o '%s' -l %08x %08x 2>&1"
5972 for (i = 0; i < C_ARRAY_LENGTH(tools); i++) {
5973 if (stat(tools[i], &st) == 0 && S_ISREG(st.st_mode)) {
5974 ctx->tool = tools[i];
5975 ctx->format = formats[i];
5979 if (ctx->tool == NULL) {
5980 ctx->unavail = TRUE;
5984 if (ctx->fname == NULL ||
5985 strNE(dl_info->dli_fname, ctx->fname)) {
5986 ctx->fname = dl_info->dli_fname;
5987 ctx->object_base_addr = dl_info->dli_fbase;
5991 /* Given an output buffer end |p| and its |start|, matches
5992 * for the atos output, extracting the source code location
5993 * and returning non-NULL if possible, returning NULL otherwise. */
5994 static const char* atos_parse(const char* p,
5996 STRLEN* source_name_size,
5997 STRLEN* source_line) {
5998 /* atos() output is something like:
5999 * perl_parse (in miniperl) (perl.c:2314)\n\n".
6000 * We cannot use Perl regular expressions, because we need to
6001 * stay low-level. Therefore here we have a rolled-out version
6002 * of a state machine which matches _backwards_from_the_end_ and
6003 * if there's a success, returns the starts of the filename,
6004 * also setting the filename size and the source line number.
6005 * The matched regular expression is roughly "\(.*:\d+\)\s*$" */
6006 const char* source_number_start;
6007 const char* source_name_end;
6008 const char* source_line_end = start;
6009 const char* close_paren;
6012 /* Skip trailing whitespace. */
6013 while (p > start && isSPACE(*p)) p--;
6014 /* Now we should be at the close paren. */
6015 if (p == start || *p != ')')
6019 /* Now we should be in the line number. */
6020 if (p == start || !isDIGIT(*p))
6022 /* Skip over the digits. */
6023 while (p > start && isDIGIT(*p))
6025 /* Now we should be at the colon. */
6026 if (p == start || *p != ':')
6028 source_number_start = p + 1;
6029 source_name_end = p; /* Just beyond the end. */
6031 /* Look for the open paren. */
6032 while (p > start && *p != '(')
6037 *source_name_size = source_name_end - p;
6038 if (grok_atoUV(source_number_start, &uv, &source_line_end)
6039 && source_line_end == close_paren
6040 && uv <= PERL_INT_MAX
6042 *source_line = (STRLEN)uv;
6048 /* Given a raw frame, read a pipe from the symbolicator (that's the
6049 * technical term) atos, reads the result, and parses the source code
6050 * location. We must stay low-level, so we use snprintf(), pipe(),
6051 * and fread(), and then also parse the output ourselves. */
6052 static void atos_symbolize(atos_context* ctx,
6055 STRLEN* source_name_size,
6056 STRLEN* source_line)
6064 /* Simple security measure: if there's any funny business with
6065 * the object name (used as "-o '%s'" ), leave since at least
6066 * partially the user controls it. */
6067 for (p = ctx->fname; *p; p++) {
6068 if (*p == '\'' || isCNTRL(*p)) {
6069 ctx->unavail = TRUE;
6073 cnt = snprintf(cmd, sizeof(cmd), ctx->format,
6074 ctx->fname, ctx->object_base_addr, raw_frame);
6075 if (cnt < sizeof(cmd)) {
6076 /* Undo nostdio.h #defines that disable stdio.
6077 * This is somewhat naughty, but is used elsewhere
6078 * in the core, and affects only OS X. */
6083 FILE* fp = popen(cmd, "r");
6084 /* At the moment we open a new pipe for each stack frame.
6085 * This is naturally somewhat slow, but hopefully generating
6086 * stack traces is never going to in a performance critical path.
6088 * We could play tricks with atos by batching the stack
6089 * addresses to be resolved: atos can either take multiple
6090 * addresses from the command line, or read addresses from
6091 * a file (though the mess of creating temporary files would
6092 * probably negate much of any possible speedup).
6094 * Normally there are only two objects present in the backtrace:
6095 * perl itself, and the libdyld.dylib. (Note that the object
6096 * filenames contain the full pathname, so perl may not always
6097 * be in the same place.) Whenever the object in the
6098 * backtrace changes, the base address also changes.
6100 * The problem with batching the addresses, though, would be
6101 * matching the results with the addresses: the parsing of
6102 * the results is already painful enough with a single address. */
6105 UV cnt = fread(out, 1, sizeof(out), fp);
6106 if (cnt < sizeof(out)) {
6107 const char* p = atos_parse(out + cnt - 1, out,
6112 *source_name_size, char);
6113 Copy(p, *source_name,
6114 *source_name_size, char);
6122 #endif /* #ifdef PERL_DARWIN */
6125 =for apidoc get_c_backtrace
6127 Collects the backtrace (aka "stacktrace") into a single linear
6128 malloced buffer, which the caller B<must> C<Perl_free_c_backtrace()>.
6130 Scans the frames back by S<C<depth + skip>>, then drops the C<skip> innermost,
6131 returning at most C<depth> frames.
6137 Perl_get_c_backtrace(pTHX_ int depth, int skip)
6139 /* Note that here we must stay as low-level as possible: Newx(),
6140 * Copy(), Safefree(); since we may be called from anywhere,
6141 * so we should avoid higher level constructs like SVs or AVs.
6143 * Since we are using safesysmalloc() via Newx(), don't try
6144 * getting backtrace() there, unless you like deep recursion. */
6146 /* Currently only implemented with backtrace() and dladdr(),
6147 * for other platforms NULL is returned. */
6149 #if defined(HAS_BACKTRACE) && defined(HAS_DLADDR)
6150 /* backtrace() is available via <execinfo.h> in glibc and in most
6151 * modern BSDs; dladdr() is available via <dlfcn.h>. */
6153 /* We try fetching this many frames total, but then discard
6154 * the |skip| first ones. For the remaining ones we will try
6155 * retrieving more information with dladdr(). */
6156 int try_depth = skip + depth;
6158 /* The addresses (program counters) returned by backtrace(). */
6161 /* Retrieved with dladdr() from the addresses returned by backtrace(). */
6164 /* Sizes _including_ the terminating \0 of the object name
6165 * and symbol name strings. */
6166 STRLEN* object_name_sizes;
6167 STRLEN* symbol_name_sizes;
6170 /* The symbol names comes either from dli_sname,
6171 * or if using BFD, they can come from BFD. */
6172 char** symbol_names;
6175 /* The source code location information. Dug out with e.g. BFD. */
6176 char** source_names;
6177 STRLEN* source_name_sizes;
6178 STRLEN* source_lines;
6180 Perl_c_backtrace* bt = NULL; /* This is what will be returned. */
6181 int got_depth; /* How many frames were returned from backtrace(). */
6182 UV frame_count = 0; /* How many frames we return. */
6183 UV total_bytes = 0; /* The size of the whole returned backtrace. */
6186 bfd_context bfd_ctx;
6189 atos_context atos_ctx;
6192 /* Here are probably possibilities for optimizing. We could for
6193 * example have a struct that contains most of these and then
6194 * allocate |try_depth| of them, saving a bunch of malloc calls.
6195 * Note, however, that |frames| could not be part of that struct
6196 * because backtrace() will want an array of just them. Also be
6197 * careful about the name strings. */
6198 Newx(raw_frames, try_depth, void*);
6199 Newx(dl_infos, try_depth, Dl_info);
6200 Newx(object_name_sizes, try_depth, STRLEN);
6201 Newx(symbol_name_sizes, try_depth, STRLEN);
6202 Newx(source_names, try_depth, char*);
6203 Newx(source_name_sizes, try_depth, STRLEN);
6204 Newx(source_lines, try_depth, STRLEN);
6206 Newx(symbol_names, try_depth, char*);
6209 /* Get the raw frames. */
6210 got_depth = (int)backtrace(raw_frames, try_depth);
6212 /* We use dladdr() instead of backtrace_symbols() because we want
6213 * the full details instead of opaque strings. This is useful for
6214 * two reasons: () the details are needed for further symbolic
6215 * digging, for example in OS X (2) by having the details we fully
6216 * control the output, which in turn is useful when more platforms
6217 * are added: we can keep out output "portable". */
6219 /* We want a single linear allocation, which can then be freed
6220 * with a single swoop. We will do the usual trick of first
6221 * walking over the structure and seeing how much we need to
6222 * allocate, then allocating, and then walking over the structure
6223 * the second time and populating it. */
6225 /* First we must compute the total size of the buffer. */
6226 total_bytes = sizeof(Perl_c_backtrace_header);
6227 if (got_depth > skip) {
6230 bfd_init(); /* Is this safe to call multiple times? */
6231 Zero(&bfd_ctx, 1, bfd_context);
6234 Zero(&atos_ctx, 1, atos_context);
6236 for (i = skip; i < try_depth; i++) {
6237 Dl_info* dl_info = &dl_infos[i];
6239 object_name_sizes[i] = 0;
6240 source_names[i] = NULL;
6241 source_name_sizes[i] = 0;
6242 source_lines[i] = 0;
6244 /* Yes, zero from dladdr() is failure. */
6245 if (dladdr(raw_frames[i], dl_info)) {
6246 total_bytes += sizeof(Perl_c_backtrace_frame);
6248 object_name_sizes[i] =
6249 dl_info->dli_fname ? strlen(dl_info->dli_fname) : 0;
6250 symbol_name_sizes[i] =
6251 dl_info->dli_sname ? strlen(dl_info->dli_sname) : 0;
6253 bfd_update(&bfd_ctx, dl_info);
6254 bfd_symbolize(&bfd_ctx, raw_frames[i],
6256 &symbol_name_sizes[i],
6258 &source_name_sizes[i],
6262 atos_update(&atos_ctx, dl_info);
6263 atos_symbolize(&atos_ctx,
6266 &source_name_sizes[i],
6270 /* Plus ones for the terminating \0. */
6271 total_bytes += object_name_sizes[i] + 1;
6272 total_bytes += symbol_name_sizes[i] + 1;
6273 total_bytes += source_name_sizes[i] + 1;
6281 Safefree(bfd_ctx.bfd_syms);
6285 /* Now we can allocate and populate the result buffer. */
6286 Newxc(bt, total_bytes, char, Perl_c_backtrace);
6287 Zero(bt, total_bytes, char);
6288 bt->header.frame_count = frame_count;
6289 bt->header.total_bytes = total_bytes;
6290 if (frame_count > 0) {
6291 Perl_c_backtrace_frame* frame = bt->frame_info;
6292 char* name_base = (char *)(frame + frame_count);
6293 char* name_curr = name_base; /* Outputting the name strings here. */
6295 for (i = skip; i < skip + frame_count; i++) {
6296 Dl_info* dl_info = &dl_infos[i];
6298 frame->addr = raw_frames[i];
6299 frame->object_base_addr = dl_info->dli_fbase;
6300 frame->symbol_addr = dl_info->dli_saddr;
6302 /* Copies a string, including the \0, and advances the name_curr.
6303 * Also copies the start and the size to the frame. */
6304 #define PERL_C_BACKTRACE_STRCPY(frame, doffset, src, dsize, size) \
6306 Copy(src, name_curr, size, char); \
6307 frame->doffset = name_curr - (char*)bt; \
6308 frame->dsize = size; \
6309 name_curr += size; \
6312 PERL_C_BACKTRACE_STRCPY(frame, object_name_offset,
6314 object_name_size, object_name_sizes[i]);
6317 PERL_C_BACKTRACE_STRCPY(frame, symbol_name_offset,
6319 symbol_name_size, symbol_name_sizes[i]);
6320 Safefree(symbol_names[i]);
6322 PERL_C_BACKTRACE_STRCPY(frame, symbol_name_offset,
6324 symbol_name_size, symbol_name_sizes[i]);
6327 PERL_C_BACKTRACE_STRCPY(frame, source_name_offset,
6329 source_name_size, source_name_sizes[i]);
6330 Safefree(source_names[i]);
6332 #undef PERL_C_BACKTRACE_STRCPY
6334 frame->source_line_number = source_lines[i];
6338 assert(total_bytes ==
6339 (UV)(sizeof(Perl_c_backtrace_header) +
6340 frame_count * sizeof(Perl_c_backtrace_frame) +
6341 name_curr - name_base));
6344 Safefree(symbol_names);
6346 bfd_close(bfd_ctx.abfd);
6349 Safefree(source_lines);
6350 Safefree(source_name_sizes);
6351 Safefree(source_names);
6352 Safefree(symbol_name_sizes);
6353 Safefree(object_name_sizes);
6354 /* Assuming the strings returned by dladdr() are pointers
6355 * to read-only static memory (the object file), so that
6356 * they do not need freeing (and cannot be). */
6358 Safefree(raw_frames);
6361 PERL_UNUSED_ARG(depth);
6362 PERL_UNUSED_ARG(skip);
6368 =for apidoc free_c_backtrace
6370 Deallocates a backtrace received from get_c_bracktrace.
6376 =for apidoc get_c_backtrace_dump
6378 Returns a SV containing a dump of C<depth> frames of the call stack, skipping
6379 the C<skip> innermost ones. C<depth> of 20 is usually enough.
6381 The appended output looks like:
6384 1 10e004812:0082 Perl_croak util.c:1716 /usr/bin/perl
6385 2 10df8d6d2:1d72 perl_parse perl.c:3975 /usr/bin/perl
6388 The fields are tab-separated. The first column is the depth (zero
6389 being the innermost non-skipped frame). In the hex:offset, the hex is
6390 where the program counter was in C<S_parse_body>, and the :offset (might
6391 be missing) tells how much inside the C<S_parse_body> the program counter was.
6393 The C<util.c:1716> is the source code file and line number.
6395 The F</usr/bin/perl> is obvious (hopefully).
6397 Unknowns are C<"-">. Unknowns can happen unfortunately quite easily:
6398 if the platform doesn't support retrieving the information;
6399 if the binary is missing the debug information;
6400 if the optimizer has transformed the code by for example inlining.
6406 Perl_get_c_backtrace_dump(pTHX_ int depth, int skip)
6408 Perl_c_backtrace* bt;
6410 bt = get_c_backtrace(depth, skip + 1 /* Hide ourselves. */);
6412 Perl_c_backtrace_frame* frame;
6413 SV* dsv = newSVpvs("");
6415 for (i = 0, frame = bt->frame_info;
6416 i < bt->header.frame_count; i++, frame++) {
6417 Perl_sv_catpvf(aTHX_ dsv, "%d", (int)i);
6418 Perl_sv_catpvf(aTHX_ dsv, "\t%p", frame->addr ? frame->addr : "-");
6419 /* Symbol (function) names might disappear without debug info.
6421 * The source code location might disappear in case of the
6422 * optimizer inlining or otherwise rearranging the code. */
6423 if (frame->symbol_addr) {
6424 Perl_sv_catpvf(aTHX_ dsv, ":%04x",
6426 ((char*)frame->addr - (char*)frame->symbol_addr));
6428 Perl_sv_catpvf(aTHX_ dsv, "\t%s",
6429 frame->symbol_name_size &&
6430 frame->symbol_name_offset ?
6431 (char*)bt + frame->symbol_name_offset : "-");
6432 if (frame->source_name_size &&
6433 frame->source_name_offset &&
6434 frame->source_line_number) {
6435 Perl_sv_catpvf(aTHX_ dsv, "\t%s:%" UVuf,
6436 (char*)bt + frame->source_name_offset,
6437 (UV)frame->source_line_number);
6439 Perl_sv_catpvf(aTHX_ dsv, "\t-");
6441 Perl_sv_catpvf(aTHX_ dsv, "\t%s",
6442 frame->object_name_size &&
6443 frame->object_name_offset ?
6444 (char*)bt + frame->object_name_offset : "-");
6445 /* The frame->object_base_addr is not output,
6446 * but it is used for symbolizing/symbolicating. */
6447 sv_catpvs(dsv, "\n");
6450 Perl_free_c_backtrace(bt);
6459 =for apidoc dump_c_backtrace
6461 Dumps the C backtrace to the given C<fp>.
6463 Returns true if a backtrace could be retrieved, false if not.
6469 Perl_dump_c_backtrace(pTHX_ PerlIO* fp, int depth, int skip)
6473 PERL_ARGS_ASSERT_DUMP_C_BACKTRACE;
6475 sv = Perl_get_c_backtrace_dump(aTHX_ depth, skip);
6478 PerlIO_printf(fp, "%s", SvPV_nolen(sv));
6484 #endif /* #ifdef USE_C_BACKTRACE */
6486 #if defined(USE_ITHREADS) && defined(I_PTHREAD)
6488 /* pthread_mutex_t and perl_mutex are typedef equivalent
6489 * so casting the pointers is fine. */
6491 int perl_tsa_mutex_lock(perl_mutex* mutex)
6493 return pthread_mutex_lock((pthread_mutex_t *) mutex);
6496 int perl_tsa_mutex_unlock(perl_mutex* mutex)
6498 return pthread_mutex_unlock((pthread_mutex_t *) mutex);
6501 int perl_tsa_mutex_destroy(perl_mutex* mutex)
6503 return pthread_mutex_destroy((pthread_mutex_t *) mutex);
6510 /* log a sub call or return */
6513 Perl_dtrace_probe_call(pTHX_ CV *cv, bool is_call)
6521 PERL_ARGS_ASSERT_DTRACE_PROBE_CALL;
6524 HEK *hek = CvNAME_HEK(cv);
6525 func = HEK_KEY(hek);
6531 start = (const COP *)CvSTART(cv);
6532 file = CopFILE(start);
6533 line = CopLINE(start);
6534 stash = CopSTASHPV(start);
6537 PERL_SUB_ENTRY(func, file, line, stash);
6540 PERL_SUB_RETURN(func, file, line, stash);
6545 /* log a require file loading/loaded */
6548 Perl_dtrace_probe_load(pTHX_ const char *name, bool is_loading)
6550 PERL_ARGS_ASSERT_DTRACE_PROBE_LOAD;
6553 PERL_LOADING_FILE(name);
6556 PERL_LOADED_FILE(name);
6561 /* log an op execution */
6564 Perl_dtrace_probe_op(pTHX_ const OP *op)
6566 PERL_ARGS_ASSERT_DTRACE_PROBE_OP;
6568 PERL_OP_ENTRY(OP_NAME(op));
6572 /* log a compile/run phase change */
6575 Perl_dtrace_probe_phase(pTHX_ enum perl_phase phase)
6577 const char *ph_old = PL_phase_names[PL_phase];
6578 const char *ph_new = PL_phase_names[phase];
6580 PERL_PHASE_CHANGE(ph_new, ph_old);
6586 * ex: set ts=8 sts=4 sw=4 et: